Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
РПЗ.docx
Скачиваний:
2
Добавлен:
01.05.2025
Размер:
6.64 Mб
Скачать

Приложение 1. Листинг

Resource.java

package ru.corinf.ws;

import java.io.*;

import java.lang.management.ManagementFactory;

import java.sql.Timestamp;

import java.util.*;

import javax.servlet.ServletContext;

import javax.ws.rs.*;

import javax.ws.rs.core.Context;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import org.apache.log4j.Logger;

import org.hibernate.*;

import org.codehaus.jettison.json.JSONArray;

import org.codehaus.jettison.json.JSONException;

import org.codehaus.jettison.json.JSONObject;

import com.sun.jersey.spi.container.servlet.PerSession;

import ru.corinf.localization.Messages;

import ru.corinf.system.*;

import ru.corinf.system.exceptions.AccessControlException;

import ru.corinf.system.exceptions.NotFoundException;

import ru.corinf.system.generator.CorinfDSLConsole;

import ru.corinf.system.meta.Menu;

import ru.corinf.system.meta.MetaClass;

import ru.corinf.system.meta.view.*;

import ru.corinf.system.meta.view.Filter;

import ru.corinf.system.security.*;

import ru.corinf.testing.TestCorinf;

import ru.corinf.utils.DateFormatter;

import ru.corinf.utils.ErrorsHandler;

import ru.corinf.utils.HibernateManager;

/**

* @author Vladislav Okulich-Kazarin

*/

// The Java class will be hosted at the URI path "/"

@Path("/")

@PerSession

