package server; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import models.Configuration; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.apache.thrift.TException; import server.generated.User; import server.generated.Image; import server.generated.Lecture; import server.generated.Server; import server.generated.Person; import com.mysql.jdbc.StringUtils; import sql.SQL; import util.XMLCreator; public class ServerHandler implements Server.Iface { static SQL sql = new SQL(); private static Logger log = Logger.getLogger(ServerHandler.class); @Override public User getFtpUser() throws TException { log.info("returning FTPUser..."); User user = new User(); user.setUserName(UUID.randomUUID().toString().substring(0, 8)); user.setPassword(getEncodedSha1Sum(UUID.randomUUID().toString() .substring(0, 8))); if (Configuration.config.getAbsolute_path().endsWith("/")) { user.setPath(Configuration.config.getAbsolute_path()); } else { user.setPath(Configuration.config.getAbsolute_path() + "/"); } // check if folder temp and folder prod exist if (folderTempExists() == true && folderProdExists() == true) { sql.writeFTPUser(user.getUserName(), user.getPassword()); return user; } else { log.info("Error: returning null user"); return null; } } public boolean folderTempExists() { // check if folder temp exists, otherwise create it Path path = null; if (Configuration.config.getAbsolute_path().endsWith("/")) { path = Paths.get(Configuration.config.getAbsolute_path() + "temp"); } else { path = Paths.get(Configuration.config.getAbsolute_path() + "/temp"); } if (Files.exists(path) == true) { log.info("folder '" + path + "' exists, no further action"); return true; } else { // create directory and set permissions boolean success = (new File(path + "")).mkdirs(); if (!success) { log.info("failed to create folder '" + path + "'"); return false; } else { // set permissions try { Runtime.getRuntime().exec("chmod 777 " + path); } catch (IOException e) { e.printStackTrace(); } log.info("folder '" + path + "' successfully created"); return true; } } }// end folderTempExists() public boolean folderProdExists() { // check if folder temp exists, otherwise create it Path path = null; if (Configuration.config.getAbsolute_path().endsWith("/")) { path = Paths.get(Configuration.config.getAbsolute_path() + "prod"); } else { path = Paths.get(Configuration.config.getAbsolute_path() + "/prod"); } if (Files.exists(path) == true) { log.info("folder '" + path + "' exists, no further action"); return true; } else { // create directory and set permissions boolean success = (new File(path + "")).mkdirs(); if (!success) { log.info("failed to create folder '" + path + "'"); return false; } else { // set permissions try { Runtime.getRuntime().exec("chmod 777 " + path); } catch (IOException e) { e.printStackTrace(); } log.info("folder '" + path + "' successfully created"); return true; } } }// end folderProdExists() public String getEncodedSha1Sum(String key) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(key.getBytes()); log.info("successfully returned EncodedSha1Sum"); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { // handle error case to taste } return null; } @Override public long DeleteFtpUser(String user) throws TException { return sql.DeleteUser(user); } @Override public String getPathOfImage(String image_id, String version) throws TException { log.info("successfully returned PathOfImage: " + sql.getPathOfImage(image_id, version)); return sql.getPathOfImage(image_id, version); } @Override public String setInstitution(String university) { return sql.setInstitution(university); } @Override public boolean writeVLdata(String imagename, String desc, String login, String firstname, String lastname, String university, String Mail, String Tel, String Fak, boolean license, boolean internet, long ram, long cpu, String imagePath, boolean isTemplate, long filesize, long shareMode, String os) throws TException { String mode = null; if (shareMode == 0) { mode = "only_local"; } else { mode = "to_be_published"; } // String pk_institution = sql.setInstitution(university); // String pk_person = sql.setPerson(login, lastname, firstname, Mail, // new Date(), pk_institution); // OS impl Select and write // ACHTUNG: Anzahl der Leerzeichen muss eingehalten werden: 'Windows 7 // 32 bit" String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)), os .substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")) .replace(" ", "")); // sql.setImageData(pk_person, license, internet, cpu, ram, // imagename,desc, imagePath, filesize,mode,pk_os); sql.setImageData(login, license, internet, cpu, ram, imagename, desc, imagePath, filesize, mode, pk_os); log.info("written VLdata"); return true; } @Override public List getImageListPermissionWrite(String userID) throws TException { return sql.getImageListPermissionWrite(userID); } @Override public List getImageListPermissionRead(String userID) throws TException { return sql.getImageListPermissionRead(userID); } @Override public List getImageListPermissionLink(String userID) throws TException { return sql.getImageListPermissionLink(userID); } @Override public List getImageListPermissionAdmin(String userID) throws TException { return sql.getImageListPermissionAdmin(userID); } @Override public List getImageListAllTemplates() throws TException { return sql.getImageListAllTemplates(); } @Override public List getAllOS() throws TException { return sql.getAllOS(); } @Override public Map getPersonData(String Vorname, String Nachname) throws TException { return sql.getPersonData(Vorname, Nachname); } public void setPerson(String login, String lastname, String firstname, String mail, String Institution) { sql.setPerson(login, lastname, firstname, mail, new Date(), Institution); } @Override public boolean writeLecturedata(String name, String shortdesc, String desc, String startDate, String endDate, boolean isActive, String imagename, String login, String firstname, String lastname, String university, String Mail, String Tel, String Fak) throws TException { String pk_image = null; Map map = new HashMap(); int imageversion = 0; String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(login, lastname, firstname, Mail, new Date(), pk_institution); map = sql.getImageIDandVersion(imagename); pk_image = map.get("GUID"); imageversion = Integer.parseInt(map.get("version")); sql.setLectureData(pk_person, pk_image, imageversion, name, desc, shortdesc, startDate, endDate, isActive); XMLCreator xml = new XMLCreator(sql.getConnection(), name); try { xml.create(name); log.info("XML created."); } catch (SQLException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } return false; } @Override public boolean startFileCopy(String filename) throws TException { // copy file from folder temp to folder prod String file = Configuration.config.getAbsolute_path() + "temp/" + filename; File tmpFile = new File(file); log.info("Trying to move file to '/srv/openslx/nfs/prod/" + tmpFile.getName() + "'"); try { FileUtils.moveFile(tmpFile, new File(Configuration.config.getAbsolute_path() + "prod/" + filename)); // int ret = sql.UpdateImagePath(filename); if (sql.UpdateImagePath(filename) == 0) { log.info("file moved and database updated."); } } catch (IOException e) { log.info("Failed to move file."); e.printStackTrace(); } return true; } @Override public Map getImageData(String imageid, String imageversion) throws TException { log.info("returning ImageData: " + sql.getImageData(imageid, imageversion).size() + "items."); return sql.getImageData(imageid, imageversion); } @Override public boolean updateImageData(String name, String newName, String desc, String image_path, boolean license, boolean internet, long ram, long cpu, String id, String version, boolean isTemplate, long filesize, long shareMode, String os) throws TException { String mode = null; if (shareMode == 0) { mode = "only_local"; } else { mode = "to_be_published"; } String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)), os .substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")) .replace(" ", "")); sql.UpdateImageData(name, newName, desc, image_path, license, internet, cpu, ram, id, version, isTemplate, filesize, mode, pk_os); return false; } @Override public List getLectureList() throws TException { log.info("returning LectureList"); return sql.getLectureList(); } @Override public List getLectureListPermissionRead(String userID) { log.info("returning LectureListRead"); return sql.getLectureListPermissionRead(userID); }// end getLectureListPermissionRead @Override public List getLectureListPermissionWrite(String userID) { log.info("returning LectureListWrite"); return sql.getLectureListPermissionWrite(userID); }// end getLectureListPermissionRead @Override public List getLectureListPermissionAdmin(String userID) { log.info("returning LectureListAdmin"); return sql.getLectureListPermissionAdmin(userID); }// end getLectureListPermissionRead @Override public boolean updateLecturedata(String name, String newName, String shortdesc, String desc, String startDate, String endDate, boolean isActive, String imageid, String imageversion, String user, String firstname, String lastname, String university, String Mail, String Tel, String Fak, String id) throws TException { Map map = new HashMap(); map = sql.getDeleteXMLData(id); sql.updateLectureData(imageid, imageversion, lastname, newName, desc, shortdesc, startDate, endDate, isActive, id); String path = Configuration.config.getAbsolute_path() + "prod/" + map.get("date").substring(0, map.get("date").length() - 2) + "_" + university + "_" + user + "_" + map.get("name") + ".xml"; File tmpFile = new File(path); try { FileUtils.forceDelete(tmpFile); } catch (IOException e1) { e1.printStackTrace(); } XMLCreator xml = new XMLCreator(sql.getConnection(), newName); try { xml.create(newName); } catch (SQLException | ParserConfigurationException | TransformerException e) { e.printStackTrace(); } return false; } @Override public boolean deleteImageServer(String imageid, String imageversion) throws TException { String stringFile = sql.getFile(imageid, imageversion); log.info(new Date() + " - File to Delete: " + stringFile); File tmpFile = new File(Configuration.config.getAbsolute_path() + stringFile); try { // File wird von Server gelöscht FileUtils.forceDelete(tmpFile); return true; } catch (IOException e) { log.info(new Date() + " - Failed to execute deleteImageServer."); e.printStackTrace(); } return false; } @Override public boolean deleteImageData(String id, String version) throws TException { boolean success=false; if(sql.deleteImage(id, version)==true){ success=true; log.info("Image '"+id+"' and permissions successfully deleted."); } return success; } @Override public boolean connectedToLecture(String id, String version) throws TException { return sql.connectedToLecture(id, version); } public boolean deleteLecture(String id, String hs, String user) { boolean success = false; Map map = new HashMap(); map = sql.getDeleteXMLData(id); try { String path = Configuration.config.getAbsolute_path() + "prod/" + map.get("date") .substring(0, map.get("date").length() - 2) + "_" + hs + "_" + user + "_" + map.get("name") + ".xml"; File xmlFile = new File(path); FileUtils.forceDelete(xmlFile); } catch (IOException e) { log.info(new Date() + " - Failed to execute deleteLecture"); e.printStackTrace(); } if(sql.deleteLecture(id) == true){ success = true; log.info("Lecture '"+id+"' and permissions successfully deleted."); } return success; } @Override public List getAllUniversities() throws TException { return sql.getAllUniversities(); } @Override public Map getLectureData(String lectureid) throws TException { log.info("returning LectureData"); return sql.getLectureData(lectureid); } public static int nthIndexOf(final String string, final String token, final int index) { int j = 0; for (int i = 0; i < index; i++) { j = string.indexOf(token, j + 1); if (j == -1) break; } return j; } @Override public boolean checkUser(String username) throws TException { return sql.checkUser(username); } @Override public boolean createUser(String loginName, String lastName, String firstName, String mail, String university) throws TException { String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(loginName, lastName, firstName, mail, new Date(), pk_institution); return true; } @Override public boolean writeImageRights(String imagename, String username, String lastName, String firstName, String mail, String university, String role) throws TException { String pk_image = null; Map map = new HashMap(); int imageversion = 0; String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(username, lastName, firstName, mail, new Date(), pk_institution); map = sql.getImageIDandVersion(imagename); //TODO do not look for the ID. Instead, give it to server from pk_image = map.get("GUID"); imageversion = Integer.parseInt(map.get("version")); if (role.equals("Dozent")) { int read = 1; int write = 1; // int changePermission=0; int admin = 1; int linkallowed = 1; int roleID = sql.getRoleID(role); sql.setImageRights(pk_person, pk_image, roleID, read, write, admin, linkallowed); } else if (role.equals("Admin")) { int read = 1; int write = 1; // int changePermission=1; int admin = 1; int linkallowed = 1; int roleID = sql.getRoleID(role); sql.setImageRights(pk_person, pk_image, roleID, read, write, admin, linkallowed); } else { int read = 1; int write = 0; // int changePermission=0; int admin = 0; int linkallowed = 0; int roleID = sql.getRoleID(role); sql.setImageRights(pk_person, pk_image, roleID, read, write, admin, linkallowed); } log.info("written image rights"); return true; } @Override public boolean writeLectureRights(String lecturename, String username, String lastName, String firstName, String mail, String university, String role) throws TException { String pk_lecture = null; String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(username, lastName, firstName, mail, new Date(), pk_institution); pk_lecture = sql.getLectureID(lecturename); if (role.equals("Dozent")) { int read = 1; int write = 1; // int changePermission=0; int admin = 1; int roleID = sql.getRoleID(role); sql.setLectureRights(pk_person, pk_lecture, roleID, read, write, admin); } else if (role.equals("Admin")) { int read = 1; int write = 1; // int changePermission=1; int admin = 1; int roleID = sql.getRoleID(role); sql.setLectureRights(pk_person, pk_lecture, roleID, read, write, admin); } else { int read = 0; int write = 0; // int changePermission=0; int admin = 0; int roleID = sql.getRoleID(role); sql.setLectureRights(pk_person, pk_lecture, roleID, read, write, admin); } return true; } @Override public List getAllOtherSatelliteUsers(List userID) throws TException { return sql.getAllOtherSatelliteUsers(userID); // return null; } //set permissions for users which are !=userID public boolean writeAdditionalImageRights(String imageName, String userID, boolean isRead, boolean isWrite, boolean isLinkAllowed, boolean isAdmin) { boolean success = false; Map map = new HashMap(); map = sql.getImageIDandVersion(imageName); String imageID = map.get("GUID"); sql.writeAdditionalImageRights(imageID, userID, isRead, isWrite, isLinkAllowed, isAdmin); log.info("written additional image rights for " + userID); return success; } public boolean writeAdditionalLectureRights(String lectureName, String userID, boolean isRead, boolean isWrite, boolean isAdmin) { Map map = new HashMap(); String lectureID = sql.getLectureID(lectureName); sql.writeAdditionalLectureRights(lectureID, userID, isRead, isWrite, isAdmin); log.info("written additional lecture rights for "+ userID); return true; } @Override public List getPermissionForUserAndImage(String userID, String imageID) throws TException { return sql.getPermissionForUserAndImage(userID, imageID); } public List getPermissionForUserAndLecture(String userID, String lectureID) { return sql.getPermissionForUserAndLecture(userID, lectureID); } @Override public void deleteAllAdditionalImagePermissions(String imageID, String userID) throws TException { sql.deleteAllAdditionalImagePermissions(imageID, userID); return; } @Override public void deleteAllAdditionalLecturePermissions(String lectureID, String userID) throws TException { sql.deleteAllAdditionalLecturePermissions(lectureID, userID); return; } @Override public List getImageList(String userID) throws TException { return sql.getImageList(userID); } @Override public List getAdditionalImageContacts(String imageID) throws TException { return sql.getAdditionalImageContacts(imageID); } @Override public String getOsNameForGuestOs(String guestOS) throws TException { return sql.getOsNameForGuestOs(guestOS); } @Override public Map getItemOwner(String itemID) throws TException { return sql.getItemOwner(itemID); } }// end class