Hi Ynze,
I write a Java program to change an OpenOffice file.
This is a colection of vairous pieces of code.
I open the file, look for some marks and change the mark for a table
that data come from a data base.
Regards.
-------------------------------------------------------
André B. Derraik
Consult
Tecgraf/PUC-Rio/Brazil http://www.tecgraf.puc-rio.br
[EMAIL PROTECTED] Tel.: +55-21-2512-8428
Ynze Zuidema wrote:
Hi,
I am new to this list, I have the following problem:,
I am writing a program in java to read ODP files, fetch some info from
the file, change some things
and write it away again. now all this go well, until I pack it again.
if I would pack the changed files with an external tool like winrar it
all works like it supposed too
if I do it from the java program the file that is produced is from the
exact same size and content as the before-mentioned.
though, if I open the java generated one, openoffice compains about
corrupcy.
Does anyone have any experience with this? or could point me into the
right direction?
Any help on this is greatly appriciated :)
Regards,
Ynze Zuidema
/*
* DocReader.java
*
* Created on April 1, 2003, 1:39 PM
*/
package OOoDocExplorer;
import nom.DannyBrewer.utils.ExceptionHandler;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.zip.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.jdom.*;
import org.jdom.Document;
import org.jdom.input.*;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
* <p>
* This class is used by OOoDoc to read an OpenOffice.org document and return it
* as a OOoDoc object.
* </p>
*
* @author danny brewer
*/
public class OOoDocReader
{
private OOoDocReader(ZipFile zipFile)
{
initialize(zipFile);
}
//----------------------------------------------------------------------
// Public API
//----------------------------------------------------------------------
public static OOoDocReader readDocFromFile(String ooDocFile)
{
return readDocFromFile(new File(ooDocFile));
}
public static OOoDocReader readDocFromFile(File ooDocFile)
{
try
{
ZipFile zipFile = new ZipFile(ooDocFile, ZipFile.OPEN_READ);
OOoDocReader docReader = new OOoDocReader(zipFile);
return docReader;
} catch (FileNotFoundException e)
{
ExceptionHandler.unexpectedException(e);
return null;
} catch (IOException e)
{
ExceptionHandler.unexpectedException(e);
return null;
}
}
public void close()
{
if (zipFile != null)
{
try
{
zipFile.close();
} catch (IOException e)
{
ExceptionHandler.unexpectedException(e);
}
zipFile = null;
}
if (items != null)
{
items.clear();
items = null;
}
}
//----------------------------------------------------------------------
// Public API
//----------------------------------------------------------------------
public boolean getAreItemsCached()
{
return cacheItemContents;
}
public void setAreItemsCached(boolean cacheItemContents)
{
this.cacheItemContents = cacheItemContents;
}
/*
* Return the JDOMFactory that will be used to construct jdom objects as XML
* documents are read from the OOo zip file.
*/
public JDOMFactory getJDOMFactory()
{
return jdomFactory;
}
/*
* <p> Set the JDOMFactory that will be used to construct jdom objects as
* XML documents are read from the OOo zip file. </p><p> You might want to
* construct custom Element objects, for instance, that allow you to attach
* additional information to each node of the XML tree. </p>
*/
public void setJDOMFactory(JDOMFactory jdomFactory)
{
this.jdomFactory = jdomFactory;
}
public String getFileName()
{
return zipFile.getName();
}
public class ItemName
{
ZipEntry zipEntry;
ItemContent itemContent = null;
boolean itemCached = cacheItemContents;
// Constructor
ItemName(ZipEntry zipEntry)
{
this.zipEntry = zipEntry;
}
public ZipEntry getZipEntry()
{
return zipEntry;
}
public boolean isItemCached()
{
return itemCached;
}
public void setItemCached(boolean itemCached)
{
this.itemCached = itemCached;
if (!itemCached && itemContent != null)
{
itemContent = null;
}
}
public String getName()
{
return zipEntry.getName();
}
public String toString()
{
return "ZipItem: " + getName();
}
public ItemContent getItemContent()
{
if (itemContent != null)
return itemContent;
ItemContent getContent = loadItemContent(this);
if (itemCached)
itemContent = getContent;
return getContent;
}
}
public abstract class ItemContent
{
}
public class XmlItem extends ItemContent
{
org.jdom.Document xmlDoc = null;
XmlItem(org.jdom.Document xmlDoc)
{
this.xmlDoc = xmlDoc;
}
public org.jdom.Document getJDomXmlDoc()
{
return xmlDoc;
}
}
public int numItems()
{
return items.size();
}
public ItemName getItem(int index)
{
return (ItemName) items.get(index);
}
public int getItemIndex(String name)
{
for (int i = 0; i < numItems(); ++i)
{
ItemName item = getItem(i);
if (item.getName().equals(name))
return i;
}
return -1;
}
public int getItemIndex(ItemName item)
{
return items.indexOf(item);
}
public ItemName getItem(String name)
{
int index = getItemIndex(name);
if (index >= 0)
return getItem(index);
return null;
}
public Enumeration getItems()
{
return new Enumeration()
{
Iterator iterator = items.iterator();
public boolean hasMoreElements()
{
return iterator.hasNext();
}
public Object nextElement()
{
return iterator.next();
}
};
}
//----------------------------------------------------------------------
// Internal support
//----------------------------------------------------------------------
private ZipFile zipFile = null;
private java.util.ArrayList items = null;
private boolean cacheItemContents = true;
private void initialize()
{
zipFile = null;
items = new java.util.ArrayList();
cacheItemContents = true;
}
private void initialize(ZipFile zipFile)
{
initialize();
this.zipFile = zipFile;
scanZipFile();
}
private void scanZipFile()
{
Enumeration zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements())
{
ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();
items.add(new ItemName(zipEntry));
}
}
private InputStream getZipEntryInputStream(String name)
{
ZipEntry zipEntry = zipFile.getEntry(name);
return getZipEntryInputStream(zipEntry);
}
private InputStream getZipEntryInputStream(ZipEntry zipEntry)
{
InputStream inputStream = null;
try
{
inputStream = zipFile.getInputStream(zipEntry);
} catch (IOException e)
{
ExceptionHandler.unexpectedException(e);
}
return inputStream;
}
private ItemContent loadItemContent(ItemName item)
{
// Based on the zip entry filename's suffix, load the right object type.
String itemNameLC = item.getName().toLowerCase();
if (itemNameLC.endsWith(".xml"))
{
org.jdom.Document jdomXmlDocument = readZipEntryAsXml(item
.getZipEntry());
if (jdomXmlDocument != null)
{
XmlItem itemContent = new XmlItem(jdomXmlDocument);
return itemContent;
}
}
return null;
}
//----------------------------------------------------------------------
// Internal support -- for parsing XML
//----------------------------------------------------------------------
JDOMFactory jdomFactory = null;
org.jdom.Document readZipEntryAsXml(ZipEntry zipEntry)
{
InputStream inputStream = getZipEntryInputStream(zipEntry);
// Parse the subInputStream and return a jdom document.
org.jdom.Document jdomXmlDocument = readXmlIntoJdom(jdomFactory,
inputStream);
return jdomXmlDocument;
}
private static org.jdom.Document readXmlIntoJdom(JDOMFactory jdomFactory,
InputStream inStream)
{
// Create an XMLReader from SAX.
XMLReader xmlReader = null;
try
{
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setValidating(true);
saxParserFactory.setNamespaceAware(true);
SAXParser saxParser = saxParserFactory.newSAXParser();
xmlReader = saxParser.getXMLReader();
} catch (ParserConfigurationException e)
{
e.printStackTrace();
return null;
} catch (SAXException e)
{
e.printStackTrace();
return null;
}
// Now tell the xmlReader what handlers to use.
// That is, tell the xmlReader who to notify as parsing events occur.
// For instance, when an element is detected in the xml input,
// call the ContentHandler.startElement() event.
// Since we're using jdom, we get an event handler from jdom
// which will get notified as sax parsing events occur,
// and which will build the jdom tree from those event firings.
SAXHandler jdomSaxHandler = null;
// try {
if (jdomFactory != null)
{
jdomSaxHandler = new SAXHandler(jdomFactory);
} else
{
jdomSaxHandler = new SAXHandler();
}
// }
// catch ( IOException e ) {
// e.printStackTrace();
// return null;
// }
boolean USE_JDOM = true;
boolean USE_FILTER = false;
if (USE_JDOM)
{
// Let the jdom handler receive the SAX parsing events.
xmlReader.setContentHandler(jdomSaxHandler);
xmlReader.setDTDHandler(jdomSaxHandler);
// xmlReader.setEntityResolver( jdomSaxHandler );
xmlReader.setErrorHandler(jdomSaxHandler);
// } else {
// nom.DannyBrewer.utils.xml.EchoSAXEvents
echoHandler = new
// nom.DannyBrewer.utils.xml.EchoSAXEvents();
// xmlReader.setContentHandler( echoHandler );
// xmlReader.setDTDHandler( echoHandler );
// xmlReader.setEntityResolver( echoHandler );
// xmlReader.setErrorHandler( echoHandler );
}
EntityResolver officeDtdEntityResolver = new OfficeDtdEntityResolver();
xmlReader.setEntityResolver(officeDtdEntityResolver);
if (USE_FILTER)
{
// Insert a filter inline to fix up names.
// This is the real trick in order to get JDOM to accept the input
// from SAX.
// Apparently, the SAX parser (Sun's Crimson parser in JDK1.4)
// passes an empty string for the local name, but supplies a
// correct fully qualified name.
// The filter just intercepts the startElement/endElement events
// and derrives the local name from the fully qualified name.
XMLFilterImpl xmlFilter = new NameFixerSAXFilter();
insertXmlFilter(xmlFilter, xmlReader);
xmlReader = xmlFilter;
}
// Now make the xmlReader do the parsing.
// (Note we might have inserted a filter in front of xmlReader above.)
InputSource inputSource = new InputSource(inStream);
inputSource.setSystemId("");
try
{
xmlReader.parse(inputSource);
} catch (SAXException e)
{
e.printStackTrace();
return null;
} catch (IOException e)
{
e.printStackTrace();
return null;
}
Document document = jdomSaxHandler.getDocument();
return document;
}
/*
* <p> This EntityResolver is able to return the office.dtd from within the
* jar file that this program is executing from. </p>
*/
private static class OfficeDtdEntityResolver implements EntityResolver
{
public InputSource resolveEntity(String publicId, String systemId)
{
// System.out.println( "myEntityResolver
systemId=" + systemId + ",
// publicId=" + publicId );
// See if the dtd is one of the office dtd's.
for (int i = 0; i < officeDtdNames.length; ++i)
{
if (officeDtdNames[i].equals(systemId))
{
// Found one
java.io.InputStream dtdInStream = getClass()
.getResourceAsStream(
"/OOoDocExplorer/Resources/OpenOffice.org.dtd");
if (dtdInStream != null)
{
InputSource inputSource = new InputSource(dtdInStream);
return inputSource;
}
break;
}
}
// use the default behaviour
return null;
}
}
private static String[] officeDtdNames = { "accelerator.dtd", "dialog.dtd",
"event.dtd", "image.dtd", "libraries.dtd", "library.dtd",
"Manifest.dtd", "menubar.dtd", "module.dtd", "office.dtd",
"statusbar.dtd", "toolbar.dtd" };
/*
* <p> An XMLFilterImpl to fix up local names. </p><p> If SAX calls
* startElement / endElement with no local name, then derrive the local name
* from the qualified name. </p><p> For instance if SAX gives us a
* localName of "", and a qualifiedName of "office:document-content", then
* derrive a localName of "document-content". </p>
*/
private static class NameFixerSAXFilter extends XMLFilterImpl
{
public NameFixerSAXFilter()
{
}
//public NameFixerSAXFilter( XMLReader reader ) { super( reader ); }
public void startElement(String namespaceURI, String localName,
String qualifiedName, Attributes atts) throws SAXException
{
// Get the localName from the qualifiedName for the element.
localName = qualifiedName.substring(qualifiedName.indexOf(':') + 1);
// If there are any attributes on this element,
// construct a new list of attributes with the local names derrived
// from qualified names.
if (atts != null && atts.getLength() > 0)
{
AttributesImpl atts2 = new AttributesImpl();
for (int i = 0; i < atts.getLength(); ++i)
{
String attrQualifiedName = atts.getQName(i);
String attrLocalName = attrQualifiedName
.substring(attrQualifiedName.indexOf(':') + 1);
atts2.addAttribute(atts.getURI(i), attrLocalName,
attrQualifiedName, atts.getType(i), atts
.getValue(i));
}
atts = atts2;
}
// Pass the event on, which is the job of a filter.
ContentHandler contentHandler = getContentHandler();
contentHandler.startElement(namespaceURI, localName, qualifiedName,
atts);
}
public void endElement(String namespaceURI, String localName,
String qualifiedName) throws SAXException
{
// Get the localName from the qualifiedName for the element.
localName = qualifiedName.substring(qualifiedName.indexOf(':') + 1);
// Pass the event on, which is the job of a filter.
ContentHandler contentHandler = getContentHandler();
contentHandler.endElement(namespaceURI, localName, qualifiedName);
}
} // class NameFixerSAXHandler
// Given an XMLFilterImpl, insert it in between an XMLReader and its event
// handlers.
private static void insertXmlFilter(XMLFilterImpl xmlFilter,
XMLReader xmlReader)
{
// Any configuration operations done to the filter
// should be passed on to the actual upstream xmlReader.
xmlFilter.setParent(xmlReader);
// The filter's handlers should be whatever handlers
// belonged to the xmlReader.
xmlFilter.setContentHandler(xmlReader.getContentHandler());
xmlFilter.setDTDHandler(xmlReader.getDTDHandler());
xmlFilter.setEntityResolver(xmlReader.getEntityResolver());
xmlFilter.setErrorHandler(xmlReader.getErrorHandler());
// Now make the xmlReader's handlers point to the filter.
// Obviously, this step must be done AFTER the previous step.
xmlReader.setContentHandler(xmlFilter);
xmlReader.setDTDHandler(xmlFilter);
xmlReader.setEntityResolver(xmlFilter);
xmlReader.setErrorHandler(xmlFilter);
}
// ----------------------------------------------------------------------
// Classe de elementos
//----------------------------------------------------------------------
/**
* <p>
* Lista de elementos com a posicao do elemento infopae no texto para futura
* substituicao pelo resultado da consulta.
* </p>
*/
private static class itemElement
{
private int index = -1;
private Element element = null;
public itemElement(int index, Element element)
{
this.index = index;
this.element = element;
}
/**
* @return Returns the index.
*/
public int getIndex()
{
return index;
}
/**
* @return Returns the element.
*/
public Element getElement()
{
return element;
}
}
//----------------------------------------------------------------------
// Verificacao dos estilos
//----------------------------------------------------------------------
/**
* <p>
* Nome padrao do estilo para as tabelas do InfoPAE.
* </p>
*/
public static final String INFOPAE_STYLE = "infopaeTable";
/**
* <p>
* Criacao do estilo das tabelas do InfoPAE.
* </p>
*
* @param root
* Root element of the XML file.
*
* @author Andre Derraik
*
* <office:automatic-styles>
*
* <style:style style:name="InfopaeTable" style:family="table">
* <style:properties style:width="17cm" table:align="margins"
fo:background-color="#ccffff">
* <style:background-image/>
* </style:properties>
* </style:style>
*
* <style:style style:name="InfopaeTable.Col" style:family="table-column">
* <style:properties style:column-width="4.249cm"
style:rel-column-width="16383*"/>
* </style:style>
*
* <style:style style:name="InfopaeTable.Cell" style:family="table-cell">
* <style:properties fo:background-color="#ccffff"
fo:padding="0.097cm" fo:border-left="0.002cm solid #000000"
fo:border-right="none" fo:border-top="0.002cm solid #000000"
fo:border-bottom="0.002cm solid #000000">
* <style:background-image/>
* </style:properties>
* </style:style>
*
* </office:automatic-styles>
*
*/
private static void createStyles(Element root)
{
// Define o Name Space dos Estilos
Namespace nsStyle = root.getNamespace("style");
Namespace nsTable = root.getNamespace("table");
Namespace nsFo = root.getNamespace("fo");
// Get the style struct
Element style = root.getChild("automatic-styles", root.getNamespace());
/**
* Cria o estilo da Tabela
*
* <style:style style:name="InfopaeTable" style:family="table">
* <style:properties style:width="17cm" table:align="margins"
fo:background-color="#ccffff">
* <style:background-image/>
* </style:properties>
* </style:style>
*/
Element e = new Element("style",nsStyle);
e.setAttribute("name",INFOPAE_STYLE, nsStyle);
e.setAttribute("family", "table", nsStyle);
Element ee = new Element("properties",nsStyle);
ee.setAttribute("width","17cm", nsStyle);
ee.setAttribute("align","margins", nsTable);
ee.setAttribute("background-color","#ccffff", nsFo);
Element eee = new Element("background-image",nsStyle);
ee.addContent(eee);
e.addContent(ee);
style.addContent(e);
/**
* Cria o estilo das Colunas
*
* <style:style style:name="InfopaeTable.A"
style:family="table-column">
* <style:properties style:column-width="4.249cm"
style:rel-column-width="16383*"/>
* </style:style>
* <style:style style:name="InfopaeTable.B"
style:family="table-column">
* <style:properties style:column-width="0.3cm"
style:rel-column-width="16383*"/>
* </style:style>
*/
e = new Element("style",nsStyle);
e.setAttribute("name",INFOPAE_STYLE+".A", nsStyle);
e.setAttribute("family", "table-column", nsStyle);
ee = new Element("properties",nsStyle);
ee.setAttribute("column-width","4.3cm", nsStyle);
ee.setAttribute("rel-column-width","16383*", nsStyle);
e.addContent(ee);
style.addContent(e);
e = new Element("style",nsStyle);
e.setAttribute("name",INFOPAE_STYLE+".B", nsStyle);
e.setAttribute("family", "table-column", nsStyle);
ee = new Element("properties",nsStyle);
ee.setAttribute("column-width","0.3cm", nsStyle);
ee.setAttribute("rel-column-width","100*", nsStyle);
e.addContent(ee);
style.addContent(e);
/**
* Cria o estilo das Celulas
*
* <style:style style:name="InfopaeTable.A1"
style:family="table-cell">
* <style:properties fo:background-color="#ccffff"
*
fo:padding="0.097cm"
*
fo:border-left="0.002cm solid #000000"
*
fo:border-right="none"
*
fo:border-top="0.002cm solid #000000"
*
fo:border-bottom="0.002cm solid #000000">
* <style:background-image/>
* </style:properties>
* </style:style>
*/
e = new Element("style",nsStyle);
e.setAttribute("name",INFOPAE_STYLE+".A1", nsStyle);
e.setAttribute("family", "table-cell", nsStyle);
ee = new Element("properties",nsStyle);
ee.setAttribute("background-color","#ccffff", nsFo);
ee.setAttribute("padding","0.097cm", nsFo);
ee.setAttribute("border-left", "0.001cm solid #000000", nsFo);
ee.setAttribute("border-right", "0.001cm solid #000000", nsFo);
ee.setAttribute("border-top", "0.001cm solid #000000", nsFo);
ee.setAttribute("border-bottom","0.001cm solid #000000", nsFo);
eee = new Element("background-image",nsStyle);
ee.addContent(eee);
e.addContent(ee);
style.addContent(e);
}
/**
* <p>
* Verifica se os estilos para as tabelas de consula ja existem no arquivo.
* </p>
*
* @param root
* Root element of the XML file.
* @return Return true if found.
*
* @author Andre Derraik
*
*/
private static boolean checkStyles(Element root)
{
// Return value
boolean achou = false;
// Get the style struct
Element style = root.getChild("automatic-styles", root.getNamespace());
// Define o Name Space dos Estilos
Namespace nsStyle = root.getNamespace("style");
// Get the infopae table styles
List infopae_style = style.getChildren("style", nsStyle);
// System.out.println("Estilos do InfoPAE:");
// Processa todos os elementos para verificar se existe o do infopae.
for (Iterator iter = infopae_style.iterator(); iter.hasNext();)
{
Element elm = (Element) iter.next();
if (elm.getAttributeValue("name", nsStyle) == INFOPAE_STYLE)
{
achou = true;
break;
}
}
return achou;
}
/**
* <p>
* Cria a o cabecalho da tabela.
* </p>
*
* @param rootTable
* Root table element of the XML file.
* @param nsTable
* Table Name Space.
* @param nsText
* Text Name Space.
*
* @author Andre Derraik
*
* <table:table-header-rows>
* <table:table-row>
* <table:table-cell table:style-name="InfopaeTable.A1"
table:value-type="string" table:protected="true">
* <text:p text:style-name="Table Heading">Titulo</text:p>
* </table:table-cell>
* ...
* </table:table-row>
* </table:table-header-rows>
*/
private static void createHeaderTable(Element rootTable, Namespace nsTable,
Namespace nsText, String [] v)
{
/**
* Cria a linha do cabecalho.
*/
Element tabheader = new Element("table-header-rows",nsTable);
Element hr = new Element("table-row",nsTable);
for (int i = 0; i < v.length; i++)
{
/**
* Cria a celula.
*/
Element hc = new Element("table-cell",nsTable);
hc.setAttribute("style-name",INFOPAE_STYLE+".A1", nsTable);
hc.setAttribute("value-type","string", nsTable);
hc.setAttribute("protected","true", nsTable);
/**
* Cria o texto da celula.
*/
Element text = new Element("p",nsText);
text.setAttribute("style-name","Table Heading", nsText);
text.addContent((String)v[i]);
/**
* Acrescenta o texto a celula.
*/
hc.addContent(text);
/**
* Acrescenta a celula a linha.
*/
hr.addContent(hc);
}
tabheader.addContent(hr);
/**
* Acrescenta a linha a tabela.
*/
rootTable.addContent(tabheader);
}
/**
* <p>
* Cria a linha da tabela.
* </p>
*
* @param rootTable
* Root table element of the XML file.
* @param nsTable
* Table Name Space.
* @param nsText
* Text Name Space.
* @param str
* Text to insert into cell.
* @return
* Return an Element (the cell element with text).
*
* @author Andre Derraik
*
* <table:table-row>
* <table:table-cell table:style-name="InfopaeTable.Cell"
table:value-type="string">
* <text:p text:style-name="Table Contents">Linha 1</text:p>
* </table:table-cell>
* ...
* </table:table-row>
*/
private static Element createCellTable(Element rootTable, Namespace
nsTable, Namespace nsText, String str)
{
/**
* Cria uma celula.
*/
Element hc = new Element("table-cell",nsTable);
hc.setAttribute("style-name",INFOPAE_STYLE+".A1", nsTable);
hc.setAttribute("value-type","string", nsTable);
hc.setAttribute("protected","true", nsTable);
/**
* Cria o texto da celula.
*/
Element text = new Element("p",nsText);
text.setAttribute("style-name","Table Contents", nsText);
text.addContent(str);
/**
* Acrescenta o texto a celula.
*/
hc.addContent(text);
/**
* Retorna a celula criada.
*/
return hc;
}
/**
* <p>
* Cria a tabela com os resultados da consulta do InfoPAE dentro do corpo
do texto.
* </p>
*
* @param root
* Root element of the XML file.
* @param id
* Table Id.
* @param ncols
* Number of columns.
* @param nlin
* Number of lines.
*
* @author Andre Derraik
*
* <table:table table:name="InfopaeTableID" table:style-name="InfopaeTable">
* <table:table-column table:style-name="InfopaeTable.Col"
table:number-columns-repeated="numero de colunas"/>
*/
private static Element createTable(Element root, Element elm)
{
/**
* Local Vars.
*/
int id = 10;
/**
* Get the body struct.
*/
Element body = root.getChild("body", root.getNamespace());
/**
* Define o Name Space das Tabelas.
*/
Namespace nsTable = root.getNamespace("table");
Namespace nsText = root.getNamespace("text");
Namespace nsInfoPAE = root.getNamespace("infopae");
/**
* Pega o comando para gerar a consulta.
*/
String cmd = elm.getAttribute("cmd",nsInfoPAE).getValue();
/**
* Gera a consulta.
*/
dbTable results = opendb(cmd);
/**
* Cria a tabela.
*/
Element tab = new Element("table",nsTable);
tab.setAttribute("name",INFOPAE_STYLE+id, nsTable);
tab.setAttribute("style-name", INFOPAE_STYLE, nsTable);
/**
* Colunas principais da tabela.
*/
Element a = new Element("table-column",nsTable);
a.setAttribute("style-name",INFOPAE_STYLE+".A", nsTable);
a.setAttribute("number-columns-repeated",""+results.getNcol(), nsTable);
/**
* Coluna Auxiliar, nao utilizada.
*/
Element b = new Element("table-column",nsTable);
b.setAttribute("style-name",INFOPAE_STYLE+".B", nsTable);
tab.addContent(a);
tab.addContent(b);
/**
* Cria o header da tabela
*/
createHeaderTable(tab, nsTable, nsText, results.getHeader());
/**
* Cria as linhas da tabela
*/
int nlin = results.getIndex();
for (int i = 0; i < nlin; i++)
{
Element r = new Element("table-row",nsTable);
String [] vcol = results.getValues(i);
for (int j = 0; j < results.getNcol(); j++)
{
r.addContent(createCellTable(tab, nsTable, nsText, vcol[j]));
}
tab.addContent(r);
}
/**
* Retorna a tabela pronta para ser inserida ao texto.
*/
return tab;
}
//----------------------------------------------------------------------
// Funcoes de Banco
//----------------------------------------------------------------------
private static class dbTable {
private String [] header = null;
private String [] [] values = null;
private int index = 0;
private int ncol = 0;
/**
*
*/
public dbTable(int ncol)
{
this.values = new String [256][ncol];
this.ncol = ncol;
// TODO Auto-generated constructor stub
}
/**
* @return Returns the ncol.
*/
public int getNcol()
{
return ncol;
}
/**
* @param header The header to set.
*/
public void setHeader(String[] header)
{
this.header = header;
}
/**
* @return The header to set.
*/
public String [] getHeader() {
return this.header;
}
/**
* @param values The values to set.
*/
public void setValues(String [] values)
{
this.values[index] = (String []) values.clone();
index++;
}
/**
* @return Returns the index.
*/
public int getIndex()
{
return index;
}
/**
* @param items The items to set.
*/
public String [] getValues(int i)
{
return (String []) this.values[i];
}
}
public static dbTable opendb(String cmd)
{
dbTable tab = null;
String [] v = null;
String [] c = null;
ResultSetMetaData col = null;
int ncol = -1;
try
{
// Open DataBase
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:jtds:sqlserver://DI:5000/UNBA_RODNEI","infopae","infopae_");
// Execute the query
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(cmd);
// Get Columns Name.
if (rs != null)
{
col = rs.getMetaData();
ncol = col.getColumnCount();
tab = new dbTable(ncol);
c = new String [ncol];
v = new String [ncol];
for (int j = 0; j < ncol; j++)
{
String s = col.getColumnName(j+1);
c[j] = new String(s);
}
}
tab.setHeader(c);
// Get values
while (rs.next())
{
for (int j = 0; j < ncol; j++)
{
v[j] = rs.getString(j+1);
}
tab.setValues(v);
}
// Fecha o Banco
conn.close();
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return tab;
}
//----------------------------------------------------------------------
// Zip File routine
//----------------------------------------------------------------------
public static ZipOutputStream zipOut = null;
public static void copyZipFile(String in, String out) throws Exception
{
/**
* Abre o arquivo de origem.
*/
FileInputStream fis = new FileInputStream(new File(in));
ZipInputStream zipFileIn = new ZipInputStream(fis);
/**
* Abre o arquivo de destino.
*/
FileOutputStream fos = new FileOutputStream ( new File(out) );
zipOut = new ZipOutputStream ( fos );
zipOut.setLevel( 9 );
zipOut.setMethod( ZipOutputStream.DEFLATED );
/**
* Pega o primeiro arquivo do zip.
*/
ZipEntry entry = zipFileIn.getNextEntry();
while (entry != null)
{
/**
* Pega um arquivo.
*/
String elementName = entry.getName();
/**
* Exclui o arquivo que sera processado.
*/
if (elementName.compareToIgnoreCase(XMLCONTENTFILE)!=0)
{
// System.out.println(elementName);
/**
* create the new entry
*/
ZipEntry entryOut = new ZipEntry( elementName );
entryOut.setTime( Calendar.getInstance().getTimeInMillis() );
/**
* no need to setCRC, or setSize as they are computed
automatically.
*/
zipOut.putNextEntry( entryOut );
/**
* Pega o conteudo do arquivo.
*/
int fileLength = (int)entry.getSize();
byte[] wholeFile = null;
if (fileLength < 0)
{
final int BUFLEN = 40*1024; // 40 KB de buffer
final int BLOCKSIZ = 500; // 500 bytes por vez de lietura
wholeFile = new byte[ BUFLEN ];
int totalRead = 0;
int bytesRead = 1;
while (bytesRead>0)
{
bytesRead = zipFileIn.read( wholeFile, totalRead,
BLOCKSIZ );
if (bytesRead>0)
{
totalRead += bytesRead;
}
}
fileLength = totalRead;
}
else
{
wholeFile = new byte[ fileLength ];
int bytesRead = zipFileIn.read( wholeFile , 0 , fileLength
);
}
/**
* write the contents into the zip element.
*/
zipOut.write( wholeFile, 0, fileLength );
zipOut.closeEntry();
}
/**
* Pega o proximo arquivo.
*/
entry = zipFileIn.getNextEntry();
}
/**
* close the files.
* Nao fecha o arquivo de saida, pois sera utilizado depois.
*/
zipFileIn.close();
fis.close();
}
//----------------------------------------------------------------------
// Test routine
//----------------------------------------------------------------------
public static final String ZIPFILENAMEORI = "Y:/Y/y.sxw";
public static final String ZIPFILENAMEDEST = "Y:/Y/yy.sxw";
public static final String XMLCONTENTFILE = "content.xml";
public static void main(String[] args) throws Exception
{
System.out.println("Input File: "+ZIPFILENAMEORI);
System.out.println("Output File: "+ZIPFILENAMEDEST);
/**
* Copia o arquivo original sem o arquivo a ser processado.
*/
copyZipFile(ZIPFILENAMEORI, ZIPFILENAMEDEST);
/**
* Open the OO document.
*/
OOoDocReader doc = readDocFromFile(ZIPFILENAMEORI);
/**
* Cria a lista de elementos para processamento e depois para
acrescentar ao texto.
*/
Collection listElement = new Vector();
/**
* Get the content file.
*/
ItemName itemName = doc.getItem(XMLCONTENTFILE);
ItemContent itemContent = itemName.getItemContent();
if (itemContent instanceof XmlItem)
{
XmlItem xmlItem = (XmlItem) itemContent;
Document jdomDoc = xmlItem.getJDomXmlDoc();
/**
* Get the root element.
*/
Element root = jdomDoc.getRootElement();
/**
* Verifica se existem os estilos do InfoPAE.
*/
if (!checkStyles(root))
{
/**
* Caso nao existam, cria os estilos.
*/
createStyles(root);
}
/**
* Get the body struct.
*/
Element body = root.getChild("body", root.getNamespace());
/**
* Get the infopae elements.
*/
List infopae_data = body.getChildren("data",
root.getNamespace("infopae"));
/**
* Processa todos os elementos infopae.
*/
for (Iterator iter = infopae_data.iterator(); iter.hasNext();)
{
Element elm = (Element) iter.next();
/**
* Pega o indice do elemento infopae na lista do 'body'.
*/
int index = body.indexOf(elm);
// /**
// * Pega os atributos da consulta.
// */
// List att = elm.getAttributes();
// for (Iterator iterator = att.iterator(); iterator.hasNext();)
// {
// Attribute value = (Attribute) iterator.next();
//// System.out.println(value.getName() + " = \"" +
value.getValue() + "\"");
// }
//
// /**
// * Pega o conteudo, ou seja, o texto ou tabela gerada pela
// * consulta.
// */
// List data = elm.getChildren();
// for (Iterator iterator = data.iterator(); iterator.hasNext();
index++)
// {
// Element value = (Element) iterator.next();
//// System.out.println("\t" + value.getName() + " = \"" +
value.getValue() + "\"");
//
// }
/**
* Copia os elementos para acreascentar na no texto.
*/
listElement.add(new itemElement(index, (Element) elm.clone()));
/**
* Retira o elemento infopae da lista.
*/
iter.remove();
}
/**
* Acrescenta os elementos da consulta no corpo do texto (body).
*/
for (Iterator iterator = listElement.iterator();
iterator.hasNext();)
{
/**
* Pega as consultas encontradas e transforma em tabela no
texto.
*/
itemElement element = (itemElement) iterator.next();
/**
* Adiciona a tabela ao texto.
*/
body.addContent(element.getIndex(), (Content)
createTable(root,element.getElement()));
}
/**
* Generate the hole file on a pretty format.
*/
XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat());
// System.out.println();
// outp.output(jdomDoc, System.out);
/**
* Fecha o pacote zip original.
*/
doc.close();
/**
* create the entry
*/
ZipEntry entry = new ZipEntry( XMLCONTENTFILE );
entry.setTime( Calendar.getInstance().getTimeInMillis() );
/**
* no need to setCRC, or setSize as they are computed automatically.
*/
zipOut.putNextEntry( entry );
/**
* write the contents into the zip element.
*/
String wholeFile = outp.outputString(jdomDoc);
zipOut.write( wholeFile.getBytes("UTF-8"), 0, wholeFile.length() );
zipOut.closeEntry();
/**
* close the entire zip.
*/
zipOut.close();
}
System.out.println("Done.");
}
}
Mensagens enviadas estão livres de vírus.
Verificado por AVG Anti-Vírus.
Versão: 7.0.323 / Banco de dados de Vírus: 267.7.11/26 - Data de Lançamento:
22/6/2005
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]