1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
|
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileSystemView;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
@SuppressWarnings("serial")
public class FenetreSaisie extends JFrame{
//labels
private JLabel label_presentation_fenetre;
private JLabel label_entree;
private JLabel label_sortie;
//zones de texte
private JTextField txtlocalPath = new JTextField(25);
private JTextField txtSortie = new JTextField(25);
//fichiers d'entrée et de sortie
File inputFile;
File outputFile;
//boutons
private JButton btnparcourir = new JButton("Parcourir...");
private JButton btntradsimple = new JButton("ebXML -> XML");
private JButton btntradcomplique = new JButton("XML -> ebXML");
//private JButton btnZero = new JButton ("Remise à zero");
//creation du panel
JPanel panel = new JPanel();
//enumération
private XmlType xmlType;
//liste des erreurs
private List<Error> listErrors = new ArrayList<Error>();
//JLabel pour afficher message d'erreur
JTextArea message_erreur = new JTextArea(2,38);
//Constructeur de la fenêtre
public FenetreSaisie(){
super();
txtlocalPath.setEditable(false);
inputFile = null;
outputFile = null;
xmlType = null;
setTitle("Utilitaire de conversion");//On donne un titre à l'application
setResizable(true);
xmlType = null;
build();//On initialise notre fenêtre
}
//initialisation Fenetre
private void build(){
setSize(450,225); //On donne une taille à notre fenêtre
setLocationRelativeTo(null); //On centre la fenêtre sur l'écran
setResizable(true); //On permet le redimensionnement
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //On dit à l'application de se fermer lors du clic sur la croix
setContentPane(buildContentPane());
}
private JPanel buildContentPane(){
//affectation du Layout GridBagLayout au panel
panel.setLayout(new GridBagLayout());
//création des composants
label_presentation_fenetre = new JLabel("Utilitaire de conversion");
//creation du bouton Parcourir afin de chercher la source
btnparcourir.addActionListener(new BoutonParcourirListener());
btnparcourir.setFocusable(false);
//creation de labels pour informer l'utilisateur
label_entree = new JLabel("Fichier à traduire");
label_sortie = new JLabel("Saisir le nom du fichier XML de sortie");
//creation du bouton Traduire ebXML vers XML
btntradsimple.addActionListener(new BoutonTradSimpleListener());
btntradsimple.setToolTipText("Traduit du ebXML vers le XML simplifié");
//creation du bouton traduire XML vers ebXML
btntradcomplique.addActionListener(new BoutonTradCompliqueListener());
btntradcomplique.setToolTipText("Traduit du XML simplifié vers le ebXML");
//creation du bouton de remise à zero
//btnZero.addActionListener(new BoutonZeroListener());
//Ajout des composants en spécifiant les contraintes
GridBagConstraints gbc = new GridBagConstraints();
panel.setPreferredSize(getPreferredSize());
message_erreur.setEditable(false);
message_erreur.setBorder(BorderFactory.createEtchedBorder());
gbc.gridx =0;
gbc.gridy = 0;
gbc.gridwidth = 0;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.fill = GridBagConstraints.CENTER;
panel.add(message_erreur,gbc);
gbc.gridx =0;
gbc.gridy = 1;
gbc.gridwidth = 10;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.CENTER;
panel.add(label_presentation_fenetre, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth =10 ;
gbc.gridheight =1;
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(label_entree, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.NONE;
panel.add(txtlocalPath, gbc);
gbc.gridx = 3;
gbc.gridy = 3;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(btnparcourir, gbc);
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 1;
gbc.gridheight =1;
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.fill = GridBagConstraints.NONE;
panel.add(label_sortie, gbc);
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.fill = GridBagConstraints.NONE;
panel.add(txtSortie, gbc);
gbc.gridx = 0;
gbc.gridy = 6;
gbc.gridwidth = 1;
gbc.gridheight =1;
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.fill = GridBagConstraints.NONE;
panel.add(btntradsimple, gbc);
gbc.gridx = 3;
gbc.gridy = 6;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.fill = GridBagConstraints.NONE;
panel.add(btntradcomplique, gbc);
//DocumentListener rajouté pour les zones de texte entrée et sortie
txtlocalPath.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
VerifAll();
}
@Override
public void insertUpdate(DocumentEvent e) {
VerifAll();
}
@Override
public void removeUpdate(DocumentEvent e) {
VerifAll();
}
});
txtSortie.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
VerifAll();
}
@Override
public void insertUpdate(DocumentEvent e) {
VerifAll();
}
@Override
public void removeUpdate(DocumentEvent e) {
VerifAll();
}
});
//fin des DocumentListener
btntradsimple.setEnabled(false);
btntradcomplique.setEnabled(false);
return panel;
}
//classe interne permettant d'écouter le bouton Parcourir
class BoutonParcourirListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent event)
{
message_erreur.setText("");
FileSystemView vueSysteme = FileSystemView.getFileSystemView();
File defaut = vueSysteme.getDefaultDirectory();
JFileChooser chooser = new JFileChooser(defaut);
//rajout d'un filtre afin de ne garder que les documents .xml
ExampleFileFilter filter = new ExampleFileFilter();
filter.addExtension("xml");
filter.setDescription("fichiers .xml");
chooser.setFileFilter(filter);
//on ne garde que
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int choix = chooser.showOpenDialog(null);
//cas où on sélectionne un fichier à l'aide du bouton Parcourir
if (choix == JFileChooser.APPROVE_OPTION) {
inputFile = chooser.getSelectedFile();
txtlocalPath.setText(inputFile.getPath());
txtSortie.requestFocus();
}
//pas besoin de rajouter où l'utilisateur annule l'opération : JFileChooser.CANCEL_OPTION
}
}//fin classe BoutonParcourirListener
//classe BoutonTradSimpleListener permettant d'écouter le bouton btntradsimple : pour passer du ebXML vers le XML simple
class BoutonTradSimpleListener implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
//récupérer le contenu de la textBox et traduire
System.setProperty("javax.xml.transform.TransformerFactory",
"net.sf.saxon.TransformerFactoryImpl");
//on crée une fabrique de transformeurs
TransformerFactory factory = TransformerFactory.newInstance();
//fichier xsl de transformation
File fxsl = new File("transfo.xsl");
//fichier xml source de type source
Source xmlSource = new StreamSource(decoupeURL());
//nom du fichier de sortie de type Result
Result sortie = new StreamResult(txtSortie.getText());
//transformer
Transformer transformer;
try {
//on récupère un transformeur à partir d'une fabrique de transformeurs
transformer = factory.newTransformer(new StreamSource(fxsl));
//encoding
// transformer.setOutputProperty("encoding", "ISO-8859-1");
transformer.setOutputProperty("encoding", "UTF-8");
//pour l'indentation
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
/*Utilisation d'un parser DOM ou SAX sans DTD ou xml schema pour la validation,
* s'il ya une erreur de parsing alors le fichier XML n'est pas bien formé càd NON XML.
*/
DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
DocumentBuilder constructeur = fabrique.newDocumentBuilder();
// lecture du contenu d'un fichier XML avec DOM
File xml = new File(decoupeURL());
Document document = constructeur.parse(xml);
//transformation en prenant en paramètre le fichier xml source et fait le fichier xml de sortie
transformer.transform(xmlSource, sortie );
//message informant que la traduction a bien été faite
message_erreur.setText("Traduction simple effectuée");
btntradcomplique.setEnabled(false);
btntradsimple.setEnabled(false);
}
catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch(SAXException se){
//C'est un fichier Non Xml
}catch(IOException ioe){
// TODO Auto-generated catch block
}
}
}//fin de la classe BoutonTradSimpleListener
//classe BoutonTradCompliqueListener permettant d'écouter le bouton btntradcomplique : pour passer du XML simple au ebXML
class BoutonTradCompliqueListener implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
//récupérer le contenu de la textBox et traduire
System.setProperty("javax.xml.transform.TransformerFactory",
"net.sf.saxon.TransformerFactoryImpl");
//on crée une fabrique de transformeurs
TransformerFactory factory = TransformerFactory.newInstance();
//fichier xsl de transformation
File fxsl = new File("transfo_eb.xsl");
//fichier xml source de type source
Source xmlSource = new StreamSource(decoupeURL());
//fichier xml de sortie de type Result
Result sortie = new StreamResult(txtSortie.getText());
//transformer
Transformer transformer;
try {
//on récupère un transformeur à partir d'une fabrique de transformeurs
transformer = factory.newTransformer(new StreamSource(fxsl));
//encoding
// transformer.setOutputProperty("encoding", "ISO-8859-1");
transformer.setOutputProperty("encoding", "UTF-8");
//pour l'indentation
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
/*Utilisation d'un parser DOM ou SAX sans DTD ou xml schema pour la validation,
* s'il ya une erreur de parsing alors le fichier XML n'est pas bien formé càd NON XML.
*/
DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
DocumentBuilder constructeur = fabrique.newDocumentBuilder();
// lecture du contenu d'un fichier XML avec DOM
File xml = new File(decoupeURL());
Document document = constructeur.parse(xml);
//transformation en prenant en paramètre le fichier xml source et fait le fichier xml de sortie
transformer.transform(xmlSource, sortie );
//message d'information
message_erreur.setText("Traduction complexe effectuée");
btntradcomplique.setEnabled(false);
btntradsimple.setEnabled(false);
/*txtlocalPath.setText("");
txtSortie.setText("");*/
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}//fin de la classe BoutonTradCOmpliqueListener
/*méthode permettant de découper l'adresse absolue qui est écrite dans le textarea du chemin : txtlocalPath
* 1) permet de récupérer l'URL du fichier xml à traduire
* 2) ne prend que le fichier .xml de cette URL
*/
public String decoupeURL(){
String s = txtlocalPath.getText();
File file = new File(s);
s = file.getName();
return s;
}
/*méthode permettant d'extraire l'extension d'un fichier
* On se servira de cette méthode pour s'assurer notamment que :
* les fichiers qui sont passés en entrée et les noms de fichiers de sortie sont bien des .xml
*/
public static String getFileExtension(String NomFichier) {
File tmpFichier = new File(NomFichier);
tmpFichier.getName();
int posPoint = tmpFichier.getName().lastIndexOf('.');
if (0 < posPoint && posPoint <= tmpFichier.getName().length() - 2 ) {
return tmpFichier.getName().substring(posPoint + 1);
}
return "";
}
private void VerifAll() {
VerificationEntree();
VerificationSortie();
}
public void VerificationEntree(){
if (inputFile == null || !inputFile.exists()) {
inputFile = null;
listErrors.add(Error.UNKNOW_INPUT_FILE);
}
else if((getFileExtension(txtlocalPath.getText())).compareTo("xml")!=0 && txtlocalPath.getText()!=null){
message_erreur.setText("Veuillez saisir un document XML");
txtSortie.setEditable(false);
}
else{
try {
DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
DocumentBuilder constructeur = fabrique.newDocumentBuilder();
Document document = constructeur.parse(inputFile);
Node racine = document.getDocumentElement();
String nomRacine = racine.getNodeName();
/*on se place sur la racine, on vérifie alors :
* - soit que le fichier d'entrée est un document ebXML
* -soit que le fichier d'entrée est un document XML simple
* - soit ni l'un ni l'autre, alors erreur...*/
if (nomRacine.equals("Dematerialisation_prix")) {
xmlType = XmlType.SIMPLE;
txtSortie.setEditable(true);
message_erreur.setText("Saisir le nom du document de sortie d'extension.xml");
} else if (nomRacine.equals("itt:InvitationToTenderDetails")) {
xmlType = XmlType.COMPLEX;
txtSortie.setEditable(true);
message_erreur.setText("Saisir le nom du document de sortie d'extension.xml");
}
}catch (ParserConfigurationException e1) {
xmlType = null;
listErrors.add(Error.PARSE_ERROR);
} catch (SAXException e1) {
xmlType = null;
listErrors.add(Error.SAX_ERROR);
} catch (IOException e1) {
xmlType = null;
listErrors.add(Error.IO_ERROR);
message_erreur.setText("Le fichier XML n'est ni un ebXML, ni un XML simple, veuillez recommencer la saisie");
message_erreur.setLineWrap(true);
txtSortie.setEditable(false);
}
}
}
//vérification du document de sortie
public void VerificationSortie() {
if(/*listErrors.isEmpty() &&*/ xmlType == XmlType.COMPLEX){
if(getFileExtension(txtSortie.getText()).compareTo("xml")==0){
btntradcomplique.setEnabled(false);
btntradsimple.setEnabled(true);
}
else if(getFileExtension(txtSortie.getText()).compareTo("xml")!=0 && !txtSortie.getText().equals("")){
}
}
else if (/*listErrors.isEmpty() &&*/ xmlType == XmlType.SIMPLE){
if(getFileExtension(txtSortie.getText()).compareTo("xml")==0){
btntradcomplique.setEnabled(true);
btntradsimple.setEnabled(false);
}
} else {
btntradcomplique.setEnabled(false);
btntradsimple.setEnabled(false);
}
}//fin de la vérification du document de sortie
//enum pour les erreurs
private enum Error {
UNKNOW_INPUT_FILE,
UNDEFINED_OUTPUT_FILE,
IO_ERROR,
SAX_ERROR,
PARSE_ERROR;
}
//enum pour les deux types de dic XML
private enum XmlType {
SIMPLE,
COMPLEX;
}
public static void main(String[] args) {
//On crée une nouvelle instance de notre FenetreTexte
FenetreSaisie fenetre = new FenetreSaisie();
fenetre.setVisible(true);//On la rend visible
}
}//fin de la classe |
Partager