Системы электронного документооборота

Разработка универсальной системы электронного документооборота HotDoc с разграничением прав доступа пользователей, с эффективной системой поиска документа, с возможностью внедрения в различные организации. Реализация программы в виде веб-приложения.

Рубрика Программирование, компьютеры и кибернетика
Вид дипломная работа
Язык русский
Дата добавления 24.09.2012
Размер файла 5,5 M

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

request.setAttribute(USERS_LIST, users);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/users.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(USER_INFO)) {

String userId = request.getParameter(USER_ID);

User user = ugsi.getUserInfo(Long.parseLong(userId));

request.setAttribute(USER, user);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/userInfo.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(USER_IN_GROUPS)) {

String userId = request.getParameter(USER_ID);

User us = ugsi.getUserInfo(Long.parseLong(userId));

User user = new User(Long.parseLong(userId));

List<Group> groups = ugsi.listUserGroups(user);

request.setAttribute(GROUPS, groups);

request.setAttribute(USER, us);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/userInGroups.jsp");

requestDispatcher.include(request, response);

}

}

}

}

catch (Exception e) {

message = e.getMessage();

request.setAttribute(MESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/message.jsp");

requestDispatcher.include(request, response);

}

}

}

FileFolderTaskServlet

package ru.ksu.eldoc.web;

import ru.ksu.eldoc.objects.*;

import ru.ksu.eldoc.services.impl.*;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import javax.servlet.ServletException;

import javax.servlet.RequestDispatcher;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

