I am new and started those days to learn XML for an implementation that must have in my application, I already made some tests with marshall()
and unmarshall()
already in Main()
to understand more, I'm doing a form that you have the following operation: the user presses on option Procurar XML
, then selects a file in that format in some file of the system to later import it for the application that I am trying to do is that when importing into the system that can read and in each tag of a certain type the load each in its respective JTextField, JCombobox y JSpinner
.
Example:
<Pedido>
<pedidos>
<pedido id = "1">
<dataCadastro>3917-04-11T00:00:00-03:00</dataCadastro> <!-- tfDataCadastro: getText(); -->
<nomeProduto>Produto C</nomeProduto> <!-- cbProduto.getSelectedItem(); -->
<numControle>41666</numControle> <!-- tfNumControle: getText(); -->
<quantidade>4</quantidade> <!-- tfQuantidade: getText(); -->
<valorUnitario>41.46</valorUnitario> <!-- tfValorUnitario: getText(); -->
<codCliente>6</codCliente> <!-- cbCodCliente.getSelectedItem(); -->
</pedido>
</Pedido>
<!-- Las tags comentadas son valores a sean recuperados en los campos -->
I tried to do that but I do not know if it's a good way to start:
DAOManager:
public interface DAOManager {
ClienteDAO getClienteDAO();
PedidoDAO getPedidoDAO();
ProdutoDAO getProdutoDAO();
}
Order (the class I'm willing to load the xml):
@XmlRootElement(name = "pedido")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
@Table(name = "pedido")
public class Pedido implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
@Temporal(javax.persistence.TemporalType.DATE)
private Date dataCadastro;
@Column
private String nomeProduto;
@Column
private int numControle;
@Column
private int quantidade;
@Column(precision=15, scale=7)
private float valorUnitario;
@Column
private Integer codCliente;
@Column(precision=15, scale=7)
private float valorTotal;
@Column(precision=2, scale=2)
private Double total;
public Pedido() {
}
public Pedido(int numControle, Date dataCadastro, String nomeProduto, float valorUnitario, float valorTotal, int quantidade, int codCliente, Double total){
this.numControle = numControle;
this.dataCadastro = dataCadastro;
this.nomeProduto = nomeProduto;
this.valorUnitario = valorUnitario;
this.valorTotal = valorTotal;
this.quantidade = quantidade;
this.codCliente = codCliente;
this.total = total;
}
/* Getters e setters del la aplicación */
}
MySQLPedidoDAO:
/**
*
* @author Vickz
*/
public class MySQLPedidoDAO implements PedidoDAO {
//null pointer exception pois esse campo estava inicializado como null antes
public ConnectionFactory cf;
public MySQLPedidoDAO(ConnectionFactory cf) {
this.cf = cf;
}
@Override
public void inserir(Pedido o) {
cf.createEm().getTransaction().begin();
//tanto persist quanto merge salvam o objeto no banco de dados
//em.persist(cliente);
cf.createEm().merge(o);
cf.createEm().getTransaction().commit();
cf.close();
}
@Override
public void alterar(Pedido o) {
cf.createEm().getTransaction().begin();
Pedido pedido = new Pedido();
pedido.getId();
cf.createEm().merge(o);
cf.createEm().getTransaction().commit();
cf.close();
}
@Override
public void excluir(Pedido o) {
cf.createEm().getTransaction().begin();
cf.createEm().remove(o);
cf.createEm().getTransaction().commit();
cf.close();
}
@Override
public Pedido pesquisar(Long id) {
cf.createEm().getTransaction().begin();
//erro abaixo
Pedido pedido = cf.createEm().find(Pedido.class, id);
cf.createEm().getTransaction().commit();
//erro ao deletar pois o factory já está fechado
//emf.close();
return pedido;
}
@Override
public List<Pedido> listar() {
cf = new ConnectionFactory();
cf.createEm().getTransaction().begin();
//pedido = *, Pedido = nome da tabela
Query consulta = cf.createEm().createQuery("select pedido from Pedido pedido");
List<Pedido> pedidos = consulta.getResultList();
cf.createEm().getTransaction().commit();
cf.close();
return pedidos;
}
}
ViewPedidos:
public class ViewPedidos extends javax.swing.JInternalFrame {
private DAOManager manager;
private PedidoModel model;
private MySQLPedidoDAO mspdao;
private MySQLClienteDAO mscdao;
private MySQLProdutoDAO msprdao;
private List<Produto> produtos;
private List<Pedido> pedidos;
private Pedido ped;
private Produto pro;
private FiltroArquivo filter;
private String xmlFile = "";
private boolean editavel;
private JAXBContext context;
/* .... Getters y Setters .... */
private void btImportarActionPerformed(java.awt.event.ActionEvent evt) {
try {
habilitarTextFieldEBotoes();
JAXBContext context = JAXBContext.newInstance(ImportarPedidoList.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Pedido pedido = (Pedido) unmarshaller.unmarshal(new File(xmlFile));
// Y a partir de ahora estoy intentando procurar como debe ser //hecho eso
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Não foi possível importar o arquivo.xml", "Falha ao carregar", JOptionPane.INFORMATION_MESSAGE);
}
}
private void btProcurarActionPerformed(java.awt.event.ActionEvent evt) {
try {
JFileChooser jFileChooser = new JFileChooser("C:\Users\Vickz\Documents\NetBeansProjects\Loja");
jFileChooser.setDialogTitle("Escolha o arquivo xml");
jFileChooser.setFileFilter(new FiltroArquivo(".xml", "Arquivo XML"));
int result = jFileChooser.showSaveDialog(this);
if(result == JFileChooser.APPROVE_OPTION){
//JOptionPane.showMessageDialog(this, jFileChooser.getName());
xmlFile = jFileChooser.getSelectedFile().getAbsolutePath();
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Não foi possível carregar o arquivo.xml", "Falha ao carregar", JOptionPane.INFORMATION_MESSAGE);
}
}
/*
@Override
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
String value = ie.getItem().toString();
// faz algo conforme a opção selecionada
if (value.equals("Produto A")) {
} else if (value.equals("Produto B")) {
} else if (value.equals("Produto C")) {
} else if (value.equals("Produto D")) {
} else if (value.equals("Produto E")) {
} else if (value.equals("Produto F")) {
} else if (value.equals("Produto G")) {
} else if (value.equals("Produto H")) {
} else if (value.equals("Produto I")) {
}
}
}*/
}
I tried to do a test on Main () but I also can not:
public class Main {
private static JAXBContext context;
public static void main(String[] args) throws JAXBException {
ConnectionFactory cf = new ConnectionFactory();
MySQLPedidoDAO mspdao = new MySQLPedidoDAO(cf);
PedidoList pl = new PedidoList();
Main.context = JAXBContext.newInstance(Pedido.class);
//Marshaller marshaller = Main.context.createMarshaller();
//marshaller.marshal(new Pedido(41666, new java.util.Date(2017, 3, 11), "Produto C", 41.46f, 0, 4, 6, 235.54), new File("pedido.xml"));
Unmarshaller unmarshaller = Main.context.createUnmarshaller();
Pedido pedidolist = (Pedido) unmarshaller.unmarshal(new File("C:\Users\Vickz\Documents\NetBeansProjects\Loja\pedido.xml"));
Marshaller marshaller = Main.context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(pedidolist, System.out);
/*for(PedidoList pedidolis: unmarshalledPedido.getPedidos()){
System.out.println(pedido.getDataCadastro());
System.out.println(pedido.getNomeProduto());
System.out.println(pedido.getNumControle());
System.out.println(pedido.getQuantidade());
System.out.println(pedido.getValorUnitario());
System.out.println(pedido.getCodCliente());
System.out.println(pedido.getValorTotal());
System.out.println(pedido.getTotal());
}*/
}
Does anyone know a way to go through all newly imported forms and retrieve the value of each tag and put each one in a field? Below are the spoken buttons: