+++ /dev/null
-/**
- *
- */
-package fr.mbdx.ixbus.client.impl;
-
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.HttpURLConnection;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-import javax.activation.MimetypesFileTypeMap;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-
-import org.apache.log4j.Logger;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import fr.mbdx.ixbus.client.Attachment;
-import fr.mbdx.ixbus.client.ClientException;
-import fr.mbdx.ixbus.client.impl.cxf.ArrayOfAttachment;
-import fr.mbdx.ixbus.client.impl.cxf.Message;
-import fr.mbdx.ixbus.client.impl.cxf.Message.Description;
-import fr.mbdx.ixbus.pj.ObjectFactory;
-import fr.srci.xmlschema.legalitycontrol.LegalityControl;
-
-public class Utils {
-
- public static DateFormat dateFormat = new SimpleDateFormat("yyyy'-'MM'-'dd");
-
- public static DateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd'_'HHmm");
-
- protected Logger log = Logger.getLogger(getClass());
-
- private ClientCxfImpl client = null;
-
- private LegalityControl legalityControl = null;
-
- public static String getValueByTagName(Element parent, String tagName) {
- String value = null;
- NodeList descList = parent.getElementsByTagName(tagName);
- if (descList.getLength() > 0) {
- value = descList.item(0).getTextContent();
- }
- return value;
- }
-
- /**
- * @param path
- * @return
- * @throws ClientException
- */
- public static URL getURL(String path) throws ClientException {
- File file = new File(path);
- URL url = null;
- try {
- if (file.exists()) {
- url = file.toURI().toURL();
- } else {
- url = new URL(path);
- }
- } catch (MalformedURLException e) {
- throw new ClientException(e);
- }
-
- return url;
- }
-
- public static Message getMessage(List<Attachment> listAttachment) {
- Message msg = new Message();
- msg.setDescription(null);
- ArrayOfAttachment doc = new ArrayOfAttachment();
- doc.getAttachment().addAll(getCfxAttachments(listAttachment));
- msg.setDocument(doc);
- return msg;
- }
-
- public static Message getInvokeMessage(String document, String date) {
- Message attach = new Message();
- Description desc = new Description();
- desc.setAny("<Operations><OperationFlux><Document>" + document + "</ Document ><Date>" + date + "</Date></ OperationFlux ></Operations>");
- attach.setDescription(desc);
- attach.setDocument(null);
- return attach;
- }
-
- public static List<fr.mbdx.ixbus.client.impl.cxf.Attachment> getCfxAttachments(List<Attachment> listAttachments) {
- List<fr.mbdx.ixbus.client.impl.cxf.Attachment> result = new ArrayList<fr.mbdx.ixbus.client.impl.cxf.Attachment>();
- for (Attachment attachment : listAttachments) {
- fr.mbdx.ixbus.client.impl.cxf.Attachment cfxAttachment = new fr.mbdx.ixbus.client.impl.cxf.Attachment();
- cfxAttachment.setContent(attachment.getContent());
- cfxAttachment.setName(attachment.getName());
- cfxAttachment.setSize(attachment.getSize());
- result.add(cfxAttachment);
- }
- return result;
- }
-
- public static List<String> getMessages(Message message) {
- Element element = (Element) message.getDescription().getAny();
- List<String> lst = new ArrayList<String>();
- NodeList lstMesssage = element.getElementsByTagName("Message");
- for (int i = 0; i < lstMesssage.getLength(); ++i) {
- Node node = lstMesssage.item(i);
- String content = node.getTextContent();
- lst.add(content);
- }
- return lst;
- }
-
- public static String getFileName(HttpURLConnection conn) {
- String filename = null;
- String disposition = conn.getHeaderField("Content-Disposition");
- if (disposition != null) {
- // extracts file name from header field
- int index = disposition.indexOf("filename=");
- if (index > 0) {
- filename = disposition.substring(index + 10, disposition.length() - 1);
- }
- } else {
- String file = conn.getURL().getFile();
- filename = file.substring(file.lastIndexOf("/") + 1, file.length());
- }
- return filename;
- }
-
- /**
- * Décompresse le fichier contenu dans une pièce jointe précédemment envoyée à iXbus
- *
- * @param attach
- * @return tableau d'octets
- * @throws IOException
- */
- public static byte[] unzipAttachment(Attachment attach) throws IOException {
- byte[] result = null;
-
- try {
- ByteArrayInputStream is = new ByteArrayInputStream(attach.getContent());
- ZipInputStream zis = new ZipInputStream(is);
- ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream();
- int bytesRead;
- byte[] tempBuffer = new byte[4096];
- ZipEntry entry = zis.getNextEntry();
- while ((bytesRead = zis.read(tempBuffer)) != -1) {
- streamBuilder.write(tempBuffer, 0, bytesRead);
- }
- result = streamBuilder.toByteArray();
- } finally {
- }
-
- return result;
- }
-
- /**
- * Compresse le contenu d'un flux au format ZIP
- *
- * @param is
- * Flux à compresser
- * @param entryName
- * Nom de l'entrée dans l'archive ZIP
- * @return tableau d'octets
- * @throws IOException
- */
- public static byte[] zipStream(InputStream is, String entryName) throws JAXBException, IOException {
- byte[] bytes = null;
- ByteArrayOutputStream baos = null;
- ZipOutputStream zos = null;
-
- try {
- baos = new ByteArrayOutputStream();
- zos = new ZipOutputStream(baos);
-
- String comment = createAttachmentDescription(entryName, null);
- zos.setComment(comment);
-
- zos.putNextEntry(new ZipEntry(entryName));
-
- byte[] byteChunk = new byte[4096];
- int n;
- while ((n = is.read(byteChunk)) > 0) {
- zos.write(byteChunk, 0, n);
- }
- zos.finish();
- bytes = baos.toByteArray();
- } finally {
- if (baos != null) {
- baos.close();
- }
- if (zos != null) {
- zos.close();
- }
- }
-
- return bytes;
- }
-
- public void putEntryIntoZipOutputStream(ZipOutputStream zos, InputStream is, String entryName) throws JAXBException, IOException {
- zos.putNextEntry(new ZipEntry(entryName));
- byte[] byteChunk = new byte[4096];
- int n;
- while ((n = is.read(byteChunk)) > 0) {
- zos.write(byteChunk, 0, n);
- }
- }
-
- /**
- * Génère une pièce jointe au format zip compatible avec le webservice iXbus à partir d'un flux entrant. Une fois lu le flux est fermé.
- *
- * @param is
- * Flux entrant
- * @return
- * @throws ClientException
- */
- public Attachment createPjFromStream(InputStream is, String name) throws ClientException {
- Attachment attach = null;
-
- try {
- byte[] bytes = zipStream(is, name);
- attach = new AttachmentCfxImpl();
- attach.setContent(bytes);
- attach.setSize(bytes.length);
- } catch (Exception e) {
- throw new ClientException(e);
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- throw new ClientException(e);
- }
- }
- }
-
- return attach;
- }
-
- /**
- * Génère une pièce jointe au format zip compatible avec le webservice iXbus à partir d'un fichier réseau.
- *
- * @param file
- * @return
- * @throws ClientException
- */
- public Attachment createPjFromFile(File file, String name) throws ClientException {
- Attachment attach = null;
- InputStream is = null;
-
- try {
- if (file.exists()) {
- is = new FileInputStream(file);
- attach = createPjFromStream(is, name);
- } else {
- throw new ClientException("Aucun fichier présent à l'emplacement " + file.getName());
- }
- } catch (FileNotFoundException e) {
- throw new ClientException(e);
- }
-
- return attach;
- }
-
- /**
- * Retourne le type MIME d'un fichier en se basant uniquement sur l'extension Utilise la librairie activation.jar d'Oracle
- *
- * N.B. Il est possible d'ajouter un nouveau type MIME en créant un fichier META-INF/mime.types. (la liste par défaut se situe dans le fichier
- * META-INF/mimetypes.default (à l'intérieur d'activation.jar)
- *
- * Exemple de format d'entrée : text/html html htm HTML HTM
- *
- * @param file
- * @return
- */
- public String getContentType(File file) {
- return new MimetypesFileTypeMap().getContentType(file);
- }
-
- /**
- * Ouvre une connexion vers un flux HTTP en vue de télécharger une ressource Web
- *
- * @param url
- * @return
- * @throws ClientException
- */
- public HttpURLConnection openConnection(String url) throws ClientException {
- HttpURLConnection conn = null;
- try {
- conn = (HttpURLConnection) new URL(url).openConnection();
- int responseCode = conn.getResponseCode();
- if (responseCode != HttpURLConnection.HTTP_OK) {
- throw new ClientException("Aucun fichier n'a pu être téléchargé à l'URL " + url + ". Le serveur a répondu avec le code "
- + responseCode);
- }
- } catch (MalformedURLException e) {
- throw new ClientException(e);
- } catch (IOException e) {
- throw new ClientException(e);
- }
-
- return conn;
- }
-
- /**
- * Extrait l'attribut actes:IDActe de l'accusé de réception reçu du TdT
- *
- * TODO par la suite il faudrait parser plus finement le contenu XML de l'accusé de réception reçu du TdT en passant par JAXB comme on le fait
- * pour générer le fichier d'accompagement XML
- *
- * @param xmlAttachment
- * @return
- */
- public String getIDActe(Attachment xmlAttachment) {
- String numeroInterne = null;
- String xml = new String(xmlAttachment.getContent());
- String token = "actes:IDActe=\"";
- int begin = xml.indexOf(token);
- if (begin > 0) {
- begin += token.length();
- int end = xml.indexOf("\"", begin);
- if (end > 0) {
- numeroInterne = xml.substring(begin, end);
- }
- }
- return numeroInterne;
- }
-
- /**
- * Génère le fichier XML d'accompagnement d'une pièce jointe à envoyer au webservice iXbus
- *
- * @param attachment
- * @return
- * @throws ClientException
- */
- public Attachment createXmlAttachment(String actID, String actNature, String matiere, String subject) throws ClientException {
- Attachment attach = null;
-
- JAXBContext jc;
- ByteArrayOutputStream baos = null;
- try {
- jc = JAXBContext.newInstance("fr.srci.xmlschema.legalitycontrol");
- Marshaller marshaller = jc.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.srci.fr/XMLSchema/LegalityControl LegalityControl.xsd");
- baos = new ByteArrayOutputStream();
-
- //Comme legalityControl est un singleton Spring il vaut mieux éviter les pb liés au multithread
- synchronized(LegalityControl.class){
- Date now = new Date();
- legalityControl.getTransaction().setActDate(dateFormat.format(now));
- legalityControl.getTransaction().setActID(actID);
- legalityControl.getTransaction().setActNature(actNature);
- legalityControl.getTransaction().setContent(matiere);
- legalityControl.getTransaction().setSubject(validateSubject(subject));
- marshaller.marshal(legalityControl, baos);
- }
-
- baos.flush();
- String s = new String(baos.toByteArray());
- int beginIndex = s.indexOf(">");
-
- // On modifie à la main l'entête du fichier XML généré
- // (la méthode proposée pour ce faire par l'implémentation officielle de JAXB semble confuse et pas très robuste)
- if (beginIndex > 0) {
- s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + s.substring(0, beginIndex)
- + " xmlns:rt=\"urn:oasis:names:tc:ubl:RepresentationTerms:1:0-beta\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xsi:type=\"CLtoMISILLType\"" + s.substring(beginIndex);
- }
-
- // On ajoute à la main un attribut xsi:type au noeud Transaction
- s = s.replace("<Transaction>", "<Transaction xsi:type=\"ActType\">");
-
- byte[] bytes = s.getBytes();
-
- attach = new AttachmentCfxImpl();
- attach.setContent(bytes);
- attach.setSize(bytes.length);
- } catch (Exception e) {
- throw new ClientException(e);
- } finally {
- if (baos != null) {
- try {
- baos.close();
- } catch (IOException e) {
- throw new ClientException(e);
- }
- }
- }
-
- return attach;
- }
-
- /**
- * Permet de nettoyer le sujet de l'envoi des caractères interdits (code tiré de sources envoyées par la mairie de Bordeaux
- *
- * @param libelle
- * @return
- */
- private String validateSubject(String libelle) {
- String validSubject = libelle;
- char quote = (char) 146; // '’'
- char euro = (char) 128; // '\u20AC';
- char demiCadratin = (char) 150; // '\u2013';
- validSubject = validSubject.replace(quote, '\'');
- validSubject = validSubject.replace(euro, 'E');
- validSubject = validSubject.replace(demiCadratin, '-');
- return validSubject;
- }
-
- /**
- * Génère le flux XML à inclure dans la zone commentaire de l'archive ZIP à envoyer au serveur iXbus
- *
- * Le flux généré est de la forme suivante : {@code
- * <?xml version="1.0" encoding="ISO-8859-1"?>
- * <Attachment>
- * <MainDocument>test_doc_principal.pdf</MainDocument>
- * <Annexe>TEST_AvecOCR.pdf</Annexe>
- * <Annexe>test.pdf</Annexe>
- * </Attachment>
- * }
- *
- * @param mainDocument
- * @param annexes
- * @return
- * @throws ClientException
- */
- public static String createAttachmentDescription(String mainDocument, List<String> annexes) throws JAXBException, IOException {
- String desc = null;
- ObjectFactory factory = new ObjectFactory();
- fr.mbdx.ixbus.pj.Attachment attach = factory.createAttachment();
- attach.setMainDocument(mainDocument);
- if (annexes != null) {
- for (String annexe : annexes) {
- attach.getAnnexe().add(annexe);
- }
- }
- JAXBContext jc;
- ByteArrayOutputStream baos = null;
- try {
- jc = JAXBContext.newInstance("fr.mbdx.ixbus.pj");
- Marshaller marshaller = jc.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-1");
- marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
- baos = new ByteArrayOutputStream();
- marshaller.marshal(attach, baos);
- baos.flush();
- desc = new String(baos.toByteArray());
- } finally {
- if (baos != null) {
- baos.close();
- }
- }
-
- return "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + desc;
- }
-
- /**
- * Génère un nom de fichier XML en principe unique composé de la manière suivante :
- * <IdentifiantEditeur>_<CodeUtilisateur>_<SIREN>_<Date>_<Heure>_<NomFichier.xml> (Cf. p. 5 Specifications_WebService_iXBxx_R1.0.doc)
- *
- * @param filename
- * @return
- */
- public String getUniqueFileName(String filename) {
- Date now = new Date();
-
- String result = client.getIdentifiantSpecifique() + "_" + client.getCodeUtilisateur() + "_" + legalityControl.getIssuer().getSIREN() + "_"
- + dateFormat2.format(now) + "_" + filename;
-
- return result;
- }
-
- /**
- * @param content
- * @return
- */
- public byte[] removeZeroBytes(byte[] content) {
- int i;
- for (i = 0; i < content.length; i++) {
- if (content[i] == 0) {
- break;
- }
- }
- byte[] cleanContent = new byte[i];
- System.arraycopy(content, 0, cleanContent, 0, i);
- return cleanContent;
- }
-
- public void saveAttachment(Attachment attachment) {
- BufferedOutputStream bos = null;
- try {
- String name = attachment.getName().isEmpty() ? "attachment.xml" : attachment.getName();
-
- int pos = name.indexOf(".");
- String prefix = pos > 0 ? name.substring(0, pos) : name;
- String suffix = pos > 0 ? name.substring(pos) : ".tmp";
- File temp = File.createTempFile(prefix, suffix);
- log.debug("Attachement : " + temp.getAbsolutePath());
- FileOutputStream fos = new FileOutputStream(temp);
- bos = new BufferedOutputStream(fos);
- bos.write(attachment.getContent());
- } catch (Exception e) {
- log.error(e.getMessage(), e);
- } finally {
- if (bos != null) {
- try {
- bos.close();
- } catch (IOException e) {
- log.error(e.getMessage(), e);
- }
- }
- }
- }
-
- public static String replaceFileExtension(String filename, String extension) {
- int endIndex = filename.lastIndexOf(".");
- if (endIndex > 0) {
- filename = filename.substring(0, endIndex);
- }
- return filename + extension;
- }
-
- /**
- * @return the client
- */
- public ClientCxfImpl getClient() {
- return client;
- }
-
- /**
- * @param client
- * the client to set
- */
- public void setClient(ClientCxfImpl client) {
- this.client = client;
- }
-
- /**
- * @return the legalityControl
- */
- public LegalityControl getLegalityControl() {
- return legalityControl;
- }
-
- /**
- * @param legalityControl
- * the legalityControl to set
- */
- public void setLegalityControl(LegalityControl legalityControl) {
- this.legalityControl = legalityControl;
- }
-}