Convertendo softwares utilizando OpenOffice e Java
Você verá como capturar documentos, substituir strings e gerar novos documentos a partir de documentos iniciais utilizando Java e OpenOffice.
Parte 3: Classe de exemplo
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
public class DocumentConverter {
static XComponentLoader xcomponentloader = null;
static String stringConvertType = "MS Word 97";
static String stringExtension = "doc";
static String indent = "";
/**
* Metodo recursivo de localização e modificação de arquivos do formato sxw para
* doc
*/
static void traverse( File fileDirectory ) {
if ( !fileDirectory.isDirectory() ) {
throw new IllegalArgumentException(
"nao é um diretório: " + fileDirectory.getName()
);
}
System.out.println(indent + "[" + fileDirectory.getName() + "]");
indent += " ";
File[] entries = fileDirectory.listFiles(
new FileFilter() {
public boolean accept( File pathname ) {
return pathname.getName().endsWith("sxw");
}
}
);
// Iteração que é realizada em cada pasta
for ( int i = 0; i < entries.length; ++i ) {
if ( entries[ i ].isDirectory() ) {
traverse( entries[ i ] );
} else {
// abaixo inicia-se a conversao
try {
// o OOo precisa que esteja no formato Url
String stringUrl = "file:///"
+ entries[ i ].getAbsolutePath().replace( '\', '/' );
System.out.println(entries[i] + ":" + stringUrl);
// Loading the wanted document
Object objectDocumentToStore =
DocumentConverter.xcomponentloader.loadComponentFromURL(
stringUrl, "_blank", 0, new PropertyValue[0] );
XStorable xstorable =
( XStorable ) UnoRuntime.queryInterface( XStorable.class,
objectDocumentToStore );
PropertyValue propertyvalue[] = new PropertyValue[ 2 ];
propertyvalue[ 0 ] = new PropertyValue();
propertyvalue[ 0 ].Name = "Overwrite";
propertyvalue[ 0 ].Value = new Boolean(true);
propertyvalue[ 1 ] = new PropertyValue();
propertyvalue[ 1 ].Name = "FilterName";
propertyvalue[ 1 ].Value = DocumentConverter.stringConvertType;
int index = stringUrl.lastIndexOf(".");
stringUrl = stringUrl.substring(0, index + 1) + DocumentConverter.stringExtension;
System.out.println(stringUrl + ":" + propertyvalue);
xstorable.storeToURL( stringUrl, propertyvalue );
XComponent xcomponent =
( XComponent ) UnoRuntime.queryInterface( XComponent.class,
xstorable );
// Closing the converted document
xcomponent.dispose();
}
catch( Exception exception ) {
exception.printStackTrace();
}
System.out.println(indent + entries[ i ].getName());
}
}
indent = indent.substring(2);
}
public static void main( String args[] ) {
try {
XComponentContext xComponentContext =
com.sun.star.comp.helper.Bootstrap.createInitialComponentContext( null );
/* Gets the service manager instance to be used (or null). This method has
been added for convenience, because the service manager is a often used
object. */
XMultiComponentFactory xMultiComponentFactory =
xComponentContext.getServiceManager();
Object objectUrlResolver = xMultiComponentFactory.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", xComponentContext );
// Create a new url resolver
XUnoUrlResolver xurlresolver = ( XUnoUrlResolver )
UnoRuntime.queryInterface( XUnoUrlResolver.class,
objectUrlResolver );
//abaixo a conexão é realizada na porta 2002
Object objectInitial = xurlresolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" );
xMultiComponentFactory = ( XMultiComponentFactory )
UnoRuntime.queryInterface( XMultiComponentFactory.class, objectInitial );
XPropertySet xpropertysetMultiComponentFactory = ( XPropertySet )
UnoRuntime.queryInterface( XPropertySet.class, xMultiComponentFactory );
Object objectDefaultContext =
xpropertysetMultiComponentFactory.getPropertyValue( "DefaultContext" );
xComponentContext = ( XComponentContext ) UnoRuntime.queryInterface(
XComponentContext.class, objectDefaultContext );
xcomponentloader = ( XComponentLoader )
UnoRuntime.queryInterface( XComponentLoader.class,
xMultiComponentFactory.createInstanceWithContext(
"com.sun.star.frame.Desktop", xComponentContext ) );
//modifique a linha abaixo para uma pasta contendo o seu arquivo
File file = new File("/home/{coloca a sua home aqui}/Teste");
traverse( file );
System.exit(0);
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
public class DocumentConverter {
static XComponentLoader xcomponentloader = null;
static String stringConvertType = "MS Word 97";
static String stringExtension = "doc";
static String indent = "";
/**
* Metodo recursivo de localização e modificação de arquivos do formato sxw para
* doc
*/
static void traverse( File fileDirectory ) {
if ( !fileDirectory.isDirectory() ) {
throw new IllegalArgumentException(
"nao é um diretório: " + fileDirectory.getName()
);
}
System.out.println(indent + "[" + fileDirectory.getName() + "]");
indent += " ";
File[] entries = fileDirectory.listFiles(
new FileFilter() {
public boolean accept( File pathname ) {
return pathname.getName().endsWith("sxw");
}
}
);
// Iteração que é realizada em cada pasta
for ( int i = 0; i < entries.length; ++i ) {
if ( entries[ i ].isDirectory() ) {
traverse( entries[ i ] );
} else {
// abaixo inicia-se a conversao
try {
// o OOo precisa que esteja no formato Url
String stringUrl = "file:///"
+ entries[ i ].getAbsolutePath().replace( '\', '/' );
System.out.println(entries[i] + ":" + stringUrl);
// Loading the wanted document
Object objectDocumentToStore =
DocumentConverter.xcomponentloader.loadComponentFromURL(
stringUrl, "_blank", 0, new PropertyValue[0] );
XStorable xstorable =
( XStorable ) UnoRuntime.queryInterface( XStorable.class,
objectDocumentToStore );
PropertyValue propertyvalue[] = new PropertyValue[ 2 ];
propertyvalue[ 0 ] = new PropertyValue();
propertyvalue[ 0 ].Name = "Overwrite";
propertyvalue[ 0 ].Value = new Boolean(true);
propertyvalue[ 1 ] = new PropertyValue();
propertyvalue[ 1 ].Name = "FilterName";
propertyvalue[ 1 ].Value = DocumentConverter.stringConvertType;
int index = stringUrl.lastIndexOf(".");
stringUrl = stringUrl.substring(0, index + 1) + DocumentConverter.stringExtension;
System.out.println(stringUrl + ":" + propertyvalue);
xstorable.storeToURL( stringUrl, propertyvalue );
XComponent xcomponent =
( XComponent ) UnoRuntime.queryInterface( XComponent.class,
xstorable );
// Closing the converted document
xcomponent.dispose();
}
catch( Exception exception ) {
exception.printStackTrace();
}
System.out.println(indent + entries[ i ].getName());
}
}
indent = indent.substring(2);
}
public static void main( String args[] ) {
try {
XComponentContext xComponentContext =
com.sun.star.comp.helper.Bootstrap.createInitialComponentContext( null );
/* Gets the service manager instance to be used (or null). This method has
been added for convenience, because the service manager is a often used
object. */
XMultiComponentFactory xMultiComponentFactory =
xComponentContext.getServiceManager();
Object objectUrlResolver = xMultiComponentFactory.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", xComponentContext );
// Create a new url resolver
XUnoUrlResolver xurlresolver = ( XUnoUrlResolver )
UnoRuntime.queryInterface( XUnoUrlResolver.class,
objectUrlResolver );
//abaixo a conexão é realizada na porta 2002
Object objectInitial = xurlresolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" );
xMultiComponentFactory = ( XMultiComponentFactory )
UnoRuntime.queryInterface( XMultiComponentFactory.class, objectInitial );
XPropertySet xpropertysetMultiComponentFactory = ( XPropertySet )
UnoRuntime.queryInterface( XPropertySet.class, xMultiComponentFactory );
Object objectDefaultContext =
xpropertysetMultiComponentFactory.getPropertyValue( "DefaultContext" );
xComponentContext = ( XComponentContext ) UnoRuntime.queryInterface(
XComponentContext.class, objectDefaultContext );
xcomponentloader = ( XComponentLoader )
UnoRuntime.queryInterface( XComponentLoader.class,
xMultiComponentFactory.createInstanceWithContext(
"com.sun.star.frame.Desktop", xComponentContext ) );
//modifique a linha abaixo para uma pasta contendo o seu arquivo
File file = new File("/home/{coloca a sua home aqui}/Teste");
traverse( file );
System.exit(0);
}
catch( Exception e ) {
e.printStackTrace();
}
}
}