public class FileFolderTaskServlet extends HttpServlet {

protected String url;

protected String driver;

protected String user;

protected String password;

// actions

public static final String FFT = "fft";

// parameters

public static final String LOGIN = "login";

public static final String PASSWORD = "password";

public static final String MESSAGE = "message";

public static final String USURNAME = "uSurname";

public static final String UNAME = "uName";

public static final String PATRONYMIC = "patronymic";

public static final String JOB = "job";

public static final String USER_ID = "uId";

public static final String FOLDERS = "folders";

public static final String NEW_DOCUMENT = "newDocument";

public static final String NEW_DOCUMENT_IN_FOLDER = "newDocumentInFolder";

public static final String MY_TASKS = "myTasks";

public static final String TASKS = "my_Tasks";

public static final String VERSION = "version";

public static final String VERSION_NUMBER = "number";

public static final String ADD_TASK = "addTask";

public static final String TASK_TO_FILE = "taskToFile";

public static final String ID = "id";

public static final String FOLDER_CONTENTS = "folderContents";

public static final String FOLDER_ID = "folderId";

public static final String FOL_ID = "folderId";

public static final String FROM_FOLDER = "fromFolder";

public static final String FROM_FOLDER_ID = "fromFolderId";

public static final String FILE_INFO = "fileInfo";

public static final String FILE_ID = "fileId";

public static final String FILEINFO = "fileinfo";

public static final String NEW_FILE = "newfile";

public static final String FILE_NAME = "fileName";

public static final String FILE_COMMENT = "comment";

public static final String FOLDER_TO_FILE = "ftf";

public static final String DAYS_OF_STORAGE = "storage";

public static final String NEWFILE = "newFile";

public static final String USERS = "users";

public static final String MY_ADDED_TASKS = "addedTasks";

public static final String ADDEDTASKS = "addedtasks";

public static final String DELETE_TASK = "deleteTask";

public static final String DELETED_TASK = "deletedTask";

public static final String ADD_TASK_TO_FILE = "addTaskToFile";

public static final String DELETE_FILE = "deleteFile";

public static final String MY_ADDED_FILES = "myAddedFiles";

public static final String MY_FILES = "myFiles";

public static final String USER_GROUP_ACCESS = "userGroupAccess";

public static final String USER_GROUP_ACCESS_POST = "userGroupAccess";

public static final String SHOW_FILE_ACCESS = "showFileAccess";

public static final String GROUP_ACCESS = "groupAccess";

public static final String EDIT_GROUP_ACCESS = "editGroupAccess";

public static final String USER_ACCESS = "userAccess";

public static final String EDIT_USER_ACCESS = "editUserAccess";

public static final String FILE = "file";

public static final String ALLGROUPS = "allgroups";

public static final String GROUPS = "groups";

public static final String FILE_ACCESS = "fileAccess";

public static final String EDIT_MY_TASKS = "editMyTasks";

public static final String EDIT_MY_ADDED_TASKS = "editMyAddedTasks";

public static final String DELETE_VERSION = "deleteVersion";

public static final String DELETE_ALL_VERSION = "deleteAllVersion";

public static final String NUMBER = "number";

public static final String FOLDER = "folder";

public static final String PAGE_NAME = "pageName";

public static final String TASKS_TO_FILE = "tasksToFile";

public static final String FILE_TASKS = "fileTasks";

public void init() throws ServletException {

super.init();

url = getInitParameter("url");

driver = getInitParameter("driver");

user = getInitParameter("user");

password = getInitParameter("password");

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setCharacterEncoding("utf-8");

response.setContentType("text/html");

String action = request.getParameter("action");

HttpSession session = request.getSession();

UserGroupServiceImpl ugsi;

FileFolderServiceImpl ffsi;

if (action == null) action = FFT;

String message = "";

try {

String login = (String) session.getAttribute(LOGIN);

String pass = (String) session.getAttribute(PASSWORD);

if (action != null) {

if (login == null)

response.sendRedirect(request.getContextPath() + "/auth");

else {

ugsi = new UserGroupServiceImpl(url, driver, user, password);

User u = ugsi.getUserInfo(login);

request.setAttribute(USER_ID, u.getId());

request.setAttribute(USURNAME, u.getSurname());

request.setAttribute(UNAME, u.getName());

request.setAttribute(PATRONYMIC, u.getPatronymic());

request.setAttribute(JOB, u.getJob());

ffsi = new FileFolderServiceImpl(url, driver, user, password);

if (action.equals(FFT)) {

} else if (action.equals(NEW_DOCUMENT_IN_FOLDER)) {

String folderId = (String) session.getAttribute(FOLDER);

request.setAttribute(FOLDER_ID, folderId);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/newDocumentInFolder.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(MY_TASKS)) {

TasksServiceImpl tsi = new TasksServiceImpl(url, driver, user, password);

List<MyTask> myTasks = tsi.showMyTasks(u);

request.setAttribute(TASKS, myTasks);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/myTasks.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(FOLDER_CONTENTS)) {

String folderId = request.getParameter(FOLDER_ID);

request.setAttribute(FROM_FOLDER_ID, folderId);

Folder f = new Folder(Long.parseLong(folderId));

request.setAttribute(FOLDER_ID, folderId);

FromFolder ff = ffsi.showFoldersAndFilesFromFolder(u, f);

request.setAttribute(FROM_FOLDER, ff);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/folderContents.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(FILE_INFO)) {

String fileId = request.getParameter(FILE_ID);

File f = new File(Long.parseLong(fileId));

FileToSee fInfo = ffsi.getInfOfFileToSee(f);

request.setAttribute(FILEINFO, fInfo);

request.setAttribute(FILE_ID, fileId);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/fileInfo.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(VERSION)) {

String fileId = request.getParameter(FILE_ID);

File f = new File(Long.parseLong(fileId));

request.setAttribute(FILE_ID, Long.parseLong(fileId));

FileToSee fInfo = ffsi.getInfOfFileToSee(f);

request.setAttribute(FILEINFO, fInfo);

List<Version> v = ffsi.showVersionOfFile(f);

request.setAttribute(VERSION_NUMBER, v);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/version.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(MY_ADDED_TASKS)) {

TasksServiceImpl tsi = new TasksServiceImpl(url, driver, user, password);

List<MyTask> myTasks = tsi.showMyAddedTasks(u);

request.setAttribute(ADDEDTASKS, myTasks);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/myAddedTasks.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(DELETE_TASK)) {

TasksServiceImpl tsi = new TasksServiceImpl(url, driver, user, password);

String taskId = request.getParameter(DELETED_TASK);

String fileId = request.getParameter(FILE_ID);

File f = new File(Long.parseLong(fileId));

MyTask myTask = new MyTask(Long.parseLong(taskId), f);

tsi.deleteTaskFromFile(myTask);

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.TASKS_TO_FILE + "&" + FileFolderTaskServlet.FILE_ID + "=" + fileId);

} else if (action.equals(ADD_TASK)) {

TasksServiceImpl tsi = new TasksServiceImpl(url, driver, user, password);

String fileId = request.getParameter(FILE_ID);

request.setAttribute(FILE_ID, Long.parseLong(fileId));

List<Tasks> tasks = tsi.showTasks();

request.setAttribute(TASK_TO_FILE, tasks);

List<User> users = ugsi.listUsers();

request.setAttribute(USERS, users);

File f = new File(Long.parseLong(fileId));

FileToSee fInfo = ffsi.getInfOfFileToSee(f);

request.setAttribute(FILEINFO, fInfo);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/addTaskToFile.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(MY_ADDED_FILES)) {

List<File> files = ffsi.showMyAddedFilesInfo(u);

request.setAttribute(MY_FILES, files);

// long name = 1;

//request.setAttribute(PAGE, name);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/myAddedFiles.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(TASKS_TO_FILE)) {

TasksServiceImpl tsi = new TasksServiceImpl(url, driver, user, password);

String fileId = request.getParameter(FILE_ID);

File file = new File(Long.parseLong(fileId));

FileToSee fInfo = ffsi.getInfOfFileToSee(file);

request.setAttribute(FILEINFO, fInfo);

List<MyTask> tasksToFile = tsi.showTasksToFile(file);

request.setAttribute(FILE_TASKS, tasksToFile);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/fileTasks.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(SHOW_FILE_ACCESS)) {

String fileId = request.getParameter(FILE_ID);

request.setAttribute(FILE_ID, fileId);

File f = new File(Long.parseLong(fileId));

FileToSee fInfo = ffsi.getInfOfFileToSee(f);

request.setAttribute(FILEINFO, fInfo);

FileAccess fa = ffsi.showMyFileAccess(f);

request.setAttribute(FILE_ACCESS, fa);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/showFileAccess.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(USER_GROUP_ACCESS)) {

String fileId = request.getParameter(FILE_ID);

request.setAttribute(FILE_ID, fileId);

File f = new File(Long.parseLong(fileId));

FileInfo fileInfo = ffsi.getInfOfFile(f);

request.setAttribute(FILEINFO, fileInfo);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/userGroupAccess.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(DELETE_FILE)) {

String fileId = request.getParameter(FILE_ID);

String folderId = request.getParameter(FOLDER_ID);

ru.ksu.eldoc.objects.File f = new ru.ksu.eldoc.objects.File(Long.parseLong(fileId));

ffsi = new FileFolderServiceImpl(url, driver, user, password);

String path1 = ffsi.getFileUrl(f);

String pathv = "";

java.io.File uploadetFile = new java.io.File(path1);

uploadetFile.delete();

int numb = ffsi.getNumberOfVersions(f);

for (int i = 2; i <= numb; i++) {

int num = path1.indexOf('.');

String sub1 = path1.substring(0, num);

String sub2 = path1.substring(num, path1.length());

String iS = String.valueOf(i);

if (iS.length() == 1)

pathv = sub1 + "#00" + iS + sub2;

else if (iS.length() == 2)

pathv = sub1 + "#0" + iS + sub2;

else if (iS.length() == 3)

pathv = sub1 + "#" + iS + sub2;

uploadetFile = new java.io.File(pathv);

uploadetFile.delete();

}

ffsi.deleteFile(f);

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.MY_ADDED_FILES);

} else if (action.equals(DELETE_VERSION)) {

String fileId = request.getParameter(FILE_ID);

String number = request.getParameter(VERSION_NUMBER);

ru.ksu.eldoc.objects.File f = new ru.ksu.eldoc.objects.File(Long.parseLong(fileId));

FileInfo fi = new FileInfo(Long.parseLong(fileId));

f.setFileinfo(fi);

int n = (int) Long.parseLong(number);

ffsi = new FileFolderServiceImpl(url, driver, user, password);

int numToPath = ffsi.getNumberToPathOfVersion(f, n);

String path = ffsi.getFileUrl(f);

String pathv = "";

int num = path.indexOf('.');

String sub1 = path.substring(0, num);

String sub2 = path.substring(num, path.length());

String iS = String.valueOf(numToPath);

if (iS.length() == 1)

pathv = sub1 + "#00" + iS + sub2;

else if (iS.length() == 2)

pathv = sub1 + "#0" + iS + sub2;

else if (iS.length() == 3)

pathv = sub1 + "#" + iS + sub2;

java.io.File uploadetFile = new java.io.File(pathv);

uploadetFile.delete();

ffsi.deleteVersion(f, n);

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.VERSION + "&" + FileFolderTaskServlet.FILE_ID + "=" + fileId);

}

}

}

}

