Version 7.5.1.1, tag libreoffice-7.5.1.1
[LibreOffice.git] / xmerge / source / bridge / java / XMergeBridge.java
blob6506326c4046e1acf47e6256f72f03ec8fc3109a
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 * https://api.libreoffice.org/docs/common/ref/com/sun/star/module-ix.html
24 /*Java Uno Helper Classes*/
25 import java.io.File;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.net.URI;
29 import java.util.Iterator;
31 import javax.xml.parsers.ParserConfigurationException;
33 import org.openoffice.xmerge.Convert;
34 import org.openoffice.xmerge.ConvertData;
35 import org.openoffice.xmerge.ConverterFactory;
36 import org.openoffice.xmerge.Document;
37 import org.openoffice.xmerge.converter.xml.OfficeDocument;
38 import org.openoffice.xmerge.util.registry.ConverterInfo;
39 import org.openoffice.xmerge.util.registry.ConverterInfoMgr;
40 import org.openoffice.xmerge.util.registry.ConverterInfoReader;
42 import com.sun.star.comp.loader.FactoryHelper;
43 import com.sun.star.frame.XConfigManager;
44 import com.sun.star.io.XInputStream;
45 import com.sun.star.io.XOutputStream;
46 import com.sun.star.lang.XMultiServiceFactory;
47 import com.sun.star.lang.XServiceInfo;
48 import com.sun.star.lang.XServiceName;
49 import com.sun.star.lang.XSingleServiceFactory;
50 import com.sun.star.lang.XTypeProvider;
51 import com.sun.star.lib.uno.adapter.XInputStreamToInputStreamAdapter;
52 import com.sun.star.lib.uno.adapter.XOutputStreamToOutputStreamAdapter;
53 import com.sun.star.registry.XRegistryKey;
54 import com.sun.star.uno.AnyConverter;
55 import com.sun.star.uno.Type;
56 import com.sun.star.uno.UnoRuntime;
57 import com.sun.star.xml.XExportFilter;
58 import com.sun.star.xml.XImportFilter;
59 import com.sun.star.xml.sax.InputSource;
60 import com.sun.star.xml.sax.XDocumentHandler;
61 import com.sun.star.xml.sax.XParser;
63 /** This outer class provides an inner class to implement the service
64 * description and a method to instantiate the
65 * component on demand (__getServiceFactory()).
67 public class XMergeBridge {
69 private static XMultiServiceFactory xMSF;
70 private static XInputStream xInStream =null;
71 private static XOutputStream xOutStream=null;
72 private static String udJarPath=null;
73 private static XOutputStream xos = null;
74 private static String offMime=null;
75 private static String sdMime=null;
76 private static String sFileName=null;
77 private static String sURL="";
79 /** This inner class provides the component as a concrete implementation
80 * of the service description. It implements the needed interfaces.
82 public static class _XMergeBridge implements
83 XImportFilter,
84 XExportFilter,
85 XServiceName,
86 XServiceInfo,
87 XDocumentHandler,
88 XTypeProvider {
90 /** The component will be registered under this name.
92 private static final String __serviceName = "com.sun.star.documentconversion.XMergeBridge";
94 public com.sun.star.uno.Type[] getTypes() {
95 Type[] typeReturn = {};
97 try {
98 typeReturn = new Type[] {
99 new Type( XTypeProvider.class ),
100 new Type( XImportFilter.class ),
101 new Type( XExportFilter.class ),
102 new Type( XServiceName.class ),
103 new Type( XServiceInfo.class ) };
105 catch( Exception exception ) {
109 return typeReturn;
112 private String getFileName(String origName)
114 String name;
115 if (origName !=null)
117 if(origName.equalsIgnoreCase(""))
118 name = "OutFile";
119 else {
120 if (origName.lastIndexOf("/")>=0){
121 origName=origName.substring(origName.lastIndexOf("/")+1,origName.length());
123 if (origName.lastIndexOf(".")>=0){
124 name = origName.substring(0, origName.lastIndexOf("."));
126 else{
127 name=origName;
131 else{
132 name = "OutFile";
134 return name;
137 public boolean importer(com.sun.star.beans.PropertyValue[] aSourceData,
138 com.sun.star.xml.sax.XDocumentHandler xDocHandler,
139 String[] msUserData) throws com.sun.star.uno.RuntimeException {
141 sFileName="";
142 sURL="";
143 udJarPath=msUserData[1];
144 offMime =msUserData[4];
145 sdMime = msUserData[5];
146 com.sun.star.io.XInputStream xis=null;
147 com.sun.star.beans.PropertyValue[] pValue = aSourceData;
149 for (int i = 0 ; i < pValue.length; i++)
152 try{
153 if (pValue[i].Name.equals("InputStream")){
154 xis=(com.sun.star.io.XInputStream)AnyConverter.toObject(new Type(com.sun.star.io.XInputStream.class), pValue[i].Value);
156 if (pValue[i].Name.equals("FileName")){
157 sFileName=(String)AnyConverter.toObject(new Type(String.class), pValue[i].Value);
161 catch(com.sun.star.lang.IllegalArgumentException AnyExec){
162 System.out.println("\nIllegalArgumentException "+AnyExec);
167 try{
169 Object xCfgMgrObj=xMSF.createInstance("com.sun.star.config.SpecialConfigManager");
170 XConfigManager xCfgMgr = UnoRuntime.queryInterface(
171 XConfigManager.class , xCfgMgrObj );
172 String PathString=xCfgMgr.substituteVariables("$(progurl)" );
173 PathString= PathString.concat("/");
174 udJarPath= PathString.concat(udJarPath);
176 Object xPipeObj=xMSF.createInstance("com.sun.star.io.Pipe");
177 xInStream = UnoRuntime.queryInterface(
178 XInputStream.class , xPipeObj );
179 xOutStream = UnoRuntime.queryInterface(
180 XOutputStream.class , xPipeObj );
181 convert (xis,xOutStream,false,udJarPath,sFileName,offMime,sdMime);
182 Object xSaxParserObj=xMSF.createInstance("com.sun.star.xml.sax.Parser");
184 XParser xParser = UnoRuntime.queryInterface(
185 XParser.class , xSaxParserObj );
186 xOutStream.closeOutput();
187 InputSource aInput = new InputSource();
188 if (sFileName==null){
189 sFileName="";
191 aInput.sSystemId = sFileName;
192 aInput.aInputStream =xInStream;
193 xParser.setDocumentHandler ( xDocHandler );
195 xParser.parseStream ( aInput );
196 xOutStream.closeOutput();
197 xInStream.closeInput();
200 catch (IOException e){
201 return false;
203 catch (Exception e){
204 return false;
206 return true;
209 public boolean exporter(com.sun.star.beans.PropertyValue[] aSourceData,
210 String[] msUserData) throws com.sun.star.uno.RuntimeException{
212 sFileName=null;
213 sURL=null;
214 udJarPath=msUserData[1];
215 offMime =msUserData[4];
216 sdMime = msUserData[5];
218 com.sun.star.beans.PropertyValue[] pValue = aSourceData;
219 for (int i = 0 ; i < pValue.length; i++)
222 try{
223 if (pValue[i].Name.equals("OutputStream")){
224 xos=(com.sun.star.io.XOutputStream)AnyConverter.toObject(new Type(com.sun.star.io.XOutputStream.class), pValue[i].Value);
227 if (pValue[i].Name.equals("FileName")){
228 sFileName=(String)AnyConverter.toObject(new Type(String.class), pValue[i].Value);
231 if (pValue[i].Name.equals("URL")){
232 sURL=(String)AnyConverter.toObject(new Type(String.class), pValue[i].Value);
235 catch(com.sun.star.lang.IllegalArgumentException AnyExec){
236 System.out.println("\nIllegalArgumentException "+AnyExec);
240 if (sURL==null){
241 sURL="";
244 try{
246 Object xCfgMgrObj=xMSF.createInstance("com.sun.star.config.SpecialConfigManager");
247 XConfigManager xCfgMgr = UnoRuntime.queryInterface(
248 XConfigManager.class , xCfgMgrObj );
250 String PathString=xCfgMgr.substituteVariables("$(progurl)" );
251 PathString= PathString.concat("/");
252 udJarPath= PathString.concat(udJarPath);
254 Object xPipeObj=xMSF.createInstance("com.sun.star.io.Pipe");
255 xInStream = UnoRuntime.queryInterface(
256 XInputStream.class , xPipeObj );
257 xOutStream = UnoRuntime.queryInterface(
258 XOutputStream.class , xPipeObj );
260 catch (Exception e){
261 System.out.println("Exception "+e);
262 return false;
265 return true;
268 private String needsMask(String origString){
269 if (origString.contains("&")) {
270 origString = origString.replace("&","&amp;");
272 if (origString.contains("\"")) {
273 origString = origString.replace("\"","&quot;");
275 if (origString.contains("<")) {
276 origString = origString.replace("<","&lt;");
278 if (origString.contains(">")) {
279 origString = origString.replace(">","&gt;");
281 return origString;
284 public void startDocument () {
287 public void endDocument()throws com.sun.star.uno.RuntimeException
290 try{
291 xOutStream.closeOutput();
292 convert (xInStream,xos,true,udJarPath,sURL,offMime,sdMime);
295 catch (IOException e){
296 throw new com.sun.star.uno.RuntimeException(e);
299 catch (Exception e){
300 throw new com.sun.star.uno.RuntimeException(e);
305 public void startElement (String str, com.sun.star.xml.sax.XAttributeList xattribs)
308 str="<".concat(str);
309 if (xattribs !=null)
311 str= str.concat(" ");
312 int len=xattribs.getLength();
313 for (short i=0;i<len;i++)
315 str=str.concat(xattribs.getNameByIndex(i));
316 str=str.concat("=\"");
317 str=str.concat(needsMask(xattribs.getValueByIndex(i)));
318 str=str.concat("\" ");
321 str=str.concat(">");
323 try{
324 xOutStream.writeBytes(str.getBytes("UTF-8"));
326 catch (Exception e){
327 System.out.println("\n"+e);
332 public void endElement(String str){
334 str="</".concat(str);
335 str=str.concat(">");
336 try{
337 xOutStream.writeBytes(str.getBytes("UTF-8"));
340 catch (Exception e){
341 System.out.println("\n"+e);
345 public void characters(String str){
346 str=needsMask(str);
347 try{
348 xOutStream.writeBytes(str.getBytes("UTF-8"));
350 catch (Exception e){
351 System.out.println("\n"+e);
356 public void ignorableWhitespace(String str){
359 public void processingInstruction(String aTarget, String aData){
363 public void setDocumentLocator(com.sun.star.xml.sax.XLocator xLocator){
367 private static void close(FileOutputStream c) throws IOException {
368 if (c == null) return;
369 c.close();
372 private void convert (com.sun.star.io.XInputStream xml,com.sun.star.io.XOutputStream device,
373 boolean convertFromOffice,String pluginUrl,String FileName,String offMime,String sdMime) throws com.sun.star.uno.RuntimeException, IOException {
375 String jarName = pluginUrl;
376 String name= getFileName(FileName);
378 Iterator<ConverterInfo> ciEnum= null;
380 XInputStreamToInputStreamAdapter xis =new XInputStreamToInputStreamAdapter(xml);
382 XOutputStreamToOutputStreamAdapter newxos =new XOutputStreamToOutputStreamAdapter(device);
384 /* make sure newxos and xis get closed */
385 try{
386 try{
387 ConverterInfoReader cir = new ConverterInfoReader(jarName,false);
388 ciEnum =cir.getConverterInfoEnumeration();
390 catch (ParserConfigurationException pexc){
391 System.out.println("Error:"+pexc);
393 catch ( org.xml.sax.SAXException pexc){
394 System.out.println("Error:"+pexc);
396 catch(Exception e){
397 System.out.println("Error:"+e);
399 ConverterInfoMgr. removeByJar(jarName);
400 if (convertFromOffice)
403 try {
405 //Check to see if jar contains a plugin Impl
407 ConverterInfoMgr.addPlugIn(ciEnum);
408 ConverterFactory cf = new ConverterFactory();
410 Convert cv = cf.getConverter(ConverterInfoMgr.findConverterInfo(sdMime,offMime),false);
411 if (cv == null) {
412 System.out.println("\nNo plug-in exists to convert from <staroffice/sxw> to <specified format> ");
415 else
417 cv.addInputStream(name,xis,false);
418 ConvertData dataOut = cv.convert();
420 Iterator<Object> docEnum = dataOut.getDocumentEnumeration();
422 if (docEnum.hasNext()){
423 Document docOut = (Document)docEnum.next();
424 docOut.write(newxos);
426 newxos.flush();
427 newxos.close();
428 newxos = null;
430 int i=1;
431 while (docEnum.hasNext() && sURL.startsWith("file:")) {
433 URI uri=new URI(sURL);
434 String newFileName= getPath(uri);
436 File newFile;
437 if (newFileName.lastIndexOf(".")!=-1){
438 newFile =new File(newFileName.substring(0,newFileName.lastIndexOf("."))+String.valueOf(i)+newFileName.substring(newFileName.lastIndexOf(".")));
440 else{
441 newFile =new File(newFileName.concat(String.valueOf(i)));
444 FileOutputStream fos = null;
445 try {
446 fos = new FileOutputStream(newFile);
447 docOut = (Document)docEnum.next();
448 docOut.write(fos);
449 fos.flush();
450 } finally {
451 close(fos);
453 i++;
459 ConverterInfoMgr.removeByJar(jarName);
461 catch (Exception ex1) {
462 IOException ex2 = new IOException();
463 ex2.initCause(ex1);
464 throw ex2;
467 else{
469 try {
470 //Check to see if jar contains a plugin Impl
471 ConverterInfoMgr.addPlugIn(ciEnum);
472 ConverterFactory cf = new ConverterFactory();
473 Convert cv = cf.getConverter(ConverterInfoMgr.findConverterInfo(sdMime,offMime),true);
474 if (cv == null) {
475 System.out.println("\nNo plug-in exists to convert to <staroffice/sxw> from <specified format>");
477 else
480 cv.addInputStream(name,xis,false);
481 ConvertData dataIn = cv.convert();
482 Iterator<Object> docEnum = dataIn.getDocumentEnumeration();
483 while (docEnum.hasNext()) {
484 OfficeDocument docIn = (OfficeDocument)docEnum.next();
486 docIn.write(newxos,false);
488 newxos.close();
489 newxos = null;
491 ConverterInfoMgr.removeByJar(jarName);
493 catch (StackOverflowError sOE){
494 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");
496 catch (Exception ex1) {
497 IOException ex2 = new IOException();
498 ex2.initCause(ex1);
499 throw ex2;
504 finally{
505 if (newxos != null){
506 try {
507 newxos.flush();
508 } catch (IOException e) {
510 newxos.close();
512 xis.close();
516 private String getPath(URI uri){
517 String path = uri.getPath();
518 String opSys=System.getProperty("os.name");
519 if(opSys.contains("Windows")){
520 path= path.replace('/','\\');
521 path = path.substring(1);
523 return path;
526 // Implement methods from interface XTypeProvider
527 public byte[] getImplementationId() {
528 return new byte[0];
531 // Implement method from interface XServiceName
532 public String getServiceName() {
533 return __serviceName;
536 // Implement methods from interface XServiceInfo
537 public boolean supportsService(String stringServiceName) {
538 return stringServiceName.equals( __serviceName );
541 public String getImplementationName() {
542 return _XMergeBridge.class.getName();
545 public String[] getSupportedServiceNames() {
546 String[] stringSupportedServiceNames = { __serviceName };
547 return stringSupportedServiceNames;
552 * Returns a factory for creating the service.
553 * This method is called by the <code>JavaLoader</code>
555 * @return returns a <code>XSingleServiceFactory</code> for creating the
556 * component
558 * @param implName the name of the implementation for which a
559 * service is desired
560 * @param multiFactory the service manager to be used if needed
561 * @param regKey the registryKey
563 * @see com.sun.star.comp.loader.JavaLoader
565 public static XSingleServiceFactory __getServiceFactory(String implName,
566 XMultiServiceFactory multiFactory,
567 XRegistryKey regKey) {
568 xMSF= multiFactory;
569 XSingleServiceFactory xSingleServiceFactory = null;
570 if (implName.equals(_XMergeBridge.class.getName()) ) {
571 xSingleServiceFactory = FactoryHelper.getServiceFactory(_XMergeBridge.class,
572 _XMergeBridge.__serviceName,
573 multiFactory,
574 regKey);
577 return xSingleServiceFactory;