001/**
002 * Copyright (C) 2014  Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
003 *
004 * This file is part of Dicoogle/dicoogle.
005 *
006 * Dicoogle/dicoogle is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * Dicoogle/dicoogle is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with Dicoogle.  If not, see <http://www.gnu.org/licenses/>.
018 */
019package pt.ua.dicoogle.server.users;
020
021import org.slf4j.LoggerFactory;
022import org.xml.sax.Attributes;
023import org.xml.sax.InputSource;
024import org.xml.sax.SAXException;
025import org.xml.sax.XMLReader;
026import org.xml.sax.helpers.AttributesImpl;
027import org.xml.sax.helpers.DefaultHandler;
028import org.xml.sax.helpers.XMLReaderFactory;
029
030import javax.crypto.Cipher;
031import javax.xml.transform.OutputKeys;
032import javax.xml.transform.Transformer;
033import javax.xml.transform.TransformerConfigurationException;
034import javax.xml.transform.TransformerFactory;
035import javax.xml.transform.sax.SAXTransformerFactory;
036import javax.xml.transform.sax.TransformerHandler;
037import javax.xml.transform.stream.StreamResult;
038import java.io.*;
039import java.util.Iterator;
040
041/**
042 * This class saves the list of roles to XML
043 *
044 * @author Luís Bastião Silva <bastiao@bmd-software.com>
045 */
046public class RolesXML extends DefaultHandler
047{
048    private RolesStruct roles = RolesStruct.getInstance();
049    private boolean isRoles = false ;
050
051    private String rolename;
052
053
054
055    public RolesXML()
056    {
057        rolename = "";
058    }
059
060
061    @Override
062    public void startElement( String uri, String localName, String qName,
063            Attributes attribs )
064    {
065
066
067
068        if (localName.equals("Roles"))
069        {
070            isRoles = true ;
071        }
072        else if (this.isRoles && localName.equals("role"))
073        {
074            this.rolename = this.resolveAttrib("name", attribs, "xp");
075        }
076        
077    }
078
079
080    @Override
081    public void endElement( String uri, String localName, String qName )
082    {
083
084        if (localName.equals("Users"))
085        {
086            isRoles = false ;
087        }
088        else if( localName.equals( "role" ) )
089        {
090            roles.addRole(new Role(rolename));
091        }
092        
093    }
094
095     private String resolveAttrib( String attr, Attributes attribs, String defaultValue) {
096         String tmp = attribs.getValue(attr);
097         return (tmp!=null)?(tmp):(defaultValue);
098     }
099
100
101    public RolesStruct getXML()
102    {
103        roles.reset();
104        
105        try
106        {
107
108            FileInputStream fin = new FileInputStream("roles.xml");
109            ByteArrayOutputStream out = new ByteArrayOutputStream();
110            byte[] data = new byte[1024];
111            int bytesRead;
112
113            while ((bytesRead = fin.read(data)) != -1) {
114                out.write(data, 0, bytesRead);
115                out.flush();
116            }
117
118            byte[] xml = out.toByteArray();
119            
120            if (xml == null)
121            {
122
123                printXML();
124                return roles;
125            }
126
127
128            // Never throws the exception cause file not exists so need try catch
129            InputSource src = new InputSource( new ByteArrayInputStream(xml) );
130            XMLReader r = XMLReaderFactory.createXMLReader();
131            r.setContentHandler(this);
132            r.parse(src);
133            return roles;
134        }
135        catch (SAXException | IOException ex)
136        {
137            LoggerFactory.getLogger(RolesXML.class).error(ex.getMessage(), ex);
138        }
139        return null;
140    }
141
142    /**
143     * Print the roles information to the XML file
144     */
145    public void printXML()
146    {
147
148        ByteArrayOutputStream out = new ByteArrayOutputStream();
149       
150
151        PrintWriter pw = new PrintWriter(out);
152        StreamResult streamResult = new StreamResult(pw);
153        SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
154
155        TransformerHandler hd = null;
156        try
157        {
158            hd = tf.newTransformerHandler();
159        } catch (TransformerConfigurationException ex)
160        {
161            LoggerFactory.getLogger(RolesXML.class).error(ex.getMessage(), ex);
162        }
163        
164        Transformer serializer = hd.getTransformer();
165        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
166        serializer.setOutputProperty(OutputKeys.METHOD, "xml");
167        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
168        serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");   
169        try
170        {
171            hd.setResult(streamResult);
172            hd.startDocument();
173        } catch (SAXException ex)
174        {
175            LoggerFactory.getLogger(RolesXML.class).error(ex.getMessage(), ex);
176        }
177
178        AttributesImpl atts = new AttributesImpl();
179        try
180        {
181            //root element
182            hd.startElement("", "", "Roles", atts);
183
184            Iterator<Role> us = RolesStruct.getInstance().getRoles().iterator();
185
186            atts.clear();
187            while (us.hasNext())
188            {
189                Role role = us.next();
190                
191                atts.addAttribute("", "", "name", "", role.getName());
192
193                hd.startElement("", "", "role", atts);
194                atts.clear();
195                hd.endElement("", "", "role");
196            }
197            hd.endElement("", "", "Roles");
198
199
200            hd.endDocument();
201        } catch (SAXException ex)
202        {
203            LoggerFactory.getLogger(RolesXML.class).error(ex.getMessage(), ex);
204        }
205        finally {
206            try {
207                out.close();
208
209                printFile(out.toByteArray());
210
211            } catch (Exception ex) {
212                  LoggerFactory.getLogger(RolesXML.class).error(ex.getMessage(), ex);
213            }
214        }
215
216
217    }
218    /**
219     * Print one byte array in File
220     * Encrypt that file with the key
221     * @param bytes
222     */
223    public void printFile(byte[] bytes) throws Exception {
224        InputStream in;
225
226
227        in = new ByteArrayInputStream(bytes);
228
229        FileOutputStream out = new FileOutputStream("roles.xml");
230
231
232        byte[] input = new byte[1024];
233        int bytesRead;
234        while ((bytesRead = in.read(input)) != -1) {
235            out.write(input, 0, bytesRead);
236            out.flush();
237        }
238
239        out.close();
240        in.close();
241    }
242
243}