public class Resource implements Serializable{

private static String status_msg = "Server is not initialized.";

private static Object[] status_msg_args = null;

private static int initProgress = 0;

public static final Logger LOG = Logger.getLogger(Resource.class);

private static int openedSessionsCounter = 0;

private ServerSession srvSession = new ServerSession();

public static enum ServerStatus{NOT_INITIALIZED, INITIALIZED, INITIALIZING, INITIALIZATION_FAILED};

public static ServerStatus serverStatus = ServerStatus.NOT_INITIALIZED;

public Resource(@Context HttpServletRequest req) {

++openedSessionsCounter;

try{

if(serverStatus == ServerStatus.NOT_INITIALIZED){

ServletContext servletContext = req.getServletContext();

String webAppContextPath = servletContext.getRealPath(File.separator);

Configuration.setWebAppContextPath(webAppContextPath);

new Thread(new Runnable() {

public void run() {

Resource.init();

}

}).start();

}

} catch (Throwable e) {

serverStatus = ServerStatus.INITIALIZATION_FAILED;

status_msg = "Error when initializing!!!\n" +ErrorsHandler.fromException(e, Locale.getDefault())+"\n";

LOG.fatal(status_msg, e);

}

try{

this.srvSession.httpSession = req.getSession(true);

this.srvSession.httpSession.setMaxInactiveInterval(7200);//2 hours

}catch (Throwable e){

LOG.fatal("Can't create session. ",e);

}

}

private static void init(){

synchronized (serverStatus){

try {

serverStatus = ServerStatus.INITIALIZING;

status_msg = "Initialization in progress... ";

long startTime = System.currentTimeMillis();

CorinfAppServerInitializer.init();

status_msg = "Initialized in "

+ (float) (System.currentTimeMillis() - startTime) / 1000

+ "sec. "+new Date();

serverStatus = ServerStatus.INITIALIZED;

} catch (Throwable e) {

serverStatus = ServerStatus.INITIALIZATION_FAILED;

status_msg = "Error when initializing!!!\n" +ErrorsHandler.fromException(e, Locale.getDefault())+"\n";

LOG.fatal(status_msg, e);

}

}

}

protected void finalize() {

--openedSessionsCounter;

}

public static void setStatusMsg(String msg,Object ...args){

status_msg = msg;

status_msg_args = args;

}

public static void setInitProgress(int percent){

if(percent<0 || percent>100)

throw new IllegalArgumentException();

initProgress = percent;

}

@GET

@Path("/status")

@Produces("text/plain;charset=UTF-8")

public String getStatus(@Context HttpServletRequest req) {

JSONObject res = new JSONObject();

try{

res = new JSONObject();

if(serverStatus==ServerStatus.INITIALIZING)

res.put("status","initializing");

else if(serverStatus==ServerStatus.INITIALIZED)

res.put("status","initialized");

else if(serverStatus==ServerStatus.NOT_INITIALIZED)

res.put("status","not_initialized");

else if(serverStatus==ServerStatus.INITIALIZATION_FAILED)

res.put("status","initialization_failed");

res.put("status_msg",(new Messages(srvSession.locale)).get(status_msg,status_msg_args));

res.put("progress",initProgress);

} catch (Throwable e){

LOG.error(e);

}

return res.toString();

}

@GET

@Path("/restart")

@Produces("text/plain;charset=UTF-8")

public String restart(@Context HttpServletRequest req) {

try {

if(srvSession.user==null || !srvSession.user.isSuperuser())

throw new AccessControlException("You do not have permission to access.");

CorinfAppServerInitializer.hotTomcatRestart();

req.getSession(true).setMaxInactiveInterval(1);

req.getSession(true).invalidate();

} catch (Throwable e){

LOG.error("Restart exception. ",e);

return ErrorsHandler.fromException(e, srvSession.locale);

}

return "New war version deployed. New session will run on new version.";

}

// The Java method will process HTTP GET requests

@GET

@Path("/stat")

// The Java method will produce content identified by the MIME Media

// type "text/plain"

@Produces("text/plain;charset=UTF-8")

public String getStat(@Context HttpServletRequest req,@Context ServletContext servletContext) {

try {

HttpSession session = req.getSession(true);

//if(srvSession.user==null || !srvSession.user.isSuperuser())

// throw new AccessControlException("You do not have permission to access.");

String openedTabs = "";

for (Integer idTab : srvSession.openedViews.keySet()) {

ViewState st = srvSession.openedViews.get(idTab);

if(st == null)

openedTabs +="\n\tid_tab=" + idTab+" WARNING: null ViewState";

else{

openedTabs += "\n\tid_tab=" + idTab + " id_view=";

openedTabs += (st.getView()==null?"null":(st.getView().getId() + " ("

+ st.getView().getCaption()) + ") opened as "

+ st.getOpenas());

}

}

String attributes = "";

Enumeration<String> attributeNames = session.getAttributeNames();

while(attributeNames.hasMoreElements()){

String an = attributeNames.nextElement();

attributes += an + " = " + session.getAttribute(an)+"\n";

}

String msg="";

if(serverStatus==ServerStatus.INITIALIZING)

msg+="["+initProgress+"%] ";

msg += (new Messages(srvSession.locale)).get(status_msg,status_msg_args);

return "CoinfAppServer\n"

+ msg

+ "\nopened sessions counter = "

+ openedSessionsCounter

+ " (May show more then real. Depends on garbge collector work.)"

+ "\nopened tabs in current session = "

+ srvSession.openedViews.size()

+ " :"

+ openedTabs

+ (serverStatus==ServerStatus.INITIALIZED?(

"\n\nhibernate statistic: "

+ HibernateManager.getSysHibernateManager().getSessionFactory().getStatistics().toString()

+ "\n\nhibernate 2nd lvl cache: hit="

+ HibernateManager.getSysHibernateManager().getSessionFactory().getStatistics()

.getSecondLevelCacheHitCount()

+ ", miss="

+ HibernateManager.getSysHibernateManager().getSessionFactory().getStatistics()

.getSecondLevelCacheMissCount()

+ ", put="

+ HibernateManager.getSysHibernateManager().getSessionFactory().getStatistics()

.getSecondLevelCachePutCount()

):"\nhibernate is not initialized yet")

+"\nMemory usage (Mb): "+((ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed()+ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed())/1048576)

// + "\nWorking sub JVMs:\n"

// + SubJVMController.getStatistics()

+ "\nhttpSession info:"

+ "\ncreation time = " + new Date(session.getCreationTime())

+ "\nID = " + session.getId()

+ "\nmax inactive interval = " + session.getMaxInactiveInterval() + " sec."

+ "\nyour ip is " + req.getRemoteAddr()

+ "\nwebapp context path = "+servletContext.getRealPath(File.separator)

+ "\nSession attributes:\n"

+ attributes

;

} catch (Throwable e) {

LOG.error("get stat exception. ",e);

return ErrorsHandler.fromException(e, srvSession.locale);

}

}

private JSONObject checkState(HttpServletRequest req) throws JSONException {

JSONObject res = new JSONObject();

if (serverStatus != ServerStatus.INITIALIZED) {

res.put("msg_type", "wrn");

res.put("msg",

"Server is not initialised. See \"/stat\" for more information.");

return res;

}

if (srvSession.user == null) {

srvSession.user = User.ANONYMOUS(); // Anonymous id=1

srvSession.locale = req.getLocale();

return null;

}

if (srvSession.httpSession == null)

srvSession.httpSession = req.getSession(true);

return null;

}

@GET

@Path("/view/download")

@Produces("application/json;charset=UTF-8")

public String downloadReport(@Context HttpServletRequest req,

@Context HttpServletResponse response,

@QueryParam("id_view") Integer id_view,

@QueryParam("page_number") Integer pageNumber,

@QueryParam("page_count") Integer pageCount,

@QueryParam("filter") String filter,

@QueryParam("sort") String sort,

@QueryParam("format") String format

){

HttpSession httpSession = req.getSession(true);

ViewState state = new ViewState();

JSONObject res = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if (id_view == null || format == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (id_view == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_view";

if (id_view == null && format == null)

moreThenOne = true;

if (format == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "format";

res.put("msg_type", "err");

res.put("msg",

missingParameter

+ ". Available parameters: id_view, format, page_count(?), filter(?), sort(?).");

return res.toString();

}

View v = (View) HibernateManager.getCurrentSession().get(View.class, id_view);

if (Authorization.getGrant(8, srvSession.user.getId(), id_view) < 1) {

res.put("msg_type", "err");

res.put("msg",

"User \"" + srvSession.user.getLogin()

+ "\" has not grants to access view \""

+ v.getCaption() + "\"");

return res.toString();

}

if (filter != null)

state.setFilter(new Filter(new JSONArray(filter)));

else

state.setFilter(null);

if (sort != null)

state.setSortOrder(new SortOrder(new JSONArray(sort)));

else if (v.getDefaultSort() != null)

state.setSortOrder(new SortOrder(new JSONArray(v

.getDefaultSort())));

else

state.setSortOrder(null);

if (pageNumber != null)

state.setPageNumber(pageNumber);

else

state.setPageNumber(1);

if (pageCount != null)

state.setPageCount(pageCount);

else

state.setPageCount(v.getDefaultPageCount());

state.setOpenas(format);

OutputStream out = response.getOutputStream();

String fileName = v.getAlias()+"_"+DateFormatter.format("dd-MM-yyyy HH-mm-ss 'GMT' Z",new Date(), req.getLocale(), srvSession.timeZone )+"."+format;

response.setContentType("application/octet-stream");

response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

ViewReportBuilder.exportReport(format, v.getData(state), v, out);

out.close();

return null;

}catch(Throwable e){

try {

response.setContentType("application/json;charset=UTF-8");

response.setHeader("Content-Disposition",null);

res.put("msg_type", "err");

res.put("msg", ErrorsHandler.fromException(e, srvSession.locale));

} catch (Exception ex) {}

LOG.error("Error when downloading view: ", e);

return res.toString();

}finally {

SessionContext.unset();

}

}

@POST

@Path("/view/open")

@Produces("application/json;charset=UTF-8")

public String openView(@Context HttpServletRequest req,

@FormParam("id_view") Integer id_view,

@FormParam("id_tab") Integer id_tab,

@FormParam("page_number") Integer pageNumber,

@FormParam("page_count") Integer pageCount,

@FormParam("filter") String filter,

@FormParam("sort") String sort,

@FormParam("openas") String openAs,

@FormParam("display_column") String displayColumn,

@FormParam("version") Long version) {

long time = 0, startTime = System.currentTimeMillis();

JSONObject stat = new JSONObject();

ViewState state;

JSONObject res = null;

JSONObject resdata = null;

boolean viewOpened = true;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if (id_view == null || openAs == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (id_view == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_view";

if (id_view == null && openAs == null)

moreThenOne = true;

if (openAs == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "openas";

res.put("msg_type", "err");

res.put("msg",

missingParameter

+ ". Available parameters: id_view, openas, id_tab(?), page_number(?), page_count(?), filter(?), sort(?).");

return res.toString();

}

View v = null;

if (id_tab != null) {

if (!srvSession.openedViews.containsKey(id_tab)) {

res.put("msg_type", "err");

res.put("msg", "Tab with id=" + id_tab + " does not exist.");

return res.toString();

}

state = srvSession.openedViews.get(id_tab);

if (state.view.getId() != id_view) {

viewOpened = false;

} else

v = state.getView();

} else {

state = new ViewState();

viewOpened = false;

}

if (!viewOpened) {

v = (View) HibernateManager.getCurrentSession().get(View.class, id_view);

if(v == null){

res.put("msg_type", "err");

res.put("msg",

"View with id=" + id_view + " does not exist.");

return res.toString();

}

if (Authorization.getGrant(Const.VIEW_ID, srvSession.user.getId(), id_view) < 1) {

res.put("msg_type", "err");

res.put("msg",

"User \"" + srvSession.user.getLogin()

+ "\" does not have grants to access view \""

+ v.getCaption() + "\"");

return res.toString();

}

viewOpened = false;

state.setView(v);

}

state.setSrvSession(srvSession);

Filter f;

if (filter != null)

state.setFilter(new Filter(new JSONArray(filter)));

else

state.setFilter(null);

if (sort != null)

state.setSortOrder(new SortOrder(new JSONArray(sort)));

else

state.setSortOrder(null);

if (pageNumber != null)

state.setPageNumber(pageNumber);

else

state.setPageNumber(1);

if (pageCount != null)

state.setPageCount(pageCount);

else

state.setPageCount(v.getDefaultPageCount());

state.setOpenas(openAs);

state.setDisplayColumn(displayColumn);

// /////////////

stat.put("other", System.currentTimeMillis() - startTime);

state.setMetaData(v.getMetaInf(srvSession.user, openAs,state));

if (!viewOpened) {

srvSession.openedViews.put(state.getId(), state);

}

resdata = new JSONObject(state.metaData.toString());

stat.put("getting meta inf", System.currentTimeMillis() - startTime

- stat.getLong("other"));

time = System.currentTimeMillis();

JSONObject data = v.getDataWithVersionControl(state).getJSONData();

JSONObject getDataStat = data.optJSONObject("stat");

if(getDataStat!=null){

stat.put("get view data", getDataStat);

}

resdata.put("preloaded_data",data);

resdata.put("id_tab", state.getId());

stat.put("total", System.currentTimeMillis() - startTime);

res.put("stat", statToString(stat));

LOG.debug("Stat: \n"+statToString(stat));

res.put("view", resdata.put("view_version",v.getVersion()));

if(id_tab!=null && version!=null && v.getVersion()>version){

res.put("msg_type", "wrn");

res.put("msg", "View was updated. Tab will be refreshed.");

}else {

res.put("msg_type", "inf");

res.put("msg", "View was opened successfully.");

}

return res.toString();

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", ErrorsHandler.fromException(e, srvSession.locale));

} catch (Exception ex) {

}

LOG.error("Error when open view: ", e);

return res.toString();

}finally {

SessionContext.unset();

}

}

@POST

@Path("/view/getmeta")

@Produces("application/json;charset=UTF-8")

public String getViewMeta(@Context HttpServletRequest req,

@FormParam("id_view") Integer id_view,

@FormParam("openas") String openas){

JSONObject res = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if (id_view == null) {

String missingParameter = "Missing parameter id_view. ";

res.put("msg_type", "err");

res.put("msg", missingParameter);

return res.toString();

}

View v = (View) HibernateManager.getCurrentSession().get(View.class, id_view);

if(v == null){

res.put("msg_type", "err");

res.put("msg",

"View with id=" + id_view + " does not exist.");

return res.toString();

}

if (Authorization.getGrant(Const.VIEW_ID, srvSession.user.getId(), id_view) < 1) {

res.put("msg_type", "err");

res.put("msg",

"User \"" + srvSession.user.getLogin()

+ "\" does not have grants to access view \""

+ v.getCaption() + "\"");

return res.toString();

}

if(openas == null)

openas = "grid";

ViewState vs = new ViewState();

vs.openas = openas;

vs.view = v;

JSONObject meta = v.getMetaInf(srvSession.user, openas, vs);

res.put("view",meta);

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("getViewMeta: ", e);

} catch (Exception ex) {}

return res.toString();

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/class/getprops")

@Produces("application/json;charset=UTF-8")

public String getClassMeta(@Context HttpServletRequest req,

@FormParam("id_class") Integer id_class

){

JSONObject res = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if (id_class == null) {

String missingParameter = "Missing parameter id_class. ";

res.put("msg_type", "err");

res.put("msg", missingParameter);

return res.toString();

}

MetaClass mc = (MetaClass) HibernateManager.getCurrentSession().get(MetaClass.class, id_class);

if(mc == null){

res.put("msg_type", "err");

res.put("msg",

"Class with id=" + id_class + " does not exist.");

return res.toString();

}

if (mc.getDefaultView()!=null && Authorization.getGrant(Const.VIEW_ID, srvSession.user.getId(), mc.getDefaultView().getId()) < 1) {

res.put("msg_type", "err");

res.put("msg",

"User \"" + srvSession.user.getLogin()

+ "\" does not have grants to access view \""

+ mc.getDefaultView().getCaption() + "\"");

return res.toString();

}

JSONArray props = new JSONArray();

for(MetaClass.Property p: mc.getProperties()){

JSONObject prop = new JSONObject();

prop.put("name",p.getName());

prop.put("caption",p.getCaption());

if(p.getTypeClass().getIsSystem())

prop.put("data_type",p.getTypeClass().getName());

prop.put("expr","this."+p.getName());

props.put(prop);

}

res.put("properties",props);

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("getClassProps: ", e);

} catch (Exception ex) {}

return res.toString();

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/view/getdata")

@Produces("application/json;charset=UTF-8")

public String getViewData(@Context HttpServletRequest req,

@FormParam("id_view") Integer id_view,

@FormParam("id_tab") Integer id_tab,

@FormParam("page_number") Integer pageNumber,

@FormParam("page_count") Integer pageCount,

@FormParam("filter") String filter,

@FormParam("sort") String sort,

@FormParam("ver") Long version) {

HttpSession httpSession = req.getSession(true);

ViewState state;

JSONObject res = null;

JSONObject stat = new JSONObject();

long start = System.currentTimeMillis();

int pageNumber_bak = 1;

int pageCount_bak = 0;

Filter filter_bak = null;

SortOrder sortOrder_bak = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if (id_view == null || id_tab == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (id_view == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_view";

if (id_view == null && id_tab == null)

moreThenOne = true;

if (id_tab == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_tab";

res.put("msg_type", "err");

res.put("msg",

missingParameter

+ ". Available parameters: id_view, id_tab, page_number(?), page_count(?), filter(?), sort(?).");

return res.toString();

}

View v = null;

if (!srvSession.openedViews.containsKey(id_tab)) {

res.put("msg_type", "err");

res.put("msg", "Tab with id=" + id_tab + " not exist.");

return res.toString();

}

state = srvSession.openedViews.get(id_tab);

if (state.view.getId() != id_view) {

res.put("msg_type", "err");

res.put("msg", "On this tab opened another view");

return res.toString();

}

v = state.getView();

pageNumber_bak = state.pageNumber;

pageCount_bak = state.pageCount;

filter_bak = state.filter;

sortOrder_bak = state.sortOrder;

try{

if(version!=null && v.getVersion()>version){

return openView(req,id_view,id_tab,pageNumber,pageCount,null,null,state.getOpenas(),state.getDisplayColumn(),version);

}

if (filter != null)

state.setFilter(new Filter(new JSONArray(filter)));

else

state.setFilter(null);

if (sort != null)

state.setSortOrder(new SortOrder(new JSONArray(sort)));

else

state.setSortOrder(null);

if (pageNumber != null)

state.setPageNumber(pageNumber);

else

state.setPageNumber(1);

if (pageCount != null)

state.setPageCount(pageCount);

else

state.setPageCount(v.getDefaultPageCount());

ViewData vd = v.getDataWithVersionControl(state);

JSONObject data = vd.getJSONData();

JSONObject getDataStat = data.optJSONObject("stat");

if(getDataStat!=null){

stat.put("get view data", getDataStat);

}

stat.put("total", System.currentTimeMillis()-start);

JSONObject preloadedData = data;

JSONObject view = new JSONObject()

.put("preloaded_data",preloadedData)

.put("view_version",v.getVersion());

res.put("view",view)

.put("stat", statToString(stat));

LOG.debug("Stat: \n"+statToString(stat));

} catch(Exception ex){

//restore previous state

state.filter = filter_bak;

state.sortOrder = sortOrder_bak;

state.pageNumber = pageNumber_bak;

state.pageCount = pageCount_bak;

throw ex;

}

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("getViewData: ", e);

} catch (Exception ex) {

}

return res.toString();

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/view/sort")

@Produces("application/json;charset=UTF-8")

public String sortView(@Context HttpServletRequest req,

@FormParam("id_view") Integer id_view,

@FormParam("id_tab") Integer id_tab,

@FormParam("sort") String sort,

@FormParam("ver") Long version) {

JSONObject res = null;

SortOrder sort_bak = null;

JSONObject stat = new JSONObject();

long start = System.currentTimeMillis();

try {

SessionContext.set(srvSession);

HttpSession httpSession = req.getSession(true);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if (id_view == null || id_tab == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (id_view == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_view";

if (id_tab == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_tab";

res.put("msg_type", "err");

res.put("msg", missingParameter

+ ". Available parameters: id_view, id_tab, sort(?).");

return res.toString();

}

View v = null;

if (!srvSession.openedViews.containsKey(id_tab)) {

res.put("msg_type", "err");

res.put("msg", "You can not use sort when view is not opened.");

return res.toString();

}

ViewState state = srvSession.openedViews.get(id_tab);

if (state.view.getId() != id_view) {

res.put("msg_type", "err");

res.put("msg", "On this tab opened another view");

return res.toString();

}

v = state.getView();

sort_bak = state.sortOrder;

try{

if(version!=null && v.getVersion()>version){

return openView(req,id_view,id_tab,state.getPageNumber(),state.getPageCount(),null,null,state.getOpenas(),state.getDisplayColumn(),version);

}

if (sort != null)

state.setSortOrder(new SortOrder(new JSONArray(sort)));

else

state.setSortOrder(null);

ViewData vd = v.getDataWithVersionControl(state);

JSONObject data = vd.getJSONData();

JSONObject getDataStat = data.optJSONObject("stat");

if(getDataStat!=null){

stat.put("get view data", getDataStat);

}

stat.put("total", System.currentTimeMillis()-start);

JSONObject preloadedData = data;

JSONObject view = new JSONObject()

.put("preloaded_data",preloadedData)

.put("view_version",v.getVersion());

res.put("view",view)

.put("stat", statToString(stat));

LOG.debug("Stat: \n"+statToString(stat));

} catch (Exception ex){

//restore previous state

state.sortOrder = sort_bak;

throw ex;

}

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("sortView: ", e);

} catch (Exception ex) {

}

return res.toString();

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/build_filter")

@Produces("application/json;charset=UTF-8")

public String filterView(@Context HttpServletRequest req,

@FormParam("filter_str") String filterStr){

JSONObject res = new JSONObject();

try{

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

Filter f = Filter.parseFilter(filterStr);

if(f == null)

res.put("filter",JSONObject.NULL);

else

res.put("filter",f.getFilters());

}catch (Throwable e){

try {

res.put("msg_type", "err");

res.put("msg", ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("Parse filter: ", e);

} catch (Exception ex) {

}

return res.toString();

}

return res.toString();

}

@POST

@Path("/view/filter")

@Produces("application/json;charset=UTF-8")

public String filterView(@Context HttpServletRequest req,

@FormParam("id_view") Integer id_view,

@FormParam("id_tab") Integer id_tab,

@FormParam("filter") String filter,

@FormParam("ver") Long version) {

HttpSession session = req.getSession(true);

JSONObject stat = new JSONObject();

long start = System.currentTimeMillis();

JSONObject res = null;

Filter filter_bak = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if (id_view == null || id_tab == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (id_view == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_view";

if (id_tab == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_tab";

res.put("msg_type", "err");

res.put("msg", missingParameter

+ ". Available parameters: id_view, id_tab, filter(?).");

return res.toString();

}

View v = null;

if (!srvSession.openedViews.containsKey(id_tab)) {

res.put("msg_type", "err");

res.put("msg",

"You can not use filter when view is not opened.");

return res.toString();

}

ViewState state = srvSession.openedViews.get(id_tab);

if (state.view.getId() != id_view) {

res.put("msg_type", "err");

res.put("msg", "On this tab opened another view");

return res.toString();

}

v = state.view;

filter_bak = state.filter;

Filter f;

try{

if(version!=null && v.getVersion()>version){

return openView(req,id_view,id_tab,state.getPageNumber(),state.getPageCount(),null,null,state.getOpenas(),state.getDisplayColumn(),version);

}

if (v.getDefaultFilter() != null) {

f = new Filter(new JSONArray(v.getDefaultFilter()));

if (filter != null) {

JSONArray fja = new JSONArray();

fja.put("and");

fja.put(new JSONArray(filter));

f.add(fja);

}

state.setFilter(f);

} else if (filter != null)

state.setFilter(new Filter(new JSONArray(filter)));

else

state.setFilter(null);

ViewData vd = v.getDataWithVersionControl(state);

JSONObject data = vd.getJSONData();

JSONObject getDataStat = data.optJSONObject("stat");

if(getDataStat!=null){

stat.put("get view data", getDataStat);

}

stat.put("total", System.currentTimeMillis()-start);

JSONObject preloadedData = data;

JSONObject view = new JSONObject()

.put("preloaded_data",preloadedData)

.put("view_version",v.getVersion());

res.put("view",view)

.put("stat", statToString(stat));

LOG.debug("Stat: \n"+statToString(stat));

} catch(Exception ex){

//restore previous state

state.filter = filter_bak;

throw ex;

}

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("filterView: ", e);

} catch (Exception ex) {

}

return res.toString();

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/view/getpage")

@Produces("application/json;charset=UTF-8")

public String getViewPage(@Context HttpServletRequest req,

@FormParam("id_view") Integer id_view,

@FormParam("id_tab") Integer id_tab,

@FormParam("page_number") Integer pageNumber,

@FormParam("page_count") Integer pageCount,

@FormParam("ver") Long version) {

HttpSession httpSession = req.getSession(true);

JSONObject stat = new JSONObject();

long start = System.currentTimeMillis();

JSONObject res = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if (id_view == null || id_tab == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (id_view == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_view";

if (id_tab == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_tab";

res.put("msg_type", "err");

res.put("msg",

missingParameter

+ ". Available parameters: id_view, id_tab, page_number(?), page_count(?).");

return res.toString();

}

View v = null;

if (!srvSession.openedViews.containsKey(id_tab)) {

res.put("msg_type", "err");

res.put("msg",

"You can not change page when view is not opened.");

return res.toString();

}

ViewState state = srvSession.openedViews.get(id_tab);

if (state.view.getId() != id_view) {

res.put("msg_type", "err");

res.put("msg", "On this tab opened another view");

return res.toString();

}

v = state.getView();

if(version!=null && v.getVersion()>version){

return openView(req,id_view,id_tab,state.getPageNumber(),state.getPageCount(),null,null,state.getOpenas(),state.getDisplayColumn(),version);

}

if (pageNumber != null)

state.setPageNumber(pageNumber);

if (pageCount != null)

state.setPageCount(pageCount);

long time = System.currentTimeMillis();

ViewData vd = v.getDataWithVersionControl(state);

JSONObject data = vd.getJSONData();

JSONObject getDataStat = data.optJSONObject("stat");

if(getDataStat!=null){

stat.put("get view data", getDataStat);

}

stat.put("total", System.currentTimeMillis()-start);

JSONObject preloadedData = data;

JSONObject view = new JSONObject()

.put("preloaded_data",preloadedData)

.put("view_version",v.getVersion());

res.put("view",view)

.put("stat", statToString(stat));

LOG.debug("Stat: \n"+statToString(stat));

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("getViewPage: ", e);

} catch (Exception ex) {

}

return res.toString();

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/tabs/getmethods")

//@Produces("application/json;charset=UTF-8")

public String tabsMethods(@Context HttpServletRequest req,

@FormParam("id_tab") String id_tab) throws JSONException {

HttpSession session = req.getSession(true);

JSONObject res = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if (id_tab==null) {

res.put("msg_type", "err");

res.put("msg","Missing parameter id_tab.");

return res.toString();

}

JSONArray tabs = null;

try{

Integer i = Integer.parseInt(id_tab);

tabs = new JSONArray();

tabs.put(i);

}catch (Exception e){

tabs = new JSONArray(id_tab);

}

JSONObject tabsToMethods = new JSONObject();

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

Integer t = tabs.getInt(i);

ViewState vs = srvSession.openedViews.get(t);

if(vs.getOpenas().equalsIgnoreCase("form")) continue;

JSONArray methods = View.getAvailableMethods(vs);

tabsToMethods.put(t.toString(),methods);

}

res.put("tab_to_methods",tabsToMethods);

res.put("msg", "OK");

res.put("msg_type", "inf");

} catch (Throwable e) {

res.put("msg_type", "err");

res.put("msg", "Can not close tab. " + ErrorsHandler.fromException(e, srvSession.locale));

return res.toString();

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/closetab")

//@Produces("application/json;charset=UTF-8")

public String closeTab(@Context HttpServletRequest req,

@FormParam("id_tab") Integer id_tab) throws JSONException {

HttpSession session = req.getSession(true);

JSONObject res = null;

try {

long time = System.currentTimeMillis();

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

long time2=System.currentTimeMillis();

if (id_tab == null) {

srvSession.openedViews.clear();

res.put("msg", "All tabs closed successfully.");

} else {

if (!srvSession.openedViews.containsKey(id_tab)) {

res.put("msg_type", "err");

res.put("msg", "Can not close tab. Tab with id=" + id_tab

+ " did not open for this session.");

return res.toString();

}

if(srvSession.openedViews.get(id_tab).methodStatus==ViewState.CallStatus.Status.STARTED){

res.put("msg_type", "wrn");

res.put("msg", "Can not close tab while method is executing.");

return res.toString();

}

srvSession.openedViews.remove(id_tab);

res.put("msg", "Tab with id=" + id_tab

+ " closed successfully.");

}

long time3 = System.currentTimeMillis();

LOG.debug("CLOSE_TAB STAT: checkState="+(time2-time)+" remove tab="+(time2-time3));

res.put("msg_type", "inf");

} catch (Throwable e) {

res.put("msg_type", "err");

res.put("msg", "Can not close tab. " + ErrorsHandler.fromException(e, srvSession.locale));

return res.toString();

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/callmethod/status")

@Produces("application/json;charset=UTF-8")

public String callStatus(@Context HttpServletRequest req,

@FormParam("id_tab") Integer id_tab,// -1 dslConsole

@FormParam("from_time") String from_time)

throws JSONException {

JSONObject res = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if(id_tab==null){

res.put("msg_type", "err");

res.put("msg","Missing parameter \"id_tab\".");

return res.toString();

}

ViewState vs = srvSession.openedViews.get(id_tab);

if(vs==null){

res.put("msg_type", "err");

res.put("msg","Tab with id = "+id_tab+" does not exist.");

return res.toString();

}

JSONArray statuses = new JSONArray();

Timestamp timestamp;

if(from_time!=null)

timestamp = DateFormatter.parseTimestamp(from_time);

else

timestamp = new Timestamp(0);

if(vs.callStatuses!=null)

for (ViewState.CallStatus cs: vs.callStatuses)

statuses.put(cs.toJSON(timestamp));

res.put("call_statuses",statuses);

if(vs.methodStatus==null){

res.put("status",JSONObject.NULL);

res.put("msg_type","inf");

res.put("msg","No methods on this tab.");

};

res.put("status",vs.methodStatus);

if(vs.methodFailMessage!=null){

res.put("msg_type","err");

res.put("msg",vs.methodFailMessage);

}

} catch (Throwable e) {

res.put("msg_type", "err");

res.put("msg",

"Failed with exception: " + ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("Get call status exception. ", e);

return res.toString();

}finally {

SessionContext.unset();

MethodListener.unset();

}

return res.toString();

}

@POST

@Path("/callmethod")

@Produces("application/json;charset=UTF-8")

public String callMethod(@Context HttpServletRequest req,

@FormParam("call") String callsGraph,/* json object or array */

@FormParam("id_tab") Integer id_tab)

throws JSONException {

JSONObject res = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if(callsGraph==null){

res.put("msg_type", "err");

res.put("msg","Missing parameter \"call\".");

return res.toString();

}

ViewState vs = srvSession.openedViews.get(id_tab);

//if(id_tab!=null && vs!=null && vs.methodStatus!=null && vs.methodStatus.equalsIgnoreCase(ViewState.CallStatus.Status.STARTED))

new Thread(new CallsGraph.NewThreadRunner(callsGraph,srvSession,id_tab)).start();

res.put("msg_type", "inf");

res.put("msg", "Method is executing...");

} catch (Throwable e) {

res.put("msg_type", "err");

res.put("msg",

"Method call was failed with exception: " + ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("Method call exception. ", e);

return res.toString();

}finally {

SessionContext.unset();

MethodListener.unset();

}

return res.toString();

}

@POST

@Path("view/callmethod_nocommit")

@Produces("application/json;charset=UTF-8")

public String callMethodNoCommit(@Context HttpServletRequest req,

@FormParam("call") String callsGraph,/* json object or array */

@FormParam("id_tab") Integer id_tab,

@FormParam("id_view") Integer id_view,

@FormParam("page_number") Integer pageNumber,

@FormParam("page_count") Integer pageCount,

@FormParam("filter") String filter,

@FormParam("sort") String sort,

@FormParam("openas") String openAs,

@FormParam("version") Long version)

throws JSONException {

JSONObject res = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if(callsGraph==null){

res.put("msg_type", "err");

res.put("msg","Missing parameter \"call\".");

return res.toString();

}

CallsGraph cg = new CallsGraph(callsGraph);

Session sysSession = HibernateManager.getCurrentSession();

MetaClass.Method firstMethod = (MetaClass.Method) sysSession.get(MetaClass.Method.class,cg.getCallsJson().getJSONObject(0).getInt("method_id"));

Session s = HibernateManager.getCurrentSession(firstMethod.getMetaClass());

Transaction tx = null;

try{

tx = s.beginTransaction();

cg.useSession(s);

cg.resolveCallsGraph();

String viewRes = openView(req, id_view, id_tab, pageNumber, pageCount, filter, sort, openAs,null, version);

return viewRes;

} finally {

try{

tx.rollback();

}catch (Exception ex){}

}

} catch (Throwable e) {

res.put("msg_type", "err");

res.put("msg",

"Method call was failed with exception: " + ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("Method call exception. ", e);

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/session_state")

@Produces("application/json;charset=UTF-8")

public String getSessionState(@Context HttpServletRequest req) throws JSONException {

JSONObject res = null;

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

res.put("data", srvSession.getCurrentState());

res.put("msg_type", "inf");

res.put("msg", "successful");

} catch (Exception e) {

res.put("msg_type", "err");

res.put("msg",

"GetSessionState was failed with exception: " + ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("Get session state exception. ", e);

return res.toString();

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/login")

@Produces("application/json;charset=UTF-8")

public String login(@Context HttpServletRequest req,

@FormParam("login") String login,

@FormParam("password") String passSHA1,

@FormParam("client_id") String clientID,

@FormParam("date_offset") Integer tzOffset, //minutes Local + tzOffset = UTC

@FormParam("disconnected") Boolean disconnected) {

if(disconnected==null)

disconnected = false;

JSONObject result = null;

User u = null;

try {

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

if (login == null || passSHA1 == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (login == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "login";

if (passSHA1 == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "password";

result.put("msg_type", "err");

result.put("msg",

missingParameter

+ ". Available parameters: id_view, caption, filter(?), sort(?), comment(?).");

return result.toString();

}

SessionContext.set(srvSession);

boolean wasAnonymous = false;

boolean needSessionState = false;

boolean needLogout = false;

if(srvSession.user==null)

srvSession.user = User.ANONYMOUS();

if(srvSession.user.equals(User.ANONYMOUS()))

wasAnonymous = true;

if(login.equals(User.ANONYMOUS().getLogin()) && !wasAnonymous){

u = srvSession.user;

needSessionState = true;

}else{

if (srvSession.user.getLogin()!=login) {

needLogout =true;

} else {

if(login.equals(User.ANONYMOUS().getLogin()) && wasAnonymous)

needLogout = true;

else

needSessionState = true;

}

u = Authorization.login(login, passSHA1);

}

if(login.equals(User.ANONYMOUS().getLogin()) && wasAnonymous && disconnected)

needSessionState = true;

JSONObject data = new JSONObject();

if(needSessionState){

JSONArray tabs = new JSONArray();

Iterator<Map.Entry<Integer,ViewState>> iterator = srvSession.openedViews.entrySet().iterator();

while (iterator.hasNext()){

Map.Entry<Integer,ViewState> e = iterator.next();

ViewState vs = e.getValue();

JSONObject tab = new JSONObject();

tab.put("id_tab",e.getKey());

if(vs.getOpenas().equalsIgnoreCase("grid") && Authorization.getGrant(Const.VIEW_ID,srvSession.user.getId(),vs.getView().getId()) > 0){

vs.refreshMetaData();

tab.put("metadata",vs.getMetaData());

tab.put("closed",false);

} else {

iterator.remove();

tab.put("closed",true);

}

tabs.put(tab);

}

data.put("tabs",tabs);

}

if(needLogout)

logout(req);

data.put("login", u.getLogin());

data.put("firstname", u.getFirstname());

data.put("midname", u.getMidname());

data.put("lastname", u.getLastname());

data.put("is_admin", u.isSuperuser());

srvSession.menu = Menu.makeMenu(u);

data.put("menu",srvSession.menu );

data.put("view_presets", ViewPreset.getAvailablePresets(u));

data.put("settings", ClientSettings.get(u,clientID));

result.put("data", data);

result.put("msg_type", "inf");

result.put("msg", "You logged in.");

srvSession.user = u;

srvSession.locale=req.getLocale();

if(tzOffset==null)

tzOffset=0;

srvSession.timeZone = TimeZone.getTimeZone(TimeZone.getAvailableIDs(-tzOffset*60000)[0]);//TODO

return result.toString();

} catch (Exception e) {

try{

result.put("msg_type", "err");

result.put("msg", ErrorsHandler.fromException(e, req.getLocale()));

}catch (JSONException je){}

LOG.error("Error when logging in. ", e);

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/logout")

@Produces("application/json;charset=UTF-8")

public String logout(@Context HttpServletRequest req) {

JSONObject result = new JSONObject();

try {

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

SessionContext.set(srvSession);

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "wrn");

result.put("msg", "You have not logged in.");

}else{

srvSession.user = null;

srvSession.openedViews.clear();

result.put("msg_type", "inf");

result.put("msg", "logged out.");

}

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when logging out. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/profile/edit")

@Produces("application/json;charset=UTF-8")

public String editProfile(@Context HttpServletRequest req,

@FormParam("cur_password") String curPass,

@FormParam("new_password") String newPass,

@FormParam("confirm_password") String confirmPass,

@FormParam("firstname") String firstName,

@FormParam("midname") String midName,

@FormParam("lastname") String lastName,

@FormParam("email") String email

) {

JSONObject result = new JSONObject();

try {

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

SessionContext.set(srvSession);

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "You have not logged in.");

return result.toString();

}

if(curPass!=null)

srvSession.user.changePassword(curPass,newPass,confirmPass);

if(firstName!=null)

srvSession.user.setFirstname(firstName);

if(midName!=null)

srvSession.user.setMidname(midName);

if(lastName!=null)

srvSession.user.setLastname(lastName);

if(email!=null)

srvSession.user.setEmail(email);

HibernateManager.getCurrentSession().update(srvSession.user);

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when edit user profile . " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/profile/get")

@Produces("application/json;charset=UTF-8")

public String editProfile(@Context HttpServletRequest req

) {

JSONObject result = new JSONObject();

try {

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

SessionContext.set(srvSession);

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "You have not logged in.");

return result.toString();

}

JSONObject profile = new JSONObject();

profile.put("id",srvSession.user.getId());

profile.put("login",srvSession.user.getLogin());

profile.put("firstname",srvSession.user.getFirstname());

profile.put("midname",srvSession.user.getMidname());

profile.put("lastname",srvSession.user.getLastname());

profile.put("email",srvSession.user.getEmail());

JSONArray groups = new JSONArray();

for(Usergroup ug: srvSession.user.getGroups()){

groups.put(ug.getCaption());

}

profile.put("usergroups",groups);

result.put("profile",profile);

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when edit user profile . " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/view_preset/save")

@Produces("application/json;charset=UTF-8")

public String saveViewPreset(@Context HttpServletRequest req,

@FormParam("id_view") Integer id_view,

@FormParam("caption") String caption,

@FormParam("filter") String filter,

@FormParam("sort") String sort,

@FormParam("comment") String comment)

{

JSONObject result = new JSONObject();

try {

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

SessionContext.set(srvSession);

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "Anonymous can not save presets.");

return result.toString();

}

if (id_view == null || caption == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (id_view == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_view";

if (caption == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "caption";

result.put("msg_type", "err");

result.put("msg",

missingParameter

+ ". Available parameters: id_view, caption, filter(?), sort(?), comment(?).");

return result.toString();

}

Session s = HibernateManager.getCurrentSession();

s.beginTransaction();

ViewPreset preset = new ViewPreset();

preset.setCaption(caption);

preset.setUser(srvSession.user);

preset.setView((View) s.get(View.class, id_view));

preset.setFilter(filter);

preset.setSort(sort);

preset.setComment(comment);

s.save(preset);

s.getTransaction().commit();

result.put("msg_type", "inf");

result.put("msg", "View preset saved.");

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when saving view preset. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/view_preset/update")

@Produces("application/json;charset=UTF-8")

public String updateViewPreset(@Context HttpServletRequest req,

@FormParam("id_preset") Integer id_preset,

@FormParam("id_view") Integer id_view,

@FormParam("caption") String caption,

@FormParam("filter") String filter,

@FormParam("sort") String sort,

@FormParam("comment") String comment)

{

JSONObject result = new JSONObject();

try {

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

SessionContext.set(srvSession);

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "Anonymous can not update presets.");

return result.toString();

}

if (id_view == null || caption == null || id_preset==null || StringUtils.isBlank(caption)) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (id_view == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_view";

if (id_view == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_preset";

if (caption == null || StringUtils.isBlank(caption))

missingParameter += " " + (moreThenOne ? ", " : "")

+ "caption";

result.put("msg_type", "err");

result.put("msg",

missingParameter

+ ". Available parameters: id_view, caption, filter(?), sort(?), comment(?).");

return result.toString();

}

Session s = HibernateManager.getCurrentSession();

s.beginTransaction();

ViewPreset preset = (ViewPreset) s.get(ViewPreset.class,id_preset);

if(preset==null)

throw new NotFoundException("View preset id="+id_preset+" does not exist.");

if(!preset.getUser().equals(srvSession.user))

throw new AccessControlException("User \""+srvSession.user.getLogin()+"\" has not grants to access preset id="+id_preset);

preset.setCaption(caption);

preset.setView((View) s.get(View.class, id_view));

preset.setFilter(filter);

preset.setSort(sort);

preset.setComment(comment);

s.update(preset);

s.getTransaction().commit();

result.put("msg_type", "inf");

result.put("msg", "View preset updated.");

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when updating view preset. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/view_preset/delete")

@Produces("application/json;charset=UTF-8")

public String deleteViewPreset(@Context HttpServletRequest req,

@FormParam("id_view") Integer id_view,

@FormParam("caption") String caption)

{

JSONObject result = new JSONObject();

try {

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

SessionContext.set(srvSession);

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "Anonymous can not delete presets.");

return result.toString();

}

if (id_view == null || caption == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (id_view == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_view";

if (caption == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "caption";

result.put("msg_type", "err");

result.put("msg",

missingParameter

+ ". Available parameters: id_view, caption.");

return result.toString();

}

Session s = HibernateManager.getCurrentSession();

s.beginTransaction();

Query q = s.createQuery("delete ViewPreset where view.id=:id_view and caption=:caption and user.id=:id_user");

q.setInteger("id_view", id_view);

q.setString("caption", caption);

q.setInteger("id_user", srvSession.user.getId());

q.executeUpdate();

s.getTransaction().commit();

result.put("msg_type", "inf");

result.put("msg", "View preset was deleted.");

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when saving view preset. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/wizard_step")

@Produces("application/json;charset=UTF-8")

public String wizardStep(@Context HttpServletRequest req,

@FormParam("data") String data,

@FormParam("id_tab") Integer id_tab,

@FormParam("cur_step") Integer curStep)

{

JSONObject result = null;

try {

SessionContext.set(srvSession);

if ((result = checkState(req)) != null)

return result.toString();

if (id_tab==null || !srvSession.openedViews.containsKey(id_tab)) {

result.put("msg_type", "err");

result.put("msg", "Tab with id=" + id_tab + " does not exist.");

return result.toString();

}

result = new JSONObject();

ViewState vs = srvSession.openedViews.get(id_tab);

if(!(vs.getView() instanceof WizardView)){

result.put("msg_type", "err");

result.put("msg", "View " + vs.getView().getAlias() + " is not a wizard.");

return result.toString();

}

JSONObject jsonData = new JSONObject(data);

Map<String, Integer> columnsToIndex = new HashMap<String, Integer>();

JSONArray columns = new JSONArray();

Iterator<String> keysIter = jsonData.keys();

int i = 0;

while (keysIter.hasNext()){

String key = keysIter.next();

columns.put(jsonData.get(key));

columnsToIndex.put(key, i);

i++;

}

JSONObject nextStep = ((WizardView)vs.getView()).nextStage(curStep,columnsToIndex,columns);

if(nextStep.get("step_num").equals(JSONObject.NULL)){

result.put("msg_type", "inf");

result.put("next_step", nextStep);

result.put("msg", "Finish step.");

} else {

result.put("msg_type", "inf");

result.put("next_step", nextStep);

result.put("msg", "Next step.");

}

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Wizard step error. " + ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("Wizard step error. ",e);

} catch (Exception e1) {

LOG.error("Error handler exception.",e1);

return "Error handler exception.";

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/view/calc_field")

@Produces("application/json;charset=UTF-8")

public String viewCalcField(@Context HttpServletRequest req,

@FormParam("id_tab") Integer id_tab,

@FormParam("field_alias") String field_alias,

@FormParam("data") String dataJson,

@FormParam("links") String linksJson)

{

JSONObject result = new JSONObject();

try {

SessionContext.set(srvSession);

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

if (id_tab==null || !srvSession.openedViews.containsKey(id_tab)) {

result.put("msg_type", "err");

result.put("msg", "Tab with id=" + id_tab + " does not exist.");

return result.toString();

}

if (field_alias == null || dataJson == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (field_alias == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "field_alias";

if (dataJson == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "data";

result.put("msg_type", "err");

result.put("msg",

missingParameter

+ ". Available parameters: field_alias, data.");

return result.toString();

}

View openedView = srvSession.openedViews.get(id_tab).getView();

CallsGraph callsGraph = null;

if(linksJson!=null){

JSONArray callsJson = new JSONArray();

JSONObject links = new JSONObject(linksJson);

Iterator<String> it = links.keys();

while (it.hasNext()){

JSONObject call = links.getJSONObject(it.next());

callsJson.put(call);

}

if(callsJson.length()>0){

callsGraph = new CallsGraph(callsJson);

callsGraph.setNoCommitMode(true);

}

}

Session session = HibernateManager.getSession(openedView.getMetaClass());

Transaction tx = null;

JSONObject data = new JSONObject(dataJson);

try{

tx = session.beginTransaction();

if(callsGraph!=null){

callsGraph.useSession(session);

callsGraph.resolveCallsGraph();

}

List<View.Property> newProps = new ArrayList<View.Property>();

View tempView = new HQLView(openedView.getMetaClass(),openedView.getAlias(), openedView.getCaption(), null, 1, openedView.getDefaultFilter(), null, false, openedView.getFromDual(), openedView.getMethod());

for(View.Property p: openedView.getProperties()){

if(p.getAlias().equals(field_alias)){

newProps.add(new View.Property(tempView,p.getCaption(),p.getAlias(),p.getExpression(),p.getIsJavaMethod(),false,false,false,p.getIsCalcField(),null,null,null,null,null,0,0,1,null,null));

break;

}

}

Iterator<String> it = data.keys();

while (it.hasNext()){

String key = it.next();

Object value = data.get(key);

String expr;

if(value instanceof JSONObject && ((JSONObject)value).has("link")){

if(callsGraph==null)

value = null;

else

value = callsGraph.getMethodResult( ((JSONObject)value).getInt("link"));

if(value != null){

try{

value = MetaClass.getIdFromObject(value);

} catch (Exception e){}

}

}

if(value==null || value.equals(JSONObject.NULL))

expr = "null";

else if(value instanceof Number || value instanceof Boolean)

expr = value.toString();

else if(value instanceof String)

expr = "'"+Filter.escapeQuotes((String)value)+"'";

else

expr = value.toString();

newProps.add(new View.Property(tempView,key,key,expr,false,false,false,false,false,null,null,null,null,null,0,0,1,null,null));

}

tempView.setProperties(newProps);

ViewData vd = tempView.getData(srvSession.openedViews.get(id_tab));

Object resultValue = vd.get(0).get(field_alias);

if(resultValue!=null){

Class<?> resClass = resultValue.getClass();

if(!(resClass.isPrimitive() || resultValue instanceof Number || resultValue instanceof String || resultValue instanceof Boolean)){

try{

resultValue = MetaClass.getIdFromObject(resultValue);

}catch (Exception e){

LOG.warn("Cant get id from object ["+resultValue+"]", e);

}

}

}

Object calcRes = DateFormatter.formatIfDate(resultValue, SessionContext.get().locale, SessionContext.get().timeZone);

if(calcRes != null)

result.put("calc_res",calcRes);

else

result.put("calc_res",JSONObject.NULL);

} finally {

try{

tx.rollback();

}catch (Exception ex){}

}

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when calculating field. " + ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("Error when calculating field. ",e);

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/console_template/save")

@Produces("application/json;charset=UTF-8")

public String saveConsoleTemplate(@Context HttpServletRequest req,

//@FormParam("id_template") Integer id_template,

@FormParam("caption") String caption,

@FormParam("text") String text,

@FormParam("comment") String comment)

{

JSONObject result = new JSONObject();

try {

SessionContext.set(srvSession);

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "Anonymous can not save console templates.");

return result.toString();

}

if (text == null || caption == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (text == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "text";

if (caption == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "caption";

result.put("msg_type", "err");

result.put("msg",

missingParameter

+ ". Available parameters: caption, text, comment(?).");

return result.toString();

}

Session s = HibernateManager.getCurrentSession();

s.beginTransaction();

ConsoleTemplate template = new ConsoleTemplate(srvSession.user, caption, comment, text);

s.save(template);

s.getTransaction().commit();

result.put("msg_type", "inf");

result.put("msg", "Console template saved.");

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when saving console template. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/console_template/update")

@Produces("application/json;charset=UTF-8")

public String updateConsoleTemplate(@Context HttpServletRequest req,

@FormParam("id_template") Integer id_template,

@FormParam("caption") String caption,

@FormParam("text") String text,

@FormParam("comment") String comment)

{

JSONObject result = new JSONObject();

try {

SessionContext.set(srvSession);

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "Anonymous can not update console templates.");

return result.toString();

}

if (id_template==null || text == null || caption == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (id_template == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "id_template";

if (text == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "text";

if (caption == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "caption";

result.put("msg_type", "err");

result.put("msg",

missingParameter

+ ". Available parameters: id_template, caption, text, comment(?).");

return result.toString();

}

Session s = HibernateManager.getCurrentSession();

s.beginTransaction();

ConsoleTemplate template = (ConsoleTemplate)s.get(ConsoleTemplate.class, id_template);

if(template==null)

throw new NotFoundException("Console template id="+id_template+" does not exist.");

if(!srvSession.user.equals(template.getUser()))

throw new AccessControlException("User \""+srvSession.user.getLogin()+"\" has not grants to access template id="+id_template);

template.setCaption(caption);

template.setComment(comment);

template.setText(text);

s.update(template);

s.getTransaction().commit();

result.put("msg_type", "inf");

result.put("msg", "Console template updated.");

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when updating console template. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/console_template/delete")

@Produces("application/json;charset=UTF-8")

public String deleteConsoleTemplate(@Context HttpServletRequest req,

@FormParam("id_template") Integer id_template)

{

JSONObject result = new JSONObject();

try {

SessionContext.set(srvSession);

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "Anonymous can not delete console templates.");

return result.toString();

}

if (id_template==null) {

String missingParameter = "Missing parameter id_template. ";

result.put("msg_type", "err");

result.put("msg", missingParameter);

return result.toString();

}

Session s = HibernateManager.getCurrentSession();

s.beginTransaction();

ConsoleTemplate template = (ConsoleTemplate)s.get(ConsoleTemplate.class, id_template);

if(template==null)

throw new NotFoundException("Console template id="+id_template+" does not exist.");

if(!srvSession.user.equals(template.getUser()))

throw new AccessControlException("User \""+srvSession.user.getLogin()+"\" has not grants to access template id="+id_template);

s.delete(template);

s.getTransaction().commit();

result.put("msg_type", "inf");

result.put("msg", "Console template deleted.");

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when deleting console template. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/console_template/list")

@Produces("application/json;charset=UTF-8")

public String deleteConsoleTemplate(@Context HttpServletRequest req)

{

JSONObject result = new JSONObject();

try {

SessionContext.set(srvSession);

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "Anonymous can not access console templates.");

return result.toString();

}

JSONArray templates = ConsoleTemplate.getAvailableTemplates(srvSession.user);

result.put("templates",templates);

result.put("msg_type", "inf");

result.put("msg", "OK");

} catch (Exception e) {

try {

result.put("msg_type", "err");

result.put("msg", "Error when getting console templates. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/execute_dsl")

@Produces("application/json;charset=UTF-8")

public String dslConsole(@Context HttpServletRequest req,

@FormParam("dsl") String dsl)

{

JSONObject result = new JSONObject();

Transaction tx = null;

Session s = HibernateManager.getCurrentSession();

try {

SessionContext.set(srvSession);

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "Anonymous can not execute DSL.");

return result.toString();

}

if(!srvSession.user.isSuperuser())

throw new AccessControlException("You do not have permission to access.");

tx = s.beginTransaction();

if (dsl==null) {

result.put("msg_type", "err");

result.put("msg","Missing parameter dsl.");

return result.toString();

}

ViewState console_tab;

if(!srvSession.openedViews.containsKey(Const.DSL_CONSOLE_TAB)){

console_tab = new ViewState();

console_tab.openas = "none";

srvSession.openedViews.put(Const.DSL_CONSOLE_TAB, console_tab);

}

try{

console_tab = srvSession.openedViews.get(Const.DSL_CONSOLE_TAB);

console_tab.callStatuses = null;

console_tab.methodFailMessage = null;

MethodListener.set(console_tab);

MethodListener.get().methodStatus = ViewState.CallStatus.Status.STARTED;

MetaClass.Method methodStub = new MetaClass.Method();

methodStub.setCaption("DSL console");

MethodListener.setMethodContext(methodStub);

String tmp = StringUtils.trim(dsl).substring(0, 6);

if(tmp.equalsIgnoreCase("create") || tmp.equalsIgnoreCase("delete")){

MetaClass.execute(dsl);

}else {

dsl = "{"+dsl+"\n}";

CorinfDSLConsole.execute(new ByteArrayInputStream( dsl.getBytes("UTF-8") ));

}

tx.commit();

MethodListener.methodEnd();

MethodListener.get().methodStatus = ViewState.CallStatus.Status.FINISHED;

} catch(Exception fail){

MethodListener.methodEnd(fail);

MethodListener.get().methodStatus = ViewState.CallStatus.Status.FAILED;

MethodListener.fail(ErrorsHandler.fromException(fail, SessionContext.get().locale));

} finally {

MethodListener.unset();

}

result.put("msg_type", "inf");

result.put("msg", "Script was successfully executed.");

} catch (Throwable e) {

if(tx!=null)

tx.rollback();

try {

LOG.error("Error when executing DSL script.",e);

result.put("msg_type", "err");

result.put("msg", "Error when executing DSL script. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/settings/save")

@Produces("application/json;charset=UTF-8")

public String saveSettings(@Context HttpServletRequest req,

@FormParam("client_id") String clientID,

@FormParam("settings") String settings)

{

JSONObject result = new JSONObject();

try {

SessionContext.set(srvSession);

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

if(srvSession.user==null || User.ANONYMOUS().getId()==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "Anonymous can not save settings.");

return result.toString();

}

if (clientID == null || settings == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (clientID == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "client_id";

if (settings == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "settings";

result.put("msg_type", "err");

result.put("msg",

missingParameter

+ ". Available parameters: client_id, settings.");

return result.toString();

}

ClientSettings.set(srvSession.user, clientID,new JSONObject(settings));

result.put("msg_type", "inf");

result.put("msg", "Settings were successfully saved.");

} catch (Throwable e) {

try {

LOG.error("Error when saving settings.",e);

result.put("msg_type", "err");

result.put("msg", "Error when saving settings. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/settings/remove")

@Produces("application/json;charset=UTF-8")

public String removeSettings(@Context HttpServletRequest req,

@FormParam("client_id") String clientID,

@FormParam("keys") String keys)//JSONArray keys to remove

{

JSONObject result = new JSONObject();

try {

SessionContext.set(srvSession);

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

if(srvSession.user==null || Const.ANONYMOUS_USER_ID==srvSession.user.getId()){

result.put("msg_type", "err");

result.put("msg", "Anonymous can not change settings.");

return result.toString();

}

if (clientID == null || keys == null) {

String missingParameter = "Missing parameter";

boolean moreThenOne = false;

if (clientID == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "client_id";

if (keys == null)

missingParameter += " " + (moreThenOne ? ", " : "")

+ "keys";

result.put("msg_type", "err");

result.put("msg",

missingParameter

+ ". Available parameters: client_id, keys.");

return result.toString();

}

ClientSettings.remove(srvSession.user, clientID,new JSONArray(keys));

result.put("msg_type", "inf");

result.put("msg", "Settings were successfully removed.");

} catch (Throwable e) {

try {

LOG.error("Error when saving settings.",e);

result.put("msg_type", "err");

result.put("msg", "Error when removing settings. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/resetgrants")

@Produces("application/json;charset=UTF-8")

public String resetGrants(@Context HttpServletRequest req) {

JSONObject result = new JSONObject();

try {

SessionContext.set(srvSession);

if ((result = checkState(req)) != null)

return result.toString();

result = new JSONObject();

if(!srvSession.user.isSuperuser())

throw new AccessControlException("You do not have permission to access.");

Authorization.generateAccessMatrixes();

result.put("msg_type", "inf");

result.put("msg", "Access matrix was regenerated.");

} catch (Throwable e) {

try {

result.put("msg_type", "err");

result.put("msg",

"Error when resetting grants. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return result.toString();

}

@POST

@Path("/testing/addusers")

@Produces("application/json;charset=UTF-8")

public String addUsers(@Context HttpServletRequest req,

@FormParam("number") Integer number,

@FormParam("users_in_group") Integer usersInGroup,

@FormParam("groups_in_group") Integer groupsInGroup) {

JSONObject res = new JSONObject();

try {

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if(!srvSession.user.isSuperuser())

throw new AccessControlException("You do not have permission to access.");

if (number == null) {

res.put("msg_type", "err");

res.put("msg",

"Missing parameter number. Available parameters: number, users_in_group(?), groups_in_group(?).");

return res.toString();

}

if (groupsInGroup == null)

groupsInGroup = 0;

if (usersInGroup == null)

usersInGroup = 0;

TestCorinf.addRandomUsers(number, usersInGroup, groupsInGroup);

res.put("msg_type", "inf");

res.put("msg", "Users have been generated successfully.");

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", "Error when generating users. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/testing/removeusers")

@Produces("application/json;charset=UTF-8")

public String removeUsers(@Context HttpServletRequest req) {

JSONObject res = new JSONObject();

try {

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

SessionContext.set(srvSession);

if(!srvSession.user.isSuperuser())

throw new AccessControlException("You do not have permission to access.");

TestCorinf.removeRandomUsers();

res.put("msg_type", "inf");

res.put("msg", "Users have been removed successfully.");

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", "Error when removing users. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/testing/addview")

@Produces("application/json;charset=UTF-8")

public String addRandomViews(@Context HttpServletRequest req,

@FormParam("number") Integer number,

@FormParam("prop_in_view") Integer propInView) {

JSONObject res = new JSONObject();

try {

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

SessionContext.set(srvSession);

if(!srvSession.user.isSuperuser())

throw new AccessControlException("You do not have permission to access.");

if (number == null) {

res.put("msg_type", "err");

res.put("msg",

"Missing parameter number. Available parameters: number, prop_in_view(?).");

return res.toString();

}

if (propInView == null)

propInView = 0;

TestCorinf.addRandomViews(number, propInView);

res.put("msg_type", "inf");

res.put("msg", "Views have been generated successfully.");

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", "Error when generating views. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return res.toString();

}

@POST

@Path("/testing/removeviews")

@Produces("application/json;charset=UTF-8")

public String removeViews(@Context HttpServletRequest req) {

JSONObject res = new JSONObject();

try {

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

SessionContext.set(srvSession);

if(!srvSession.user.isSuperuser())

throw new AccessControlException("You do not have permission to access.");

TestCorinf.removeRandomViews();

res.put("msg_type", "inf");

res.put("msg", "Views have been removed successfully.");

} catch (Throwable e) {

try {

res.put("msg_type", "err");

res.put("msg", "Error when removing views. " + ErrorsHandler.fromException(e, srvSession.locale));

} catch (JSONException e1) {

e1.printStackTrace();

}

}finally {

SessionContext.unset();

}

return res.toString();

}

@GET

@Path("/stat/cache/clear")

@Produces("application/json;charset=UTF-8")

public String clearCache(@Context HttpServletRequest req){

JSONObject res = new JSONObject();

try{

SessionContext.set(srvSession);

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if(!srvSession.user.isSuperuser())

throw new AccessControlException("You do not have permission to access.");

HibernateManager.getCurrentSession().clear();//clears first lvl cache (Session cache)

HibernateManager.getSysHibernateManager().clearCache();//clears second lvl cache and query cache for system session factory

res.put("msg_type", "inf");

res.put("msg", "Hibernate cache was successfully cleared.");

}catch(Throwable e){

try{

res.put("msg_type", "err");

res.put("msg","Hibernate cache clearing fails with exception: "+ ErrorsHandler.fromException(e, srvSession.locale));

LOG.error("Hibernate cache clearing fails with exception.",e);

}catch (JSONException e1) {}

}finally {

SessionContext.unset();

}

return res.toString();

}

@GET

@Path("/ping")

@Produces("text/plain;charset=UTF-8")

public String ping(@Context HttpServletRequest req) {

JSONObject res = new JSONObject();

try{

if ((res = checkState(req)) != null)

return res.toString();

res = new JSONObject();

if(srvSession.user != null){

res.put("current_user",srvSession.user.getLogin().toLowerCase());

} else {

res.put("current_user",User.ANONYMOUS().getLogin().toLowerCase());

}

} catch (Throwable e){

}

return res.toString();

}

@GET

@Path("/stat/log")

@Produces("application/json;charset=UTF-8")

public String showLog(@Context HttpServletRequest req, @QueryParam("name") String name){

BufferedReader reader = null;

try{

SessionContext.set(srvSession);

//if(srvSession.user==null || !srvSession.user.isSuperuser())//TODO

// throw new AccessControlException("You do not have permission to access.");

if(name == null)

name = "CorinfAppServerALL";

else {

if(name.contains("/") || name.contains("\\") )

throw new AccessControlException("Invalid name ["+name+"]");

}

File file = new File(Configuration.getRoot(), "logs/"+name+".log");

reader = new BufferedReader( new FileReader (file));

String line = null;

StringBuilder stringBuilder = new StringBuilder();

String ls = System.getProperty("line.separator");

long skip = file.length() - 100000;

if(skip>0)

reader.skip(skip);

int offset = 0;

StringBuilder normOrder = new StringBuilder();

while( ( line = reader.readLine() ) != null ) {

if(line.startsWith("aa ")){

if(normOrder.length()>0){

stringBuilder.insert(offset, normOrder);

normOrder = new StringBuilder();

}

stringBuilder.insert(0, line );

stringBuilder.insert(0, ls );

offset = line.length() + ls.length();

}else{

normOrder.append(line);

normOrder.append(ls);

}

}

if(normOrder.length()>0){

stringBuilder.insert(offset, normOrder);

normOrder = new StringBuilder();

}

reader.close();

return stringBuilder.toString();

} catch (Throwable e) {

LOG.error("ShowLog error: ",e);

return ErrorsHandler.fromException(e, srvSession.locale);

}finally {

SessionContext.unset();

}

}

private static String statToString(JSONObject stat) throws JSONException{

return statToString(stat, "TOTAL", 0);

}

private static String statToString(JSONObject stat, String parentNode, int indent) throws JSONException{

StringBuilder res = new StringBuilder(indent(indent));

res.append("SERVER ");

res.append(parentNode);

res.append(": ");

if(stat.has("total"))

res.append(stat.get("total"));

res.append("\n");

@SuppressWarnings("unchecked")

Iterator<String> keys = stat.keys();

while(keys.hasNext()){

String k = keys.next();

if(k.equals("total")) continue;

if(stat.get(k) instanceof JSONObject){

res.append(statToString((JSONObject) stat.get(k), k, indent+1));

continue;

}

res.append(indent(indent+1))

.append(k)

.append(": ")

.append(stat.get(k))

.append("\n");

}

return res.toString();

}

private static String indent(int i){

String s = "";

while(i>0){

s+="\t";

i--;

}

return s;

}

}

CallsGraph.java

package ru.corinf.system;

import java.io.Serializable;

import java.lang.reflect.InvocationTargetException;

import java.security.AccessControlException;

import java.util.*;

import java.util.Map.Entry;

import org.apache.log4j.Logger;

import org.codehaus.jettison.json.JSONArray;

import org.codehaus.jettison.json.JSONException;

import org.codehaus.jettison.json.JSONObject;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.Transaction;

import ru.corinf.system.exceptions.InvalidParameterException;

import ru.corinf.system.exceptions.UnresolvableCallsGraphException;

import ru.corinf.system.meta.Meta;

import ru.corinf.system.meta.MetaClass;

import ru.corinf.system.meta.MetaClass.Method;

import ru.corinf.system.meta.MetaClass.Property;

import ru.corinf.system.meta.view.View;

import ru.corinf.system.meta.view.ViewState;

import ru.corinf.system.security.Authorization;

import ru.corinf.system.security.ServerSession;

import ru.corinf.system.security.SessionContext;

import ru.corinf.system.security.User;

import ru.corinf.utils.ErrorsHandler;

import ru.corinf.utils.HibernateManager;

import ru.corinf.utils.StringsHelper;

public class CallsGraph implements Serializable{

private static final long serialVersionUID = 1L;

public static final Logger LOG = Logger.getLogger(CallsGraph.class);

private static enum Was{

UPDATED, CREATED, DELETED

}

private HashMap<Link, Node> graph = new HashMap<Link, Node>();// key=link

private HashMap<Meta,Was> changedClasses = new HashMap<Meta, CallsGraph.Was>();

private JSONArray callsJson = new JSONArray();

private boolean wasFakes = false;

private int fakeLink = -1;

public int successCalls = 0;

private User user = SessionContext.get().user;

private Session s;

private boolean noCommitMode = false;

// JSONObject calls graph example

// {method_id:14, obj_id:null, link:1, params:["arg",{method_id:15,

// obj_id:null, link:2, params:["arg",{link:1}]}]}

// {method_id:1,obj_id:null,link:1,params:[9,\"testGraph2\",\"Caption\",{method_id:1,obj_id:null,link:2,params:[9,\"testGraphp\",\"Caption\",null,null,null]},null,null]}

public CallsGraph(String callsGraph) throws JSONException{

if(callsGraph.indexOf('[')<callsGraph.indexOf('{') && callsGraph.indexOf('[')>=0)

callsJson = new JSONArray(callsGraph);

else

callsJson.put(new JSONObject(callsGraph));

}

public Object firstMethodResult(){

Integer link = callsJson.optJSONObject(0).optInt("link");

if(link==null)

link = -1;

return graph.get(new Link(link)).res;

}

public CallsGraph(JSONObject callsGraph){

callsJson.put(callsGraph);

}

public CallsGraph(JSONArray callsGraph){

this.callsJson = callsGraph;

}

public void useSession(Session session){

s = session;

}

public JSONArray getCallsJson(){

return callsJson;

}

public void setNoCommitMode(boolean noCommit){

noCommitMode = noCommit;

}

public static CallsGraph doCall(String callsGraph) throws Exception{

CallsGraph g = new CallsGraph(callsGraph);

g.resolveCallsGraph();

return g;

}

private void createNodes(JSONObject callsGraph, int priority) throws Exception,

HibernateException, ClassNotFoundException,

InvalidParameterException {

Session sysSession = HibernateManager.getCurrentSession();

Node n = new Node();

Integer m_id = callsGraph.getInt("method_id");

if (m_id == null)

throw new InvalidParameterException(

"Missing parameter \"method_id\".");

else if (Authorization.getGrant(3, user.getId(), m_id) < 1)

throw new AccessControlException("User \"" + user.getLogin()

+ "\" does not have grants to access method id=" + m_id

+ ".");

n.method = (MetaClass.Method) sysSession.get(MetaClass.Method.class, m_id);

Integer lnkInt = null;

try{

lnkInt = callsGraph.getInt("link");

}catch (Exception je){}

Link link;

if (lnkInt != null)

link = new Link(lnkInt);

else

link = new Link(fakeLink--);

Object obj_id = callsGraph.opt("obj_id");

if (obj_id != null)

if (obj_id instanceof JSONArray) {

JSONArray ids = (JSONArray) obj_id;

Object[] objs = new Object[ids.length()];

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

objs[i] = n.method.getMetaClass().getObjectByID( (Serializable)ids.get(i));

n.obj = objs;

} else if (!obj_id.equals(JSONObject.NULL))

n.obj = n.method.getMetaClass().getObjectByID((Serializable) obj_id);

n.priority = priority;

JSONArray params;

//params can be an JSONObject with method parameters aliases as keys or just an JSONArray

JSONObject JsonObjParams = callsGraph.optJSONObject("params");

if(JsonObjParams!=null){

Iterator<String> keys = JsonObjParams.keys();

JSONObject lowercaseJO = new JSONObject();

while (keys.hasNext()){

String k = keys.next();

lowercaseJO.put(k.toLowerCase(), JsonObjParams.get(k));

}

JsonObjParams = lowercaseJO;

params = new JSONArray();

for(Method.Parameter mp: n.method.getParameters()){

try{

//method parameters are case insensitive

Object p = JsonObjParams.get(mp.getAlias().toLowerCase());

if(p instanceof String){

if(((String)p).isEmpty())

p = JSONObject.NULL;

}

params.put(p);

}catch(Exception notFoundExc){

//do not throw exception but set parameter to NULL

params.put(JSONObject.NULL);

//throw new InvalidParameterException("Parameter \""+mp.getTypeClass().getName()+" "+mp.getAlias()+"\" not given for method "+n.method.getMethodDifinition());

}

}

}else

params = callsGraph.optJSONArray("params");

if (params != null && params.length() > 0) {

n.params = new Object[params.length()];

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

Object p = params.get(i);

if (p instanceof JSONObject && ((JSONObject)p).has("link")) {

Link l = new Link(((JSONObject) p).getInt("link"));

n.params[i] = l;

n.notSolvedLinks.add(l);

n.haveLinks = true;

if (((JSONObject) p).has("method_id"))

createNodes((JSONObject) p,priority);

} else if(p instanceof JSONArray){

JSONArray arrayParam = (JSONArray) p;

Collection<Object> collectionParam = new ArrayList<Object>(arrayParam.length());

for(int i1=0; i1<arrayParam.length(); i1++){

Object o = arrayParam.get(i1);

if(o instanceof JSONObject && ((JSONObject)o).has("link")){

Link l = new Link(((JSONObject) o).getInt("link"));

collectionParam.add(l);

n.notSolvedLinks.add(l);

n.haveLinks = true;

} else

collectionParam.add(o);

}

n.params[i] = collectionParam;

} else

n.params[i] = p;

}

}

graph.put(link, n);

return;

}

public void resolveCallsGraph() throws Exception {

if(user==null)

throw new AccessControlException("User can not be NULL.");

LOG.info("Resolving calls graph: "+callsJson);

if(s == null){ //else use given session

Session sysSession = HibernateManager.getCurrentSession();

Method firstMethod = (Method) sysSession.get(Method.class,callsJson.getJSONObject(0).getInt("method_id"));

s = HibernateManager.getCurrentSession(firstMethod.getMetaClass());

}

Transaction tx = null;

boolean existActiveTransaction = false;

try {

tx = s.getTransaction();

if(tx.isActive())

existActiveTransaction = true;

else

tx = s.beginTransaction();

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

createNodes(callsJson.getJSONObject(i),i);

}

while (callMin());

if (wasFakes)

replaceFakes();

if(!changedClasses.isEmpty())

updateClasses();

if(!existActiveTransaction){

if(noCommitMode)

tx.rollback();

else

tx.commit();

}

tx = null;

} catch(Exception e) {

if (tx != null && !existActiveTransaction)

tx.rollback();

throw e;

}

}

private void replaceFakes() throws SecurityException,

NoSuchMethodException, ClassNotFoundException,

IllegalArgumentException, IllegalAccessException,

InvocationTargetException {

for (Node n : graph.values()) {

if (!n.fakes.isEmpty()) {

Set<Link> links = n.fakes.keySet();

for (Link l : links) {

int i = n.fakes.get(l);

String s = n.method.getParameters().get(i).getAlias();

Class<?> c = n.method.getMetaClass().getClazz();

// TODO how do i know the name of the property for this

// parameter?

java.lang.reflect.Method m = c.getMethod("set"

+ StringsHelper.firstToUpper(s),

graph.get(l).obj.getClass());

if (n.obj.getClass().equals(Object[].class)) {

Object[] objs = (Object[]) n.obj;

for (int j = 0; j < objs.length; j++) //TODO check why iterate over j?

m.invoke(objs[i], graph.get(l).obj);

} else

m.invoke(n.obj, graph.get(l).obj);

}

}

}

}

private void call(Node n) throws Exception {

System.out.println("Call node "+n.toString());

if(n.method == null)//skip empty node

return;

MethodListener.setMethodContext(n.method);

try{

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

Object p = n.params[i];

if (p instanceof Link) {

if (n.notSolvedLinks.contains(p)) {

if(graph.get(p).method == null){

if(noCommitMode){//if noCommitMode then replace empty node with new instance

n.params[i] = n.method.getParameters().get(i).getTypeClass()

.getClazz().newInstance();

} else {// else replace empty node with NULL

n.params[i] = null;

}

continue;

}

//TODO does this work? no newInstance for primitive classes

n.params[i] = graph.get(p).method.getResultClass()

.getClazz().newInstance();

n.fakes.put((Link) p, i);

wasFakes = true;

} else {

if(!graph.containsKey(p))

throw new UnresolvableCallsGraphException("Method call for link {"+p+"} not found. ");

n.params[i] = graph.get(p).res;

}

} else if(p instanceof Collection){

List<Object> list = (List<Object>) p;

for(int j=0; j<list.size(); j++){

Object o = list.get(j);

if(o instanceof Link){

if(!graph.containsKey(p))

throw new UnresolvableCallsGraphException("Cant resolve calls graph. Method call for link {"+p+"} not found. ");

if(n.notSolvedLinks.contains(o))

throw new UnresolvableCallsGraphException("Cant resolve calls graph with cycled dependencies. ");

list.set(j,graph.get(o).res);

}

}

}

}

if (n.obj != null && n.obj instanceof Object[]) {

Object[] objs = (Object[]) n.obj;

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

n.res = n.method.call(objs[i], n.params);

successCalls++;

}

} else {

n.res = n.method.call(n.obj, n.params);

if(n.method.isConstructor())

n.obj=n.res;

successCalls++;

}

n.called = true;

if(n.method.getMetaClass().isMeta()){

Object[] objs = {n.obj};

if(n.obj instanceof Object[])

objs = (Object[]) n.obj;

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

Meta m = (Meta) objs[i];

if(n.obj instanceof Property){

if(n.method.getName().equals("edit") || n.method.isDestructor() || n.method.isConstructor()){

MetaClass mc = ((Property)n.obj).getMetaClass();

System.out.println(mc.getName()+" - "+mc.getClass().getSimpleName());

if(!changedClasses.containsKey(mc))

changedClasses.put(mc, Was.UPDATED);

}

}else if(n.obj instanceof MetaClass.Method){

if(n.method.getName().equals("edit") || n.method.isDestructor() || n.method.isConstructor()){

MetaClass mc = ((MetaClass.Method)n.obj).getMetaClass();

if(!changedClasses.containsKey(mc))

changedClasses.put(mc, Was.UPDATED);

}

}else if(n.obj instanceof MetaClass.Method.Parameter){

if(n.method.getName().equals("edit") || n.method.isDestructor() || n.method.isConstructor()){

MetaClass.Method meth = ((MetaClass.Method.Parameter)n.obj).getMethod();

MetaClass mc = meth.getMetaClass();

if(!changedClasses.containsKey(mc))

changedClasses.put(mc, Was.UPDATED);

if(!changedClasses.containsKey(meth))

changedClasses.put(meth, Was.UPDATED);

}

}else if(n.obj instanceof View.Property){

if(n.method.getName().equals("edit") || n.method.isDestructor() || n.method.isConstructor()){

View v = ((View.Property)n.obj).getView();

if(!changedClasses.containsKey(v))

changedClasses.put(v, Was.UPDATED);

}

}

//(MetaClass) n.obj;

if(n.method.getName().equals("edit")){

if(n.res!=null)

if(!changedClasses.containsKey(m))

changedClasses.put(m, Was.UPDATED);

}else if(n.method.isConstructor()){

changedClasses.put(m, Was.CREATED);

}else if(n.method.isDestructor())

changedClasses.put(m, Was.DELETED);

}

}

} catch (Exception e){

MethodListener.methodEnd(e);

if(noCommitMode){//ignore method errors

try{

n.res = n.method.getResultClass()

.getClazz().newInstance();

}catch (Exception nie){

n.res = null;

}

return;

}

throw e;

}

MethodListener.methodEnd();

System.out.println("call");

}

private void updateClasses() throws Exception{

if(changedClasses.isEmpty()) return;

for(Entry<Meta, Was> entry: changedClasses.entrySet()){

Meta m = entry.getKey();

Was was = entry.getValue();

}

//int i = 5/0;

long version = System.currentTimeMillis();

Set<Entry<Meta, Was>> other = new HashSet<Map.Entry<Meta,Was>>();

Meta m = null;

Was was=null;

for(Entry<Meta, Was> entry: changedClasses.entrySet()){

m = entry.getKey();

was = entry.getValue();

if(MetaClass.class.isInstance(m)){

switch (was){

case CREATED: m.ifCreated(version, user); System.out.println("ifCreated metaClass ("+was+")"); break;

case DELETED: m.ifDeleted(version, user); System.out.println("ifDeleted metaClass ("+was+")"); break;

case UPDATED: m.ifUpdated(version, user); System.out.println("ifUpdated metaClass ("+was+")"); break;

}

}else{

System.out.println("add entry "+entry.getKey().getClass().getSimpleName()+" "+entry.getValue());

other.add(entry);

}

}

for(Entry<Meta, Was> entry: other){

m = entry.getKey();

was = entry.getValue();

switch (was){

case CREATED: m.ifCreated(version, user); System.out.println("ifCreated meta "+m.getClass().getSimpleName()+"("+was+")"); break;

case DELETED: m.ifDeleted(version, user); System.out.println("ifDelited meta "+m.getClass().getSimpleName()+"("+was+")"); break;

case UPDATED: m.ifUpdated(version, user); System.out.println("ifUpdated meta "+m.getClass().getSimpleName()+"("+was+")"); break;

}

}

}

private boolean callMin() throws Exception {

System.out.println("callMin");

Collection<Node> values = graph.values();

System.out.println("graph size "+values.size()+"("+graph.size()+")");

Node min = values.iterator().next();

for (Node n : values) {

System.out.println("For node "+n);

if (!n.called) {

if (!n.haveLinks) {

if(min.called || min.haveLinks || min.priority>n.priority)

min = n;

continue;

}

Set<Link> solved = new HashSet<Link>();

for (Link l : n.notSolvedLinks) {

if (graph.get(l).called)

solved.add(l);

}

n.notSolvedLinks.removeAll(solved);

if (n.notSolvedLinks.size() == 0) {

n.haveLinks = false;

if(min.called || min.haveLinks || min.priority>n.priority)

min = n;

continue;

} else {

if (n.notSolvedLinks.size() < min.notSolvedLinks.size())

min = n;

}

}

}

System.out.println("min node "+min);

if (!min.called) {

call(min);

return true;

}

return false;

}

public Object getMethodResult(int link){

return graph.get(new Link(link)).res;

}

private static class Node {

Object obj = null;

Object res = null;

boolean called = false;

Set<Link> notSolvedLinks = new HashSet<CallsGraph.Link>();

MetaClass.Method method;

boolean haveLinks = false;

HashMap<Link, Integer> fakes = new HashMap<CallsGraph.Link, Integer>();

Object[] params = new Object[0];

int priority = 0;

public Node() {

}

}

private static class Link {

int link;

public Link(Integer lnk) {

link = lnk;

}

public boolean equals(Object obj) {

if (obj instanceof Link)

return link == ((Link) obj).link;

else

try {

return link == ((Integer) obj);

} catch (ClassCastException e) {}

return false;

}

public int hashCode() {

return link;

}

}

public static class NewThreadRunner implements Runnable{

private String callsGraph;

private ServerSession srvSession;

private Integer id_tab;

public NewThreadRunner(String callsGraph, ServerSession serverSession, Integer id_tab){

this.callsGraph = callsGraph;

this.srvSession = serverSession;

this.id_tab = id_tab;

}

@Override

public void run(){

try{

SessionContext.set(srvSession);

if(id_tab!=null)

MethodListener.set(srvSession.openedViews.get(id_tab));

MethodListener.get().methodStatus = ViewState.CallStatus.Status.STARTED;

CallsGraph.doCall(callsGraph);

MethodListener.get().methodStatus = ViewState.CallStatus.Status.FINISHED;

} catch (Throwable e){

LOG.error("Method call exception. ",e);

MethodListener.get().methodStatus = ViewState.CallStatus.Status.FAILED;

MethodListener.fail(ErrorsHandler.fromException(e,SessionContext.get().locale));

} finally {

SessionContext.unset();

MethodListener.unset();

}

}

}

}

HQLView.java

package ru.corinf.system.meta.view;

import java.util.*;

import org.antlr.runtime.ANTLRStringStream;

import org.antlr.runtime.CharStream;

import org.antlr.runtime.CommonTokenStream;

import org.antlr.runtime.RecognitionException;

import org.antlr.runtime.tree.CommonTree;

import org.antlr.runtime.tree.CommonTreeNodeStream;

import org.apache.commons.lang.StringUtils;

import org.apache.log4j.Logger;

import org.codehaus.jettison.json.JSONArray;

import org.codehaus.jettison.json.JSONException;

import org.codehaus.jettison.json.JSONObject;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

import org.hibernate.engine.SessionFactoryImplementor;

import org.hibernate.hql.QueryTranslator;

import org.hibernate.hql.ast.QueryTranslatorImpl;

import org.hibernate.type.Type;

import ru.corinf.localization.LocalizedException;

import ru.corinf.system.exceptions.FilterException;

import ru.corinf.system.exceptions.InvalidParameterException;

import ru.corinf.system.exceptions.ParseException;

import ru.corinf.system.exceptions.SortOrderException;

import ru.corinf.system.generator.grammar.ast.DefaultQueryFactory;

import ru.corinf.system.generator.grammar.ast.SelectStatement;

import ru.corinf.system.generator.grammar.code.*;

import ru.corinf.system.generator.grammar.code.VQLParser.selectStatement_return;

import ru.corinf.system.meta.MetaClass;

import ru.corinf.system.meta.view.ViewData.ViewDataRow;

import ru.corinf.utils.HibernateManager;

public class HQLView extends View {

private static final long serialVersionUID = 1L;

protected static final Logger LOG = Logger.getLogger(HQLView.class);

private Set<ViewJoin> joins = new HashSet<ViewJoin>();

public HQLView(){}

public HQLView(MetaClass metaClass,

String alias,

String caption,

String comment,

Integer defaultPageCount,

String defaultFilter,

String defaultSort,

Boolean isDefault,

Boolean fromDual,

MetaClass.Method method){

this.metaClass = metaClass;

this.alias = alias;

this.caption = caption;

this.comment = comment;

this.defaultPageCount = defaultPageCount;

this.defaultFilter = defaultFilter;

this.defaultSort = defaultSort;

this.isDefault = isDefault;

this.fromDual = fromDual;

this.method = method;

}

public View edit(

MetaClass metaClass,

String alias,

String caption,

String comment,

Integer defaultPageCount,

String defaultFilter,

String defaultSort,

Boolean isDefault,

Boolean fromDual,

MetaClass.Method method

) throws LocalizedException {

Session s = HibernateManager.getCurrentSession();

if (alias == null)

throw new InvalidParameterException(

"Invalid parameter. Parameter\"String alias\" can not be NULL.");

if (caption == null)

throw new InvalidParameterException(

"Invalid parameter. Parameter\"String caption\" can not be NULL.");

this.setMetaClass(metaClass);

this.setAlias(alias);

this.setCaption(caption);

this.setComment(comment);

if(defaultPageCount!=null)

this.setDefaultPageCount(defaultPageCount);

if(defaultFilter==null || StringUtils.trim(defaultFilter).startsWith("["))

this.setDefaultFilter(defaultFilter);

else

this.setDefaultFilter(Filter.parseFilter(defaultFilter).getFilters().toString());

this.setDefaultSort(defaultSort);

if(isDefault!=null)

this.setIsDefault(isDefault);

if(fromDual!=null)

this.setFromDual(fromDual);

this.setMethod(method);

s.update(this);

return this;

}

public static HQLView create(

MetaClass metaClass,

String alias,

String caption,

String comment,

Integer defaultPageCount,

String defaultFilter,

String defaultSort,

Boolean isDefault,

Boolean fromDual,

MetaClass.Method method

) throws LocalizedException {

Session s = HibernateManager.getCurrentSession();

HQLView v = new HQLView();

if (alias == null)

throw new InvalidParameterException(

"Invalid parameter. Parameter\"String alias\" can not be NULL.");

if (caption == null)

throw new InvalidParameterException(

"Invalid parameter. Parameter\"String caption\" can not be NULL.");

v.setMetaClass(metaClass);

v.setAlias(alias);

v.setCaption(caption);

v.setComment(comment);

if(defaultPageCount!=null)

v.setDefaultPageCount(defaultPageCount);

if(defaultFilter==null || StringUtils.trim(defaultFilter).startsWith("["))

v.setDefaultFilter(defaultFilter);

else

v.setDefaultFilter(Filter.parseFilter(defaultFilter).getFilters().toString());

v.setDefaultSort(defaultSort);

if(isDefault!=null)

v.setIsDefault(isDefault);

else

v.setIsDefault(false);

if(fromDual!=null)

v.setFromDual(fromDual);

else v.setFromDual(false);

v.setMethod(method);

s.save(v);

return v;

}

public HQLView copy(String newAlias, String newCaption){

HQLView copy = new HQLView(this.getMetaClass(),newAlias,newCaption,this.getComment(),this.getDefaultPageCount(), this.getDefaultFilter(), this.getDefaultSort(), false, this.getFromDual(),this.getMethod());

for(Property p:getProperties()){

Property pCopy = new Property(copy,p.getCaption(),p.getAlias(),p.getExpression(),p.getIsJavaMethod(),p.getIsHidden(),p.getIsRequired(),p.getIsReadonly(),p.getIsCalcField(),p.getSelectorType(),p.getLinkViewExpression(),p.getLinkFilterJSON(),p.getComment(),p.getDataType(),p.getWidth(),p.getHeight(),p.getColumnNumber(),p.getTab(),p.getGroup());

copy.getProperties().add(pCopy);

}

for(ViewJoin j: getJoins()){

ViewJoin jCopy = new ViewJoin(copy, j.getType(), j.getJoinOn(), j.getAlias());

copy.getJoins().add(jCopy);

}

HibernateManager.getCurrentSession().save(copy);

return copy;

}

public static HQLView createByVQL(String vql) throws LocalizedException, RecognitionException{

CharStream input = new ANTLRStringStream(vql);

VQLLexer lexer = new VQLLexer(input);

CommonTokenStream tokens = new CommonTokenStream(lexer);

VQLParser parser = new VQLParser(tokens);

selectStatement_return query = parser.selectStatement();

LOG.debug("VQL parese tree: "+((CommonTree)query.getTree()).toStringTree());

if(parser.reporter.getErrorsNumber()>0){

parser.reporter.throwAsException();

}

CommonTreeNodeStream nodeStream = new CommonTreeNodeStream(query.getTree());

nodeStream.setTokenStream(tokens);

VQLWalker walker = new VQLWalker(new DefaultQueryFactory(),nodeStream);

SelectStatement ss = walker.selectStatement().ret;

HQLView v = (HQLView) ss.buildViews().get(0);

HibernateManager.getCurrentSession().save(v);

return v;

}

@Override

public ViewData getData(ViewState state) throws Exception {

if(state.getOpenas().equalsIgnoreCase("form") && !this.getFromDual() && state.getFilter()==null){

ViewData vd = new ViewData(this);

vd.setState(state);

return vd;

}

Session s;

if(fromDual)

s = HibernateManager.getSession();

else

s = HibernateManager.getSession(getMetaClass());

try{

return getDataUsingSession(state,s );

}finally {

s.close();

}

}

public ViewData getDataUsingSession(ViewState state, Session session) throws Exception {

JSONObject stat = new JSONObject();

long time = System.currentTimeMillis(), startTime = System

.currentTimeMillis();

ViewData result = new ViewData(this);

new JSONObject();

// mapping property names into column indexes

HashMap<String, Integer> propNameToIndexMap = new HashMap<String, Integer>();

Transaction tx = null;

boolean existActiveTransaction = false;

try {

if(session.getTransaction().isActive()){

existActiveTransaction = true;

tx = session.getTransaction();

}

else

tx = session.beginTransaction();

List<JavaMethodCallsExpression> callsExprs = new ArrayList<JavaMethodCallsExpression>();

StringBuffer queryString = new StringBuffer();

queryString.append("SELECT ");

boolean conditionFound = false;

int countNotJMetColumns = 0;

int countProp = 0;

time = System.currentTimeMillis() - time;

stat.put("init variables", time);

time = System.currentTimeMillis();

List<MetaClass.Property> keys = null;

if(!fromDual){

//add id and displayName columns

keys = this.getMetaClass().getKeyProperties();

if(keys.size()==0){

queryString.append("this.id, ");

countNotJMetColumns++;

}

for(MetaClass.Property p: keys){

queryString.append("this."+p.getName()+", ");

countNotJMetColumns++;

}

queryString.append(this.getMetaClass().getDisplayNameExpression()==null?"'no display name expr'":this.getMetaClass().getDisplayNameExpression());

countNotJMetColumns ++;

}

Map<String, String> propExprMap = new HashMap<String, String>();

for(Property p: this.getProperties())

propExprMap.put(p.getAlias(), HQLView.processExpression(p.getExpression()));

for (Property p : properties) {

propNameToIndexMap.put(p.alias, countProp);

countProp++;

String expr = propExprMap.get(p.getAlias());

//parse expression and replace dependencies to expressions from propExprMap

if(p.getIsCalcField()){

expr = replaceDependencies(expr, propExprMap);

}

if (p.isJavaMethod) {

// parse, find and check methods using reflection

callsExprs.add(new JavaMethodCallsExpression(expr,p));

} else {

if (expr != null) {

if(countNotJMetColumns>0)

queryString.append(", ");

++countNotJMetColumns;

queryString.append(expr).append(" as ").append(p.getAlias()).append(" ");

}

}

}

final String classAlias = "this";

if(!this.getFromDual() && (state.fetchObjects || !callsExprs.isEmpty())){

queryString.append((countNotJMetColumns>0?", ":"")).append(classAlias).append(" ");

}else

queryString.append((countNotJMetColumns>0?", ":"")).append(processExpression("null"));

if (!callsExprs.isEmpty()) {

for(JavaMethodCallsExpression jmcs: callsExprs)

queryString.append(jmcs.getMethodsParams());

}

StringBuilder fromClause = new StringBuilder();

fromClause.append(" FROM ");

if(this.getFromDual()){

fromClause.append("Dual as dual ");

}else{

fromClause.append(metaClass.getMetaPackage().getName())

.append('.')

.append(metaClass.getNameForHibernate())

.append(' ')

.append(classAlias)

.append(' ');

}

queryString.append(fromClause);

//joins

if(!this.getJoins().isEmpty()){

StringBuilder joinsClause = new StringBuilder();

for(ViewJoin vj: getJoins()){

joinsClause.append(vj.getType())

.append(" join ")

.append(vj.getJoinOn())

.append(" as ")

.append(vj.getAlias())

.append(' ');

}

queryString.append(joinsClause);

}

time = System.currentTimeMillis() - time;

stat.put("preparing HQL and parse methods", time);

time = System.currentTimeMillis();

// check filter whether we can use HQL filter

boolean useJavaFilter = false;

JSONArray hj[] = null;

Filter methodsFilter = null;

StringBuilder whereClause = new StringBuilder(" WHERE 1=1 ");

if(defaultFilter!=null){

Filter df = new Filter(new JSONArray(defaultFilter));

df.setDefault(true);

whereClause.append("and (")

.append(df.toStringForQuery(propNameToIndexMap, properties,state))

.append(") ");

}

if (state.filter != null && !this.getFromDual()) {

Filter.LOG.debug("Before divide: "+state.filter.filters.toString());

hj = state.filter.divide(propNameToIndexMap, properties);

if (hj[0].length() > 0) {

Filter.LOG.debug("H filter: "+hj[0].toString());

whereClause.append("and (")

.append(Filter.toStringForQuery(hj[0],

propNameToIndexMap, properties,false,state.filter.getKeyColumns(),state))

.append(") ");

}

if (hj[1].length() > 0) {

Filter.LOG.debug("J filter: "+hj[1].toString());

useJavaFilter = true;

methodsFilter = new Filter();

methodsFilter.setFilters(hj[1]);

}

}

queryString.append(whereClause);

time = System.currentTimeMillis() - time;

stat.put("preparing HQL filter", time);

time = System.currentTimeMillis();

// check sort whether we can use HQL order by

boolean useJavaSort = false;

if (state.sortOrder != null || defaultSort!=null) {

SortOrder sortOrder;

if(state.sortOrder != null)

sortOrder = state.sortOrder;

else

sortOrder = new SortOrder(defaultSort);

StringBuffer orderClause = new StringBuffer(" ORDER BY ");

conditionFound = false;

int startJavaSortFrom = -1; // 0 - only java sorting

JSONArray sorts = sortOrder.getSorts();

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

JSONArray so = sorts.getJSONArray(i);

Property p = null;

startJavaSortFrom++;

try{

if(propNameToIndexMap.get(so.getString(0))==null && state.sortOrder==null){ //is default sort

if (conditionFound)

orderClause.append(", ");

else

conditionFound = true;

orderClause

.append(so.getString(0) + " " + so.getString(1));

continue;

}

p = properties.get(propNameToIndexMap.get(so

.getString(0)));

}catch(Exception npe){

throw new SortOrderException("Incorrect sort order. Column with alias \""+so

.getString(0)+"\" does not exist in this view.");

}

if (p.isJavaMethod) {

useJavaSort = true;

break;

} else {

if (conditionFound)

orderClause.append(", ");

else

conditionFound = true;

orderClause

.append(p.expression + " " + so.getString(1));

}

}

sortOrder.setStartJavaSortFrom(startJavaSortFrom);

if (((startJavaSortFrom > 0 && useJavaSort) || !useJavaSort)

&& startJavaSortFrom >= 0)

queryString.append(orderClause);

}

time = System.currentTimeMillis() - time;

stat.put("preparing HQL sort", time);

time = System.currentTimeMillis();

// print Query

LOG.debug(queryString.toString());

// Creating hql query from string

Query q = session.createQuery(queryString.toString());

// paging in HQL if we will not use sorting or filtering in java

if (!useJavaFilter && !useJavaSort && state.pageCount > 0 && !fromDual) {

q.setFirstResult(state.pageCount * (state.pageNumber - 1));

q.setMaxResults(state.pageCount);

// if we've used HQL paging we must use HQL count(*)

Query countQuery = session.createQuery("SELECT count(*) "

+ fromClause.toString()

+ whereClause.toString());

LOG.debug(countQuery.getQueryString());

result.setTotal((Long) countQuery.uniqueResult());

result.setStartIndex(state.pageCount * (state.pageNumber - 1));

result.setEndIndex(state.pageCount * (state.pageNumber - 1) + state.pageCount);

}

if(fromDual){

q.setMaxResults(1);

result.setTotal(1);

result.setStartIndex(0);

result.setEndIndex(1);

}

result.setState(state);

// executing query

@SuppressWarnings("unchecked")

List<Object> qr = q.list();

time = System.currentTimeMillis() - time;

stat.put("executing HQL", time);

time = System.currentTimeMillis();

if (qr.isEmpty()) {

stat.put("total", System.currentTimeMillis() - startTime);

return result;

}

Object res;

for (Object abstractRow : qr) {

Object[] row = null;

if(abstractRow instanceof Object[])

row = (Object[]) abstractRow;

else{

row = new Object[1];

row[0] = abstractRow;

}

Iterator<JavaMethodCallsExpression> iterMethods = callsExprs.iterator();

int i = 0;

int resColumn = 0;

if(!fromDual){

i = keys.size()+1; // synthetic id columns + 1 - displayName column

resColumn = 1;//first column for {id,displayName}

}

Object resRow[] = new Object[properties.size()+resColumn];

if(!fromDual){//add {id,displayName} column for each object

if(keys.size()>1){

i = keys.size()+1; // synthetic id columns + 1 - displayName column

JSONObject compositeKey = new JSONObject();

for (int k=0;k<keys.size();k++)

compositeKey.put(keys.get(k).getName(),row[k]==null?JSONObject.NULL:row[k]);

resRow[0] = new JSONObject().put("composite_id", compositeKey).put("display_name", row[keys.size()]==null?compositeKey.toString(): row[keys.size()]);

}else{

resRow[0] = new JSONObject().put("id", row[0]==null?JSONObject.NULL:row[0]).put("display_name", row[1]==null?(getMetaClass().getCaption()+" "+row[0]):row[1]);

i = 2; // synthetic id column + 1 - displayName column

}

}

for (Property p : properties) {

if (p.isJavaMethod) {

res = row[countNotJMetColumns];

JavaMethodCallsExpression methodSequence = iterMethods

.next();

res = methodSequence.invoke(res, row, countNotJMetColumns+1);

resRow[resColumn] = res;

resColumn++;

} else {

resRow[resColumn] = row[i];

i++;

resColumn++;

}

}

// filtering

if (useJavaFilter) {

if (methodsFilter.match(resRow, propNameToIndexMap))

result.add(new ViewDataRow(result, row[countNotJMetColumns], resRow));

} else

result.add(new ViewDataRow(result, row[countNotJMetColumns], resRow));

}

if(!existActiveTransaction)

tx.commit();

tx = null;

// Sorting table

if (useJavaSort)

Collections.sort(result.getTable(), new ViewDataRowComparator(

state.sortOrder, propNameToIndexMap));

if (useJavaFilter || useJavaSort || state.pageCount <= 0) {

result.setTotal(result.getTable().size());

result.setStartIndex(0);

result.setEndIndex(result.getTotal());

}

}catch(Exception e){

if(tx!=null && !existActiveTransaction)

tx.rollback();

tx = null;

throw e;

}

time = System.currentTimeMillis() - time;

stat.put("methods call java sort and filter", time);

stat.put("total", System.currentTimeMillis() - startTime);

result.setStat(stat);

return result;

}

public static String processExpression(String expression) {

expression = StringUtils.trim(expression);

if(expression.equalsIgnoreCase("true"))

return "always_true()";

if(expression.equalsIgnoreCase("false"))

return "always_false()";

if(expression.equalsIgnoreCase("null"))

return "always_null()";

return expression;

}

public String[] getReturnTypes() throws ParseException {

String[] res = new String[properties.size()];

Map<String, String> propExprMap = new HashMap<String, String>();

for(Property p: this.getProperties())

propExprMap.put(p.getAlias(), HQLView.processExpression(p.getExpression()));

StringBuilder queryStr = new StringBuilder("SELECT ");

boolean first = true;

String expr;

for(Property p:properties){

expr = propExprMap.get(p.getAlias());

if(!first) queryStr.append(", ");

//parse expression and replace dependencies to expressions from propExprMap

if(p.getIsCalcField()){

expr = replaceDependencies(expr, propExprMap);

}

if(p.isJavaMethod)

expr = "'str'";

queryStr.append(processExpression(expr));

first = false;

}

queryStr.append(" FROM " + metaClass.getMetaPackage().getName()

+ "." + metaClass.getNameForHibernate() + " "

+ "AS this ");

//joins

if(!this.getJoins().isEmpty()){

StringBuilder joinsClause = new StringBuilder();

for(ViewJoin vj: getJoins()){

joinsClause.append(vj.getType())

.append(" join ")

.append(vj.getJoinOn())

.append(" as ")

.append(vj.getAlias())

.append(' ');

}

queryStr.append(joinsClause);

}

QueryTranslator qt = new QueryTranslatorImpl("query", queryStr.toString(),

new HashMap<Object, Object>(), (SessionFactoryImplementor) HibernateManager.getInstance(metaClass).getSessionFactory());

qt.compile(new HashMap<Object, Object>(), true);

Type[] types = qt.getReturnTypes();

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

res[i] = (types[i].getReturnedClass().getSimpleName());

}

return res;

}

public String printAsDSL(){

StringBuilder sb = new StringBuilder("CREATE VIEW ");

sb.append(alias).append(" AS ").append("'").append(caption.replace("'","\\'")).append("' ");

if(fromDual) sb.append("FROM_DUAL ");

if(isDefault) sb.append("IS_DEFAULT ");

if(defaultPageCount!=0) sb.append("DEFAULT_PAGE_COUNT(").append(defaultPageCount).append(") ");

if(defaultFilter!=null) sb.append("DEFAULT_FILTER(").append(defaultFilter).append(") ");

if(defaultSort!=null) sb.append("DEFAULT_SORT(").append(defaultSort).append(") ");

if(getMethod()!=null) sb.append("METHOD(").append(getMethod().getId()).append(" /*").append(getMethod().getCaption()).append("*/) ");

if(comment!=null) sb.append("COMMENT(").append("'").append(caption.replace("'", "\\'")).append("'").append(") ");

//properties

sb.append("\n(");//OPEN

boolean first = true;

for(Property p: getProperties()){

if(!first)

sb.append(",\n");

sb.append(p.getAlias()).append(" = ").append("'").append(p.getExpression().replace("'", "\\'")).append("'");

sb.append(" AS ").append("'").append(p.getCaption().replace("'","\\'")).append("' ");

if(p.getIsHidden()) sb.append("IS_HIDDEN ");

if(p.getIsJavaMethod()) sb.append("IS_JAVA_METHOD ");

if(p.getSelectorType()!=null){

sb.append(p.getSelectorType().getAlias().toUpperCase());

}

if(p.getIsReadonly()) sb.append("IS_READONLY ");

if(p.getIsRequired()) sb.append("IS_REQUIRED ");

if(p.getLinkViewExpression()!=null){

sb.append("IS_LINK(").append("'").append(p.getLinkViewExpression()).append("'");

if(p.getLinkFilterJSON()!=null)

sb.append("; ").append(p.getLinkFilterJSON());

sb.append(") ");

}

if(p.getColumnNumber()!=1) sb.append("COLUMN(").append(p.getColumnNumber()).append(") ");

if(p.getTab()!=null) sb.append("TAB(").append(p.getTab().replace("'", "\\'")).append(") ");

if(p.getGroup()!=null) sb.append("TAB(").append(p.getGroup().replace("'","\\'")).append(") ");

}

sb.append("\n)");//CLOSE

for(ViewJoin vj: getJoins()){

sb.append("\n").append(vj.getType().toUpperCase()).append(" JOIN ").append(vj.getJoinOn()).append(" AS ").append(vj.getAlias());

}

return sb.toString();

}

protected static String replaceDependencies(String expr, Map<String, String> propExprMap) throws ParseException {

ViewMethodParametersLexer lexer = new ViewMethodParametersLexer(new ANTLRStringStream(expr));

ViewMethodParametersParser parser = new ViewMethodParametersParser(new CommonTokenStream(lexer),propExprMap);

try{

String res = parser.parse().str;

if(parser.reporter.getErrorsNumber()>0)

parser.reporter.throwAsException();

return res;

} catch (RecognitionException re){

throw new ParseException(re);

}catch (LocalizedException le){

throw new ParseException(le);

}

}

public String printAsVQL() throws FilterException, JSONException, SortOrderException{

StringBuilder sb = new StringBuilder();

boolean first = true;

if(properties.size()>0)

sb.append("SELECT ");

for(Property p: properties){

if(!first) sb.append(", ");

first = false;

sb.append(p.expression)

.append(" as ")

.append(p.alias)

.append(" '").append(p.caption).append("' ");

if(p.isHidden) sb.append("IS_HIDDEN ");

if(p.isJavaMethod) sb.append("IS_JAVA_METHOD ");

if(p.isRequired) sb.append("IS_REQUIRED ");

if(p.isReadonly) sb.append("IS_READONLY ");

if(p.getSelectorType()!=null){

sb.append(p.getSelectorType().getAlias().toUpperCase());

}

if(p.linkViewExpression!=null){

sb.append("IS_LINK('").append(p.linkViewExpression).append("' ");

if(p.linkFilterJSON!=null)

sb.append(", ").append(p.linkFilterJSON);

sb.append(") ");

}

if(p.width!=0) sb.append("WIDTH(").append(p.width).append(") ");

if(p.comment!=null) sb.append("COMMENT('").append(p.comment).append("') ");

}

sb.append("\nFROM CLASS ")

.append(this.getMetaClass().getFullName())

.append(" as ").append(alias)

.append(" '").append(caption).append("' ");

if(isDefault) sb.append("IS_DEFAULT ");

if(fromDual) sb.append("IS_FROMDUAL ");

if(defaultPageCount!=0) sb.append("DEFAULT_PAGE_COUNT(").append(defaultPageCount).append(") ");

if(method!=null) sb.append("METHOD(").append(method.getId()).append(") ");

if(comment!=null) sb.append("COMMENT('").append(comment).append("') ");

for(ViewJoin vj: joins){

sb.append("\n")

.append(vj.getType().toUpperCase())

.append(" JOIN ")

.append(vj.getJoinOn())

.append(" as ")

.append(vj.getAlias());

}

if(getDefaultFilter()!=null){

Filter defFilter = new Filter(new JSONArray(getDefaultFilter()));

sb.append("\nWHERE ")

.append(defFilter.toStringForVQL());

}

if(getDefaultSort()!=null){

SortOrder sort = new SortOrder(new JSONArray(getDefaultSort()));

sb.append("\nORDER BY ")

.append(sort.toString());

}

return sb.toString();

}

public Set<ViewJoin> getJoins() {

return joins;

}

public void setJoins(Set<ViewJoin> joins) {

this.joins = joins;

}

}

HibernateManager.java

package ru.corinf.utils;

import org.apache.commons.javaflow.bytecode.transformation.bcel.analyser.ControlFlowGraph;

import org.apache.commons.lang.SystemUtils;

import org.apache.log4j.Logger;

import org.hibernate.*;

import org.hibernate.cfg.Configuration;

import org.hibernate.criterion.Restrictions;

import org.hibernate.dialect.function.SQLFunctionTemplate;

import org.hibernate.util.ReflectHelper;

import ru.corinf.system.Const;

import ru.corinf.system.classloading.LoadingManager;

import ru.corinf.system.exceptions.ModuleLoadingException;

import ru.corinf.system.generator.Generator;

import ru.corinf.system.meta.ConnectionProperties;

import ru.corinf.system.meta.MetaClass;

import ru.corinf.system.meta.MetaPackage;

import ru.corinf.ws.Resource;

import java.io.*;

import java.sql.Types;

import java.util.*;

import java.util.concurrent.ConcurrentHashMap;

/**

* @author Vladislav Okulich-Kazarin

* Date: 25.10.12

* Time: 20:21

*/

public class HibernateManager {

public static final Logger LOG = Logger.getLogger(HibernateManager.class);

//key - package name

private static Map<String,HibernateManager> instances = new ConcurrentHashMap<String, ru.corinf.utils.HibernateManager>();

private ThreadLocalSession threadLocalSession;

private String name;

private LoadingManager loadingManager = null;

private ConnectionProperties connectionProperties=null;

private SessionFactory sessionFactory = null;

private Configuration configuration = null;

private int sessionsCounter = 0;

public static boolean loadClasses = true;

private int loadedClassesCounter = 0;

private List<String> moduleClasses = new ArrayList<String>();

public static final HashMap<Class<?>, String> JAVA_TO_HIBERNATE = new HashMap<Class<?>, String>();

static {

JAVA_TO_HIBERNATE.put(int.class, "integer");

JAVA_TO_HIBERNATE.put(Integer.class, "integer");

JAVA_TO_HIBERNATE.put(short.class, "short");

JAVA_TO_HIBERNATE.put(Short.class, "short");

JAVA_TO_HIBERNATE.put(long.class, "long");

JAVA_TO_HIBERNATE.put(Long.class, "long");

JAVA_TO_HIBERNATE.put(boolean.class, "boolean");

JAVA_TO_HIBERNATE.put(Boolean.class, "boolean");

JAVA_TO_HIBERNATE.put(float.class, "float");

JAVA_TO_HIBERNATE.put(Float.class, "float");

JAVA_TO_HIBERNATE.put(double.class, "double");

JAVA_TO_HIBERNATE.put(Double.class, "double");

JAVA_TO_HIBERNATE.put(char.class, "character");

JAVA_TO_HIBERNATE.put(Character.class, "character");

JAVA_TO_HIBERNATE.put(String.class, "string");

JAVA_TO_HIBERNATE.put(byte[].class, "binary");

JAVA_TO_HIBERNATE.put(Byte[].class, "binary");

JAVA_TO_HIBERNATE.put(Class.class, "class");

JAVA_TO_HIBERNATE.put(java.sql.Blob.class, "blob");

JAVA_TO_HIBERNATE.put(java.sql.Clob.class, "clob");

JAVA_TO_HIBERNATE.put(java.sql.Timestamp.class, "timestamp");

JAVA_TO_HIBERNATE.put(java.util.Currency.class, "currency");

JAVA_TO_HIBERNATE.put(Date.class, "timestamp");

JAVA_TO_HIBERNATE.put(java.util.TimeZone.class, "timezone");

JAVA_TO_HIBERNATE.put(java.util.Locale.class, "locale");

JAVA_TO_HIBERNATE.put(java.util.Calendar.class, "calendar");

JAVA_TO_HIBERNATE.put(Date.class, "timestamp");

JAVA_TO_HIBERNATE.put(java.math.BigDecimal.class, "big_decimal");

}

public final static Map<Integer,Class<?>> SQL_TYPE_TO_JAVA_CLASS = new HashMap<Integer, Class<?>>();

static {

SQL_TYPE_TO_JAVA_CLASS.put(Types.ARRAY, Object[].class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.BIGINT, java.math.BigInteger.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.BINARY, Byte[].class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.BIT, Boolean.class);//??

SQL_TYPE_TO_JAVA_CLASS.put(Types.BLOB, java.sql.Blob.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.BOOLEAN, Boolean.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.CHAR, Character.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.CLOB, java.sql.Clob.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.DATALINK, Object.class);//??

SQL_TYPE_TO_JAVA_CLASS.put(Types.DATE, Date.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.DECIMAL, Integer.class);//java.math.BigDecimal.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.DISTINCT, Object.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.DOUBLE, Double.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.FLOAT, Float.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.INTEGER, Integer.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.JAVA_OBJECT, Object.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.LONGNVARCHAR, String.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.LONGVARBINARY, byte[].class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.LONGVARCHAR, String.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.NCHAR, Character.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.NCLOB, java.sql.Clob.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.NULL, null);

SQL_TYPE_TO_JAVA_CLASS.put(Types.NUMERIC, Double.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.NVARCHAR, String.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.OTHER, Byte[].class);//??

SQL_TYPE_TO_JAVA_CLASS.put(Types.REAL, Float.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.REF, null);//??

SQL_TYPE_TO_JAVA_CLASS.put(Types.ROWID, null);//??

SQL_TYPE_TO_JAVA_CLASS.put(Types.SMALLINT, Short.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.SQLXML, String.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.STRUCT, null);//??

SQL_TYPE_TO_JAVA_CLASS.put(Types.TIME, java.sql.Time.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.TIMESTAMP, java.sql.Timestamp.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.TINYINT, Byte.class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.VARBINARY, Byte[].class);

SQL_TYPE_TO_JAVA_CLASS.put(Types.VARCHAR, String.class);

}

public static String getHibernateType(MetaClass mc)

throws ClassNotFoundException {

Class<?> c = ReflectTools.getClassFromMeta(mc);

return getHibernateType(c);

}

public static String getHibernateType(Class<?> c)

throws ClassNotFoundException {

String res = JAVA_TO_HIBERNATE.get(c);

if (res == null) {

if (ReflectHelper.implementsInterface(c, Serializable.class))

return "serializable";

}

return res;

}

private HibernateManager(){

threadLocalSession = new ThreadLocalSession(this);

}

protected void finalize(){

try{

if(sessionFactory!=null){

if(!sessionFactory.isClosed())

sessionFactory.close();

LOG.debug("Old session factory for \""+this.name+"\" module was closed successfully. ");

}

}catch (Exception e){

LOG.error("Can't close old session factory.");

}

}

public static HibernateManager getSysHibernateManager(){

return instances.get("ru.corinf.system");

}

public static Collection<HibernateManager> getInstancesList(){

return instances.values();

}

public LoadingManager getLoadingManager() {

return loadingManager;

}

public ClassLoader getClassLoader(){

if(loadingManager==null)

return this.getClass().getClassLoader();

else

return loadingManager.getClassLoader();

}

public String getName(){

return name;

}

public ConnectionProperties getConnectionProperties(){

return connectionProperties;

}

public static void init(){

Resource.setStatusMsg("%init_sys_module%");

initSystemSessionFactory();

Resource.setInitProgress(15);

Session s = getSysHibernateManager().getCurrentSession_();

Map<String,HibernateManager> foundConnections = new TreeMap<String, HibernateManager>();

//put system connection

foundConnections.put("system",getSysHibernateManager());

Criteria c = s.createCriteria(MetaPackage.class).add(Restrictions.isNotNull("connectionProperties"));

List<MetaPackage> packagesList = (List<MetaPackage>)c.list();

for(MetaPackage pkg: packagesList){

ConnectionProperties props = pkg.getConnectionProperties();

HibernateManager hm;

//if(foundConnections.containsKey(props.getName())){

// hm = foundConnections.get(props.getName());

//} else {

hm = new HibernateManager();

hm.name = pkg.getName();

hm.loadingManager = new LoadingManager();

hm.configure(props);

foundConnections.put(props.getName(),hm);

//}

hm.connectionProperties = props;

if(!props.getName().equals("system"))

instances.put(pkg.getName(),hm);

}

Query q = s.createQuery("FROM MetaPackage WHERE name like '%.%.%' and name not like '%.%.%.%' and name not like 'java.%' and name not like 'ru.corinf.system' and name not like 'ru.corinf.system.%'");

Map<String,HibernateManager> modules = new HashMap<String, HibernateManager>();

for(MetaPackage mp: (List<MetaPackage>)q.list()){

String p = mp.getName();

HibernateManager moduleHM;

if(instances.containsKey(p) && !instances.get(p).name.equals("system")){

moduleHM = instances.get(p);

} else {

moduleHM = new HibernateManager();

HibernateManager copyFrom = findManagerForPackage(p);

moduleHM.connectionProperties = copyFrom.connectionProperties;

moduleHM.name = p;

moduleHM.configure(copyFrom.connectionProperties);

moduleHM.loadingManager = new LoadingManager();

}

modules.put(p,moduleHM);

}

instances.putAll(modules);

//remove duplicate hm (with the same connection)

for(MetaPackage pkg: packagesList){

if(pkg.getParent()==null)

continue;

HibernateManager thisHm = instances.get(pkg.getName());

HibernateManager subHm = findManagerForPackage(pkg.getParent().getName());

if(subHm.getName().matches("^[A-z_]+[A-z0-9_]*(\\.[A-z_]+[A-z0-9_]*)?$"))

continue;

if(thisHm.connectionProperties.getName().equals(subHm.connectionProperties.getName())){

instances.remove(pkg.getName());

}

}

if(loadClasses){

Resource.setStatusMsg("%recompiling_modules%");

includeUserClasses();

Resource.setInitProgress(25);

s.close();

//getSysHibernateManager().buildSessionFactory();

}

int modulesCount = instances.size();

int curProgress = 25;

for(HibernateManager hm: instances.values()){

int progressPerModule = (90-curProgress)/modulesCount;

modulesCount--;

if(hm.name.equals("system"))

continue;

if(hm.loadedClassesCounter==0){

LOG.warn("Empty module \""+hm.name+"\" skipped. ");

continue;

}

try{

Resource.setStatusMsg("%loading_?_module%",hm.getName());

hm.loadingManager.loadModule(hm.moduleClasses, hm);

curProgress +=progressPerModule;

Resource.setInitProgress(curProgress);

} catch (Exception loadExc){

LOG.error("Can't load \""+hm.name+"\" module. ",loadExc);

}

}

}

private static void includeUserClasses(){

Session s = HibernateManager.getCurrentSession();

Query q = s.createQuery("from MetaClass where status.id=:status_id").setInteger("status_id", Const.ClassStatuses.DEPLOYED_STATUS_ID);

List<MetaClass> list = q.list();

List<MetaClass> ready = new ArrayList<MetaClass>();

for(MetaClass mc: list){

try{

try{

Generator.copyToClasspath(mc);

LOG.info("Class "+mc.getName()+" copied to classpath.");

} catch (Exception exc){

Generator.generateClass(mc);

Generator.copyToClasspath(mc);

LOG.info("Class "+mc.getName()+" generated and copied to classpath.");

}

ready.add(mc);

}catch(Exception e){

LOG.warn("Class "+mc.getName()+" can not be generated.", e);

}

HibernateManager hm = findManagerForPackage(mc.getMetaPackage().getName());

hm.moduleClasses.add(mc.getFullNameForHibernate());

hm.loadedClassesCounter++;

}

// for (MetaClass mc: ready){

// File hbm = new File(ru.corinf.system.Configuration.getParameter("classpath")+"/"+mc.getFullNameForHibernate().replace('.','/')+".hbm.xml");

// try{

// HibernateManager hm = findManagerForPackage(mc.getMetaPackage().getName());

// hm.configuration.addFile(hbm);

// hm.moduleClasses.add(mc.getFullNameForHibernate());

// hm.loadedClassesCounter++;

// LOG.info("Mapping added to "+hm.name+". ("+hbm.getAbsolutePath()+")");

// } catch (Exception ex){

// LOG.warn("Mapping "+hbm.getAbsolutePath()+" can not be added.", ex);

// }

// }

}

public void reloadModule() throws ModuleLoadingException {

if(this.name.equals("system"))

throw new ModuleLoadingException("System module can't be reloaded. You must reboot server.");

try{

HibernateManager newHM = new HibernateManager();

newHM.name = this.name;

newHM.connectionProperties = this.connectionProperties;

newHM.loadingManager = new LoadingManager();

newHM.configure(newHM.connectionProperties);

Session s = HibernateManager.getCurrentSession();

Query q = s.createQuery("from MetaClass where status.id=:status_id and (metaPackage.name like '"+this.name+"' or metaPackage.name like '"+this.name+".%') ").setInteger("status_id", Const.ClassStatuses.DEPLOYED_STATUS_ID);

List<MetaClass> list = q.list();

for (MetaClass mc: list){

HibernateManager hm = findManagerForPackage(mc.getMetaPackage().getName());

if(!hm.name.equals(this.name))

continue;

newHM.moduleClasses.add(mc.getFullNameForHibernate());

newHM.loadedClassesCounter++;

}

newHM.loadingManager.loadModule(newHM.moduleClasses,newHM);

instances.put(this.name, newHM);

} catch (Exception e){

throw new ModuleLoadingException("Exception occurred while reloading module \""+this.name+"\". ",e);

}

}

public static HibernateManager getInstance(MetaPackage metaPackage){

return findManagerForPackage(metaPackage.getName());

}

public static HibernateManager getInstance(MetaClass metaClass){

return findManagerForPackage(metaClass.getMetaPackage().getName());

}

public static HibernateManager getInstance(Class<?> clazz){

return findManagerForPackage(clazz.getPackage().getName());

}

public static HibernateManager getInstance(String pkg){

return findManagerForPackage(pkg);

}

public static Set<HibernateManager> getAllInstances(){

return new TreeSet<HibernateManager>(instances.values());

}

public static HibernateManager findManagerForPackage(String pkg){

while (true){

LOG.debug("pkg = "+pkg);

if(pkg==null)

return getSysHibernateManager();

if(instances.containsKey(pkg)){

return instances.get(pkg);

}

if(pkg.contains(".")){

String subPkg = pkg.substring(0,pkg.lastIndexOf('.'));

//if package 3rd lvl does not have Hibernate manager then we create a new one for this

if(Resource.serverStatus == Resource.ServerStatus.INITIALIZED && subPkg.matches("^[A-z_]+[A-z0-9_]*\\.[A-z_]+[A-z0-9_]*$")){

LOG.debug("sub_pkg = "+subPkg);

HibernateManager newHm = new HibernateManager();

newHm.name = pkg;

MetaPackage mp = (MetaPackage)getCurrentSession().createCriteria(MetaPackage.class).add(Restrictions.eq("name",pkg)).uniqueResult();

LOG.debug("mp = "+mp);

if(mp.getConnectionProperties()!=null)

newHm.connectionProperties = mp.getConnectionProperties();

else

newHm.connectionProperties = findManagerForPackage(subPkg).connectionProperties;

newHm.loadingManager = new LoadingManager();

newHm.configure(newHm.connectionProperties);

instances.put(pkg,newHm);

return newHm;

}

pkg = subPkg;

} else {

return HibernateManager.getSysHibernateManager();

}

}

}

private void configure(ConnectionProperties props){

long start = System.currentTimeMillis();

LOG.info("Configuring hibernate for "+props.getName()+" ...");

Configuration cfg = new Configuration();

Properties sysProps = getSysHibernateManager().configuration.getProperties();

Properties myProps = new Properties();

myProps.putAll(sysProps);

for(Map.Entry<String,String> e: props.getProperties().entrySet())

myProps.put("hibernate."+e.getKey(), e.getValue());

myProps.put("hibernate.session_factory_name", name + "SessionFactory");

cfg.setProperties(myProps);

StringBuilder propsLog = new StringBuilder("Hibernate cfg properties for '"+name+"' connection: "+ SystemUtils.LINE_SEPARATOR);

for(Map.Entry<Object,Object> e:myProps.entrySet()){

if(e.getKey().toString().startsWith("hibernate") || e.getKey().toString().startsWith("connection")){

if(e.getKey().toString().contains("password"))

propsLog.append("\t").append(e.getKey()).append('=').append("*****").append(SystemUtils.LINE_SEPARATOR);

else

propsLog.append("\t").append(e.getKey()).append('=').append(e.getValue()).append(SystemUtils.LINE_SEPARATOR);

}

}

LOG.debug(propsLog.toString());

//cfg.mergeProperties(sysProps);

configuration = cfg;

configuration.addSqlFunction("always_true", new SQLFunctionTemplate(org.hibernate.type.StandardBasicTypes.BOOLEAN, "1"));

configuration.addSqlFunction("always_false", new SQLFunctionTemplate(org.hibernate.type.StandardBasicTypes.BOOLEAN, "0"));

configuration.addSqlFunction("always_null", new SQLFunctionTemplate(org.hibernate.type.StandardBasicTypes.STRING, "cast(null as char)"));

LOG.info("End Hibernate configuring for "+props.getName()+" ... OK ["+(System.currentTimeMillis() - start)+"]");

}

private static void initSystemSessionFactory(){

HibernateManager hm = new HibernateManager();

hm.name = "system";

hm.configureSystem();

hm.buildSessionFactory();

instances.put("ru.corinf.system",hm);

}

public void buildSessionFactory(){

long start = System.currentTimeMillis();

LOG.info("Building "+name+" SessionFactory... ");

// if(sessionFactory!=null)

// try{

// LOG.info("Closing existing session factory...");

// sessionFactory.close();

// }catch(Exception e){

// e.printStackTrace();

// }

sessionFactory = getConfiguration().buildSessionFactory();

LOG.info("End building "+name+" SessionFactory... OK ["+(System.currentTimeMillis() - start)+"]");

}

public void rebuildSessionFactory(Configuration newCfg){

long start = System.currentTimeMillis();

LOG.info("Building new SessionFactory... ");

SessionFactory newSF = newCfg.buildSessionFactory();

LOG.info("End building new SessionFactory... OK ["+(System.currentTimeMillis() - start)+"]");

if(sessionFactory!=null)

try{

LOG.info("Closing existing (old) session factory...");

sessionFactory.close();

}catch(Exception e){

e.printStackTrace();

}

sessionFactory = newSF;

}

private Session getSession_() {

try{

sessionsCounter++;

return getSessionFactory().openSession();

} catch (HibernateException he){

sessionsCounter--;

throw he;

}

}

public static Session getSession() {

return getSysHibernateManager().getSession_();

}

public static Session getSession(Class<?> clazz) {

return findManagerForPackage(clazz.getPackage().getName()).getSession_();

}

public static Session getSession(MetaClass metaClass) {

return findManagerForPackage(metaClass.getMetaPackage().getName()).getSession_();

}

public static Session getSession(String pkg) {

return findManagerForPackage(pkg).getSession_();

}

private Session getCurrentSession_() {

return threadLocalSession.getThreadLocalSession();

//return getSessionFactory().getCurrentSession_();

}

public static Session getCurrentSession(){

return getSysHibernateManager().getCurrentSession_();

}

public static Session getCurrentSession(Class<?> clazz){

return findManagerForPackage(clazz.getPackage().getName()).getCurrentSession_();

}

public static Session getCurrentSession(MetaClass metaClass) {

return findManagerForPackage(metaClass.getMetaPackage().getName()).getCurrentSession_();

}

public static Session getCurrentSession(String pkg){

return findManagerForPackage(pkg).getCurrentSession_();

}

public void clearCache(){

long start = System.currentTimeMillis();

Cache cache = sessionFactory.getCache();

cache.evictCollectionRegions();

cache.evictEntityRegions();

cache.evictQueryRegions();

cache.evictDefaultQueryRegion();

LOG.info("Hibernate cache was successfully cleared ["+(System.currentTimeMillis() - start)+"]");

}

public SessionFactory getSessionFactory() {

if (sessionFactory == null)

buildSessionFactory();

return sessionFactory;

}

public Configuration getConfiguration() {

return configuration;

}

private void configureSystem() {

long start = System.currentTimeMillis();

LOG.info("Configuring System Hibernate... ");

File f = new File(ru.corinf.system.Configuration.getParameter("users_classes_path")+"/cfg.cache");

if(ru.corinf.system.Configuration.getParameterAsBoolean("use_cached_configuration")){

if(f.exists()){

ObjectInputStream oi=null;

try{

oi = new ObjectInputStream(new FileInputStream(f));

configuration=(Configuration) oi.readObject();

oi.close();

}catch(Exception e){

LOG.warn("Error when reading hibernate configuration from cache file. ",e);

configuration = new Configuration().configure();

}

}else{

try{

configuration = new Configuration().configure();

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));

oos.writeObject(configuration);

oos.close();

}catch(Exception e){

LOG.warn("Error when writing hibernate configuration to cache file. ",e);

}

}

}else{

if(f.exists())

f.delete();

configuration = new Configuration().configure();

}

connectionProperties = new ConnectionProperties();

connectionProperties.setName("system");

connectionProperties.getProperties().put("connection.username", configuration.getProperty("hibernate.connection.username"));

connectionProperties.getProperties().put("connection.password",configuration.getProperty("hibernate.connection.password"));

connectionProperties.getProperties().put("connection.url",configuration.getProperty("hibernate.connection.url"));

connectionProperties.getProperties().put("dialect",configuration.getProperty("hibernate.dialect"));

connectionProperties.getProperties().put("connection.driver_class",configuration.getProperty("hibernate.connection.driver_class"));

configuration.addSqlFunction("always_true", new SQLFunctionTemplate(org.hibernate.type.StandardBasicTypes.BOOLEAN, "1"));

configuration.addSqlFunction("always_false", new SQLFunctionTemplate(org.hibernate.type.StandardBasicTypes.BOOLEAN, "0"));

configuration.addSqlFunction("always_null", new SQLFunctionTemplate(org.hibernate.type.StandardBasicTypes.STRING, "cast(null as char)"));

LOG.info("End System Hibernate configuring... OK ["+(System.currentTimeMillis() - start)+"]");

}

private static class ThreadLocalSession{

private ThreadLocal<SessionHolder> context = new ThreadLocal<SessionHolder>();

private HibernateManager hibernateManager;

public ThreadLocalSession(HibernateManager hibernateManager){

this.hibernateManager = hibernateManager;

}

public Session getThreadLocalSession(){

if(context.get()==null)

context.set(new SessionHolder(hibernateManager));

Session s = context.get().getSession();

return s;

}

private static class SessionHolder{

private Session session;

HibernateManager hibernateManager;

public SessionHolder(HibernateManager hibernateManager){

this.hibernateManager = hibernateManager;

session = hibernateManager.getSession_();

}

public Session getSession(){

if(!session.isOpen() || session.getSessionFactory().isClosed()){

session = hibernateManager.getSession_();

//LOG.debug("Open ThreadLocalSession.");

}

return session;

}

protected void finalize(){

if(session.isOpen()){

session.close();

this.hibernateManager.sessionsCounter--;

//LOG.debug("Close ThreadLocalSession.");

}

}

}

}

}

Приложение 2. Руководство пользователя

Назначение программы

Программа предназначена для автоматизации бизнес-процессов на предприятии. Платформа «Коринф» предоставляет набор инструментов для описания предметной области и построения приложения, решающего задачи автоматизации бизнес-процессов с учетом специфики конкретного предприятия.

Установка программы

В случае использования веб-клиента не требуется установка на персональный компьютер, работа с ресурсами ПО происходит по средствам интернета и веб-браузера.

Выполнение программы

Для начала работы с приложением необходимо проверить наличие интернет-подключения, запустить имеющийся веб-браузер. В адресной строке веб-браузера прописать адрес заданный администратором сервера приложений. Для дальнейшей работы с данными необходимо авторизоваться (ввести логин и пароль).

Создание нового класса

Для создания нового класса предметной области необходимо открыть меню «Класс» и перейти на представление «Классы», затем нужно выбрать на панели инструментов метод «Создать новый класс» или «Создать класс по таблице», в результате чего, откроется форма создания класса (рисунок 1).

Рисунок 1 – Форма создания класса

На данной форме необходимо выбрать пакет (модуль), к которому будет принадлежать созданный класс, задать имя класса, а так же задать свойства класса и методы, перейдя в соответствующие вкладки. Форма создания новых свойств, представлена на рисунке 2.

Рисунок 2 – Задание свойств класса

В случае успешного создания класса он появится в таблице со статусом «NEW». Для того чтобы данный класс стал доступен для использования в системе необходимо его развернуть, для чего нужно выбрать созданный класс и вызвать метод «Развернуть класс». В процессе развертывания создается таблица в базе данных, генерируются и компилируются файлы класса, а так же создаются стандартные методы и представления.

Формирование отчета Excel

Для получения отчета необходимо перейти на нужное представление, затем применить необходимые фильтры и сортировку, после чего нажать на кнопку с пиктограммой Excel на панели инструментов. Появится всплывающее окно для выбора экспортируемых страниц (рисунок 3).

Рисунок 3 – Экспорт в excel

После подтверждения начнется загрузка xls файла. Пример экспортированного файла открытого в Excel приведен на рисунке 4.

Рисунок 4 – Экспортированное представление

ФКиИТ.ВТиП.ДП.608215 ПЗ

Лист

Изм

Лист

документа

Подпись

Дата

195