20 package cz.vutbr.fit.knot.annotations.comet;
31 import java.io.BufferedReader;
32 import java.io.IOException;
33 import java.io.PrintWriter;
34 import java.io.StringReader;
35 import java.io.StringWriter;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.ListIterator;
42 import java.util.logging.Level;
43 import java.util.logging.Logger;
44 import javax.persistence.EntityManager;
45 import javax.persistence.EntityTransaction;
46 import javax.servlet.ServletException;
47 import javax.servlet.http.HttpServlet;
48 import javax.servlet.http.HttpServletRequest;
49 import javax.servlet.http.HttpServletResponse;
50 import javax.xml.parsers.DocumentBuilder;
51 import javax.xml.parsers.DocumentBuilderFactory;
52 import javax.xml.parsers.ParserConfigurationException;
53 import org.w3c.dom.Document;
54 import org.w3c.dom.Element;
55 import org.w3c.dom.NodeList;
56 import org.xml.sax.InputSource;
57 import org.xml.sax.SAXException;
78 protected void doGet(HttpServletRequest request, HttpServletResponse response)
79 throws ServletException, IOException {
80 response.setContentType(
"text/html;charset=UTF-8");
81 PrintWriter out = response.getWriter();
85 Logger.getLogger(DrupAuthServlet.class.getName()).log(Level.ALL,
"GET request on DrupAuthServlet");
101 protected void doPost(HttpServletRequest request, HttpServletResponse response)
102 throws ServletException, IOException {
103 BufferedReader bufReader = request.getReader();
105 String responseString =
"OK";
109 StringWriter writer =
new StringWriter();
111 while ((nextChar = bufReader.read()) != -1) {
112 writer.write(nextChar);
114 String requestStr = writer.toString();
117 Document doc =
parseXml(requestStr);
120 String msg =
"Bad XML received from Drupal: " + requestStr;
121 Logger.getLogger(DrupAuthServlet.class.getName()).log(Level.ALL, msg);
123 throw new RuntimeException(
"Bad data sent!");
125 Element docEl = doc.getDocumentElement();
127 ArrayList<User> users =
new ArrayList<User>();
128 Map<String,String> authData =
new HashMap<String, String>();
130 String drupalAddress =
"";
132 NodeList drupalNL = docEl.getElementsByTagName(
"drupal");
133 Element drupalEl = (Element) drupalNL.item(0);
134 if (drupalEl != null) {
135 drupalAddress = drupalEl.getAttribute(
"address");
136 if (drupalAddress == null) {
141 if (drupalAddress.isEmpty()) {
143 Logger.getLogger(DrupAuthServlet.class.getName()).log(Level.SEVERE,
"Missing Drupal address.");
145 throw new RuntimeException(
"No drupal address included!");
148 String remoteAddr = request.getRemoteAddr();
149 String remoteHost = request.getRemoteHost();
153 String msg =
"Bad IP of Drupal: " + remoteAddr;
154 Logger.getLogger(DrupAuthServlet.class.getName()).log(Level.ALL, msg);
156 throw new RuntimeException(
"Bad IP");
161 String msg =
"Bad host of Drupal: " + remoteHost;
162 Logger.getLogger(DrupAuthServlet.class.getName()).log(Level.ALL, msg);
164 throw new RuntimeException(
"Bad Host Name");
167 NodeList userNodes = docEl.getElementsByTagName(
"user");
168 int uCount = userNodes.getLength();
169 for (
int i = 0; i < uCount; i++) {
170 Element userEl = (Element) userNodes.item(i);
176 String msg =
"Bad entry in authentication data from Drupal " + drupalAddress
177 +
" " + userEl.toString();
178 Logger.getLogger(DrupAuthServlet.class.getName()).log(Level.SEVERE, msg);
180 throw new RuntimeException(
"Bad entry found!");
186 }
catch (Exception e) {
188 String msg =
"Unknown exception:";
189 Logger.getLogger(DrupAuthServlet.class.getName()).log(Level.SEVERE, msg, e);
195 PrintWriter resWriter = response.getWriter();
196 resWriter.write(responseString);
207 private void saveUsers(List users, Map<String, String> aData) {
208 EntityManager em = AppBean.getPersistenceManager().getEM();
209 EntityTransaction transaction = em.getTransaction();
210 boolean errorOccurred =
false;
215 for (Iterator uIt = users.iterator(); uIt.hasNext();) {
217 ArrayList<UserGroup> groups = user.getGroupsAL();
218 user.setGroups(null);
220 user = em.merge(user);
222 for (Iterator<UserGroup> gIt = groups.iterator(); gIt.hasNext();) {
225 if (!ug.getUsers().contains(user)) {
233 transaction.commit();
235 }
catch (Exception e) {
237 String msg =
"Saving of users failed.";
238 Logger.getLogger(DrupAuthServlet.class.getName()).log(Level.SEVERE, msg, e);
240 transaction.rollback();
241 errorOccurred =
true;
246 throw new RuntimeException(
"Database failure!");
249 for (Iterator uIt = users.iterator(); uIt.hasNext();) {
252 if(user.
getId() == null){
255 Object[] params = {
"login",user.getLogin(),
"comeFrom",user.
getComeFrom()};
256 @SuppressWarnings(
"unchecked")
257 List<User> userList = AppBean.getPersistenceManager().queryDB(
"User.findByLoginAndSystem",params);
259 if(userList != null){
261 if(resultError != null){
262 throw(
new RuntimeException(
"Error occured during default user settings save procedure."));
264 }
else throw(
new RuntimeException(
"Error: Can't find user."));
267 AppBean.setExtAuthData(user.getComeFrom(), user.
getLogin(), aData.get(user.getLogin()));
282 private User processUser(Element userEl, Map<String,String> authData, String drupalAddress) {
286 String loginAtt = userEl.getAttribute(
"login");
287 String tokenAtt = userEl.getAttribute(
"token");
288 String idAtt = userEl.getAttribute(
"id");
289 String nameAtt = userEl.getAttribute(
"name");
290 String passwordAtt = userEl.getAttribute(
"password");
291 String emailAtt = userEl.getAttribute(
"email");
292 if (loginAtt == null) {
295 if (tokenAtt == null) {
301 if (nameAtt == null) {
304 if (passwordAtt == null) {
307 if (emailAtt == null) {
311 if (loginAtt.isEmpty()) {
316 Object[] params =
new Object[4];
318 params[1] = loginAtt;
319 params[2] =
"comeFrom";
320 params[3] = drupalAddress;
321 List uList = AppBean.getPersistenceManager().queryDB(
"User.findByLoginAndSystem", params);
322 if (uList != null && !uList.isEmpty()) {
323 user = (
User) uList.get(0);
327 user =
new User(loginAtt, nameAtt, emailAtt, passwordAtt);
328 user.setGroups(
new ArrayList<UserGroup>());
332 user.setComeFrom(drupalAddress);
334 authData.put(loginAtt, tokenAtt);
336 NodeList groupsNL = userEl.getElementsByTagName(
"group");
337 int groupsCnt = groupsNL.getLength();
338 for (
int i = 0; i < groupsCnt; i++) {
339 Element gropEl = (Element) groupsNL.item(i);
340 String groupName = gropEl.getAttribute(
"name");
341 if (groupName == null) {
344 if (groupName.isEmpty()) {
350 params[1] = groupName;
351 List gList = AppBean.getPersistenceManager().queryDB(
"UserGroup.findByName", params);
352 if (gList != null && !gList.isEmpty()) {
355 user.addGroup(group);
371 String retString =
"<html>"
373 +
"<title>Error</title>"
376 +
"<h1>Access to this page is not allowed!</h1>"
388 private static Document
parseXml(String XMLString)
throws SAXException, ParserConfigurationException, IOException {
390 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
391 dbf.setNamespaceAware(
true);
393 DocumentBuilder db = dbf.newDocumentBuilder();
394 InputSource is =
new InputSource();
395 is.setCharacterStream(
new StringReader(XMLString));
408 return "Servlet which allows Drupal CMS to send informations about it's users";
412 @SuppressWarnings(
"unchecked")
413 List<DefaultSettings> settingsList = AppBean.getPersistenceManager().queryDB(
"DefaultSettings.findAll");
414 if(settingsList != null){
415 String errorMessageOut;
416 ListIterator<DefaultSettings> resultIt = settingsList.listIterator();
417 while(resultIt.hasNext()){
422 errorMessageOut = MessageProvider.getMessage(
"newUserSettingDBFailure");
424 String msg =
"Persisting of new user settings failed.";
425 Logger.getLogger(EditUser.class.getName()).log(Level.SEVERE, msg);
427 return errorMessageOut;
442 @SuppressWarnings(
"unchecked")
443 List<DrupAuthServer> results = AppBean.getPersistenceManager().getEntitiesByName(
"DrupAuthServer");
444 if(results == null || results.isEmpty()){
448 Iterator<DrupAuthServer> resultsIt = results.iterator();
449 if(resultsIt.hasNext()){
450 if(resultsIt.next().getIpAddress().equals(ipAdderess)){
465 @SuppressWarnings(
"unchecked")
466 List<DrupAuthServer> results = AppBean.getPersistenceManager().getEntitiesByName(
"DrupAuthServer");
467 if(results == null || results.isEmpty()){
471 Iterator<DrupAuthServer> resultsIt = results.iterator();
472 if(resultsIt.hasNext()){
473 if(resultsIt.next().getHostName().equals(hostName)){
static final int LOG_LEVEL_ALL_ERRORS
User processUser(Element userEl, Map< String, String > authData, String drupalAddress)
static final int LOG_LEVEL_SERVER_INTERNAL_ERRORS
boolean isAuthorizedByName(String hostName)
Singleton for storing global variables.
Class representing approved drupal authentization server.
Class for getting localized messages from message bundle.
static Document parseXml(String XMLString)
ArrayList< UserGroup > getGroupsAL()
static final int AUTH_DRUPAL
Servlet which allows Drupal CMS to send informations about it's users.
void doGet(HttpServletRequest request, HttpServletResponse response)
String loadDefaultSettings(User user)
Class representing user group.
Class representing parameter of user settings.
static final int LOG_LEVEL
Backbean for adding, editing and deleting of users.
static final int LOG_LEVEL_ALL
static PersistM getPersistenceManager()
Class representing parameter of default user settings.
static final int AUTH_DRUPAL_BY_HOST
static final int LOG_LEVEL_SERVER_ERRORS
void doPost(HttpServletRequest request, HttpServletResponse response)
void saveUsers(List users, Map< String, String > aData)
static final int AUTH_DRUPAL_BY_IP
boolean isAuthorizedByIp(String ipAdderess)