рефакторинг
This commit is contained in:
@@ -1,386 +0,0 @@
|
||||
package _VisualDVM.Repository.Server;
|
||||
import Common.Database.Objects.DBObject;
|
||||
import Common.Database.RepositoryRefuseException;
|
||||
import Common.Utils.Utils_;
|
||||
import _VisualDVM.Constants;
|
||||
import _VisualDVM.Global;
|
||||
import _VisualDVM.GlobalData.Account.Account;
|
||||
import _VisualDVM.GlobalData.Machine.Machine;
|
||||
import _VisualDVM.GlobalData.Machine.MachineType;
|
||||
import _VisualDVM.GlobalData.RemoteFile.RemoteFile;
|
||||
import _VisualDVM.GlobalData.User.User;
|
||||
import _VisualDVM.Passes.All.ArchivesBackupPass;
|
||||
import _VisualDVM.Passes.All.UnzipFolderPass;
|
||||
import _VisualDVM.Passes.All.ZipFolderPass;
|
||||
import _VisualDVM.ProjectData.LanguageName;
|
||||
import _VisualDVM.Repository.BugReport.BugReport;
|
||||
import _VisualDVM.Repository.BugReport.Json.BugReportAdditionJson;
|
||||
import _VisualDVM.Repository.BugReportsDatabase;
|
||||
import _VisualDVM.Repository.Component.ComponentType;
|
||||
import _VisualDVM.Repository.Component.Json.ComponentPublicationInfoJson;
|
||||
import _VisualDVM.Repository.Component.Json.ComponentVersionsInfoJson;
|
||||
import _VisualDVM.Repository.EmailMessage;
|
||||
import _VisualDVM.Repository.RepositoryServer;
|
||||
import _VisualDVM.Repository.Subscribes.Subscriber;
|
||||
import _VisualDVM.Utils;
|
||||
import javafx.util.Pair;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Arrays;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Vector;
|
||||
public class ComponentsServer extends RepositoryServer<BugReportsDatabase> {
|
||||
public static ZipFolderPass zip = new ZipFolderPass();
|
||||
public static UnzipFolderPass unzip = new UnzipFolderPass();
|
||||
public static ArchivesBackupPass backupSession = new ArchivesBackupPass();
|
||||
//-
|
||||
public static Vector<Pair<Machine, User>> storages = new Vector<>(
|
||||
Arrays.asList(new Pair<>(new Machine("titan",
|
||||
"dvmh.keldysh.ru",
|
||||
22, MachineType.Server),
|
||||
new User("dvmuser1", "mprit_2011"))
|
||||
));
|
||||
//-
|
||||
protected Thread backUp = new Thread(() -> {
|
||||
while (true) {
|
||||
try {
|
||||
//-------------------------------------
|
||||
Calendar rightNow = Calendar.getInstance();
|
||||
int year = rightNow.get(Calendar.YEAR);
|
||||
int month = rightNow.get(Calendar.MONTH);
|
||||
int day = rightNow.get(Calendar.DAY_OF_MONTH);
|
||||
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
|
||||
int minute = rightNow.get(Calendar.MINUTE);
|
||||
if ((hour == Global.componentsServerProperties.BackupHour) && (minute == Global.componentsServerProperties.BackupMinute)) {
|
||||
//определить имя папки с багом.
|
||||
String backUpName = year + "_" + (month + 1) + "_" + (day);
|
||||
File todayBackUp = Paths.get(Global.DataBackUpsDirectory.getAbsolutePath(), backUpName).toFile();
|
||||
File todayBackUpArchive = Paths.get(Global.DataBackUpsDirectory.getAbsolutePath(), backUpName + ".zip").toFile();
|
||||
//-
|
||||
File bugsDBBackUp = Paths.get(todayBackUp.getAbsolutePath(), db.getFile().getName()).toFile();
|
||||
File bugsArchives = Paths.get(todayBackUp.getAbsolutePath(), "Bugs.zip").toFile();
|
||||
//-
|
||||
// Чистка старых бекапов на самом сервере.
|
||||
Utils.keepNewFiles(todayBackUp.getParentFile(), 2);
|
||||
if (!todayBackUpArchive.exists()) {
|
||||
FileUtils.forceMkdir(todayBackUp);
|
||||
Files.copy(db.getFile().toPath(), bugsDBBackUp.toPath());
|
||||
//-
|
||||
zip.Do("Bugs", bugsArchives.getAbsolutePath());
|
||||
zip.Do(todayBackUp.getAbsolutePath(), todayBackUpArchive.getAbsolutePath());
|
||||
Utils_.forceDeleteWithCheck(todayBackUp);
|
||||
//-
|
||||
for (Pair<Machine, User> cred : storages) {
|
||||
backupSession.Do(cred.getKey(), cred.getValue(), todayBackUpArchive);
|
||||
}
|
||||
//bonus backup
|
||||
//todo оформить как у планировщика, так как это нить, напрямую сервер трогать нельзя.
|
||||
if (rightNow.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
|
||||
EmailMessage message = new EmailMessage("db backup", "копия баз данных журнала ошибок");
|
||||
message.addAttachement(db.getFile());
|
||||
for (String address : Constants.admins_mails) {
|
||||
Email(message, address);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//-------------------------------------
|
||||
Thread.sleep(60000);
|
||||
} catch (Exception ex) {
|
||||
Utils_.MainLog.PrintException(ex);
|
||||
}
|
||||
}
|
||||
});
|
||||
public ComponentsServer() {
|
||||
super(BugReportsDatabase.class);
|
||||
}
|
||||
@Override
|
||||
public String getServerFileName() {
|
||||
return "VisualSapfor.jar";
|
||||
}
|
||||
@Override
|
||||
public String getServerHomeName() {
|
||||
return "_sapfor_x64";
|
||||
}
|
||||
@Override
|
||||
public int getPort() {
|
||||
return Constants.ComponentsServerPort;
|
||||
}
|
||||
@Override
|
||||
protected void beforePublishAction(DBObject object) throws Exception {
|
||||
if (object instanceof BugReport) {
|
||||
BugReport bugReport = (BugReport) object;
|
||||
if (bugReport.packed_archive != null) {
|
||||
File bugArchive = Utils_.getFile(Utils_.getHomePath(), "Bugs", bugReport.id);
|
||||
Utils_.bytesToFile(bugReport.packed_archive, bugArchive);
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected void afterDeleteAction(DBObject object) throws Exception {
|
||||
if (object instanceof BugReport) {
|
||||
BugReport bugReport = (BugReport) object;
|
||||
if (!bugReport.project_version.isEmpty()) Utils_.forceDeleteWithCheck(bugReport.getArchiveFile());
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void StartAction() throws Exception {
|
||||
if (Global.componentsServerProperties.EmailAdminsOnStart) {
|
||||
EmailMessage message = new EmailMessage("Сервер Sapfor запущен", new Date().toString());
|
||||
for (String address : Constants.admins_mails) {
|
||||
Email(message, address);
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected void startAdditionalThreads() {
|
||||
backUp.start();
|
||||
}
|
||||
//-
|
||||
void DVMConvertProject() throws Exception {
|
||||
String[] args = request.arg.split("\n");
|
||||
//-
|
||||
String projectName = args[0];
|
||||
LanguageName projectLanguage = LanguageName.valueOf(args[1]);
|
||||
String options = args[2];
|
||||
Vector<String> filesNames = new Vector<>(Arrays.asList(args).subList(3, args.length));
|
||||
//-
|
||||
File workspace = Utils.getTempFileName("convertation");
|
||||
FileUtils.forceMkdir(workspace);
|
||||
File archive = new File(workspace, projectName + ".zip");
|
||||
request.Unpack(archive);
|
||||
File project = new File(workspace, projectName);
|
||||
Vector<String> badFiles = new Vector<>();
|
||||
if (unzip.Do(archive.getAbsolutePath(), workspace.getAbsolutePath()) && project.exists()) {
|
||||
String output = "";
|
||||
for (String fileName : filesNames) {
|
||||
File program = Paths.get(project.getAbsolutePath(), fileName).toFile();
|
||||
//--
|
||||
File convertedProgram = Paths.get(program.getParent(), Utils_.getFileNameWithoutExtension(program) + ".DVMH." + (projectLanguage.equals(LanguageName.fortran) ? "f" : "c")).toFile();
|
||||
String command = Utils_.DQuotes(Constants.server_dvm_drv) + " " + projectLanguage.getDVMCompile() + "dv " + options + " " + Utils_.DQuotes(program.getName());
|
||||
//--
|
||||
File fileWorkspace = program.getParentFile();
|
||||
Process process = Utils.startScript(workspace, fileWorkspace, Utils_.getDateName("convert_script"), command);
|
||||
process.waitFor();
|
||||
String convertationOut = Utils.readAllOutput(process);
|
||||
convertationOut = convertationOut.replace(program.getName(), fileName); //для учета пути.
|
||||
if (!convertationOut.isEmpty()) output += convertationOut + "\n";
|
||||
try {
|
||||
if (convertedProgram.exists()) {
|
||||
FileUtils.forceDelete(program);
|
||||
convertedProgram.renameTo(program);
|
||||
} else badFiles.add(program.getName());
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
//--
|
||||
}
|
||||
response.arg = String.join("\n", badFiles) + "|" + output;
|
||||
File resultArchive = new File(workspace, projectName + "_result.zip");
|
||||
if (ComponentsServer.zip.Do(project.getAbsolutePath(), resultArchive.getAbsolutePath())) {
|
||||
response.object = Utils_.fileToBytes(resultArchive);
|
||||
} else throw new RepositoryRefuseException("Внутренняя ошибка. Не удалось запаковать версию");
|
||||
//--
|
||||
} else throw new RepositoryRefuseException("Внутренняя ошибка. Не удалось распаковать проект");
|
||||
}
|
||||
void AppendBugReportField() throws Exception {
|
||||
BugReportAdditionJson transport = (BugReportAdditionJson) request.object;
|
||||
if (db.bugReports.containsKey(transport.id)) {
|
||||
BugReport actual = db.bugReports.get(transport.id);
|
||||
Field field = BugReport.class.getField(transport.fieldName);
|
||||
field.set(actual, field.get(actual) + "\n" + transport.textAddition);
|
||||
actual.change_date = new Date().getTime();
|
||||
db.Update(actual);
|
||||
response.object = actual;
|
||||
} else throw new RepositoryRefuseException("Баг репорт с ключом " + transport.id + " не существует.");
|
||||
}
|
||||
void ReceiveAllArchives() throws Exception {
|
||||
ZipFolderPass zip = new ZipFolderPass();
|
||||
File archives = new File(Utils_.getDateName("Bugs"));
|
||||
if (zip.Do("Bugs", archives.getAbsolutePath())) {
|
||||
response.object = Utils_.fileToBytes(archives);
|
||||
} else throw new RepositoryRefuseException("Не удалось запаковать архивы");
|
||||
}
|
||||
void ReceiveBugReportsDatabase() throws Exception{
|
||||
response.object = Utils_.fileToBytes(db.getFile());
|
||||
}
|
||||
void ReceiveBugReport() throws Exception {
|
||||
File bugArchive = Utils_.getFile(Utils_.getHomePath(), "Bugs", request.arg);
|
||||
response.object = Utils_.fileToBytes(bugArchive);
|
||||
}
|
||||
void UpdateBugReport() throws Exception {
|
||||
BugReport oldBugReport = (BugReport) request.object;
|
||||
if (db.bugReports.containsKey(oldBugReport.id)) {
|
||||
BugReport bugReport = db.bugReports.get(oldBugReport.id);
|
||||
bugReport.SynchronizeFields(oldBugReport);
|
||||
bugReport.change_date = new Date().getTime();
|
||||
db.Update(bugReport);
|
||||
} else
|
||||
throw new RepositoryRefuseException("Баг репорт с ключом " + oldBugReport.id + " не существует.");
|
||||
}
|
||||
//--
|
||||
void CheckSubscriberRole() throws Exception {
|
||||
Account account = (Account) request.object;
|
||||
Subscriber subscriber = null;
|
||||
if (db.subscribers.containsKey(account.email)) {
|
||||
subscriber = db.subscribers.get(account.email);
|
||||
} else {
|
||||
subscriber = new Subscriber();
|
||||
subscriber.name = account.name;
|
||||
subscriber.address = account.email;
|
||||
subscriber.mailOn = 1;
|
||||
db.Insert(subscriber);
|
||||
}
|
||||
response.object = subscriber; //возвращаем информацию о подписчике.
|
||||
}
|
||||
void GetComponentsBackUps() throws Exception {
|
||||
File backupsDirectory = Paths.get(Utils_.getHomePath(), "Components", request.arg, "Backups").toFile();
|
||||
//--
|
||||
if (backupsDirectory.exists()) {
|
||||
File[] files = backupsDirectory.listFiles(File::isFile);
|
||||
if (files != null) {
|
||||
Vector<RemoteFile> res = new Vector<>();
|
||||
for (File file : files)
|
||||
res.add(new RemoteFile(file.getAbsolutePath(), false)); //тут всегда линух.
|
||||
response.object = res;
|
||||
} else throw new RepositoryRefuseException("Не удалось получить список предыдущих версий");
|
||||
} else {
|
||||
//баги еще не создавались. штатная ситуация.
|
||||
response.object = new Vector<>();
|
||||
}
|
||||
}
|
||||
void CheckURLRegistered() throws Exception {
|
||||
String[] data = request.arg.split("\n");
|
||||
String email = data[0];
|
||||
String machineURL = data[1];
|
||||
String login = data[2];
|
||||
response.object = db.workspaces.findWorkspace(email, machineURL, login);
|
||||
}
|
||||
void GetComponentChangesLog() throws Exception {
|
||||
response.object = Utils_.fileToBytes(Paths.get(Utils_.getHomePath(), "Components", request.arg, "changes.txt").toFile());
|
||||
}
|
||||
void PublishComponent() throws Exception {
|
||||
ComponentPublicationInfoJson info = (ComponentPublicationInfoJson) request.object;
|
||||
File componentHome = Utils_.getFile(Utils_.getHomePath(), "Components", info.componentType.toString());
|
||||
File componentFile = new File(componentHome, info.fileName);
|
||||
File versionFile = new File(componentHome, "version.txt");
|
||||
File backupsFolder = new File(componentHome, "Backups");
|
||||
//0 архивация старой версии, если она есть.
|
||||
if (componentFile.exists()) {
|
||||
String versionText = "";
|
||||
if (versionFile.exists()) versionText = Utils.ReadAllText(versionFile);
|
||||
//---->>
|
||||
Utils_.CheckDirectory(backupsFolder);
|
||||
Utils.keepNewFiles(backupsFolder, Global.componentsServerProperties.ComponentsBackUpsCount);
|
||||
//-->>
|
||||
File backupFile = new File(backupsFolder, info.componentType + "_" + versionText);
|
||||
if (backupFile.exists()) Utils_.forceDeleteWithCheck(backupFile);
|
||||
FileUtils.moveFile(componentFile, backupFile);
|
||||
}
|
||||
//1 распаковка компонента
|
||||
Utils_.bytesToFile((byte[]) info.packedFile, componentFile);
|
||||
//2 запись версии компонента
|
||||
FileUtils.writeStringToFile(versionFile, info.versionText);
|
||||
//3 запись в журнал компонента
|
||||
File changesLog = new File(componentHome, "changes.txt");
|
||||
FileWriter writer = new FileWriter(changesLog.getAbsolutePath(), true);
|
||||
BufferedWriter bufferWriter = new BufferedWriter(writer);
|
||||
bufferWriter.write(info.changeRecord);
|
||||
bufferWriter.close();
|
||||
//-
|
||||
if (info.needsUpdateMinimalVersion) {
|
||||
Print("Поднять минимальную версию компонента " + info.componentType);
|
||||
File minimal_versionFile = new File(componentHome, "minimal_version.txt");
|
||||
FileUtils.writeStringToFile(minimal_versionFile, info.versionText);
|
||||
//-
|
||||
//3 запись в журнал компонента
|
||||
FileWriter writer_ = new FileWriter(changesLog, true);
|
||||
BufferedWriter bufferWriter_ = new BufferedWriter(writer_);
|
||||
bufferWriter_.write("Минимальная версия поднята до " + info.versionText + "\n");
|
||||
bufferWriter_.close();
|
||||
}
|
||||
}
|
||||
void GetComponentsVersionsInfo() throws Exception {
|
||||
Vector<String> types = (Vector<String>) request.object;
|
||||
Vector<ComponentVersionsInfoJson> res = new Vector<>();
|
||||
for (String sType : types) {
|
||||
ComponentType componentType = ComponentType.valueOf(sType);
|
||||
File actualVersionFile = Paths.get(Utils_.getHomePath(), "Components", sType, "version.txt").toFile();
|
||||
File minimalVersionFile = Paths.get(Utils_.getHomePath(), "Components", sType, "minimal_version.txt").toFile();
|
||||
ComponentVersionsInfoJson info = new ComponentVersionsInfoJson(componentType);
|
||||
info.actual_version = Utils_.removeCharacters(Utils.ReadAllText(actualVersionFile), "\n", "\r");
|
||||
info.minimal_version = Utils_.removeCharacters(Utils.ReadAllText(minimalVersionFile), "\n", "\r");
|
||||
res.add(info);
|
||||
}
|
||||
response.object = res;
|
||||
}
|
||||
void ReceiveComponent() throws Exception {
|
||||
String[] packed1 = request.arg.split("\n");
|
||||
//тип/имя файла
|
||||
File componentFile1 = Paths.get(Utils_.getHomePath(), "Components", packed1[0], packed1[1]).toFile();
|
||||
Print("Получить компонент " + packed1[0]);
|
||||
response.object = Utils_.fileToBytes(componentFile1);
|
||||
}
|
||||
//--
|
||||
@Override
|
||||
protected void UnsafeSession() throws Exception {
|
||||
switch (code) {
|
||||
case CheckSubscriberRole:
|
||||
CheckSubscriberRole();
|
||||
break;
|
||||
case GetComponentsBackups:
|
||||
GetComponentsBackUps();
|
||||
break;
|
||||
case UpdateComponent:
|
||||
//возможно со стороны админа ввод подтверждения по почте запрашивать.
|
||||
PublishComponent();
|
||||
break;
|
||||
case ReceiveComponent:
|
||||
ReceiveComponent();
|
||||
break;
|
||||
case CheckURLRegistered:
|
||||
CheckURLRegistered();
|
||||
break;
|
||||
case GetComponentsVersionsInfo:
|
||||
GetComponentsVersionsInfo();
|
||||
break;
|
||||
case GetComponentChangesLog:
|
||||
GetComponentChangesLog();
|
||||
break;
|
||||
default:
|
||||
throw new RepositoryRefuseException("Неподдерживаемый код: " + code);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected void Session() throws Exception {
|
||||
switch (code) {
|
||||
case ReceiveAllArchives:
|
||||
ReceiveAllArchives();
|
||||
break;
|
||||
case UpdateBugReport:
|
||||
UpdateBugReport();
|
||||
break;
|
||||
case AppendBugReportTextField:
|
||||
AppendBugReportField();
|
||||
break;
|
||||
case ReceiveBugReportsDatabase:
|
||||
ReceiveBugReportsDatabase();
|
||||
break;
|
||||
case ReceiveBugReport:
|
||||
ReceiveBugReport();
|
||||
break;
|
||||
case DVMConvertProject:
|
||||
DVMConvertProject();
|
||||
break;
|
||||
default:
|
||||
throw new RepositoryRefuseException("Неподдерживаемый код: " + code);
|
||||
}
|
||||
}
|
||||
}
|
||||
394
src/_VisualDVM/Repository/Server/RepositoryServer.java
Normal file
394
src/_VisualDVM/Repository/Server/RepositoryServer.java
Normal file
@@ -0,0 +1,394 @@
|
||||
package _VisualDVM.Repository.Server;
|
||||
import Common.Database.Database;
|
||||
import Common.Database.Objects.DBObject;
|
||||
import Common.Database.Objects.riDBObject;
|
||||
import Common.Database.RepositoryRefuseException;
|
||||
import Common.Utils.InterruptThread;
|
||||
import Common.Utils.Utils_;
|
||||
import _VisualDVM.Constants;
|
||||
import _VisualDVM.Passes.Server.RepositoryPass;
|
||||
import _VisualDVM.Repository.EmailMessage;
|
||||
import _VisualDVM.Utils;
|
||||
import javafx.util.Pair;
|
||||
import sun.misc.SignalHandler;
|
||||
|
||||
import javax.activation.DataHandler;
|
||||
import javax.activation.DataSource;
|
||||
import javax.activation.FileDataSource;
|
||||
import javax.mail.*;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeBodyPart;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import javax.mail.internet.MimeMultipart;
|
||||
import java.io.*;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Properties;
|
||||
import java.util.Vector;
|
||||
public abstract class RepositoryServer<D extends Database> {
|
||||
protected static FileWriter Log;
|
||||
protected static boolean printOn = true;
|
||||
public abstract String getServerFileName();
|
||||
public abstract String getServerHomeName();
|
||||
//-
|
||||
public D db;
|
||||
protected Socket clientSocket; //сокет для общения
|
||||
protected ServerSocket server; // серверсокет
|
||||
protected ObjectInputStream in; // поток чтения из сокета
|
||||
protected ObjectOutputStream out; // поток записи в сокет
|
||||
protected ServerExchangeUnit_2021 request;
|
||||
protected ServerExchangeUnit_2021 response;
|
||||
//-
|
||||
protected ServerCode code;
|
||||
protected long count = 0; //для отладки.
|
||||
protected Thread interruptThread = new InterruptThread(10000,
|
||||
() -> {
|
||||
System.exit(0);
|
||||
return null;
|
||||
});
|
||||
Class<D> d_class;
|
||||
//-----------RECURSION ->
|
||||
SignalHandler signalHandler = signal -> {
|
||||
};
|
||||
public RepositoryServer(Class<D> d_class_in) {
|
||||
d_class = d_class_in;
|
||||
}
|
||||
protected static void ResetLog() {
|
||||
if (printOn) {
|
||||
try {
|
||||
Log = new FileWriter("Log.txt", false);
|
||||
Log.close();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
protected static void Print(String message) {
|
||||
if (printOn) {
|
||||
try {
|
||||
Log = new FileWriter("Log.txt", true);
|
||||
String dmessage = Utils_.Brackets("SESSION -> ") + new Date() +
|
||||
" " + message;
|
||||
Log.write(dmessage + "\n");
|
||||
Log.close();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
//-DVMTestingChecker
|
||||
public abstract int getPort();
|
||||
protected void Session() throws Exception {};
|
||||
protected void UnsafeSession() throws Exception {}
|
||||
protected void startAdditionalThreads() {
|
||||
}
|
||||
public void ActivateDB() {
|
||||
try {
|
||||
db = d_class.newInstance();
|
||||
db.Activate();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
public void Email(EmailMessage message_in, String address_in) throws Exception {
|
||||
Thread thread = new Thread(() -> {
|
||||
try {
|
||||
Properties props = new Properties();
|
||||
props.put("mail.smtp.host", Constants.SMTPHost);
|
||||
props.put("mail.smtp.auth", "true");
|
||||
props.put("mail.smtp.port", String.valueOf(Constants.SMTPPort));
|
||||
props.put("mail.smtp.socketFactory.port", String.valueOf(Constants.MailSocketPort));
|
||||
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
|
||||
props.put("mail.smtp.connectiontimeout", String.valueOf(15000));
|
||||
props.put("mail.smtp.timeout", String.valueOf(15000));
|
||||
props.put("mail.smtp.writetimeout", String.valueOf(15000));
|
||||
//------------------------------
|
||||
LinkedHashMap<String, File> innerFiles = new LinkedHashMap<>();
|
||||
for (String aName : message_in.files.keySet()) {
|
||||
File f = Utils.getTempFileName(aName);
|
||||
Utils_.bytesToFile(message_in.files.get(aName), f);
|
||||
innerFiles.put(aName, f);
|
||||
}
|
||||
//------------------------------
|
||||
Session session = Session.getDefaultInstance(props,
|
||||
new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(
|
||||
Constants.MailAddress,
|
||||
Constants.MailPassword);
|
||||
}
|
||||
});
|
||||
try {
|
||||
MimeMessage message = new MimeMessage(session);
|
||||
message.setFrom(new InternetAddress(Constants.MailAddress));
|
||||
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(address_in));
|
||||
message.setSubject(message_in.subject);
|
||||
Multipart multipart = new MimeMultipart();
|
||||
MimeBodyPart textBodyPart = new MimeBodyPart();
|
||||
textBodyPart.setText(message_in.text);
|
||||
multipart.addBodyPart(textBodyPart);
|
||||
for (String aName : innerFiles.keySet()) {
|
||||
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
|
||||
DataSource source = new FileDataSource(innerFiles.get(aName));
|
||||
attachmentBodyPart.setDataHandler(new DataHandler(source));
|
||||
attachmentBodyPart.setFileName(aName);
|
||||
multipart.addBodyPart(attachmentBodyPart);
|
||||
}
|
||||
message.setContent(multipart);
|
||||
Transport.send(message);
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Исключение во время отправки сообщения абоненту " + Utils_.Brackets(address_in));
|
||||
ex.printStackTrace();
|
||||
Utils_.sleep(1000);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Исключение во время выполнения рассылки.");
|
||||
ex.printStackTrace();
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
}
|
||||
public boolean canDelete(DBObject object) throws Exception {
|
||||
return true;
|
||||
}
|
||||
public void StartAction() throws Exception {
|
||||
}
|
||||
public void Start() throws Exception {
|
||||
DiagnosticSignalHandler.install("TERM", signalHandler);
|
||||
DiagnosticSignalHandler.install("INT", signalHandler);
|
||||
DiagnosticSignalHandler.install("ABRT", signalHandler);
|
||||
interruptThread.start();
|
||||
startAdditionalThreads();
|
||||
server = new ServerSocket(getPort());
|
||||
StartAction();
|
||||
while (true) {
|
||||
try {
|
||||
clientSocket = server.accept();
|
||||
ResetLog();
|
||||
Print((count++) + " клиент присоединился, IP=" + clientSocket.getInetAddress());
|
||||
code = ServerCode.Undefined;
|
||||
out = new ObjectOutputStream(clientSocket.getOutputStream());
|
||||
in = new ObjectInputStream(clientSocket.getInputStream());
|
||||
//->
|
||||
DBObject dbObject = null;
|
||||
Pair<Class, Object> p = null;
|
||||
Print("Ожидание команды от клиента...");
|
||||
Object transport = in.readObject();
|
||||
Print("Команда прочитана.");
|
||||
//-->
|
||||
if (transport instanceof ServerExchangeUnit_2021) {
|
||||
request = (ServerExchangeUnit_2021) transport;
|
||||
response = new ServerExchangeUnit_2021(ServerCode.OK);
|
||||
Print("клиент: <- " + (request.codeName));
|
||||
//--
|
||||
try {
|
||||
code = request.getCode();
|
||||
//--
|
||||
if (transport instanceof SafeServerExchangeUnit){
|
||||
SafeServerExchangeUnit safe_request= (SafeServerExchangeUnit) transport;
|
||||
if (safe_request.version!=Constants.version){
|
||||
//версия не совпала. не даем работать.
|
||||
throw new RepositoryRefuseException("Версия клиента не совпадает с версией сервера!");
|
||||
}
|
||||
//БЕЗОПАСНАЯ СЕССИЯ
|
||||
switch (code) {
|
||||
case Email:
|
||||
Email();
|
||||
break;
|
||||
case EditObject:
|
||||
EditObject();
|
||||
break;
|
||||
case GetObjectCopyByPK:
|
||||
GetObjectCopyByPK();
|
||||
break;
|
||||
case GetObjectsCopiesByPK:
|
||||
GetObjectsCopiesByPK();
|
||||
break;
|
||||
case PublishObject:
|
||||
PublishObject();
|
||||
break;
|
||||
case PublishObjects:
|
||||
PublishObjects();
|
||||
break;
|
||||
case DeleteObjectByPK:
|
||||
DeleteObjectByPK();
|
||||
break;
|
||||
case DeleteObjectsByPK:
|
||||
DeleteObjectsByPK();
|
||||
break;
|
||||
case CloneObjectByPK:
|
||||
CloneObject();
|
||||
break;
|
||||
default:
|
||||
Session();
|
||||
break;
|
||||
}
|
||||
}else {
|
||||
//ОПАСНАЯ СЕССИЯ
|
||||
switch (code){
|
||||
case Ping:
|
||||
Ping();
|
||||
break;
|
||||
case ReceiveFile:
|
||||
ReceiveFile();
|
||||
break;
|
||||
case Email:
|
||||
Email();
|
||||
break;
|
||||
default:
|
||||
UnsafeSession();
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
response = new ServerExchangeUnit_2021(ServerCode.FAIL, "Исключение сервера", ex);
|
||||
} finally {
|
||||
Print("сервер: -> " + response.codeName);
|
||||
out.writeObject(response);
|
||||
Print("Ответ отправлен.");
|
||||
}
|
||||
}
|
||||
Print("Соединение с клиентом завершено.");
|
||||
//->
|
||||
} catch (Exception ex) {
|
||||
Print("Исключение.Соединение с клиентом завершено.");
|
||||
} finally {
|
||||
//->
|
||||
try {
|
||||
if (clientSocket != null)
|
||||
clientSocket.close();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
// потоки тоже хорошо бы закрыть
|
||||
try {
|
||||
if (in != null)
|
||||
in.close();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
try {
|
||||
if (out != null)
|
||||
out.close();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
Print("Сервер ждет следующего клиента.");
|
||||
}
|
||||
}
|
||||
}
|
||||
//--
|
||||
void Ping() {}
|
||||
public boolean PingFromClient() {
|
||||
RepositoryPass pingPass = new RepositoryPass(this) {
|
||||
boolean success;
|
||||
@Override
|
||||
protected boolean needsAnimation() {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
protected boolean canStart(Object... args) throws Exception {
|
||||
success = false;
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Ping";
|
||||
}
|
||||
@Override
|
||||
protected void body() throws Exception {
|
||||
try {
|
||||
super.body();
|
||||
success = true;
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected void ServerAction() throws Exception {
|
||||
unsafe_command(new ServerExchangeUnit_2021(ServerCode.Ping));
|
||||
}
|
||||
@Override
|
||||
protected boolean validate() {
|
||||
return success;
|
||||
}
|
||||
};
|
||||
return pingPass.Do();
|
||||
}
|
||||
void ReceiveFile() throws Exception {
|
||||
File file = new File(request.arg);
|
||||
response.object = file.exists() ? Utils_.fileToBytes(file) : null;
|
||||
}
|
||||
void Email() throws Exception {
|
||||
Email((EmailMessage) request.object, request.arg);
|
||||
}
|
||||
//----
|
||||
void PublishObject() throws Exception {
|
||||
DBObject dbObject = (DBObject) request.object;
|
||||
beforePublishAction(dbObject);
|
||||
response.object = (Serializable) db.InsertS(dbObject).getPK();
|
||||
afterPublishAction(dbObject);
|
||||
}
|
||||
void PublishObjects() throws Exception {
|
||||
Vector<DBObject> objects = (Vector<DBObject>) request.object;
|
||||
for (DBObject dbObject : objects) {
|
||||
beforePublishAction(dbObject);
|
||||
response.object = (Serializable) db.InsertS(dbObject).getPK();
|
||||
afterPublishAction(dbObject);
|
||||
}
|
||||
}
|
||||
void CloneObject() throws Exception {
|
||||
Pair<Class, Object> to_clone = (Pair<Class, Object>) request.object;
|
||||
Object pk = to_clone.getValue();
|
||||
if (db.getTable(to_clone.getKey()).containsKey(to_clone.getValue())) {
|
||||
riDBObject src = (riDBObject) db.getTable(to_clone.getKey()).get(to_clone.getValue());
|
||||
riDBObject dst = (riDBObject) to_clone.getKey().newInstance();
|
||||
dst.SynchronizeFields(src);
|
||||
//единственное отличие клона - текущий автор
|
||||
dst.description += " копия";
|
||||
String[] packed = request.arg.split("\n");
|
||||
dst.sender_name = packed[0];
|
||||
dst.sender_address = packed[1];
|
||||
db.Insert(dst);
|
||||
afterCloneAction(src, dst);
|
||||
response.object = (Serializable) dst.getPK();
|
||||
}
|
||||
}
|
||||
void GetObjectCopyByPK() throws Exception {
|
||||
Pair<Class, Object> p = (Pair<Class, Object>) request.object;
|
||||
DBObject dbObject = db.getObjectCopyByPK(p.getKey(), p.getValue());
|
||||
response.object = dbObject;
|
||||
}
|
||||
void GetObjectsCopiesByPK() throws Exception {
|
||||
Pair<Class, Object> p = (Pair<Class, Object>) request.object;
|
||||
response.object = db.getObjectsCopies(p.getKey(), (Vector<Object>) p.getValue());
|
||||
}
|
||||
void EditObject() throws Exception {
|
||||
DBObject new_object = (DBObject) request.object;
|
||||
db.UpdateWithCheck(new_object);
|
||||
afterEditAction(new_object);
|
||||
}
|
||||
void DeleteObjectByPK() throws Exception {
|
||||
Pair<Class, Object> to_delete = (Pair<Class, Object>) request.object;
|
||||
afterDeleteAction(db.DeleteByPK(to_delete.getKey(), to_delete.getValue()));
|
||||
}
|
||||
void DeleteObjectsByPK() throws Exception {
|
||||
Pair<Class, Vector<Object>> to_delete = (Pair<Class, Vector<Object>>) request.object;
|
||||
for (Object object : to_delete.getValue()) {
|
||||
afterDeleteAction(db.DeleteByPK(to_delete.getKey(), object));
|
||||
}
|
||||
}
|
||||
protected void afterCloneAction(riDBObject src, riDBObject dst) throws Exception {
|
||||
}
|
||||
protected void beforePublishAction(DBObject object) throws Exception {
|
||||
}
|
||||
protected void afterPublishAction(DBObject object) throws Exception {
|
||||
}
|
||||
protected void afterEditAction(DBObject object) throws Exception {
|
||||
}
|
||||
protected void afterDeleteAction(DBObject object) throws Exception {
|
||||
}
|
||||
}
|
||||
@@ -63,9 +63,16 @@ public enum ServerCode {
|
||||
PerformAutoSapforTesting,
|
||||
JoinSapforVersionsToGroup,
|
||||
ReplaceDVMPackageResults,
|
||||
DetectTestsMinMaxDim;
|
||||
DetectTestsMinMaxDim,
|
||||
GetUserAccountByKey,
|
||||
GetUserAccountByEmail,
|
||||
;
|
||||
public String getDescription(){
|
||||
switch (this){
|
||||
case GetUserAccountByEmail:
|
||||
return "Получение информации об аккаунте по адресу почты";
|
||||
case GetUserAccountByKey:
|
||||
return "Получение информации об аккаунте по ключу";
|
||||
case DetectTestsMinMaxDim:
|
||||
return "Определить размерность тестов на сервере";
|
||||
case ReplaceDVMPackageResults:
|
||||
|
||||
Reference in New Issue
Block a user