Olá Pessoal,
será que alguém já ouviu falar
do Castor xml? O meu professor
aqui da Universidade Federal de Lavras(UFLA)
falou para eu usá-lo, eu estava usando o framework
Xstream que eu fiquei conhecendo aqui no GUJ mesmo,
ele é muito bom e simples, mas o meu professor
quer que eu use o Castor xml acho que é por causa
do JDO que eu terei que usar mais tarde.
Eu estou implementando o seguinte:
arquivo order.xml:
<Order reference="12343-AHSHE-314159">
<Client>
<Name>Jean Smith</Name>
<Address>2000, Alameda de las Pulgas, San Mateo, CA 94403</Address>
</Client>
<Item reference="RF-0001">
<Description>Stuffed Penguin</Description>
<Quantity>10</Quantity>
<UnitPrice>8.95</UnitPrice>
</Item>
<Item reference="RF-0034">
<Description>Chocolate</Description>
<Quantity5</Quantity>
<UnitPrice>28.50</UnitPrice>
</Item>
<Item reference="RF-3341">
<Description>Cookie</Description>
<Quantity>30</Quantity>
<UnitPrice>0.85</UnitPrice>
</Item>
</Order>
Arquivo MyOrder.java:
import java.util.Vector;
import java.util.Enumeration;
public class MyOrder {
private String _ref;
private ClientData _client;
private Vector _items;
private float _total;
public void setReference(String ref) {
_ref = ref;
}
public String getReference() {
return _ref;
}
public void setClientData(ClientData client) {
_client = client;
}
public ClientData getClientData() {
return _client;
}
public void setItemsList(Vector items) {
_items = items;
}
public Vector getItemsList() {
return _items;
}
public void setTotal(float total) {
_total = total;
}
public float getTotal() {
return _total;
}
// Do some processing on the data
public float getTotalPrice() {
float total = 0.0f;
for (Enumeration e = _items.elements() ; e.hasMoreElements() ;) {
Item item = (Item) e.nextElement();
total += item._quantity * item._unitPrice;
}
return total;
}
}
arquivo ClientData.java:
public class ClientData {
private String _name;
private String _address;
public void setName(String name) {
_name = name;
}
public String getName() {
return _name;
}
public void setAddress(String address) {
_address = address;
}
public String getAddress() {
return _address;
}
}
arquivo Item.java:
public class Item {
public String _reference;
public int _quantity;
public float _unitPrice;
public String _description;
}
arquivo mapping.xml:
<?xml version="1.0"?>
<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN"
"http://castor.org/mapping.dtd">
<mapping>
<class name="MyOrder">
<map-to xml="Order"/>
<field name="Reference"
type="java.lang.String">
<bind-xml name="reference" node="attribute"/>
</field>
<field name="Total"
type="float">
<bind-xml name="total-price" node="attribute"/>
</field>
<field name="ClientData"
type="ClientData">
<bind-xml name="Client"/>
</field>
<field name="ItemsList"
type="Item"
collection="vector">
<bind-xml name="Item"/>
</field>
</class>
<class name="ClientData">
<field name="Name"
type="java.lang.String">
<bind-xml name="Name" node="element"/>
</field>
<field name="Address"
type="java.lang.String">
<bind-xml name="Address" node="element"/>
</field>
</class>
<class name="Item">
<field name="_reference"
type="java.lang.String"
direct="true">
<bind-xml name="reference" node="attribute"/>
</field>
<field name="_quantity"
type="integer"
direct="true">
<bind-xml name="Quantity" node="element"/>
</field>
<field name="_unitPrice"
type="float"
direct="true">
<bind-xml name="UnitPrice" node="element"/>
</field>
<field name="_description"
type="string"
direct="true">
<bind-xml name="Description" node="element"/>
</field>
</class>
</mapping>
arquivo Main.java:
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.Marshaller;
import java.io.IOException;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import org.xml.sax.InputSource;
public class main {
public static void main(String args[]) {
Mapping mapping = new Mapping();
try {
// 1. Load the mapping information from the file
mapping.loadMapping( "mapping.xml" );
// 2. Unmarshal the data
Unmarshaller unmar = new Unmarshaller(mapping);
MyOrder order = (MyOrder)unmar.unmarshal(new InputSource(new FileReader("order.xml")));
// 3. Do some processing on the data
float total = order.getTotalPrice();
System.out.println("Order total price = " + total);
order.setTotal(total);
// 4. marshal the data with the total price back and print the XML in the console
Marshaller marshaller = new Marshaller(new OutputStreamWriter(System.out));
marshaller.setMapping(mapping);
marshaller.marshal(order);
} catch (Exception e) {
System.out.println(e);
return;
}
}
}
Blz Thingol?
Então eu já adicionei
o jar do Castor no meu Path
e estou tentando fazer
este exemplo do site
do castor mesmo para
poder usar-lo no meu
projeto aqui, mas o exemplo
está dando erro toda hora
e eu não sei o acotencendo,
será que você thingol ou alguém poderia
me ajudar?
O erro é o seguinte:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.exolab.castor.mapping.Mapping.<clinit>(Mapping.java:70)
at pack.Main.main(Main.java:14)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 2 more
já quebrei a cabeça aqui mas não estou conseguindo.
[]'s.
O meu Projeto
é sobre Autenticação
e Autorização distribuida,
e vou precisar usar o Castor.
Será que alguém poderia me
ajudar?
[]'s.
Você precisa adicionar mais alguns jars. No seu caso deve ser o commons-logging (pela mensagem de erro, org/apache/commons/logging/LogFactory é o nome da classe, e ela pode ser encontrada em http://commons.apache.org/logging/ ) e o log4j, http://logging.apache.org/log4j/
Como que eu iria saber
que tinha adicionar
esses jars extras?
Muito Obrigado mesmo
pela ajuda thingol
eu não iria saber
o que fazer, pois
eu nunca tinha visto
este tipo de erro antes.
Nô agora apareceu outro erro
aqui:
20/03/2009 11:25:14 org.exolab.castor.mapping.Mapping setBaseURL
INFO: mapping.xml is not a URL, trying to convert it to a file URL
20/03/2009 11:25:15 org.exolab.castor.mapping.Mapping loadMapping
INFO: Loading mapping descriptors from mapping.xml
org.exolab.castor.mapping.MappingException: Could not find the class MyOrder
Eu só não entendi agora é como que ele não está encontrando
a classe MyOrder sendo que ela está aqui no meu Projeto
e os arquivos mapping.xml e order.xml já estão salvo
no meu projeto e posso até vê-los aqui dentro do eclipse?
[]'s
thingol eu estou
olhando aqui no javadoc
do Castor sobre o método loadMapping:
http://www.castor.org/1.2/javadoc/org/exolab/castor/mapping/Mapping.html
mas eu estou achando meio estrnho a parte da URL
que fala
loadMapping(java.lang.String url)
Loads the mapping from the specified URL with type defaults to 'CastorXmlMapping'.
mas e esse valor default ‘CastorXmlMapping’?
Será que você thingol ou alguém poderia me ajudar?
[]'s.