LibreOffice Module xmerge (master)  1
XMergeBridge.java
Go to the documentation of this file.
1 /*
2  * This file is part of the LibreOffice project.
3  *
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/.
7  *
8  * This file incorporates work covered by the following license notice:
9  *
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 .
17  */
18 
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;
30 
31 import javax.xml.parsers.ParserConfigurationException;
32 
37 import org.openoffice.xmerge.converter.xml.OfficeDocument;
41 
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;
62 
67 public class XMergeBridge {
68 
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="";
78 
82  public static class _XMergeBridge implements
83  XImportFilter,
84  XExportFilter,
85  XServiceName,
86  XServiceInfo,
87  XDocumentHandler,
88  XTypeProvider {
89 
92  private static final String __serviceName = "com.sun.star.documentconversion.XMergeBridge";
93 
94  public com.sun.star.uno.Type[] getTypes() {
95  Type[] typeReturn = {};
96 
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 ) };
104  }
105  catch( Exception exception ) {
106 
107  }
108 
109  return typeReturn;
110  }
111 
112  private String getFileName(String origName)
113  {
114  String name;
115  if (origName !=null)
116  {
117  if(origName.equalsIgnoreCase(""))
118  name = "OutFile";
119  else {
120  if (origName.lastIndexOf("/")>=0){
121  origName=origName.substring(origName.lastIndexOf("/")+1,origName.length());
122  }
123  if (origName.lastIndexOf(".")>=0){
124  name = origName.substring(0, origName.lastIndexOf("."));
125  }
126  else{
127  name=origName;
128  }
129  }
130  }
131  else{
132  name = "OutFile";
133  }
134  return name;
135  }
136 
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 {
140 
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;
148 
149  for (int i = 0 ; i < pValue.length; i++)
150  {
151 
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);
155  }
156  if (pValue[i].Name.equals("FileName")){
157  sFileName=(String)AnyConverter.toObject(new Type(String.class), pValue[i].Value);
158  }
159 
160  }
161  catch(com.sun.star.lang.IllegalArgumentException AnyExec){
162  System.out.println("\nIllegalArgumentException "+AnyExec);
163  }
164 
165  }
166 
167  try{
168 
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);
175 
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");
183 
184  XParser xParser = UnoRuntime.queryInterface(
185  XParser.class , xSaxParserObj );
186  xOutStream.closeOutput();
187  InputSource aInput = new InputSource();
188  if (sFileName==null){
189  sFileName="";
190  }
191  aInput.sSystemId = sFileName;
192  aInput.aInputStream =xInStream;
193  xParser.setDocumentHandler ( xDocHandler );
194 
195  xParser.parseStream ( aInput );
196  xOutStream.closeOutput();
197  xInStream.closeInput();
198 
199  }
200  catch (IOException e){
201  return false;
202  }
203  catch (Exception e){
204  return false;
205  }
206  return true;
207  }
208 
209  public boolean exporter(com.sun.star.beans.PropertyValue[] aSourceData,
210  String[] msUserData) throws com.sun.star.uno.RuntimeException{
211 
212  sFileName=null;
213  sURL=null;
214  udJarPath=msUserData[1];
215  offMime =msUserData[4];
216  sdMime = msUserData[5];
217 
218  com.sun.star.beans.PropertyValue[] pValue = aSourceData;
219  for (int i = 0 ; i < pValue.length; i++)
220  {
221 
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);
225  }
226 
227  if (pValue[i].Name.equals("FileName")){
228  sFileName=(String)AnyConverter.toObject(new Type(String.class), pValue[i].Value);
229  }
230 
231  if (pValue[i].Name.equals("URL")){
232  sURL=(String)AnyConverter.toObject(new Type(String.class), pValue[i].Value);
233  }
234  }
235  catch(com.sun.star.lang.IllegalArgumentException AnyExec){
236  System.out.println("\nIllegalArgumentException "+AnyExec);
237  }
238  }
239 
240  if (sURL==null){
241  sURL="";
242  }
243 
244  try{
245 
246  Object xCfgMgrObj=xMSF.createInstance("com.sun.star.config.SpecialConfigManager");
247  XConfigManager xCfgMgr = UnoRuntime.queryInterface(
248  XConfigManager.class , xCfgMgrObj );
249 
250  String PathString=xCfgMgr.substituteVariables("$(progurl)" );
251  PathString= PathString.concat("/");
252  udJarPath= PathString.concat(udJarPath);
253 
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 );
259  }
260  catch (Exception e){
261  System.out.println("Exception "+e);
262  return false;
263  }
264 
265  return true;
266  }
267 
268  private String needsMask(String origString){
269  if (origString.contains("&")) {
270  origString = origString.replace("&","&amp;");
271  }
272  if (origString.contains("\"")) {
273  origString = origString.replace("\"","&quot;");
274  }
275  if (origString.contains("<")) {
276  origString = origString.replace("<","&lt;");
277  }
278  if (origString.contains(">")) {
279  origString = origString.replace(">","&gt;");
280  }
281  return origString;
282  }
283 
284  public void startDocument () {
285  }
286 
287  public void endDocument()throws com.sun.star.uno.RuntimeException
288  {
289 
290  try{
291  xOutStream.closeOutput();
292  convert (xInStream,xos,true,udJarPath,sURL,offMime,sdMime);
293 
294  }
295  catch (IOException e){
296  throw new com.sun.star.uno.RuntimeException(e);
297 
298  }
299  catch (Exception e){
300  throw new com.sun.star.uno.RuntimeException(e);
301 
302  }
303  }
304 
305  public void startElement (String str, com.sun.star.xml.sax.XAttributeList xattribs)
306  {
307 
308  str="<".concat(str);
309  if (xattribs !=null)
310  {
311  str= str.concat(" ");
312  int len=xattribs.getLength();
313  for (short i=0;i<len;i++)
314  {
315  str=str.concat(xattribs.getNameByIndex(i));
316  str=str.concat("=\"");
317  str=str.concat(needsMask(xattribs.getValueByIndex(i)));
318  str=str.concat("\" ");
319  }
320  }
321  str=str.concat(">");
322 
323  try{
324  xOutStream.writeBytes(str.getBytes("UTF-8"));
325  }
326  catch (Exception e){
327  System.out.println("\n"+e);
328  }
329 
330  }
331 
332  public void endElement(String str){
333 
334  str="</".concat(str);
335  str=str.concat(">");
336  try{
337  xOutStream.writeBytes(str.getBytes("UTF-8"));
338 
339  }
340  catch (Exception e){
341  System.out.println("\n"+e);
342  }
343 
344  }
345  public void characters(String str){
346  str=needsMask(str);
347  try{
348  xOutStream.writeBytes(str.getBytes("UTF-8"));
349  }
350  catch (Exception e){
351  System.out.println("\n"+e);
352  }
353 
354  }
355 
356  public void ignorableWhitespace(String str){
357 
358  }
359  public void processingInstruction(String aTarget, String aData){
360 
361  }
362 
363  public void setDocumentLocator(com.sun.star.xml.sax.XLocator xLocator){
364 
365  }
366 
367  private static void close(FileOutputStream c) throws IOException {
368  if (c == null) return;
369  c.close();
370  }
371 
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 {
374 
375  String jarName = pluginUrl;
376  String name= getFileName(FileName);
377 
378  Iterator<ConverterInfo> ciEnum= null;
379 
380  XInputStreamToInputStreamAdapter xis =new XInputStreamToInputStreamAdapter(xml);
381 
382  XOutputStreamToOutputStreamAdapter newxos =new XOutputStreamToOutputStreamAdapter(device);
383 
384  /* make sure newxos and xis get closed */
385  try{
386  try{
387  ConverterInfoReader cir = new ConverterInfoReader(jarName,false);
388  ciEnum =cir.getConverterInfoEnumeration();
389  }
390  catch (ParserConfigurationException pexc){
391  System.out.println("Error:"+pexc);
392  }
393  catch ( org.xml.sax.SAXException pexc){
394  System.out.println("Error:"+pexc);
395  }
396  catch(Exception e){
397  System.out.println("Error:"+e);
398  }
399  ConverterInfoMgr. removeByJar(jarName);
400  if (convertFromOffice)
401  {
402 
403  try {
404 
405  //Check to see if jar contains a plugin Impl
406 
407  ConverterInfoMgr.addPlugIn(ciEnum);
409 
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> ");
413 
414  }
415  else
416  {
417  cv.addInputStream(name,xis,false);
418  ConvertData dataOut = cv.convert();
419 
420  Iterator<Object> docEnum = dataOut.getDocumentEnumeration();
421 
422  if (docEnum.hasNext()){
423  Document docOut = (Document)docEnum.next();
424  docOut.write(newxos);
425 
426  newxos.flush();
427  newxos.close();
428  newxos = null;
429 
430  int i=1;
431  while (docEnum.hasNext() && sURL.startsWith("file:")) {
432 
433  URI uri=new URI(sURL);
434  String newFileName= getPath(uri);
435 
436  File newFile;
437  if (newFileName.lastIndexOf(".")!=-1){
438  newFile =new File(newFileName.substring(0,newFileName.lastIndexOf("."))+String.valueOf(i)+newFileName.substring(newFileName.lastIndexOf(".")));
439  }
440  else{
441  newFile =new File(newFileName.concat(String.valueOf(i)));
442  }
443 
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);
452  }
453  i++;
454 
455  }
456 
457  }
458  }
459  ConverterInfoMgr.removeByJar(jarName);
460  }
461  catch (Exception ex1) {
462  IOException ex2 = new IOException();
463  ex2.initCause(ex1);
464  throw ex2;
465  }
466  }
467  else{
468 
469  try {
470  //Check to see if jar contains a plugin Impl
471  ConverterInfoMgr.addPlugIn(ciEnum);
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>");
476  }
477  else
478  {
479 
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();
485 
486  docIn.write(newxos,false);
487  }
488  newxos.close();
489  newxos = null;
490  }
491  ConverterInfoMgr.removeByJar(jarName);
492  }
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");
495  }
496  catch (Exception ex1) {
497  IOException ex2 = new IOException();
498  ex2.initCause(ex1);
499  throw ex2;
500  }
501 
502  }
503  }
504  finally{
505  if (newxos != null){
506  try {
507  newxos.flush();
508  } catch (IOException e) {
509  }
510  newxos.close();
511  }
512  xis.close();
513  }
514  }
515 
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);
522  }
523  return path;
524  }
525 
526  // Implement methods from interface XTypeProvider
528  return new byte[0];
529  }
530 
531  // Implement method from interface XServiceName
533  return __serviceName;
534  }
535 
536  // Implement methods from interface XServiceInfo
537  public boolean supportsService(String stringServiceName) {
538  return stringServiceName.equals( __serviceName );
539  }
540 
542  return _XMergeBridge.class.getName();
543  }
544 
546  String[] stringSupportedServiceNames = { __serviceName };
547  return stringSupportedServiceNames;
548  }
549  }
550 
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,
573  multiFactory,
574  regKey);
575  }
576 
577  return xSingleServiceFactory;
578  }
579 }
Type
Factory that provides access to.
void convert(com.sun.star.io.XInputStream xml, com.sun.star.io.XOutputStream device, boolean convertFromOffice, String pluginUrl, String FileName, String offMime, String sdMime)
exports com.sun.star. xml
Provides general purpose utilities.
static boolean removeByJar(String jar)
Removes any.
Provides an interface for plug-in registration.
static String sFileName
OUString Name
static final String __serviceName
The component will be registered under this name.
void endElement(String str)
String needsMask(String origString)
void setDocumentLocator(com.sun.star.xml.sax.XLocator xLocator)
static XSingleServiceFactory __getServiceFactory(String implName, XMultiServiceFactory multiFactory, XRegistryKey regKey)
Returns a factory for creating the service.
static String sURL
Convert getConverter(String mimeTypeIn, String mimeTypeOut)
Returns the.
This inner class provides the component as a concrete implementation of the service description...
exports com.sun.star. java
static XMultiServiceFactory xMSF
int i
boolean exporter(com.sun.star.beans.PropertyValue[] aSourceData, String[] msUserData)
com.sun.star.uno.Type[] getTypes()
static XOutputStream xOutStream
void startElement(String str, com.sun.star.xml.sax.XAttributeList xattribs)
Manages the converter plug-ins that are currently active.
boolean importer(com.sun.star.beans.PropertyValue[] aSourceData, com.sun.star.xml.sax.XDocumentHandler xDocHandler, String[] msUserData)
static void addPlugIn(ConverterInfo ci)
Adds a converter plug-in to the registry.
static ConverterInfo findConverterInfo(String deviceMime, String officeMime)
Returns the.
String getFileName(String origName)
void characters(String str)
static XInputStream xInStream
unsigned char byte
static XOutputStream xos
This outer class provides an inner class to implement the service description and a method to instant...
void ignorableWhitespace(String str)
static void close(FileOutputStream c)
void write(OutputStream os)
Writes out the.
const char * name
Class for storing the information about a converter plug-in.
static String udJarPath
static String offMime
Provides interfaces for converting between two.
Definition: Convert.java:19
void addInputStream(String name, InputStream is)
Adds an.
Definition: Convert.java:80
boolean supportsService(String stringServiceName)
ConvertData convert()
Convert the input specified in calls to the.
Definition: Convert.java:181
Iterator< ConverterInfo > getConverterInfoEnumeration()
Returns an.
void processingInstruction(String aTarget, String aData)
static String sdMime
exports com.sun.star. uri