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 java.io.ByteArrayInputStream;
022import java.io.ByteArrayOutputStream;
023import java.io.IOException;
024import java.io.PrintWriter;
025import java.util.Iterator;
026
027import org.apache.commons.lang3.StringUtils;
028import org.slf4j.LoggerFactory;
029
030import javax.xml.transform.OutputKeys;
031import javax.xml.transform.Transformer;
032import javax.xml.transform.TransformerConfigurationException;
033import javax.xml.transform.TransformerFactory;
034import javax.xml.transform.sax.SAXTransformerFactory;
035import javax.xml.transform.sax.TransformerHandler;
036import javax.xml.transform.stream.StreamResult;
037
038import org.xml.sax.Attributes;
039import org.xml.sax.InputSource;
040import org.xml.sax.SAXException;
041import org.xml.sax.XMLReader;
042import org.xml.sax.helpers.AttributesImpl;
043import org.xml.sax.helpers.DefaultHandler;
044import org.xml.sax.helpers.XMLReaderFactory;
045
046/**
047 * This class saves the list of users to XML
048 *
049 * @author Samuel Campos <samuelcampos@ua.pt>
050 */
051public class UsersXML extends DefaultHandler
052{
053    private UsersStruct users = UsersStruct.getInstance();
054    private boolean isUsers = false ;
055
056    private String username;
057    private String Hash;
058    private boolean admin;
059    private String roles;
060
061
062    public UsersXML()
063    {
064        username = "";
065        Hash = "";
066        roles = "";
067        admin = false;
068    }
069
070
071    @Override
072    public void startElement( String uri, String localName, String qName,
073            Attributes attribs )
074    {
075
076
077
078        if (localName.equals("Users"))
079        {
080            isUsers = true ;
081        }
082        else if (this.isUsers && localName.equals("user"))
083        {
084            this.username = this.resolveAttrib("username", attribs, "xp");
085            this.Hash = this.resolveAttrib("hash", attribs, "xp");
086
087            String temp = this.resolveAttrib("admin", attribs, "xp");
088            if(temp.equals("true"))
089                this.admin = true;
090            else
091                this.admin = false;
092            this.roles = this.resolveAttrib("roles", attribs, "xp");
093
094        }
095        
096    }
097
098
099    @Override
100    public void endElement( String uri, String localName, String qName )
101    {
102
103        if (localName.equals("Users"))
104        {
105            isUsers = false ;
106        }
107        else if( localName.equals( "user" ) )
108        {
109
110            User u = new User(username, Hash, admin);
111            users.addUser(u);
112            if (roles!=null)
113            {
114                String [] rolesTmp = roles.split(",");
115                for (int i = 0; i<rolesTmp.length; i++)
116                {
117                    Role role = RolesStruct.getInstance().getRole(rolesTmp[i]);
118                    u.addRole(role);
119                }
120
121            }
122        }
123        
124    }
125
126     private String resolveAttrib( String attr, Attributes attribs, String defaultValue) {
127         String tmp = attribs.getValue(attr);
128         return (tmp!=null)?(tmp):(defaultValue);
129     }
130
131
132    public UsersStruct getXML()
133    {
134        users.reset();
135        
136        try
137        {
138            UserFileHandle file = new UserFileHandle();
139            byte[] xml = file.getFileContent();
140            
141            if (xml == null)
142            {
143                //DebugManager.getInstance().debug("Setting users default, writing a file with the default information!");
144                users.setDefaults();
145                printXML();
146                return users;
147            }
148
149
150            // Never throws the exception cause file not exists so need try catch
151            InputSource src = new InputSource( new ByteArrayInputStream(xml) );
152            XMLReader r = XMLReaderFactory.createXMLReader();
153            r.setContentHandler(this);
154            r.parse(src);
155            return users;
156        }
157        catch (SAXException | IOException ex)
158        {
159            LoggerFactory.getLogger(UsersXML.class).error(ex.getMessage(), ex);
160        }
161        return null;
162    }
163
164    /**
165     * Print the users information to the XML file
166     */
167    public void printXML()
168    {
169
170        ByteArrayOutputStream out = new ByteArrayOutputStream();
171       
172
173        PrintWriter pw = new PrintWriter(out);
174        StreamResult streamResult = new StreamResult(pw);
175        SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
176        //      SAX2.0 ContentHandler.
177        TransformerHandler hd = null;
178        try
179        {
180            hd = tf.newTransformerHandler();
181        } catch (TransformerConfigurationException ex)
182        {
183            LoggerFactory.getLogger(UsersXML.class).error(ex.getMessage(), ex);
184        }
185        
186        Transformer serializer = hd.getTransformer();
187        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
188        serializer.setOutputProperty(OutputKeys.METHOD, "xml");
189        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
190        serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");   
191        try
192        {
193            hd.setResult(streamResult);
194            hd.startDocument();
195        } catch (SAXException ex)
196        {
197            LoggerFactory.getLogger(UsersXML.class).error(ex.getMessage(), ex);
198        }
199
200        AttributesImpl atts = new AttributesImpl();
201        try
202        {
203            //root element
204            hd.startElement("", "", "Users", atts);
205
206            Iterator<User> us = UsersStruct.getInstance().getUsers().iterator();
207
208            atts.clear();
209            while (us.hasNext())
210            {
211                User user = us.next();
212                
213                atts.addAttribute("", "", "username", "", user.getUsername());
214                atts.addAttribute("", "", "hash", "", user.getPasswordHash()) ;
215
216                String temp = "false";
217                if(user.isAdmin())
218                    temp = "true";
219                if (user.getRoles()!=null&&user.getRoles().size()>0)
220                {
221                    String roles = "";
222                    for (Role r : user.getRoles())
223                    {
224                        roles+=r.getName()+",";
225                    }
226                    StringUtils.removeEnd(roles, ",");
227
228
229                    atts.addAttribute("", "", "roles", "", roles ) ;
230                }
231
232                atts.addAttribute("", "", "admin", "", temp) ;
233
234                hd.startElement("", "", "user", atts);
235                atts.clear();
236                hd.endElement("", "", "user");
237            }
238            hd.endElement("", "", "Users");
239
240
241            hd.endDocument();
242        } catch (SAXException ex)
243        {
244            LoggerFactory.getLogger(UsersXML.class).error(ex.getMessage(), ex);
245        }
246        finally {
247            try {
248                out.close();
249                
250                UserFileHandle file = new UserFileHandle();
251                file.printFile(out.toByteArray());
252            } catch (Exception ex) {
253                  LoggerFactory.getLogger(UsersXML.class).error(ex.getMessage(), ex);
254            }
255        }
256
257
258    }
259}