package com.vst.webapp.action;
import com.vst.model.Answer;
import com.vst.model.BuildingObject;
import com.vst.model.ObjectAnswer;
import com.vst.model.ObjectConstruction;
import com.vst.service.BuildingObjectManager;
import com.vst.service.QuestionManager;
import com.vst.service.SynchronizationManager;
import com.vst.util.StringUtil;
import com.vst.util.FileHelper;
import com.vst.exceptions.ServerDataUnloadException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Properties;
/**
* Created by IntelliJ IDEA.
* User: ALEXEI
* Date: 01.04.2008
* Time: 0:46:55
* To change this template use File | Settings | File Templates.
*/
public class SinchronizationController implements Controller {
private SynchronizationManager synchronizationManager;
private BuildingObjectManager buildingObjectManager;
private QuestionManager questionManager;
public void setQuestionManager(QuestionManager questionManager) {
this.questionManager = questionManager;
}
public void setBuildingObjectManager(BuildingObjectManager buildingObjectManager) {
this.buildingObjectManager = buildingObjectManager;
}
public void setSynchronizationManager(SynchronizationManager synchronizationManager) {
this.synchronizationManager = synchronizationManager;
}
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
String ipAddress = httpServletRequest.getParameter("ipAddress");
if (ipAddress != null && !ipAddress.trim().equals("")) {
//checking if connection exists
if (!ipAddress.equals("localhost") && synchronizationManager.hasConnection(ipAddress, httpServletRequest)) {
//creating success sinchronization file message
String secureDate = StringUtil.encodeString(String.valueOf((new Date()).getTime()));
FileOutputStream fileOutputStream = new FileOutputStream(FileHelper.getCurrentPath(httpServletRequest) + "message.properties");
fileOutputStream.write(secureDate.getBytes());
fileOutputStream.close();
//checking if all objects were filled and reserached till the end
String errorMessage = "";
List buildingObjectList = buildingObjectManager.getBuildingObjects(null);
for (int i = 0; i < buildingObjectList.size(); i++) {
BuildingObject buildingObject = (BuildingObject) buildingObjectList.get(i);
List answerList = buildingObject.getDocumentationQuestions();
//retrieving construction answers
List objectConstructions = buildingObject.getConstructionTypes();
for (int j = 0; j < objectConstructions.size(); j++) {
ObjectConstruction objectConstruction = (ObjectConstruction) objectConstructions.get(j);
List constructionAnswers = objectConstruction.getDocumentationQuestions();
answerList.addAll(constructionAnswers);
if (constructionAnswers.size() == 0 && questionManager.hasQuestionForConstruction(objectConstruction.getConstructionType().getConstructionTypeId().toString())) {
errorMessage += "Не даны ответы по конструкции - <a target=blank href='objectConstructions.html?objectId=" + objectConstruction.getObjectId() + "&typeId=" + objectConstruction.getTypeId() + "'>" + objectConstruction.getConstructionType() + ". Объект - " + buildingObject.getName() + "</a><br/>";
}
}
// checking if all questions have answer
for (int j = 0; j < answerList.size(); j++) {
ObjectAnswer objectAnswer = (ObjectAnswer) answerList.get(j);
if ((objectAnswer == null ||
objectAnswer.getAnswers() == null
|| objectAnswer.getAnswers().size() == 0
|| ((Answer) objectAnswer.getAnswers().get(0)).getAnswerId().equals(new Integer(-1)))
&& (objectAnswer.getAnswerContents() == null
|| objectAnswer.getAnswerContents().trim().equals("")) && objectAnswer.getQuestion().isNecessary()) {
errorMessage += "<a target=blank href='buildingObjects.html?objectId=" + buildingObject.getObjectId() + "'>" + objectAnswer.getQuestion().getContents() + " - " + buildingObject.getName() + "</a><br/>";
}
}
if (buildingObject.getDocumentationQuestions().size() == 0 && questionManager.hasQuestionForObjectDocumentation()) {
errorMessage += "Не даны ответы по документации и по структуре объекта <a target=blank href='buildingObjects.html?objectId=" + buildingObject.getObjectId() + "'>" + buildingObject.getName() + "</a><br/>";
}
}
if (!errorMessage.equals("")) {
httpServletRequest.setAttribute("errormessage", errorMessage);
setDefaultIpAddress(httpServletRequest);
return new ModelAndView("sinchronization");
}
//adding new building objects to the server if they were filled till the end
//sinchronization with server
ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources");
httpServletRequest.setAttribute("message", bundle.getString("sinchronization.success") + "<br/>Объекты исследования переданы на сервер.<br/>От сервера получено обновление по 24 справочникам");
httpServletRequest.setAttribute("ipAddress", ipAddress);
//connection for prolonging the date of the end of work without server
// Socket socket=new Socket();
// socket.connect(new InetSocketAddress(ipAddress, Constants.PORT));
// String sentMessage="extraMessage";
// socket.getOutputStream().write(sentMessage.getBytes());
// socket.close();
try {
synchronizationManager.synchronizeSpravochnikFromServer(
ipAddress,
httpServletRequest,
httpServletResponse);
}
catch (ServerDataUnloadException e) {
e.printStackTrace();
httpServletRequest.setAttribute("errormessage", "Произошла ошибка!<br>" + e.getMessage());
setDefaultIpAddress(httpServletRequest);
}
} else {
ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources");
if (!ipAddress.equals("localhost")) {
httpServletRequest.setAttribute("errormessage", bundle.getString("sinchronization.fail.noDatabaseConnection"));
setDefaultIpAddress(httpServletRequest);
} else {
httpServletRequest.setAttribute("errormessage", bundle.getString("sinchronization.fail.localAddress"));
setDefaultIpAddress(httpServletRequest);
}
}
} else {
setDefaultIpAddress(httpServletRequest);
}
return new ModelAndView("sinchronization");
}
private void setDefaultIpAddress(HttpServletRequest httpServletRequest) {
//reading default ip-address from property-file
Properties props = new Properties();
try {
props.load(new FileInputStream(FileHelper.getCurrentPath(httpServletRequest) + "common.properties"));
String serverIp = props.getProperty("serverIp");
httpServletRequest.setAttribute("serverIp", serverIp);
}
catch (Exception e) {
e.printStackTrace();
}
}
}