bump product version to 4.1.6.2
[LibreOffice.git] / xmerge / source / bridge / java / XMergeBridge.java
blob4cee3362e60ba2f0fca6417aee42c8f67ca7d7c5
1 /*
2 * This file is part of the LibreOffice project.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 * This file incorporates work covered by the following license notice:
10 * Licensed to the Apache Software Foundation (ASF) under one or more
11 * contributor license agreements. See the NOTICE file distributed
12 * with this work for additional information regarding copyright
13 * ownership. The ASF licenses this file to you under the Apache
14 * License, Version 2.0 (the "License"); you may not use this file
15 * except in compliance with the License. You may obtain a copy of
16 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
19 /** You can find more
20 * information on the following web page:
21 * http://api.libreoffice.org/docs/common/ref/com/sun/star/module-ix.html
25 /*Java Uno Helper Classes*/
26 import java.io.File;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.net.URI;
30 import java.util.Iterator;
32 import javax.xml.parsers.ParserConfigurationException;
34 import org.openoffice.xmerge.Convert;
35 import org.openoffice.xmerge.ConvertData;
36 import org.openoffice.xmerge.ConverterFactory;
37 import org.openoffice.xmerge.Document;
38 import org.openoffice.xmerge.converter.xml.OfficeDocument;
39 import org.openoffice.xmerge.util.registry.ConverterInfo;
40 import org.openoffice.xmerge.util.registry.ConverterInfoMgr;
41 import org.openoffice.xmerge.util.registry.ConverterInfoReader;
43 import com.sun.star.comp.loader.FactoryHelper;
44 import com.sun.star.frame.XConfigManager;
45 import com.sun.star.io.XInputStream;
46 import com.sun.star.io.XOutputStream;
47 import com.sun.star.lang.XMultiServiceFactory;
48 import com.sun.star.lang.XServiceInfo;
49 import com.sun.star.lang.XServiceName;
50 import com.sun.star.lang.XSingleServiceFactory;
51 import com.sun.star.lang.XTypeProvider;
52 import com.sun.star.lib.uno.adapter.XInputStreamToInputStreamAdapter;
53 import com.sun.star.lib.uno.adapter.XOutputStreamToOutputStreamAdapter;
54 import com.sun.star.registry.XRegistryKey;
55 import com.sun.star.uno.AnyConverter;
56 import com.sun.star.uno.Type;
57 import com.sun.star.uno.UnoRuntime;
58 import com.sun.star.xml.XExportFilter;
59 import com.sun.star.xml.XImportFilter;
60 import com.sun.star.xml.sax.InputSource;
61 import com.sun.star.xml.sax.XDocumentHandler;
62 import com.sun.star.xml.sax.XParser;
65 /** This outer class provides an inner class to implement the service
66 * description and a method to instantiate the
67 * component on demand (__getServiceFactory()).
69 public class XMergeBridge {
72 private static XMultiServiceFactory xMSF;
73 private static XInputStream xInStream =null;
74 private static XOutputStream xOutStream=null;
75 private static String udJarPath=null;
76 private static XOutputStream xos = null;
77 private static String offMime=null;
78 private static String sdMime=null;
79 private static String sFileName=null;
80 private static String sURL="";
82 /** This inner class provides the component as a concrete implementation
83 * of the service description. It implements the needed interfaces.
85 static public class _XMergeBridge implements
86 XImportFilter,
87 XExportFilter,
88 XServiceName,
89 XServiceInfo,
90 XDocumentHandler,
91 XTypeProvider {
93 /** The component will be registered under this name.
95 static private final String __serviceName = "com.sun.star.documentconversion.XMergeBridge";
99 public com.sun.star.uno.Type[] getTypes() {
100 Type[] typeReturn = {};
102 try {
103 typeReturn = new Type[] {
104 new Type( XTypeProvider.class ),
105 new Type( XImportFilter.class ),
106 new Type( XExportFilter.class ),
107 new Type( XServiceName.class ),
108 new Type( XServiceInfo.class ) };
110 catch( Exception exception ) {
114 return( typeReturn );
117 String getFileName(String origName)
119 String name=null;
120 if (origName !=null)
122 if(origName.equalsIgnoreCase(""))
123 name = "OutFile";
124 else {
125 if (origName.lastIndexOf("/")>=0){
126 origName=origName.substring(origName.lastIndexOf("/")+1,origName.length());
128 if (origName.lastIndexOf(".")>=0){
129 name = origName.substring(0,(origName.lastIndexOf(".")));
131 else{
132 name=origName;
136 else{
137 name = "OutFile";
139 return name;
144 public boolean importer(com.sun.star.beans.PropertyValue[] aSourceData,
145 com.sun.star.xml.sax.XDocumentHandler xDocHandler,
146 java.lang.String[] msUserData) throws com.sun.star.uno.RuntimeException {
148 sFileName="";
149 sURL="";
150 udJarPath=msUserData[1];
151 offMime =msUserData[4];
152 sdMime = msUserData[5];
153 com.sun.star.io.XInputStream xis=null;
154 com.sun.star.beans.PropertyValue[] pValue = aSourceData;
156 for (int i = 0 ; i < pValue.length; i++)
159 try{
160 if (pValue[i].Name.compareTo("InputStream")==0){
161 xis=(com.sun.star.io.XInputStream)AnyConverter.toObject(new Type(com.sun.star.io.XInputStream.class), pValue[i].Value);
163 if (pValue[i].Name.compareTo("FileName")==0){
164 sFileName=(String)AnyConverter.toObject(new Type(java.lang.String.class), pValue[i].Value);
168 catch(com.sun.star.lang.IllegalArgumentException AnyExec){
169 System.out.println("\nIllegalArgumentException "+AnyExec);
177 try{
179 Object xCfgMgrObj=xMSF.createInstance("com.sun.star.config.SpecialConfigManager");
180 XConfigManager xCfgMgr = UnoRuntime.queryInterface(
181 XConfigManager.class , xCfgMgrObj );
182 String PathString=xCfgMgr.substituteVariables("$(progurl)" );
183 PathString= PathString.concat("/");
184 udJarPath= PathString.concat(udJarPath);
186 Object xPipeObj=xMSF.createInstance("com.sun.star.io.Pipe");
187 xInStream = UnoRuntime.queryInterface(
188 XInputStream.class , xPipeObj );
189 xOutStream = UnoRuntime.queryInterface(
190 XOutputStream.class , xPipeObj );
191 convert (xis,xOutStream,false,udJarPath,sFileName,offMime,sdMime);
192 Object xSaxParserObj=xMSF.createInstance("com.sun.star.xml.sax.Parser");
194 XParser xParser = UnoRuntime.queryInterface(
195 XParser.class , xSaxParserObj );
196 if (xParser==null){
197 System.out.println("\nParser creation Failed");
199 xOutStream.closeOutput();
200 InputSource aInput = new InputSource();
201 if (sFileName==null){
202 sFileName="";
204 aInput.sSystemId = sFileName;
205 aInput.aInputStream =xInStream;
206 xParser.setDocumentHandler ( xDocHandler );
208 xParser.parseStream ( aInput );
209 xOutStream.closeOutput();
210 xInStream.closeInput();
213 catch (IOException e){
214 return false;
216 catch (Exception e){
217 return false;
219 return true;
222 public boolean exporter(com.sun.star.beans.PropertyValue[] aSourceData,
223 java.lang.String[] msUserData) throws com.sun.star.uno.RuntimeException{
225 sFileName=null;
226 sURL=null;
227 udJarPath=msUserData[1];
228 offMime =msUserData[4];
229 sdMime = msUserData[5];
231 com.sun.star.beans.PropertyValue[] pValue = aSourceData;
232 for (int i = 0 ; i < pValue.length; i++)
236 try{
237 if (pValue[i].Name.compareTo("OutputStream")==0){
238 xos=(com.sun.star.io.XOutputStream)AnyConverter.toObject(new Type(com.sun.star.io.XOutputStream.class), pValue[i].Value);
241 if (pValue[i].Name.compareTo("FileName")==0){
242 sFileName=(String)AnyConverter.toObject(new Type(java.lang.String.class), pValue[i].Value);
245 if (pValue[i].Name.compareTo("URL")==0){
246 sURL=(String)AnyConverter.toObject(new Type(java.lang.String.class), pValue[i].Value);
249 catch(com.sun.star.lang.IllegalArgumentException AnyExec){
250 System.out.println("\nIllegalArgumentException "+AnyExec);
255 if (sURL==null){
256 sURL="";
259 try{
261 Object xCfgMgrObj=xMSF.createInstance("com.sun.star.config.SpecialConfigManager");
262 XConfigManager xCfgMgr = UnoRuntime.queryInterface(
263 XConfigManager.class , xCfgMgrObj );
265 String PathString=xCfgMgr.substituteVariables("$(progurl)" );
266 PathString= PathString.concat("/");
267 udJarPath= PathString.concat(udJarPath);
269 Object xPipeObj=xMSF.createInstance("com.sun.star.io.Pipe");
270 xInStream = UnoRuntime.queryInterface(
271 XInputStream.class , xPipeObj );
272 xOutStream = UnoRuntime.queryInterface(
273 XOutputStream.class , xPipeObj );
275 catch (Exception e){
276 System.out.println("Exception "+e);
277 return false;
280 return true;
283 public String replace(String origString, String origChar, String replaceChar){
284 String tmp="";
285 int index=origString.indexOf(origChar);
286 if(index !=-1){
287 while (index !=-1){
288 String first =origString.substring(0,index);
289 first=first.concat(replaceChar);
290 tmp=tmp.concat(first);
291 origString=origString.substring(index+1,origString.length());
292 index=origString.indexOf(origChar);
293 if(index==-1) {
294 tmp=tmp.concat(origString);
300 return tmp;
303 public String needsMask(String origString){
304 if (origString.indexOf("&")!=-1){
305 origString=replace(origString,"&","&amp;");
307 if (origString.indexOf("\"")!=-1){
308 origString=replace(origString,"\"","&quot;");
310 if (origString.indexOf("<")!=-1){
311 origString=replace(origString,"<","&lt;");
313 if (origString.indexOf(">")!=-1){
314 origString=replace(origString,">","&gt;");
316 return origString;
322 public void startDocument () {
325 public void endDocument()throws com.sun.star.uno.RuntimeException
328 try{
329 xOutStream.closeOutput();
330 convert (xInStream,xos,true,udJarPath,sURL,offMime,sdMime);
333 catch (IOException e){
334 throw new com.sun.star.uno.RuntimeException(e.getMessage());
337 catch (Exception e){
338 throw new com.sun.star.uno.RuntimeException("Xmerge Exception");
345 public void startElement (String str, com.sun.star.xml.sax.XAttributeList xattribs)
348 str="<".concat(str);
349 if (xattribs !=null)
351 str= str.concat(" ");
352 int len=xattribs.getLength();
353 for (short i=0;i<len;i++)
355 str=str.concat(xattribs.getNameByIndex(i));
356 str=str.concat("=\"");
357 str=str.concat(needsMask(xattribs.getValueByIndex(i)));
358 str=str.concat("\" ");
361 str=str.concat(">");
363 try{
364 xOutStream.writeBytes(str.getBytes("UTF-8"));
366 catch (Exception e){
367 System.out.println("\n"+e);
372 public void endElement(String str){
374 str="</".concat(str);
375 str=str.concat(">");
376 try{
377 xOutStream.writeBytes(str.getBytes("UTF-8"));
380 catch (Exception e){
381 System.out.println("\n"+e);
386 public void characters(String str){
387 str=needsMask(str);
388 try{
389 xOutStream.writeBytes(str.getBytes("UTF-8"));
391 catch (Exception e){
392 System.out.println("\n"+e);
398 public void ignorableWhitespace(String str){
402 public void processingInstruction(String aTarget, String aData){
406 public void setDocumentLocator(com.sun.star.xml.sax.XLocator xLocator){
415 public void convert (com.sun.star.io.XInputStream xml,com.sun.star.io.XOutputStream device,
416 boolean convertFromOffice,String pluginUrl,String FileName,String offMime,String sdMime) throws com.sun.star.uno.RuntimeException, IOException {
418 String jarName = pluginUrl;
419 String name= getFileName(FileName);
421 Iterator<ConverterInfo> ciEnum= null;
423 XInputStreamToInputStreamAdapter xis =new XInputStreamToInputStreamAdapter(xml);
426 XOutputStreamToOutputStreamAdapter newxos =new XOutputStreamToOutputStreamAdapter(device);
427 try{
428 ConverterInfoReader cir = new ConverterInfoReader(jarName,false);
429 ciEnum =cir.getConverterInfoEnumeration();
431 catch (ParserConfigurationException pexc){
432 System.out.println("Error:"+pexc);
434 catch ( org.xml.sax.SAXException pexc){
435 System.out.println("Error:"+pexc);
437 catch(Exception e){
438 System.out.println("Error:"+e);
440 ConverterInfoMgr. removeByJar(jarName);
441 if (convertFromOffice)
444 try {
446 //Check to see if jar contains a plugin Impl
448 ConverterInfoMgr.addPlugIn(ciEnum);
449 ConverterFactory cf = new ConverterFactory();
451 Convert cv = cf.getConverter(ConverterInfoMgr.findConverterInfo(sdMime,offMime),false);
452 if (cv == null) {
453 System.out.println("\nNo plug-in exists to convert from <staroffice/sxw> to <specified format> ");
456 else
458 cv.addInputStream(name,xis,false);
459 ConvertData dataOut = cv.convert();
461 Iterator<Object> docEnum = dataOut.getDocumentEnumeration();
463 if (docEnum.hasNext()){
464 Document docOut = (Document)docEnum.next();
465 docOut.write(newxos);
467 newxos.flush();
468 newxos.close();
471 int i=1;
472 while (docEnum.hasNext() && sURL.startsWith("file:")) {
474 URI uri=new URI(sURL);
475 String newFileName= getPath(uri);
477 File newFile=null;
478 if (newFileName.lastIndexOf(".")!=-1){
479 newFile =new File(newFileName.substring(0,newFileName.lastIndexOf("."))+String.valueOf(i)+newFileName.substring(newFileName.lastIndexOf(".")));
481 else{
482 newFile =new File(newFileName.concat(String.valueOf(i)));
485 FileOutputStream fos = new FileOutputStream(newFile);
486 docOut = (Document)docEnum.next();
487 docOut.write(fos);
488 fos.flush();
489 fos.close();
490 i++;
496 ConverterInfoMgr.removeByJar(jarName);
498 catch (StackOverflowError sOE){
499 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");
502 catch (Exception e) {
503 System.out.println("Error:"+e);
504 throw new IOException("Xmerge Exception");
507 else{
509 try {
510 //Check to see if jar contains a plugin Impl
511 ConverterInfoMgr.addPlugIn(ciEnum);
512 ConverterFactory cf = new ConverterFactory();
513 Convert cv = cf.getConverter(ConverterInfoMgr.findConverterInfo(sdMime,offMime),true);
514 if (cv == null) {
515 System.out.println("\nNo plug-in exists to convert to <staroffice/sxw> from <specified format>");
517 else
520 cv.addInputStream(name,xis,false);
521 ConvertData dataIn = cv.convert();
522 Iterator<Object> docEnum = dataIn.getDocumentEnumeration();
523 while (docEnum.hasNext()) {
524 OfficeDocument docIn = (OfficeDocument)docEnum.next();
526 docIn.write(newxos,false);
528 newxos.close();
530 ConverterInfoMgr.removeByJar(jarName);
532 catch (StackOverflowError sOE){
533 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");
535 catch (Exception e) {
536 System.out.println("Error:"+e);
537 throw new IOException("Xmerge Exception");
545 private String getPath(URI uri){
546 String path = uri.getPath();
547 String opSys=System.getProperty("os.name");
548 if(opSys.indexOf("Windows")!=-1){
549 path= path.replace('/','\\');
550 path = path.substring(1);
552 return path;
555 // Implement methods from interface XTypeProvider
556 public byte[] getImplementationId() {
557 byte[] byteReturn = {};
559 byteReturn = new String( "" + this.hashCode() ).getBytes();
561 return( byteReturn );
564 // Implement method from interface XServiceName
565 public String getServiceName() {
566 return( __serviceName );
569 // Implement methods from interface XServiceInfo
570 public boolean supportsService(String stringServiceName) {
571 return( stringServiceName.equals( __serviceName ) );
574 public String getImplementationName() {
575 return( _XMergeBridge.class.getName() );
578 public String[] getSupportedServiceNames() {
579 String[] stringSupportedServiceNames = { __serviceName };
580 return( stringSupportedServiceNames );
585 * Returns a factory for creating the service.
586 * This method is called by the <code>JavaLoader</code>
588 * @return returns a <code>XSingleServiceFactory</code> for creating the
589 * component
591 * @param implName the name of the implementation for which a
592 * service is desired
593 * @param multiFactory the service manager to be used if needed
594 * @param regKey the registryKey
596 * @see com.sun.star.comp.loader.JavaLoader
598 public static XSingleServiceFactory __getServiceFactory(String implName,
599 XMultiServiceFactory multiFactory,
600 XRegistryKey regKey) {
601 xMSF= multiFactory;
602 XSingleServiceFactory xSingleServiceFactory = null;
603 if (implName.equals(_XMergeBridge.class.getName()) ) {
604 xSingleServiceFactory = FactoryHelper.getServiceFactory(_XMergeBridge.class,
605 _XMergeBridge.__serviceName,
606 multiFactory,
607 regKey);
610 return xSingleServiceFactory;