catch (Exception e) {

message = e.getMessage();

request.setAttribute(MESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/message.jsp");

requestDispatcher.include(request, response);

}

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setCharacterEncoding("utf-8");

response.setContentType("text/html");

String action = request.getParameter("action");

HttpSession session = request.getSession();

UserGroupServiceImpl ugsi;

FileFolderServiceImpl ffsi;

String message = "";

try {

String login = (String) session.getAttribute(LOGIN);

String pass = (String) session.getAttribute(PASSWORD);

if (action != null) {

if (login == null)

response.sendRedirect(request.getContextPath() + "/auth");

else {

ugsi = new UserGroupServiceImpl(url, driver, user, password);

User u = ugsi.getUserInfo(login);

request.setAttribute(USURNAME, u.getSurname());

request.setAttribute(UNAME, u.getName());

request.setAttribute(PATRONYMIC, u.getPatronymic());

request.setAttribute(JOB, u.getJob());

if (action.equals(NEW_FILE)) {

String fName = request.getParameter(FILE_NAME);

String comment = request.getParameter(FILE_COMMENT);

String folderId = request.getParameter(FOLDER_TO_FILE);

String days = request.getParameter(DAYS_OF_STORAGE);

FileInfo fi = new FileInfo(u, Long.parseLong(days));

Folder folder = new Folder(Long.parseLong(folderId));

File f = new File(fName, comment, folder, fi);

ffsi = new FileFolderServiceImpl(url, driver, user, password);

ffsi.addFile2(f);

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.FOLDER_CONTENTS + "&" + FileFolderTaskServlet.FOLDER_ID + "=" + folderId);

} else if (action.equals(ADD_TASK_TO_FILE)) {

TasksServiceImpl tsi = new TasksServiceImpl(url, driver, user, password);

String fileId = request.getParameter(FILE_ID);

File f = new File(Long.parseLong(fileId));

String[] taskId = request.getParameterValues("task");

Tasks t = new Tasks(Long.parseLong(taskId[0]));

String[] userId = request.getParameterValues("user");

User user = new User(Long.parseLong(userId[0]));

MyTask myTask = new MyTask(t, f, user, u);

tsi.addTaskToFile(myTask);

MailLogger ml = new MailLogger();

String mess = "You have a new task";

String address = ugsi.getLogin(Long.parseLong(userId[0]));

ml.postMail(mess, address);

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.MY_ADDED_TASKS);

} else if (action.equals(USER_GROUP_ACCESS_POST)) {

String fileId = request.getParameter(FILE_ID);

request.setAttribute(FILE_ID, fileId);

File f = new File(Long.parseLong(fileId));

ffsi = new FileFolderServiceImpl(url, driver, user, password);

FileInfo fileInfo = ffsi.getInfOfFile(f);

request.setAttribute(FILEINFO, fileInfo);

String[] isAll = request.getParameterValues("isAll");

if (isAll[0].equals("yes")) {

ffsi.allowAllAccess(f);

message = "файл виден всем пользователям";

request.setAttribute(MESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/message.jsp");

requestDispatcher.include(request, response);

} else {

ffsi.denyAllAccess(f);

List<User> users = ugsi.listUsers();

request.setAttribute(USERS, users);

boolean userAccess[] = new boolean[users.size()];

for (int i = 0; i < users.size(); i++) {

User us = users.get(i);

userAccess[i] = ffsi.checkUserAccess(f, us);

}

request.setAttribute(USER_ACCESS, userAccess);

List<Group> groups = ugsi.listGroups();

request.setAttribute(ALLGROUPS, groups);

boolean groupAccess[] = new boolean[groups.size()];

for (int i = 0; i < groups.size(); i++) {

Group gs = groups.get(i);

groupAccess[i] = ffsi.checkGroupAccess(f, gs);

}

request.setAttribute(GROUP_ACCESS, groupAccess);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/editUserGroupAccess.jsp");

requestDispatcher.include(request, response);

}

} else if (action.equals(EDIT_USER_ACCESS)) {

String fileId = request.getParameter(FILE_ID);

request.setAttribute(FILE_ID, fileId);

File f = new File(Long.parseLong(fileId));

ffsi = new FileFolderServiceImpl(url, driver, user, password);

FileInfo fileInfo = ffsi.getInfOfFile(f);

request.setAttribute(FILEINFO, fileInfo);

String[] userIds = request.getParameterValues("users");

if (userIds != null) {

User[] checkedUsers = new User[userIds.length];

for (int i = 0; i < userIds.length; i++) {

checkedUsers[i] = new User(Long.parseLong(userIds[i]));

}

List<User> allUsers = ugsi.listUsers();

for (int i = 0; i < allUsers.size(); i++) {

User us = allUsers.get(i);

Long uId = us.getId();

boolean checked = false;

for (int j = 0; j < userIds.length; j++) {

if (uId == Long.parseLong(userIds[j])) {

checked = true;

break;

}

}

boolean allow = ffsi.checkUserAccess(f, us);

if (checked) {

if (!allow) {

ffsi.allowAccessToUser(f, us);

}

} else {

if (allow)

ffsi.denyAccessToUser(f, us);

}

}

} else {

List<User> allUsers = ugsi.listUsers();

for (int i = 0; i < allUsers.size(); i++) {

User us = allUsers.get(i);

boolean allow = ffsi.checkUserAccess(f, us);

if (allow)

ffsi.denyAccessToUser(f, us);

}

}

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.SHOW_FILE_ACCESS + "&" + FileFolderTaskServlet.FILE_ID + "=" + fileId + "&" + FileFolderTaskServlet.FILE_INFO + "=" + fileInfo);

} else if (action.equals(EDIT_GROUP_ACCESS)) {

String fileId = request.getParameter(FILE_ID);

request.setAttribute(FILE_ID, fileId);

File f = new File(Long.parseLong(fileId));

ffsi = new FileFolderServiceImpl(url, driver, user, password);

FileInfo fileInfo = ffsi.getInfOfFile(f);

request.setAttribute(FILEINFO, fileInfo);

String[] groupIds = request.getParameterValues("groups");

if (groupIds != null) {

User[] checkedGroups = new User[groupIds.length];

for (int i = 0; i < groupIds.length; i++) {

checkedGroups[i] = new User(Long.parseLong(groupIds[i]));

}

List<Group> allGroups = ugsi.listGroups();

for (int i = 0; i < allGroups.size(); i++) {

Group gs = allGroups.get(i);

Long gId = gs.getId();

boolean checked = false;

for (int j = 0; j < groupIds.length; j++) {

if (gId == Long.parseLong(groupIds[j])) {

checked = true;

break;

}

}

boolean allow = ffsi.checkGroupAccess(f, gs);

if (checked) {

if (!allow) {

ffsi.allowAccessToGroup(f, gs);

}

} else {

if (allow)

ffsi.denyAccessToGroup(f, gs);

}

}

} else {

List<Group> allGroups = ugsi.listGroups();

for (int i = 0; i < allGroups.size(); i++) {

Group gs = allGroups.get(i);

boolean allow = ffsi.checkGroupAccess(f, gs);

if (allow)

ffsi.denyAccessToGroup(f, gs);

}

}

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.SHOW_FILE_ACCESS + "&" + FileFolderTaskServlet.FILE_ID + "=" + fileId + "&" + FileFolderTaskServlet.FILE_INFO + "=" + fileInfo);

} else if (action.equals(EDIT_USER_ACCESS)) {

String fileId = request.getParameter(FILE_ID);

request.setAttribute(FILE_ID, fileId);

File f = new File(Long.parseLong(fileId));

ffsi = new FileFolderServiceImpl(url, driver, user, password);

FileInfo fileInfo = ffsi.getInfOfFile(f);

request.setAttribute(FILEINFO, fileInfo);

String[] userIds = request.getParameterValues("users");

if (userIds != null) {

User[] checkedUsers = new User[userIds.length];

for (int i = 0; i < userIds.length; i++) {

checkedUsers[i] = new User(Long.parseLong(userIds[i]));

}

List<User> allUsers = ugsi.listUsers();

for (int i = 0; i < allUsers.size(); i++) {

User us = allUsers.get(i);

Long uId = us.getId();

boolean checked = false;

for (int j = 0; j < userIds.length; j++) {

if (uId == Long.parseLong(userIds[j])) {

checked = true;

break;

}

}

boolean allow = ffsi.checkUserAccess(f, us);

if (checked) {

if (!allow) {

ffsi.allowAccessToUser(f, us);

}

} else {

if (allow)

ffsi.denyAccessToUser(f, us);

}

}

} else {

List<User> allUsers = ugsi.listUsers();

for (int i = 0; i < allUsers.size(); i++) {

User us = allUsers.get(i);

boolean allow = ffsi.checkUserAccess(f, us);

if (allow)

ffsi.denyAccessToUser(f, us);

}

}

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.SHOW_FILE_ACCESS + "&" + FileFolderTaskServlet.FILE_ID + "=" + fileId + "&" + FileFolderTaskServlet.FILE_INFO + "=" + fileInfo);

} else if (action.equals(EDIT_MY_TASKS)) {

ffsi = new FileFolderServiceImpl(url, driver, user, password);

String[] taskIds = request.getParameterValues("tasks");

TasksServiceImpl tsi = new TasksServiceImpl(url, driver, user, password);

if (taskIds != null) {

MyTask[] checkedTasks = new MyTask[taskIds.length];

for (int i = 0; i < taskIds.length; i++) {

checkedTasks[i] = new MyTask(Long.parseLong(taskIds[i]));

}

List<MyTask> allMyTasks = tsi.showMyTasks(u);

for (int i = 0; i < allMyTasks.size(); i++) {

MyTask t = allMyTasks.get(i);

Long tId = t.getId();

boolean checked = false;

for (int j = 0; j < taskIds.length; j++) {

if (tId == Long.parseLong(taskIds[j])) {

checked = true;

break;

}

}

boolean finished = tsi.isTaskFinished(t);

if (checked) {

if (!finished) {

tsi.taskIsFinished(t);

}

} else {

if (finished)

tsi.taskIsNotFinished(t);

}

}

} else {

List<MyTask> allMyTasks = tsi.showMyTasks(u);

for (int i = 0; i < allMyTasks.size(); i++) {

MyTask t = allMyTasks.get(i);

boolean finished = tsi.isTaskFinished(t);

if (finished)

tsi.taskIsNotFinished(t);

}

}

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.MY_TASKS);

} else if (action.equals(EDIT_MY_ADDED_TASKS)) {

ffsi = new FileFolderServiceImpl(url, driver, user, password);

String[] taskIds = request.getParameterValues("tasks");

TasksServiceImpl tsi = new TasksServiceImpl(url, driver, user, password);

if (taskIds != null) {

MyTask[] checkedTasks = new MyTask[taskIds.length];

for (int i = 0; i < taskIds.length; i++) {

checkedTasks[i] = new MyTask(Long.parseLong(taskIds[i]));

}

List<MyTask> allMyAddedTasks = tsi.showMyAddedTasks(u);

for (int i = 0; i < allMyAddedTasks.size(); i++) {

MyTask t = allMyAddedTasks.get(i);

Long tId = t.getId();

boolean checked = false;

for (int j = 0; j < taskIds.length; j++) {

if (tId == Long.parseLong(taskIds[j])) {

checked = true;

break;

}

}

boolean finished = tsi.isTaskFinished(t);

if (checked) {

if (!finished) {

tsi.taskIsFinished(t);

}

} else {

if (finished) {

tsi.taskIsNotFinished(t);

Long toUserId = tsi.getUserOfMyTask(t);

MailLogger ml = new MailLogger();

String mess = "Вы не выполнили задание!";

String address = ugsi.getLogin(toUserId);

ml.postMail(mess, address);

}

}

}

} else {

List<MyTask> allMyAddedTasks = tsi.showMyAddedTasks(u);

for (int i = 0; i < allMyAddedTasks.size(); i++) {

MyTask t = allMyAddedTasks.get(i);

boolean finished = tsi.isTaskFinished(t);

if (finished)

tsi.taskIsNotFinished(t);

Long toUserId = tsi.getUserOfMyTask(t);

MailLogger ml = new MailLogger();

String mess = "Вы не выполнили задание!";

String address = ugsi.getLogin(toUserId);

ml.postMail(mess, address);

}

}

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.MY_ADDED_TASKS);

} else if (action.equals(DELETE_ALL_VERSION)) {

ffsi = new FileFolderServiceImpl();

String fileId = request.getParameter(FILE_ID);

File f = new File(Long.parseLong(fileId));

FileInfo fi = new FileInfo(Long.parseLong(fileId));

f.setFileinfo(fi);

String[] deletedId = request.getParameterValues("deleted");

if (deletedId != null) {

int n = (int) (Long.parseLong(deletedId[0]));

int numb = ffsi.getNumberOfVersions(f);

String path1 = ffsi.getFileUrl(f);

String pathv = "";

for (int i = 2; i <= numb; i++) {

int numToPath = ffsi.getNumberToPathOfVersion(f, numb);

int num = path1.indexOf('.');

String sub1 = path1.substring(0, num);

String sub2 = path1.substring(num, path1.length());

String iS = String.valueOf(numToPath);

if (iS.length() == 1)

pathv = sub1 + "#00" + iS + sub2;

else if (iS.length() == 2)

pathv = sub1 + "#0" + iS + sub2;

else if (iS.length() == 3)

pathv = sub1 + "#" + iS + sub2;

java.io.File uploadetFile = new java.io.File(pathv);

uploadetFile.delete();

}

ffsi.deleteAllVersion(f, n);

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.VERSION + "&" + FileFolderTaskServlet.FILE_ID + "=" + fileId);

} else

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.VERSION + "&" + FileFolderTaskServlet.FILE_ID + "=" + fileId);

} else if (action.equals("testTree")) {

ffsi = new FileFolderServiceImpl(url, driver, user, password);

String folderId = request.getParameter("dir").replaceAll("\\/", "");

session.removeAttribute(FOLDER);

session.setAttribute(FOLDER, folderId);

long name = 2;

Folder f = new Folder(Long.parseLong(folderId));

FromFolder ff = ffsi.showFoldersAndFilesFromFolder(u, f);

PrintWriter out = response.getWriter();

out.print("<ul class=\"jqueryFileTree\" style=\"display: none;\">");

// All dirs

for (Folder folder: ff.getFolders()) {

out.print("<li class=\"directory collapsed\"><a href=\"#\" rel=\"" + folder.getId() + "/\">"

+ folder.getName() + "</a></li>");

}

// All files

for (File file: ff.getFiles()) {

int dotIndex = file.getName().lastIndexOf('.');

String ext = dotIndex > 0 ? file.getName().substring(dotIndex + 1): "";

out.print("<li class=\"file ext_" + ext + "\"><a href=\"#\" rel=\"" + +file.getId() + "\">"

+ file.getName() + "</a></li>");

}

out.print("</ul>");

}

}

}

}

catch (Exception

e) {

message = e.getMessage();

request.setAttribute(MESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/message.jsp");

requestDispatcher.include(request, response);

}

}

}

Upload

package ru.ksu.eldoc.web;

import java.io.File;

import java.io.IOException;

import java.util.Iterator;

import java.util.List;

import java.util.Random;

import java.util.Date;

import javax.servlet.ServletException;

import javax.servlet.RequestDispatcher;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import ru.ksu.eldoc.services.impl.UserGroupServiceImpl;

import ru.ksu.eldoc.services.impl.FileFolderServiceImpl;

import ru.ksu.eldoc.objects.User;

import ru.ksu.eldoc.objects.Group;

import ru.ksu.eldoc.objects.FileInfo;

import ru.ksu.eldoc.objects.Folder;

public class Upload extends HttpServlet {

private Random random = new Random();

protected String url;

protected String driver;

protected String user;

protected String password;

protected String path;

public static final String LOGIN = "login";

public static final String PASSWORD = "password";

public static final String EXIT = "exit";

public static final String MAIN_PAGE = "mainPage";

public static final String UPLOADMESSAGE = "message";

public static final String USURNAME = "uSurname";

public static final String UNAME = "uName";

public static final String PATRONYMIC = "patronymic";

public static final String JOB = "job";

public static final String NEW_DOCUMENT = "newDocument";

public static final String NEW_DOCUMENT_IN_FOLDER = "newDocumentInFolder";

public static final String NEW_VERSION = "newVersion";

public static final String CREATE_DOCUMENT = "createDocument";

public static final String CREATE_VERSION = "createVersion";

public static final String NEW_FILE = "newfile";

public static final String FILE_NAME = "fileName";

public static final String FILE_COMMENT = "comment";

public static final String FOLDER_TO_FILE = "ftf";

public static final String FOLDER_ID = "folderId";

public static final String DAYS_OF_STORAGE = "storage";

public static final String NEWFILE = "newFile";

public static final String FILE_ID = "fileId";

public static final String VERSION_NUMBER = "vNumber";

public static final String DELETE_FILE = "deleteFile";

public static final String PAGE = "page";

public static final String FOLDER = "folder";

public void init() throws ServletException {

super.init();

url = getInitParameter("url");

driver = getInitParameter("driver");

user = getInitParameter("user");

password = getInitParameter("password");

path = getInitParameter("rootFolder");

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setCharacterEncoding("utf-8");

response.setContentType("text/html");

String action = request.getParameter("action");

HttpSession session = request.getSession();

UserGroupServiceImpl ugsi;

FileFolderServiceImpl ffsi;

if (action == null) action = NEW_DOCUMENT;

String message = "";

try {

String login = (String) session.getAttribute(LOGIN);

String pass = (String) session.getAttribute(PASSWORD);

if (login == null)

response.sendRedirect(request.getContextPath() + "/auth");

else {

if (action != null) {

ugsi = new UserGroupServiceImpl(url, driver, user, password);

User u = ugsi.getUserInfo(login);

request.setAttribute(USURNAME, u.getSurname());

request.setAttribute(UNAME, u.getName());

request.setAttribute(PATRONYMIC, u.getPatronymic());

request.setAttribute(JOB, u.getJob());

if (action.equals(NEW_DOCUMENT_IN_FOLDER)) {

String folderId = (String) session.getAttribute(FOLDER);

request.setAttribute(FOLDER_ID, folderId);

request.setAttribute(FOLDER_ID, folderId);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/newDocumentInFolder.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(NEW_VERSION)) {

String fileId = request.getParameter(FILE_ID);

request.setAttribute(FILE_ID, fileId);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/newVersion.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(DELETE_FILE)) {

String fileId = request.getParameter(FILE_ID);

String folderId = request.getParameter(FOLDER_ID);

ru.ksu.eldoc.objects.File f = new ru.ksu.eldoc.objects.File(Long.parseLong(fileId));

ffsi = new FileFolderServiceImpl(url, driver, user, password);

String path1 = ffsi.getFileUrl(f);

String pathv = "";

File uploadetFile = new File(path1);

uploadetFile.delete();

int numb = ffsi.getNumberOfVersions(f);

for (int i = 2; i <= numb; i++) {

int num = path1.indexOf('.');

String sub1 = path1.substring(0, num);

String sub2 = path1.substring(num, path1.length());

String iS = String.valueOf(i);

if (iS.length() == 1)

pathv = sub1 + "#00" + iS + sub2;

else if (iS.length() == 2)

pathv = sub1 + "#0" + iS + sub2;

else if (iS.length() == 3)

pathv = sub1 + "#" + iS + sub2;

uploadetFile = new File(pathv);

uploadetFile.delete();

}

ffsi.deleteFile(f);

String page = request.getParameter(PAGE);

if (Long.parseLong(page) == 1)

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.MY_ADDED_FILES);

if (Long.parseLong(page) == 2)

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.FOLDER_CONTENTS + "&" + FileFolderTaskServlet.FOLDER_ID + "=" + folderId);

}

}

}

}

catch (Exception e) {

message = e.getMessage();

request.setAttribute(UPLOADMESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/uploadMessage.jsp");

requestDispatcher.include(request, response);

}

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setCharacterEncoding("utf-8");

response.setContentType("text/html");

String action = request.getParameter("action");

HttpSession session = request.getSession();

UserGroupServiceImpl ugsi;

FileFolderServiceImpl ffsi;

if (action == null) action = MAIN_PAGE;

String message = "";

boolean isVersion = false;

try {

String login = (String) session.getAttribute(LOGIN);

String pass = (String) session.getAttribute(PASSWORD);

if (login == null)

response.sendRedirect(request.getContextPath() + "/auth");

else {

ugsi = new UserGroupServiceImpl(url, driver, user, password);

User u = ugsi.getUserInfo(login);

request.setAttribute(USURNAME, u.getSurname());

request.setAttribute(UNAME, u.getName());

request.setAttribute(PATRONYMIC, u.getPatronymic());

request.setAttribute(JOB, u.getJob());

//проверяем является ли полученный запрос multipart/form-data

boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (!isMultipart) {

response.sendError(HttpServletResponse.SC_BAD_REQUEST);

return;

}

DiskFileItemFactory factory = new DiskFileItemFactory();

// Максимальный буфера данных в байтах,

// при его привышении данные начнут записываться на диск во временную директорию

// устанавливаем один мегабайт

factory.setSizeThreshold(1024 * 1024);

// устанавливаем временную директорию

File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");

factory.setRepository(tempDir);

//Создаём сам загрузчик

ServletFileUpload upload = new ServletFileUpload(factory);

//максимальный размер данных который разрешено загружать в байтах

//по умолчанию -1, без ограничений. Устанавливаем 10 мегабайт.

upload.setSizeMax(1024 * 1024 * 10);

String urlbd;

String folderId = "";

boolean error = false;

String fileId = "";

try {

String fName = "";

String comment = "";

String days = "";

List items = upload.parseRequest(request);

Iterator iter = items.iterator();

String name = "";

FileItem item;

while (iter.hasNext()) {

item = (FileItem) iter.next();

if (item.isFormField()) {//если текущий элемент не файл

name = item.getFieldName();//имя параметра

String value = item.getString();//значение параметра

if (name.equals("n1")) {

fName = value;

if (fName.equals(""))

error = true;

} else if (name.equals("n2")) {

comment = value;

} else if (name.equals("n3")) {

days = value;

}

} else {

//в противном случае рассматриваем как файл

if (action.equals(CREATE_DOCUMENT)) {

long size = item.getSize();

folderId = request.getParameter(FOLDER_ID);

isVersion = false;

urlbd = processUploadedFile(item, isVersion, "");

FileInfo fi;

Date d = new Date();

if (days.length() != 0) {

fi = new FileInfo(u, d, Long.parseLong(days), size);

} else {

fi = new FileInfo(u, d, size, 1);

}

Folder folder = new Folder(Long.parseLong(folderId));

if ((!urlbd.equals("")) && (!fName.equals(""))) {

ru.ksu.eldoc.objects.File f = new ru.ksu.eldoc.objects.File(fName, comment, folder, fi, urlbd);

ffsi = new FileFolderServiceImpl(url, driver, user, password);

ffsi.addFile2(f);

} else {

error = true;

}

} else if (action.equals(CREATE_VERSION)) {

fileId = request.getParameter(FILE_ID);

isVersion = true;

urlbd = processUploadedFile(item, isVersion, fileId);

Date d = new Date();

if (!urlbd.equals("")) {

ru.ksu.eldoc.objects.File file = new ru.ksu.eldoc.objects.File(Long.parseLong(fileId));

ffsi = new FileFolderServiceImpl(url, driver, user, password);

ffsi.setVersionOfFile(file, u, comment);

} else {

error = true;

}

}

}

}

}

catch (Exception

e) {

message = e.getMessage();

request.setAttribute(UPLOADMESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/uploadMessage.jsp");

requestDispatcher.include(request, response);

}

if (error) {

message = "Заполните все поля, отмеченные звездочкой!";

request.setAttribute(UPLOADMESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/uploadMessage.jsp");

requestDispatcher.include(request, response);

} else if (action.equals(CREATE_DOCUMENT)) {

response.sendRedirect(request.getContextPath() + "/main");

} else if (action.equals(CREATE_VERSION))

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.VERSION + "&" + FileFolderTaskServlet.FILE_ID + "=" + fileId);

}

}

catch (Exception e)

{

message = e.getMessage();

request.setAttribute(UPLOADMESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/uploadMessage.jsp");

requestDispatcher.include(request, response);

}

//перенаправляем на страницу с уведомлением о успешной загрузке файлов

}

private String processUploadedFile(FileItem item, boolean isVersion, String fileId) throws Exception {

if (item.getSize() == 0) {

return "";

}

String path1 = "";

File uploadetFile = null;

if (!isVersion) {

//выбираем файлу имя, пока не найдём свободное

do {

path1 = path + random.nextInt() + item.getName();

uploadetFile = new File(path1);

} while (uploadetFile.exists());

} else {

ru.ksu.eldoc.objects.File f = new ru.ksu.eldoc.objects.File(Long.parseLong(fileId));

FileFolderServiceImpl ffsi = new FileFolderServiceImpl(url, driver, user, password);

String fUrl = ffsi.getFileUrl(f);

int num = fUrl.indexOf('.');

String sub1 = fUrl.substring(0, num);

String sub2 = fUrl.substring(num, fUrl.length());

int numb = ffsi.getNumberToPath(f) + 1;

String numbS = String.valueOf(numb);

if (numbS.length() == 1)

path1 = sub1 + "#00" + numbS + sub2;

else if (numbS.length() == 2)

path1 = sub1 + "#0" + numbS + sub2;

else if (numbS.length() == 3)

path1 = sub1 + "#" + numbS + sub2;

uploadetFile = new File(path1);

}

//создаём файл

uploadetFile.createNewFile();

//записываем в него данные

item.write(uploadetFile);

return path1;

}

private void processFormField

(FileItem

item) {

System.out.println(item.getFieldName() + "=" + item.getString());

}

}

Download

package ru.ksu.eldoc.web;

import ru.ksu.eldoc.services.impl.*;

import ru.ksu.eldoc.objects.*;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import javax.servlet.ServletException;

import javax.servlet.RequestDispatcher;

import java.io.IOException;

import java.io.File;

import java.io.FileInputStream;

import java.util.List;

import java.util.Iterator;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Download extends HttpServlet {

protected String url;

protected String driver;

protected String user;

protected String password;

protected String path;

public void init() throws ServletException {

super.init();

url = getInitParameter("url");

driver = getInitParameter("driver");

user = getInitParameter("user");

password = getInitParameter("password");

path = getInitParameter("rootFolder");

}

public static final String LOGIN = "login";

public static final String PASSWORD = "password";

public static final String USURNAME = "uSurname";

public static final String UNAME = "uName";

public static final String PATRONYMIC = "patronymic";

public static final String JOB = "job";

public static final String USER_ID = "uId";

public static final String DOWNLOAD = "download";

public static final String DOWNLOAD_FILE = "downloadFile";

public static final String DOWNLOAD_VERSION = "downloadVersion";

public static final String VERSION_NUMBER = "versionNumber";

public static final String FILE_ID = "fileId";

public static final String PATH = "path";

public static final String UPLOADMESSAGE = "message";

public static final String FOLDER_ID = "folderId";

public static final String FILEINFO = "fileinfo";

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setCharacterEncoding("utf-8");

response.setContentType("text/html");

String action = request.getParameter("action");

HttpSession session = request.getSession();

UserGroupServiceImpl ugsi;

FileFolderServiceImpl ffsi;

String message = "";

try {

String login = (String) session.getAttribute(LOGIN);

String pass = (String) session.getAttribute(PASSWORD);

if (login == null)

response.sendRedirect(request.getContextPath() + "/auth");

else {

if (action != null) {

ugsi = new UserGroupServiceImpl(url, driver, user, password);

User u = ugsi.getUserInfo(login);

request.setAttribute(USURNAME, u.getSurname());

request.setAttribute(UNAME, u.getName());

request.setAttribute(PATRONYMIC, u.getPatronymic());

request.setAttribute(JOB, u.getJob());

if (action.equals(DOWNLOAD)) {

String fileId = request.getParameter(FILE_ID);

request.setAttribute(FILE_ID, fileId);

String folderId = request.getParameter(FOLDER_ID);

ffsi = new FileFolderServiceImpl(url, driver, user, password);

ru.ksu.eldoc.objects.File file = new ru.ksu.eldoc.objects.File(Long.parseLong(fileId));

FileToSee fInfo = ffsi.getInfOfFileToSee(file);

request.setAttribute(FILEINFO, fInfo);

String path = ffsi.getFileUrl(file);

request.setAttribute(PATH, path);

dowload(request, response, path);

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.FOLDER_CONTENTS + "&" + FileFolderTaskServlet.FOLDER_ID + "=" + folderId);

} else if (action.equals(DOWNLOAD_VERSION)) {

String fileId = request.getParameter(FILE_ID);

request.setAttribute(FILE_ID, fileId);

String number = request.getParameter(VERSION_NUMBER);

ffsi = new FileFolderServiceImpl(url, driver, user, password);

ru.ksu.eldoc.objects.File file = new ru.ksu.eldoc.objects.File(Long.parseLong(fileId));

int numberToPath = ffsi.getNumberToPathOfVersion(file, Integer.parseInt(number));

String path = ffsi.getFileUrl(file);

String pathv = "";

int num = path.indexOf('.');

String sub1 = path.substring(0, num);

String sub2 = path.substring(num, path.length());

String iS = String.valueOf(numberToPath);

if (iS.length() == 1)

pathv = sub1 + "#00" + iS + sub2;

else if (iS.length() == 2)

pathv = sub1 + "#0" + iS + sub2;

else if (iS.length() == 3)

pathv = sub1 + "#" + iS + sub2;

dowload(request, response, pathv);

response.sendRedirect(request.getContextPath() + "/fft?action=" + FileFolderTaskServlet.VERSION + "&" + FileFolderTaskServlet.FILE_ID + "=" + fileId);

}

}

}

}

catch (Exception e) {

message = e.getMessage();

request.setAttribute(UPLOADMESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/uploadMessage.jsp");

requestDispatcher.include(request, response);

}

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setCharacterEncoding("utf-8");

response.setContentType("text/html");

String action = request.getParameter("action");

HttpSession session = request.getSession();

UserGroupServiceImpl ugsi;

FileFolderServiceImpl ffsi;

String message = "";

boolean isVersion = false;

try {

String login = (String) session.getAttribute(LOGIN);

String pass = (String) session.getAttribute(PASSWORD);

if (login == null)

response.sendRedirect(request.getContextPath() + "/auth");

else {

ugsi = new UserGroupServiceImpl(url, driver, user, password);

User u = ugsi.getUserInfo(login);

request.setAttribute(USURNAME, u.getSurname());

request.setAttribute(UNAME, u.getName());

request.setAttribute(PATRONYMIC, u.getPatronymic());

request.setAttribute(JOB, u.getJob());

if (action.equals(DOWNLOAD_FILE)) {

String path = request.getParameter(PATH);

DiskFileItemFactory factory = new DiskFileItemFactory();

// Максимальный буфера данных в байтах,

// при его привышении данные начнут записываться на диск во временную директорию

// устанавливаем один мегабайт

factory.setSizeThreshold(1024 * 1024);

// устанавливаем временную директорию

File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");

factory.setRepository(tempDir);

ServletFileUpload upload = new ServletFileUpload(factory);

List items = upload.parseRequest(request);

Iterator iter = items.iterator();

String name = "";

FileItem item;

item = (FileItem) iter.next();

String saveAs = item.getString();

message = "Документ скачан";

request.setAttribute(UPLOADMESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/uploadMessage.jsp");

requestDispatcher.include(request, response);

}

}

}

catch (Exception e)

{

message = e.getMessage();

request.setAttribute(UPLOADMESSAGE, message);

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/uploadMessage.jsp");

requestDispatcher.include(request, response);

}

}

private void dowload(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {

File file = new File(path);

FileInputStream fin = new FileInputStream(file);

int available = fin.available();

byte[] buffer = new byte[available];

fin.read(buffer);

fin.close();

int num = path.indexOf('.');

String sub2 = path.substring(num + 1, path.length());

if (sub2.equals("doc"))

response.setContentType("application/msword");

else if (sub2.equals("jpg") || sub2.equals("JPG"))

response.setContentType("image/jpg");

else if (sub2.equals("bmp"))

response.setContentType("image/bmp");

else if (sub2.equals("xls"))

response.setContentType("application/vnd.ms-excel");

else if (sub2.equals("pdf"))

response.setContentType("application/pdf");

else if (sub2.equals("gif"))

response.setContentType("image/gif");

else if (sub2.equals("zip"))

response.setContentType("application/zip");

else if (sub2.equals("ppt"))

response.setContentType("application/vnd.ms-powerpoint");

else if (sub2.equals("txt"))

response.setContentType("text/plain");

response.getOutputStream().write(buffer);

response.getOutputStream().close();

}

}

ПРИЛОЖЕНИЕ 4

Служебные классы, отвечающие за рассылку оповещений на электронную почту

MailLogger

package ru.ksu.eldoc.web;

import javax.mail.*;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import java.util.Properties;

public class MailLogger {

private static final String SMTP_HOST_NAME = "smtp.mail.ru";

private static final String subject = "Log Message";

private static final String from = "lenakonfeta88@mail.ru";

// Add List of Email address to who email needs to be sent to

private static final String[] recipients = {"lenakonfeta88@mail.ru"};

public void postMail(String message, String recipient) throws MessagingException {

boolean debug = false;

//Set the host smtp address

Properties props = new Properties();

props.put("mail.smtp.host", SMTP_HOST_NAME);

props.put("mail.smtp.auth", "true");

Authenticator auth = new SMTPAuthenticator();

Session session = Session.getDefaultInstance(props, auth);

session.setDebug(debug);

// create a message

Message msg = new MimeMessage(session);

// set the from and to address

InternetAddress addressFrom = new InternetAddress(from);

msg.setFrom(addressFrom);

InternetAddress addressTo = new InternetAddress(recipient);

msg.setRecipient(Message.RecipientType.TO, addressTo);

// Setting the Subject and Content Type

msg.setSubject(subject);

msg.setContent(message, "text/plain; charset=windows-1251");

Transport.send(msg);

}

}

SMTPAuthenticator

package ru.ksu.eldoc.web;

import javax.mail.Authenticator;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import java.util.Properties;

import javax.mail.PasswordAuthentication;

public class SMTPAuthenticator extends Authenticator {

private static final String SMTP_AUTH_USER = "lenakonfeta88";

private static final String SMTP_AUTH_PWD = "zgecmrf";

public PasswordAuthentication getPasswordAuthentication() {

String username = SMTP_AUTH_USER;

String password = SMTP_AUTH_PWD;

return new PasswordAuthentication(username, password); } }

Приложение 5

Описание некоторых функций из ключевых сервисов по работе с БД

1. Показать список файлов из папки

public List<File> showFilesFromFolder (User user, Folder folder) throws ClassNotFoundException, IOException, SQLException {

Connection connection = getConnection();

PreparedStatement statement;

File f;

List<File> result = new ArrayList<File>();

boolean allow = false;

try {

statement = connection.prepareStatement("SELECT fileId FROM FILES WHERE folderId=?");

statement.setLong(1, folder.getId());

ResultSet resultSet = statement.executeQuery();

while (resultSet.next()) {

long fileId = resultSet.getLong("fileId");

statement = connection.prepareStatement("SELECT fullAccess FROM FILES WHERE fileId=?");

statement.setLong(1, fileId);

ResultSet resultSet2 = statement.executeQuery();

resultSet2.next();

int fullAccess = resultSet2.getInt("fullAccess");

if (fullAccess == 1)

allow = true;

else {

statement = connection.prepareStatement("SELECT ga.fileId FROM GROUPACCESS ga, GROUPSLIST gl WHERE ga.fileId=? AND gl.userId=? AND ga.groupId=gl.groupId");

statement.setLong(1, fileId);

statement.setLong(2, user.getId());

resultSet2 = statement.executeQuery();

if (resultSet2.next())

allow = true;

else {

statement = connection.prepareStatement("SELECT * FROM USERACCESS WHERE fileId=? AND userId=?");

statement.setLong(1, fileId);

statement.setLong(2, user.getId());

resultSet2 = statement.executeQuery();

if (resultSet2.next())

allow = true;

}

}

if (allow == true) {

statement = connection.prepareStatement("SELECT fName, comment, url, addDate, size, dayOfStorage, folderId, fi.userId, surname, uName, patronymic, job FROM FILES f, FILEINFO fi, USERS u WHERE fileId=? AND fi.userId=u.userId");

statement.setLong(1, fileId);

resultSet2 = statement.executeQuery();

resultSet2.next();

String fName = resultSet2.getString("fName");

String comment = resultSet2.getString("comment");

String url = resultSet2.getString("url");

String surname = resultSet2.getString("surname");

String uName = resultSet2.getString("uName");

String patronymic = resultSet2.getString("patronymic");

String job = resultSet2.getString("job");

Long size = resultSet2.getLong("size");

Long dayOfStorage = resultSet2.getLong("dayOfStorage");

Long folderId = resultSet2.getLong("folderId");


Подобные документы

  • Процесс создания программы для электронного документооборота учреждения. Оценка ее качественных и количественных показателей. Выбор аппаратной и программной платформы Web-сайта. Разработка функциональной схемы обработки документов и доступа пользователей.

    дипломная работа [233,9 K], добавлен 02.10.2013

  • Значение документооборота как средства для управления предприятием. Организации системы электронного документооборота и требований, предъявляемых к системам. Проблема выбора системы электронного документооборота на предприятиях малого и среднего бизнеса.

    контрольная работа [31,8 K], добавлен 14.09.2015

  • Аппаратное, сетевое, программное обеспечение предприятия. Разработка системы электронного документооборота. Последовательность создания и технология построения информационной системы. Выбор системы управления базами данных, среды разработки приложения.

    дипломная работа [1,5 M], добавлен 15.10.2013

  • Назначение системы электронного документооборота. Построение функциональной модели поставки товаров в супермаркет. Основные свойства системы электронного документооборота ООО "Ксенокс". Особенности проектирования системы обеспечения продукцией в BPwin.

    курсовая работа [1,4 M], добавлен 15.01.2010

  • Современные электронные системы управления и работы с документами. Проблемы традиционных и электронных технологий ДОУ. Выбор эффективной СЭУД (классификация систем электронного управления документами). Защищенность электронного документооборота.

    дипломная работа [124,9 K], добавлен 12.12.2007

  • Задачи системы электронного документооборота. Анализ существующих информационных систем. Методы и средства инженерии программного обеспечения. Концептуальная модель данных в BPWin. Построение инфологической модели системы документооборота "Doc_Univer".

    курсовая работа [56,1 K], добавлен 25.03.2014

  • Основные понятия и преимущества электронного документооборота над бумажным. Проблемы внедрения системы, реализация электронного документооборота. Обеспечение подготовки, автоматизация, форматы и стандарты обмена. Обеспечение гарантированной доставки.

    реферат [1,0 M], добавлен 23.02.2011

  • Понятие системы электронного документооборота. Документ - способ упорядочения информации. Современные системы электронного оборота документации и их технические возможности. Обзор разработчиков СЭД. Глобальные государственные инициативы в этой сфере.

    реферат [1,5 M], добавлен 09.12.2013

  • Решения по разработке системы электронного документооборота, государственные инициативы и стандарты в данной области, существующие проблемы и направления их разрешения. Модель данных общей и пользовательской части, принципы разработки интерфейса.

    дипломная работа [1,9 M], добавлен 20.12.2013

  • Принципы организации документооборота управленческой деятельности. Создание компонентов систем электронного документооборота. Directum: краткое описание системы, решаемые задачи, архитектура. Безопасные приемы работы. Виды опасных и вредных факторов.

    дипломная работа [1,7 M], добавлен 17.03.2013

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.