diff --git a/amp/TEMPLATE/ampTemplate/css_2/comparePrint.css b/amp/TEMPLATE/ampTemplate/css_2/comparePrint.css new file mode 100644 index 00000000000..14e93cfe56e --- /dev/null +++ b/amp/TEMPLATE/ampTemplate/css_2/comparePrint.css @@ -0,0 +1,5 @@ +.yui-nav {visibility:hidden;} +button, html input[type="button"] {visibility:hidden;} +@page { + margin: 2cm; +} \ No newline at end of file diff --git a/amp/TEMPLATE/ampTemplate/site-config.xml b/amp/TEMPLATE/ampTemplate/site-config.xml index 0df6ef455fd..e0f0ef6d83b 100644 --- a/amp/TEMPLATE/ampTemplate/site-config.xml +++ b/amp/TEMPLATE/ampTemplate/site-config.xml @@ -1,7 +1,7 @@ - + + ]> diff --git a/amp/WEB-INF/src/org/digijava/kernel/ampapi/endpoints/config/utils/ConfigHelper.java b/amp/WEB-INF/src/org/digijava/kernel/ampapi/endpoints/config/utils/ConfigHelper.java index 0b5fe58e08f..5b96aadb1be 100644 --- a/amp/WEB-INF/src/org/digijava/kernel/ampapi/endpoints/config/utils/ConfigHelper.java +++ b/amp/WEB-INF/src/org/digijava/kernel/ampapi/endpoints/config/utils/ConfigHelper.java @@ -44,7 +44,6 @@ public class ConfigHelper { public static final String T_DOUBLE = "t_Double"; public static final String T_STATIC_YEAR = "t_static_year"; public static final String T_YEAR = "t_year"; - public static final String T_AUDIT_TRIAL_CLENAUP = "t_audit_trial_clenaup"; public static final String T_COMPONENTS_SORT = "t_components_sort"; public static final String T_DAILY_CURRENCY_UPDATE_HOUR = "t_daily_currency_update_hour"; public static final String T_SECURE_VALUES = "t_secure_values"; @@ -150,7 +149,6 @@ public static boolean validateGlobalSetting(AmpGlobalSettings ampGlobalSetting, case T_INTEGER_NON_NEGATIVE: case T_INTEGER_POSITIVE: case T_TIMEOUT_CURRENCY_UPDATE: - case T_AUDIT_TRIAL_CLENAUP: case T_STATIC_RANGE: try { isValid = isValidNumber(Integer.class, value); diff --git a/amp/WEB-INF/src/org/digijava/module/aim/action/AuditExcelExporter.java b/amp/WEB-INF/src/org/digijava/module/aim/action/AuditExcelExporter.java new file mode 100644 index 00000000000..00608cc42b3 --- /dev/null +++ b/amp/WEB-INF/src/org/digijava/module/aim/action/AuditExcelExporter.java @@ -0,0 +1,157 @@ +package org.digijava.module.aim.action; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.util.CellRangeAddress; +import org.digijava.kernel.request.TLSUtils; +import org.digijava.kernel.translator.TranslatorWorker; +import org.digijava.module.aim.annotations.activityversioning.CompareOutput; +import org.digijava.module.aim.util.ActivityVersionUtil; +import org.digijava.module.aim.util.versioning.ActivityComparisonResult; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFRichTextString; +import org.apache.poi.hssf.usermodel.HSSFRow; + +public class AuditExcelExporter { + private static final Integer CELL_LIMIT = 32767; + private static int rowIndex = 1; + private static int cellIndex = 0; + private static final Integer FIRST_COLUMN = 0; + private static final Integer LAST_COLUMN = 2; + private static final Integer VALUE_NAME = 0; + private AuditXLSExportService auditXLSExportService; + + public AuditExcelExporter() { + auditXLSExportService = new AuditXLSExportService(); + } + + public AuditXLSExportService getAuditXLSExportService() { + return auditXLSExportService; + } + + public void setAuditXLSExportService(AuditXLSExportService auditXLSExportService) { + this.auditXLSExportService = auditXLSExportService; + } + + public HSSFWorkbook generateExcel(List outputCollection) { + + HSSFSheet sheet = createWorkbook(); + for (ActivityComparisonResult result : outputCollection) { + cellIndex = 0; + String name = result.getName(); + HSSFRow nameRow = sheet.createRow(rowIndex); + sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, FIRST_COLUMN, LAST_COLUMN)); + rowIndex++; + HSSFCell nameCell = nameRow.createCell(cellIndex); + nameCell.setCellValue(name); + nameCell.setCellStyle(auditXLSExportService.getOrCreateTitleStyle(sheet.getWorkbook())); + Map> outputCollectionGrouped = result.getCompareOutput(); + rowIndex = getCellValues(outputCollectionGrouped, sheet, rowIndex); + } + auditXLSExportService.setColumnWidth(sheet); + return sheet.getWorkbook(); + } + + public HSSFRow createHeader(HSSFWorkbook wb, HSSFSheet sheet) { + HSSFCellStyle titleCS = auditXLSExportService.getOrCreateTitleStyle(wb); + + rowIndex = 0; + cellIndex = 0; + + HSSFRow titleRow = sheet.createRow(rowIndex++); + + HSSFCell titleCell = titleRow.createCell(cellIndex++); + HSSFRichTextString title = new HSSFRichTextString( + TranslatorWorker.translateText("Value Name", TLSUtils.getEffectiveLangCode(), TLSUtils.getSiteId())); + titleCell.setCellValue(title); + titleCell.setCellStyle(titleCS); + + HSSFCell cellName = titleRow.createCell(cellIndex++); + HSSFRichTextString previous = new HSSFRichTextString( + TranslatorWorker.translateText("Previous Version", TLSUtils.getEffectiveLangCode(), + TLSUtils.getSiteId())); + cellName.setCellValue(previous); + cellName.setCellStyle(titleCS); + + HSSFCell cellNew = titleRow.createCell(cellIndex++); + HSSFRichTextString newVersion = new HSSFRichTextString( + TranslatorWorker.translateText("New Version", TLSUtils.getEffectiveLangCode(), TLSUtils.getSiteId())); + cellNew.setCellValue(newVersion); + cellNew.setCellStyle(titleCS); + + return titleRow; + } + + public int checkMaxCellLimit(String cellValue, HSSFSheet sheet, int rowIndex, int cellIndex, HSSFCell cell) { + int length = cellValue.length(); + int mergeIndex = rowIndex; + if (length > CELL_LIMIT) { + String valueOne = cellValue.substring(0, CELL_LIMIT); + cell.setCellValue(valueOne); + int remain = length - CELL_LIMIT; + for (int i = CELL_LIMIT; i < length; i += CELL_LIMIT) { + String valueNext = null; + HSSFRow newvalueRow = sheet.createRow(++rowIndex); + HSSFCell valuescell = newvalueRow.createCell(cellIndex); + if (remain < CELL_LIMIT) { + valueNext = cellValue.substring(i); + } else { + valueNext = cellValue.substring(i, i + CELL_LIMIT); + } + valuescell.setCellValue(valueNext); + HSSFWorkbook wb = sheet.getWorkbook(); + valuescell.setCellStyle(auditXLSExportService.getOrCreateOrdinaryStyle(wb)); + remain = length - (i + CELL_LIMIT); + } + sheet.addMergedRegion(new CellRangeAddress(mergeIndex, rowIndex, FIRST_COLUMN, FIRST_COLUMN)); + } else { + cell.setCellValue(cellValue); + } + return rowIndex; + } + + public HSSFSheet createWorkbook() { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet(TranslatorWorker.translateText("Audit Logger")); + createHeader(wb, sheet); + return sheet; + } + + public int getCellValues(Map> outputCollectionGrouped, HSSFSheet sheet, + int rowIndex) { + + HSSFWorkbook wb = sheet.getWorkbook(); + HSSFCellStyle cs = auditXLSExportService.getOrCreateOrdinaryStyle(wb); + Set keyset = outputCollectionGrouped.keySet(); + for (String key : keyset) { + cellIndex = 0; + HSSFRow valueRow = sheet.createRow(rowIndex); + HSSFCell colcell = valueRow.createCell(cellIndex++); + colcell.setCellValue(key); + colcell.setCellStyle(cs); + + List nameList = outputCollectionGrouped.get(key); + CompareOutput comp = nameList.get(VALUE_NAME); + HSSFCell groupcell = valueRow.createCell(cellIndex++); + String[] value = comp.getStringOutput(); + String oldValue = value[1]; + String old = ActivityVersionUtil.sanitizeHtmlForExport(oldValue); + rowIndex = checkMaxCellLimit(old, sheet, rowIndex, cellIndex, groupcell); + groupcell.setCellStyle(cs); + + HSSFCell newcell = valueRow.createCell(cellIndex); + String newValue = value[0]; + String newVal = ActivityVersionUtil.sanitizeHtmlForExport(newValue); + rowIndex = checkMaxCellLimit(newVal, sheet, rowIndex, cellIndex, newcell); + rowIndex++; + newcell.setCellStyle(cs); + } + return rowIndex; + } + +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/action/AuditLoggerManager.java b/amp/WEB-INF/src/org/digijava/module/aim/action/AuditLoggerManager.java index c5019d1753d..166d452891f 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/action/AuditLoggerManager.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/action/AuditLoggerManager.java @@ -27,7 +27,10 @@ import org.digijava.module.aim.util.AuditLoggerUtil; public class AuditLoggerManager extends MultiAction { - + + private static final Integer PAGES_TO_SHOW = 10; + private static final Integer TOTAL_RECORDS = 20; + public ActionForward modePrepare(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { @@ -40,7 +43,7 @@ public ActionForward modePrepare(ActionMapping mapping, ActionForm form, OutputStream out = response.getOutputStream(); try { - XlsMaker(vForm, request, response).write(out); + xlsMaker(vForm, request, response).write(out); out.flush(); out.close(); return null; @@ -61,85 +64,19 @@ public ActionForward modePrepare(ActionMapping mapping, ActionForm form, } } - Collection logs=AuditLoggerUtil.getLogObjects(vForm.isWithLogin()); - - if (request.getParameter("sortBy")!=null){ + vForm.populateEffectiveFilters(); + Collection logs = AuditLoggerUtil.getLogObjects(vForm.isWithLogin(), + vForm.getEffectiveSelectedUser(), vForm.getEffectiveSelectedTeam(), vForm.getEffectiveDateFrom(), + vForm.getEffectiveDateTo()); + vForm.setUserList(AuditLoggerUtil.getEditorNameFromLog()); + vForm.setTeamList(AuditLoggerUtil.getTeamFromLog()); + + if (request.getParameter("sortBy") != null) { vForm.setSortBy(request.getParameter("sortBy")); } - if(vForm.getSortBy()!=null){ - Long siteId = RequestUtils.getSiteDomain(request).getSite().getId(); - String langCode = RequestUtils.getNavigationLanguage(request).getCode(); - if(vForm.getSortBy().equalsIgnoreCase("nameasc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerNameComparator()) ; - } - else if(vForm.getSortBy().equalsIgnoreCase("namedesc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerNameComparator()); - Collections.reverse((List)logs); - } - else if(vForm.getSortBy().equalsIgnoreCase("typeasc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerTypeComparator()); - } - else if(vForm.getSortBy().equalsIgnoreCase("typedesc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerTypeComparator()); - Collections.reverse((List)logs); - } - else if(vForm.getSortBy().equalsIgnoreCase("teamasc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerTeamComparator()); - } - else if(vForm.getSortBy().equalsIgnoreCase("teamdesc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerTeamComparator()); - Collections.reverse((List)logs); - } - else if(vForm.getSortBy().equalsIgnoreCase("authorasc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerAuthorComparator()); - } - else if(vForm.getSortBy().equalsIgnoreCase("authordesc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerAuthorComparator()); - Collections.reverse((List)logs); - } - else if(vForm.getSortBy().equalsIgnoreCase("creationdateasc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerCreationDateComparator()); - } - else if(vForm.getSortBy().equalsIgnoreCase("creationdatedesc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerCreationDateComparator()); - Collections.reverse((List)logs); - } - else if(vForm.getSortBy().equalsIgnoreCase("editorasc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerEditorNameComparator()); - } - else if(vForm.getSortBy().equalsIgnoreCase("editordesc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerEditorNameComparator()); - Collections.reverse((List)logs); - } - else if(vForm.getSortBy().equalsIgnoreCase("actionasc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerActionComparator()); - } - else if(vForm.getSortBy().equalsIgnoreCase("actiondesc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerActionComparator()); - Collections.reverse((List)logs); - } - else if(vForm.getSortBy().equalsIgnoreCase("changedateasc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerChangeDateComparator()); - } - else if(vForm.getSortBy().equalsIgnoreCase("changedatedesc")){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerChangeDateComparator()); - Collections.reverse((List)logs); - } - else { - if (vForm.getSortBy().equalsIgnoreCase("detaildesc")) { - Collections.sort((List) logs, new AuditLoggerUtil.HelperAuditloggerDetailComparator(langCode, siteId)); - Collections.reverse((List) logs); - } else { - if (vForm.getSortBy().equalsIgnoreCase("detailasc")) { - Collections.sort((List) logs, new AuditLoggerUtil.HelperAuditloggerDetailComparator(langCode, siteId)); - } - - } - - } - } - vForm.setPagesToShow(10); - int totalrecords=20; + applySortBy(request, vForm, (List) logs); + vForm.setPagesToShow(PAGES_TO_SHOW); + int totalrecords = TOTAL_RECORDS; int page = 0; if (request.getParameter("page") == null) { page = 1; @@ -180,20 +117,81 @@ else if(vForm.getSortBy().equalsIgnoreCase("changedatedesc")){ return modeSelect(mapping, form, request, response); } - public ActionForward modeSelect(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { + private void applySortBy(HttpServletRequest request, AuditLoggerManagerForm vForm, List logs) { + if (vForm.getSortBy() != null) { + Long siteId = RequestUtils.getSiteDomain(request).getSite().getId(); + String langCode = RequestUtils.getNavigationLanguage(request).getCode(); + if (vForm.getSortBy().equalsIgnoreCase("nameasc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerNameComparator()); + } else if (vForm.getSortBy().equalsIgnoreCase("namedesc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerNameComparator()); + Collections.reverse(logs); + } else if (vForm.getSortBy().equalsIgnoreCase("typeasc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerTypeComparator()); + } else if (vForm.getSortBy().equalsIgnoreCase("typedesc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerTypeComparator()); + Collections.reverse(logs); + } else if (vForm.getSortBy().equalsIgnoreCase("teamasc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerTeamComparator()); + } else if (vForm.getSortBy().equalsIgnoreCase("teamdesc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerTeamComparator()); + Collections.reverse(logs); + } else if (vForm.getSortBy().equalsIgnoreCase("authorasc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerAuthorComparator()); + } else if (vForm.getSortBy().equalsIgnoreCase("authordesc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerAuthorComparator()); + Collections.reverse(logs); + } else if (vForm.getSortBy().equalsIgnoreCase("creationdateasc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerCreationDateComparator()); + } else if (vForm.getSortBy().equalsIgnoreCase("creationdatedesc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerCreationDateComparator()); + Collections.reverse(logs); + } else if (vForm.getSortBy().equalsIgnoreCase("editorasc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerEditorNameComparator()); + } else if (vForm.getSortBy().equalsIgnoreCase("editordesc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerEditorNameComparator()); + Collections.reverse(logs); + } else if (vForm.getSortBy().equalsIgnoreCase("actionasc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerActionComparator()); + } else if (vForm.getSortBy().equalsIgnoreCase("actiondesc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerActionComparator()); + Collections.reverse(logs); + } else if (vForm.getSortBy().equalsIgnoreCase("changedateasc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerChangeDateComparator()); + } else if (vForm.getSortBy().equalsIgnoreCase("changedatedesc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerChangeDateComparator()); + Collections.reverse(logs); + } else { + if (vForm.getSortBy().equalsIgnoreCase("detaildesc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerDetailComparator(langCode, siteId)); + Collections.reverse(logs); + } else { + if (vForm.getSortBy().equalsIgnoreCase("detailasc")) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerDetailComparator(langCode, siteId)); + } + + } + + } + } + } + + public ActionForward modeSelect(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { return mapping.findForward("forward"); } - private HSSFWorkbook XlsMaker( AuditLoggerManagerForm form, HttpServletRequest request, HttpServletResponse response) { + private HSSFWorkbook xlsMaker(AuditLoggerManagerForm form, HttpServletRequest request, + HttpServletResponse response) { int interval = Integer.parseInt(form.getFrecuency()); - Collection Xlslogs=AuditLoggerUtil.getLogByPeriod(interval); + Collection xlslogs = AuditLoggerUtil.getLogByPeriod(interval); HSSFWorkbook wb = new HSSFWorkbook(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "inline; filename=Audit-logger.xls"); HSSFSheet sheet = wb.createSheet("Audit-logger.xls"); - HSSFRow row = sheet.createRow((short)(0)); + HSSFRow row = sheet.createRow((short) (0)); HSSFRichTextString str = null; HSSFFont titlefont = wb.createFont(); @@ -221,7 +219,7 @@ private HSSFWorkbook XlsMaker( AuditLoggerManagerForm form, HttpServletRequest r style.setFont(font); int i = 1; - for (Iterator iterator = Xlslogs.iterator(); iterator.hasNext();) { + for (Iterator iterator = xlslogs.iterator(); iterator.hasNext();) { AmpAuditLogger ampAuditLogger = (AmpAuditLogger) iterator.next(); row = sheet.createRow((short)(i)); diff --git a/amp/WEB-INF/src/org/digijava/module/aim/action/AuditPDFexporter.java b/amp/WEB-INF/src/org/digijava/module/aim/action/AuditPDFexporter.java new file mode 100644 index 00000000000..c7ba9be8f2e --- /dev/null +++ b/amp/WEB-INF/src/org/digijava/module/aim/action/AuditPDFexporter.java @@ -0,0 +1,142 @@ + +package org.digijava.module.aim.action; + +import com.itextpdf.text.BaseColor; +import com.itextpdf.text.Document; +import com.itextpdf.text.DocumentException; +import com.itextpdf.text.Element; +import com.itextpdf.text.Font; +import com.itextpdf.text.Header; +import com.itextpdf.text.Paragraph; +import com.itextpdf.text.pdf.PdfPCell; +import com.itextpdf.text.pdf.PdfPTable; +import com.itextpdf.text.pdf.PdfWriter; + +import org.digijava.kernel.request.TLSUtils; +import org.digijava.kernel.translator.TranslatorWorker; +import org.digijava.module.aim.annotations.activityversioning.CompareOutput; +import org.digijava.module.aim.util.ActivityVersionUtil; +import org.digijava.module.aim.util.versioning.ActivityComparisonResult; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public final class AuditPDFexporter { + + private static final Integer VALUE_NAME = 0; + private static final Integer HEADER_COLSPAN = 3; + private static final Integer HEADER_COLUMNS = 3; + private static final Integer TABLE_WIDTH = 100; + private static AuditPDFexporter auditPDFexporter; + private static final Font PLAIN_FONT = new Font(Font.FontFamily.HELVETICA, 10, Font.NORMAL, new BaseColor(0, 0, 0)); + private static final BaseColor HEADER_BRACKGROUND_COLOR = new BaseColor(244, 244, 242); + private static final Font HEADER_FONT = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, new BaseColor(0, 0, 0)); + + public static AuditPDFexporter getInstance() { + if (auditPDFexporter == null) { + auditPDFexporter = new AuditPDFexporter(); + } + return auditPDFexporter; + } + + private AuditPDFexporter() { + + } + + public ByteArrayOutputStream buildPDFexport(List activityComparisonResult) { + return generatePDFExport(activityComparisonResult); + } + + private ByteArrayOutputStream generatePDFExport(List activityComparisonResult) { + ByteArrayOutputStream baos = null; + try { + Document document = new Document(); + baos = new ByteArrayOutputStream(); + PdfWriter.getInstance(document, baos); + document.open(); + PdfPTable mainLayout = createHeader(); + for (ActivityComparisonResult cr : activityComparisonResult) { + generateSimpleCell(mainLayout, TranslatorWorker.translateText("Activity") + " : " + cr.getName(), + Element.ALIGN_CENTER, HEADER_FONT, HEADER_BRACKGROUND_COLOR, HEADER_COLSPAN); + Map> outputCollectionGrouped = cr.getCompareOutput(); + createValues(outputCollectionGrouped, mainLayout); + } + document.add(mainLayout); + document.close(); + } catch (DocumentException e) { + e.printStackTrace(); + //TODO properly handle exception + } + return baos; + } + + private PdfPTable createHeader() throws DocumentException { + + PdfPTable mainLayout = buildPdfTable(HEADER_COLUMNS); + mainLayout.setWidths(new float[]{1f, 2f, 2f}); + mainLayout.setWidthPercentage(TABLE_WIDTH); + mainLayout.getDefaultCell().setBorder(0); + + generateSimpleCell(mainLayout, TranslatorWorker.translateText("Activity difference", + TLSUtils.getEffectiveLangCode(), TLSUtils.getSiteId()), Header.ALIGN_CENTER, HEADER_FONT, + HEADER_BRACKGROUND_COLOR, HEADER_COLSPAN); + + + generateSimpleCell(mainLayout, TranslatorWorker.translateText("Value Name", + TLSUtils.getEffectiveLangCode(), TLSUtils.getSiteId()), Header.ALIGN_CENTER, HEADER_FONT, + HEADER_BRACKGROUND_COLOR, null); + generateSimpleCell(mainLayout, TranslatorWorker.translateText("Previous Version", + TLSUtils.getEffectiveLangCode(), TLSUtils.getSiteId()), Header.ALIGN_CENTER, HEADER_FONT, + HEADER_BRACKGROUND_COLOR, null); + generateSimpleCell(mainLayout, TranslatorWorker.translateText("New Version", + TLSUtils.getEffectiveLangCode(), TLSUtils.getSiteId()), Header.ALIGN_CENTER, HEADER_FONT, + HEADER_BRACKGROUND_COLOR, null); + + return mainLayout; + + + } + + private void createValues(Map> outputCollectionGrouped, PdfPTable mainLayout) { + Set keyset = outputCollectionGrouped.keySet(); + for (String key : keyset) { + List nameList = outputCollectionGrouped.get(key); + CompareOutput comp = nameList.get(VALUE_NAME); + generateSimpleCell(mainLayout, ActivityVersionUtil.sanitizeHtmlForExport(key), + Element.ALIGN_CENTER, PLAIN_FONT, null, null); + generateSimpleCell(mainLayout, ActivityVersionUtil.sanitizeHtmlForExport(comp.getStringOutput()[1])); + generateSimpleCell(mainLayout, ActivityVersionUtil.sanitizeHtmlForExport(comp.getStringOutput()[0])); + + } + } + + private void generateSimpleCell(PdfPTable mainLayout, String value) { + generateSimpleCell(mainLayout, value, null, PLAIN_FONT, null, null); + } + + private void generateSimpleCell(PdfPTable mainLayout, String value, Integer alignment, Font font, + BaseColor backgroundColor, Integer colSpan) { + + PdfPCell cell = new PdfPCell(); + Paragraph p = new Paragraph(value, font); + if (alignment != null) { + p.setAlignment(alignment); + } + if (backgroundColor != null) { + cell.setBackgroundColor(backgroundColor); + } + if (colSpan != null) { + cell.setColspan(colSpan); + } + cell.addElement(p); + mainLayout.addCell(cell); + } + + private static PdfPTable buildPdfTable(int columns) { + PdfPTable table = new PdfPTable(columns); + return table; + } + +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/action/AuditXLSExportService.java b/amp/WEB-INF/src/org/digijava/module/aim/action/AuditXLSExportService.java new file mode 100644 index 00000000000..a20ef71ec47 --- /dev/null +++ b/amp/WEB-INF/src/org/digijava/module/aim/action/AuditXLSExportService.java @@ -0,0 +1,57 @@ +package org.digijava.module.aim.action; + +import static org.apache.poi.ss.usermodel.CellStyle.BORDER_THIN; + +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFFont; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; + +public class AuditXLSExportService { + + private static final Integer first_COLUMN_WIDTH = 3840; + private static final Integer COLUMN_WIDTH = 12800; + private HSSFCellStyle cs; + private HSSFCellStyle titleCS; + + public AuditXLSExportService() { + + } + + public HSSFCellStyle getOrCreateTitleStyle(HSSFWorkbook wb) { + if (titleCS == null) { + titleCS = wb.createCellStyle(); + wb.createCellStyle(); + titleCS.setWrapText(true); + HSSFFont fontHeader = wb.createFont(); + fontHeader.setFontName(HSSFFont.FONT_ARIAL); + fontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + titleCS.setAlignment(HSSFCellStyle.ALIGN_CENTER); + titleCS.setFont(fontHeader); + addBorderToCell(titleCS); + } + return titleCS; + } + + private void addBorderToCell(HSSFCellStyle cell) { + cell.setBorderLeft(BORDER_THIN); + cell.setBorderRight(BORDER_THIN); + cell.setBorderTop(BORDER_THIN); + cell.setBorderBottom(BORDER_THIN); + } + + public HSSFCellStyle getOrCreateOrdinaryStyle(HSSFWorkbook wb) { + if (cs == null) { + cs = wb.createCellStyle(); + cs.setWrapText(true); + cs.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP); + addBorderToCell(cs); + } + return cs; + } + public void setColumnWidth(HSSFSheet sheet) { + sheet.setColumnWidth(0, first_COLUMN_WIDTH); + sheet.setColumnWidth(1, COLUMN_WIDTH); + sheet.setColumnWidth(2, COLUMN_WIDTH); + } +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/action/CompareActivityVersions.java b/amp/WEB-INF/src/org/digijava/module/aim/action/CompareActivityVersions.java index 22e9e703e0a..d91e8e01a46 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/action/CompareActivityVersions.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/action/CompareActivityVersions.java @@ -1,23 +1,23 @@ package org.digijava.module.aim.action; - -import java.lang.reflect.Field; +import java.io.ByteArrayOutputStream; import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.Arrays; import java.util.Calendar; -import java.util.Collection; import java.util.Date; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; +import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; -import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; @@ -29,456 +29,93 @@ import org.digijava.kernel.entity.Locale; import org.digijava.kernel.persistence.PersistenceManager; import org.digijava.kernel.request.Site; +import org.digijava.kernel.request.TLSUtils; import org.digijava.kernel.util.RequestUtils; import org.digijava.module.aim.annotations.activityversioning.CompareOutput; -import org.digijava.module.aim.annotations.activityversioning.VersionableCollection; -import org.digijava.module.aim.annotations.activityversioning.VersionableFieldSimple; -import org.digijava.module.aim.annotations.activityversioning.VersionableFieldTextEditor; import org.digijava.module.aim.dbentity.AmpActivityContact; import org.digijava.module.aim.dbentity.AmpActivityFields; import org.digijava.module.aim.dbentity.AmpActivityGroup; import org.digijava.module.aim.dbentity.AmpActivityVersion; import org.digijava.module.aim.dbentity.AmpTeamMember; -import org.digijava.module.aim.dbentity.Versionable; import org.digijava.module.aim.form.CompareActivityVersionsForm; -import org.digijava.module.aim.helper.ActivityHistory; import org.digijava.module.aim.helper.Constants; -import org.digijava.module.aim.helper.FormatHelper; import org.digijava.module.aim.helper.TeamMember; +import org.digijava.module.aim.util.versioning.ActivityComparisonContext; +import org.digijava.module.aim.util.versioning.ActivityComparisonResult; import org.digijava.module.aim.util.ActivityUtil; import org.digijava.module.aim.util.ActivityVersionUtil; import org.digijava.module.aim.util.AuditLoggerUtil; import org.digijava.module.aim.util.LuceneUtil; import org.digijava.module.aim.util.TeamMemberUtil; -import org.digijava.module.editor.util.DbUtil; import org.digijava.module.translation.util.ContentTranslationUtil; import org.hibernate.FlushMode; -import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.Transaction; + public class CompareActivityVersions extends DispatchAction { private static Logger logger = Logger.getLogger(EditActivity.class); - + + public ActionForward unspecified(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) + HttpServletRequest request, HttpServletResponse response) throws java.lang.Exception { return compare(mapping, form, request, response); } - + public ActionForward compare(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws Exception { + HttpServletResponse response) throws Exception { CompareActivityVersionsForm vForm = (CompareActivityVersionsForm) form; Session session = PersistenceManager.getRequestDBSession(); - setAdvancemode(vForm, request); - + + + if (request.getParameter("action") != null && request.getParameter("action").equals("setVersion") && request.getParameter("activityCurrentVersion") != null) { Long activityId = Long.parseLong(request.getParameter("activityCurrentVersion")); AmpActivityVersion activity = (AmpActivityVersion) session.load(AmpActivityVersion.class, activityId); AmpActivityGroup group = activity.getAmpActivityGroup(); - + AmpActivityVersion prevVer = group.getAmpActivityLastVersion(); //Why send the activity to the top of the list? It's confusing for users //thus we don't set the modifiedDate - //activity.setModifiedDate(Calendar.getInstance().getTime()); + //activity.setModifiedDate(Calendar.getInstance().getTime()); group.setAmpActivityLastVersion(activity); session.update(group); - //session.update(activity); Site site = RequestUtils.getSite(request); Locale navigationLanguage = RequestUtils.getNavigationLanguage(request); java.util.Locale locale = new java.util.Locale(navigationLanguage.getCode()); - LuceneUtil.addUpdateActivity(request.getSession().getServletContext().getRealPath("/"), true, site, locale, activity, prevVer); - - return new ActionForward(mapping.findForward("reload").getPath() + "?ampActivityId=" + activityId,true); + LuceneUtil.addUpdateActivity(request.getSession().getServletContext().getRealPath("/"), true, site, locale, + activity, prevVer); + + return new ActionForward(mapping.findForward("reload").getPath() + "?ampActivityId=" + activityId, true); } vForm.setOutputCollection(new ArrayList()); - // Load the activities. - vForm.setActivityOne((AmpActivityVersion) session.load(AmpActivityVersion.class, vForm.getActivityOneId())); - Hibernate.initialize(vForm.getActivityOne()); - ActivityVersionUtil.initializeActivity(vForm.getActivityOne()); - vForm.setActivityTwo((AmpActivityVersion) session.load(AmpActivityVersion.class, vForm.getActivityTwoId())); - Hibernate.initialize(vForm.getActivityTwo()); - ActivityVersionUtil.initializeActivity(vForm.getActivityTwo()); - - vForm.setOldActivity(vForm.getActivityOne()); - - - ActivityHistory auditHistory1 = getAuditHistory(vForm.getActivityOne()); - ActivityHistory auditHistory2 = getAuditHistory(vForm.getActivityTwo()); - - // Retrieve annotated for versioning fields. - Field[] fields = AmpActivityFields.class.getDeclaredFields(); - for (int i = 0; i < fields.length; i++) { - //logger.info(fields[i]); - CompareOutput output = new CompareOutput(); - - if (fields[i].isAnnotationPresent(VersionableFieldSimple.class)) { - // Obtain "get" method from field. - Method auxMethod = ActivityVersionUtil.getMethodFromFieldName(fields[i].getName(), AmpActivityVersion.class, "get"); - - // Compare values from 2 versions. - Object auxResult1 = auxMethod.invoke(vForm.getActivityOne(), null); - Object auxResult2 = auxMethod.invoke(vForm.getActivityTwo(), null); - - // Obtain annotation object. - VersionableFieldSimple auxAnnotation = (VersionableFieldSimple) fields[i] - .getAnnotation(VersionableFieldSimple.class); - - // Sanitize String values. - if (auxMethod.getReturnType().getName().equals("java.lang.String")) { - if (auxResult1 != null && auxResult1.toString().trim().equals("")) { - auxResult1 = null; - } - if (auxResult2 != null && auxResult2.toString().trim().equals("")) { - auxResult2 = null; - } - } - - // AMP-25074 - retrieve information about who and when modified the activity - // from amp_audit_logger (if it is empty in the activity object) - if (StringUtils.equals(fields[i].getName(), "modifiedBy")) { - auxResult1 = ActivityUtil.getModifiedByUserName(vForm.getActivityOne(), auditHistory1); - auxResult2 = ActivityUtil.getModifiedByUserName(vForm.getActivityTwo(), auditHistory2); - } else if (StringUtils.equals(fields[i].getName(), "updatedDate")) { - auxResult1 = ActivityUtil.getModifiedByDate(vForm.getActivityOne(), auditHistory1); - auxResult2 = ActivityUtil.getModifiedByDate(vForm.getActivityTwo(), auditHistory2); - } + ActivityComparisonContext context = new ActivityComparisonContext(TLSUtils.getSite().getId(), + TLSUtils.getSite().getName(), TLSUtils.getEffectiveLangCode()); + + vForm.setOutputCollectionGrouped(ActivityVersionUtil.compareActivities(vForm.getActivityOneId(), + vForm.getActivityTwoId(), context)); - // Compare values, if both are null then they are considered equal. - if (!(auxResult1 == null && auxResult2 == null)) { - if ((auxResult1 != null && auxResult2 == null) - || (auxResult1 == null && auxResult2 != null) - || (!auxResult1.equals(auxResult2))) { - - logger.warn(fields[i].getName() + ": " + auxResult1 + "-" + auxResult2); - output.setDescriptionOutput(auxAnnotation.fieldTitle()); - output.setFieldOutput(fields[i]); - - // Identity "read-value" and "mandatory" fields. - // TODO: If needed do the same for - // @VersionableFieldTextEditor and - // @VersionableCollection. - output.setBlockSingleChangeOutput(auxAnnotation.blockSingleChange()); - output.setMandatoryForSingleChangeOutput(auxAnnotation.mandatoryForSingleChange()); - - // Differentiate Wrappers from Classes that implements Versionable. - Class auxReturnType = auxMethod.getReturnType(); - - if (auxReturnType.getName().equals("java.util.Date") - || auxReturnType.getName().equals("java.sql.Date") - || auxReturnType.getName().equals("java.lang.String") - || auxReturnType.getName().equals("java.lang.Double") - || auxReturnType.getName().equals("java.lang.Integer") - || auxReturnType.getName().equals("java.lang.Long") - || auxReturnType.getName().equals("java.lang.Short") - || auxReturnType.getName().equals("java.lang.Float") - || auxReturnType.getName().equals("java.lang.Boolean") - || auxReturnType.getName().equals("java.math.BigDecimal")) { - - - String aux1String = getStringOrEmpty(auxResult1); - String aux2String = getStringOrEmpty(auxResult2); - - output.setStringOutput(new String[] {aux1String, aux2String}); - output.setOriginalValueOutput(new Object[] {auxResult1, auxResult2}); - } else if (ActivityVersionUtil.implementsVersionable(auxReturnType.getInterfaces())) { - Versionable auxVersionable1 = Versionable.class.cast(auxMethod.invoke(vForm - .getActivityOne(), null)); - Versionable auxVersionable2 = Versionable.class.cast(auxMethod.invoke(vForm - .getActivityTwo(), null)); - - String output1 = (auxVersionable1 != null) ? ActivityVersionUtil.generateFormattedOutput( - request, auxVersionable1.getOutput()) : null; - String output2 = (auxVersionable2 != null) ? ActivityVersionUtil.generateFormattedOutput( - request, auxVersionable2.getOutput()) : null; - output.setStringOutput(new String[] { output1, output2 }); - output.setOriginalValueOutput(new Object[] { auxResult1, auxResult2 }); - } else { - if ("modifiedBy".equals(fields[i].getName())) { - // this field cannot be used in merging - output.setBlockSingleChangeOutput(true); - } - - output.setStringOutput(new String[] {getStringOrEmpty(auxResult1), getStringOrEmpty(auxResult2)}); - output.setOriginalValueOutput(new Object[] {auxResult1, auxResult2}); - } - - - vForm.getOutputCollection().add(output); - } - } - } - if (fields[i].isAnnotationPresent(VersionableFieldTextEditor.class)) { - // Obtain "get" method from field. - Method auxMethod = ActivityVersionUtil.getMethodFromFieldName(fields[i].getName(), AmpActivityVersion.class, - "get"); - - // Compare values from 2 versions. - String auxResult1 = (String) auxMethod.invoke(vForm.getActivityOne(), null); - String auxResult2 = (String) auxMethod.invoke(vForm.getActivityTwo(), null); - - // Obtain annotation object. - VersionableFieldTextEditor auxAnnotation = (VersionableFieldTextEditor) fields[i] - .getAnnotation(VersionableFieldTextEditor.class); - - // Compare values, if both are null then they are considered - // equal. - if (!(auxResult1 == null && auxResult2 == null)) { - if ((auxResult1 != null && auxResult2 == null) || (auxResult1 == null && auxResult2 != null) - || (!auxResult1.equals(auxResult2))) { - output.setFieldOutput(fields[i]); - output.setBlockSingleChangeOutput(false); - output.setMandatoryForSingleChangeOutput(false); - - output.setDescriptionOutput(auxAnnotation.fieldTitle()); - Site site = RequestUtils.getSite(request); - String lang = RequestUtils.getNavigationLanguage(request).getCode(); - String auxBody1 = DbUtil.getEditorBody(site, auxResult1, lang); - String auxBody2 = DbUtil.getEditorBody(site, auxResult2, lang); - auxBody1 = auxBody1 != null ? auxBody1 : ""; - auxBody2 = auxBody2 != null ? auxBody2 : ""; - if (!auxBody1.trim().equals(auxBody2.trim())) { - output.setStringOutput(new String[] { auxBody1, auxBody2 }); - output.setOriginalValueOutput(new String[] { auxResult1, auxResult2 }); - vForm.getOutputCollection().add(output); - } - } - } - } - if (fields[i].isAnnotationPresent(VersionableCollection.class)) { - // Obtain "get" method from field. - Method auxMethod = ActivityVersionUtil.getMethodFromFieldName(fields[i].getName(), AmpActivityVersion.class, - "get"); - // Get values from 2 versions. - // Sometimes I have a problem with lazy collections and - // apparently closed session. - // Delete these lines if there are problems when saving: two - // sessions problem. - session = PersistenceManager.getRequestDBSession(); - Object auxResult1 = auxMethod.invoke(vForm.getActivityOne(), null); - Hibernate.initialize(auxResult1); - Object auxResult2 = auxMethod.invoke(vForm.getActivityTwo(), null); - Hibernate.initialize(auxResult2); - // Obtain annotation object. - VersionableCollection auxAnnotation = (VersionableCollection) fields[i] - .getAnnotation(VersionableCollection.class); - // Create list of differences. - List differences = new ArrayList(); - Collection auxCollection1 = (Collection) auxResult1; - Collection auxCollection2 = (Collection) auxResult2; - - // Evaluate the type of objects stored in the collection. - // TODO: Assuming everything is a Collection, later to implement - // other types. - if ((auxCollection1 == null && auxCollection2 == null) - || (auxCollection1 == null && auxCollection2.size() == 0) - || (auxCollection1.size() == 0 && auxCollection2 == null) - || (auxCollection1.size() == 0 && auxCollection2.size() == 0)) { - // Collections are equal. - continue; - } - Class auxReturnType = null; - if (auxCollection1 != null && auxCollection1.size() != 0) { - auxReturnType = auxCollection1.toArray()[0].getClass(); - } else { - auxReturnType = auxCollection2.toArray()[0].getClass(); - } - if (auxReturnType.getName().equals("java.util.Date") || auxReturnType.getName().equals("java.sql.Date") - || auxReturnType.getName().equals("java.lang.String") - || auxReturnType.getName().equals("java.lang.Double") - || auxReturnType.getName().equals("java.lang.Integer") - || auxReturnType.getName().equals("java.lang.Long") - || auxReturnType.getName().equals("java.lang.Short") - || auxReturnType.getName().equals("java.lang.Float") - || auxReturnType.getName().equals("java.lang.Boolean") - || auxReturnType.getName().equals("java.math.BigDecimal")) { - - // Wrappers don't have IDs then we can't detect "updates". - // Iterate each collection and show as different the values - // not present in the other. - Iterator iter1 = auxCollection1.iterator(); - while (iter1.hasNext()) { - int coincidence = 0; - Object auxObject1 = iter1.next(); - String auxValue1 = auxObject1.toString(); - Iterator iter2 = auxCollection2.iterator(); - while (iter2.hasNext()) { - if (auxValue1.equals((String) iter2.next())) { - coincidence++; - } - } - if (coincidence == 0) { - CompareOutput auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), new String[] { - auxValue1, "" }, fields[i], new Object[] { auxObject1, null }, false, false); - vForm.getOutputCollection().add(auxOutput); - } - } - iter1 = auxCollection2.iterator(); - while (iter1.hasNext()) { - int coincidence = 0; - Object auxObject2 = iter1.next(); - String auxValue2 = auxObject2.toString(); - Iterator iter2 = auxCollection1.iterator(); - while (iter2.hasNext()) { - if (auxValue2.equals((String) iter2.next())) { - coincidence++; - } - } - if (coincidence == 0) { - CompareOutput auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), new String[] { "", - auxValue2 }, fields[i], new Object[] { null, auxObject2 }, false, false); - vForm.getOutputCollection().add(auxOutput); - } - } - } else if (ActivityVersionUtil.implementsVersionable(auxReturnType.getInterfaces())) { - List auxList = new ArrayList(); - Iterator iter1 = auxCollection1.iterator(); - while (iter1.hasNext()) { - int coincidence = 0; - Object auxObject1 = iter1.next(); - Versionable auxVersionable1 = (Versionable) auxObject1; - Iterator iter2 = auxCollection2.iterator(); - while (iter2.hasNext()) { - Object auxObject2 = iter2.next(); - Versionable auxVersionable2 = (Versionable) auxObject2; - if (auxVersionable1.equalsForVersioning(auxVersionable2)) { - coincidence++; - Object auxValue1 = auxVersionable1.getValue() != null ? auxVersionable1.getValue() : ""; - Object auxValue2 = auxVersionable2.getValue() != null ? auxVersionable2.getValue() : ""; - if (!auxValue1.equals(auxValue2)) { - CompareOutput auxOutput = null; - - if (auxVersionable1.getClass().getName(). - equals("org.digijava.module.aim.dbentity.AmpFunding") && - auxVersionable2.getClass().getName(). - equals("org.digijava.module.aim.dbentity.AmpFunding") - ) { - auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), - new String[] { - ActivityVersionUtil.generateFormattedOutput(request, - auxVersionable1.getOutput(), - auxVersionable2.getOutput()), - ActivityVersionUtil.generateFormattedOutput(request, - auxVersionable2.getOutput(), - auxVersionable1.getOutput()) }, fields[i], new Object[] { - auxObject1, auxObject2 }, false, false); - - } else { - auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), - new String[] { - ActivityVersionUtil.generateFormattedOutput(request, - auxVersionable1.getOutput()), - ActivityVersionUtil.generateFormattedOutput(request, - auxVersionable2.getOutput()) }, fields[i], new Object[] { - auxObject1, auxObject2 }, false, false); - } - vForm.getOutputCollection().add(auxOutput); - auxList.add(auxVersionable1); - auxList.add(auxVersionable2); - } - } - } - if (coincidence == 0) { - CompareOutput auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), new String[] { - ActivityVersionUtil.generateFormattedOutput(request, auxVersionable1.getOutput()), - "" }, fields[i], new Object[] { auxObject1, null }, false, false); - vForm.getOutputCollection().add(auxOutput); - auxList.add(auxVersionable1); - } - } - iter1 = auxCollection2.iterator(); - while (iter1.hasNext()) { - int coincidence = 0; - Object auxObject2 = iter1.next(); - Versionable auxVersionable2 = (Versionable) auxObject2; - Iterator iter2 = auxCollection1.iterator(); - while (iter2.hasNext()) { - Object auxObject1 = iter2.next(); - Versionable auxVersionable1 = (Versionable) auxObject1; - if (auxVersionable2.equalsForVersioning(auxVersionable1)) { - coincidence++; - Object auxValue1 = auxVersionable1.getValue() != null ? auxVersionable1.getValue() : ""; - Object auxValue2 = auxVersionable2.getValue() != null ? auxVersionable2.getValue() : ""; - if (!auxValue2.equals(auxValue1)) { - // Check if the object was added in the - // previous iteration. - if (!auxList.contains(auxVersionable2)) { - CompareOutput auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), - new String[] { - ActivityVersionUtil.generateFormattedOutput(request, - auxVersionable1.getOutput()), - ActivityVersionUtil.generateFormattedOutput(request, - auxVersionable2.getOutput()) }, fields[i], - new Object[] { auxObject1, auxObject2 }, false, false); - vForm.getOutputCollection().add(auxOutput); - } - } - } - } - if (coincidence == 0) { - // Check if the object was added in the - // previous iteration. - if (!auxList.contains(auxVersionable2)) { - CompareOutput auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), new String[] { - "", - ActivityVersionUtil.generateFormattedOutput(request, auxVersionable2 - .getOutput()) }, fields[i], new Object[] { null, auxObject2 }, false, - false); - vForm.getOutputCollection().add(auxOutput); - } - } - } - } else { - output.setStringOutput(new String[] { auxResult1 != null ? auxResult1.toString() : "", - auxResult2 != null ? auxResult2.toString() : "" }); - output.setDescriptionOutput(auxAnnotation.fieldTitle()); - vForm.getOutputCollection().add(output); - } - } - } - Map> outputGroupped = groupOutputCollection (vForm.getOutputCollection()); - modifyFundingOutputs (outputGroupped); - vForm.setOutputCollectionGrouped(outputGroupped); - return mapping.findForward("forward"); } - private void modifyFundingOutputs (Map> outputGroupped) { + private void modifyFundingOutputs(Map> outputGroupped) { } - private Map> groupOutputCollection (List outputCollection) { - Map> retVal = new HashMap>(); - int idx = 0; - for (CompareOutput obj: outputCollection) { - if (!obj.getBlockSingleChangeOutput()) { - obj.setIndex(idx); - idx ++; - } else { - obj.setIndex(-1); // skip from merge process - } - if (!retVal.containsKey(obj.getDescriptionOutput())) { - retVal.put(obj.getDescriptionOutput(), new ArrayList()); - } - retVal.get(obj.getDescriptionOutput()).add(obj); - - } - - return retVal; - } public ActionForward enableMerge(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws Exception { + HttpServletResponse response) throws Exception { CompareActivityVersionsForm vForm = (CompareActivityVersionsForm) form; List filteredList = new ArrayList(); @@ -495,20 +132,20 @@ public ActionForward enableMerge(ActionMapping mapping, ActionForm form, HttpSer } public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws Exception { + HttpServletResponse response) throws Exception { return mapping.findForward("reload"); } public ActionForward saveNewActivity(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws Exception { + HttpServletResponse response) throws Exception { CompareActivityVersionsForm vForm = (CompareActivityVersionsForm) form; // Get data from jsp. ActionErrors errors = new ActionErrors(); boolean hasErrors = false; - + setAdvancemode(vForm, request); - + List auxData = new ArrayList(); for (int i = 0; i < vForm.getMergedValues().length; i++) { CompareOutput auxOutput = vForm.getOutputCollection().get(i); @@ -524,7 +161,8 @@ public ActionForward saveNewActivity(ActionMapping mapping, ActionForm form, Htt // The user didn't select a value, then is empty (this is // important because the merged activity is a copy of one of the // compared versions). - newOutput.setOriginalValueOutput(new Object[] { null, auxOutput.getOriginalValueOutput()[0] }); //remove the one from right + newOutput.setOriginalValueOutput(new Object[] { null, auxOutput.getOriginalValueOutput()[0] }); + //remove the one from right // Raise error if mandatory fields have no values. if (newOutput.getMandatoryForSingleChangeOutput()) { @@ -541,8 +179,8 @@ public ActionForward saveNewActivity(ActionMapping mapping, ActionForm form, Htt vForm.setMethod("enableMerge"); return mapping.findForward("forward"); } - - + + // The main idea is: once we have the collection with fields selected by // the user we need to COPY one of the AmpActivity objects and call the // getters from these fields and push those values into the matching @@ -566,9 +204,9 @@ public ActionForward saveNewActivity(ActionMapping mapping, ActionForm form, Htt AmpActivityVersion oldActivity = (AmpActivityVersion) session.load(AmpActivityVersion.class, vForm .getOldActivity().getAmpActivityId()); - - - + + + // Insert fields selected by user into AmpActity properties. Iterator iter = auxData.iterator(); while (iter.hasNext()) { @@ -601,14 +239,14 @@ public ActionForward saveNewActivity(ActionMapping mapping, ActionForm form, Htt } //session.update(auxActivity); } - - if (remOriginalValueObject != null){ + + if (remOriginalValueObject != null) { Class[] params = auxMethod.getParameterTypes(); if (params != null && params[0].getName().contains("java.util.Set")) { Class clazz = remOriginalValueObject.getClass(); String idProperty = session.getSessionFactory().getClassMetadata(clazz) - .getIdentifierPropertyName(); - + .getIdentifierPropertyName(); + Method method = clazz.getMethod("get" + Strings.capitalize(idProperty)); Long remId = (Long) method.invoke(remOriginalValueObject); @@ -620,19 +258,18 @@ public ActionForward saveNewActivity(ActionMapping mapping, ActionForm form, Htt while (it.hasNext()) { Object tmp = (Object) it.next(); Long tmpId = (Long) method.invoke(tmp); - - if (tmpId.compareTo(remId) == 0){ + + if (tmpId.compareTo(remId) == 0) { it.remove(); break; } } } auxMethod.invoke(oldActivity, auxSet); - } - else{ - if (addOriginalValueObject == null){ + } else { + if (addOriginalValueObject == null) { // this is the case where no value was selected; - auxMethod.invoke(oldActivity, (Object)null); + auxMethod.invoke(oldActivity, (Object) null); } } } @@ -643,20 +280,20 @@ public ActionForward saveNewActivity(ActionMapping mapping, ActionForm form, Htt auxActivity.setAmpActivityId(null); session.evict(oldActivity); - + // Code related to versioning. AmpActivityGroup auxActivityGroup = (AmpActivityGroup) session.load(AmpActivityGroup.class, vForm .getOldActivity().getAmpActivityGroup().getAmpActivityGroupId()); AmpActivityVersion prevVersion = auxActivityGroup.getAmpActivityLastVersion(); auxActivityGroup.setAmpActivityLastVersion(auxActivity); session.save(auxActivityGroup); - + Date updatedTime = Calendar.getInstance().getTime(); auxActivity.setAmpActivityGroup(auxActivityGroup); auxActivity.setModifiedDate(updatedTime); auxActivity.setUpdatedDate(updatedTime); auxActivity.setModifiedBy(member); - + auxActivity.setMergedActivity(true); auxActivity.setMergeSource1(vForm.getActivityOne()); auxActivity.setMergeSource2(vForm.getActivityTwo()); @@ -667,9 +304,9 @@ public ActionForward saveNewActivity(ActionMapping mapping, ActionForm form, Htt AmpActivityContact actCont; Set contacts = new HashSet(); Set activityContacts = auxActivity.getActivityContacts(); - if (activityContacts != null){ + if (activityContacts != null) { Iterator it = activityContacts.iterator(); - while(it.hasNext()){ + while (it.hasNext()) { actCont = it.next(); actCont.setId(null); actCont.setActivity(auxActivity); @@ -682,11 +319,12 @@ public ActionForward saveNewActivity(ActionMapping mapping, ActionForm form, Htt transaction.commit(); logger.warn("Activity Saved."); - + Site site = RequestUtils.getSite(request); Locale navigationLanguage = RequestUtils.getNavigationLanguage(request); java.util.Locale locale = new java.util.Locale(navigationLanguage.getCode()); - LuceneUtil.addUpdateActivity(request.getSession().getServletContext().getRealPath("/"), true, site, locale, auxActivity, prevVersion); + LuceneUtil.addUpdateActivity(request.getSession().getServletContext().getRealPath("/"), true, site, locale, + auxActivity, prevVersion); AuditLoggerUtil.logObject(request, auxActivity, "add", "merged"); } catch (Exception e) { logger.error("Can't save merged activity:", e); @@ -697,41 +335,102 @@ public ActionForward saveNewActivity(ActionMapping mapping, ActionForm form, Htt return mapping.findForward("index"); } - private void setAdvancemode(CompareActivityVersionsForm vForm, HttpServletRequest request){ + private void setAdvancemode(CompareActivityVersionsForm vForm, HttpServletRequest request) { boolean ispartofamanagetmentworkspace = false; boolean iscurrentworkspacemanager = false; - - TeamMember currentMember = (TeamMember)request.getSession().getAttribute("currentMember"); + + TeamMember currentMember = (TeamMember) request.getSession().getAttribute("currentMember"); AmpTeamMember ampCurrentMember = TeamMemberUtil.getAmpTeamMember(currentMember.getMemberId()); - - if (ampCurrentMember.getAmpMemberRole().getTeamHead()) + + if (ampCurrentMember.getAmpMemberRole().getTeamHead()) { iscurrentworkspacemanager = true; - if (ampCurrentMember.getAmpTeam().getAccessType().equalsIgnoreCase(Constants.ACCESS_TYPE_MNGMT)) + } + if (ampCurrentMember.getAmpTeam().getAccessType().equalsIgnoreCase(Constants.ACCESS_TYPE_MNGMT)) { ispartofamanagetmentworkspace = true; - - //If the current user is part of the management workspace or is not the workspace manager of a workspace that's not management then hide. + } + + // If the current user is part of the management workspace or is not the + // workspace manager of a workspace that's not management then hide. vForm.setAdvancemode(!ispartofamanagetmentworkspace & iscurrentworkspacemanager); } - - private String getStringOrEmpty(Object o) { - if (o != null) { - if (o instanceof Date || o instanceof java.sql.Date) { - return FormatHelper.formatDate((Date) o); + + public ActionForward viewDifferences(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { + + CompareActivityVersionsForm vForm = (CompareActivityVersionsForm) form; + + ActivityComparisonResult result = ActivityVersionUtil.compareActivities(vForm.getActivityOneId()); + if (result != null) { + vForm.setOutputCollectionGrouped(result.getCompareOutput()); + vForm.setActivityName(result.getName()); + } else { + vForm.setOutputCollectionGrouped(null); + vForm.setActivityName(null); + } + + return mapping.findForward("forward"); + } + + public ActionForward compareAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { + + CompareActivityVersionsForm vForm = (CompareActivityVersionsForm) form; + HttpSession session = request.getSession(); + TeamMember tm = (TeamMember) session.getAttribute("currentMember"); + boolean isPermitted = AuditLoggerUtil.checkPermission(request); + if (isPermitted) { + vForm.populateEffectiveFilters(); + if (tm.getTeamHead()) { + vForm.setEffectiveSelectedTeam(tm.getTeamName()); } - - return o.toString(); + vForm.setActivityComparisonResultList(ActivityVersionUtil.getOutputCollectionGrouped( + vForm.getEffectiveSelectedUser(), vForm.getEffectiveSelectedTeam(), vForm.getEffectiveDateFrom(), + vForm.getEffectiveDateTo())); } - - return ""; + return mapping.findForward("forward"); } - - private ActivityHistory getAuditHistory(AmpActivityVersion activity) { - ActivityHistory auditHistory = null; - - if (activity.getModifiedBy() == null || (activity.getUpdatedDate() == null && activity.getModifiedDate() == null)) { - auditHistory = ActivityUtil.getModifiedByInfoFromAuditLogger(activity.getAmpActivityId()); + public ActionForward pdfExport(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { + CompareActivityVersionsForm vForm = (CompareActivityVersionsForm) form; + Map> outputCollectionGrouped = vForm.getOutputCollectionGrouped(); + ByteArrayOutputStream baos; + List comparisonResult; + if (vForm.getActivityOneId() == 0) { + comparisonResult = vForm.getActivityComparisonResultList(); + } else { + AmpActivityVersion av = ActivityUtil.loadActivity(vForm.getActivityOneId()); + comparisonResult = new ArrayList(Arrays.asList(new ActivityComparisonResult(av.getAmpActivityId(), + av.getAmpId() + " " + av.getName(), outputCollectionGrouped))); + } + baos = AuditPDFexporter.getInstance().buildPDFexport(comparisonResult); + + response.setContentType("application/pdf; charset=UTF-8"); + response.setHeader("content-disposition", "attachment;filename=activity.pdf"); + response.setContentLength(baos.size()); + ServletOutputStream out = response.getOutputStream(); + baos.writeTo(out); + out.flush(); + return null; + } + + public ActionForward xlsExport(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { + List comparisonResult; + response.setContentType("application/vnd.ms-excel"); + response.setHeader("Content-disposition", "inline; filename=AuditLogger.xls"); + CompareActivityVersionsForm vForm = (CompareActivityVersionsForm) form; + AuditExcelExporter auditExcelExporter = new AuditExcelExporter(); + if (vForm.getActivityOneId() == 0) { + List outputCollection = vForm.getActivityComparisonResultList(); + HSSFWorkbook wb = auditExcelExporter.generateExcel(outputCollection); + wb.write(response.getOutputStream()); + } else { + Map> outputCollectionGrouped = vForm.getOutputCollectionGrouped(); + comparisonResult = new ArrayList(Arrays.asList(new ActivityComparisonResult(vForm.getActivityOneId(), + vForm.getActivityName(), outputCollectionGrouped))); + HSSFWorkbook wb = auditExcelExporter.generateExcel(comparisonResult); + wb.write(response.getOutputStream()); } - - return auditHistory; + return null; } -} +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/action/TeamAuditLogger.java b/amp/WEB-INF/src/org/digijava/module/aim/action/TeamAuditLogger.java index 4d4756cbee1..1416301bb6d 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/action/TeamAuditLogger.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/action/TeamAuditLogger.java @@ -21,30 +21,17 @@ import org.digijava.module.aim.util.AuditLoggerUtil; public class TeamAuditLogger extends MultiAction { - + private static Logger logger = Logger.getLogger(TeamAuditLogger.class); - + private ServletContext ampContext = null; - + public ActionForward modePrepare(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) + HttpServletRequest request, HttpServletResponse response) throws Exception { - - boolean permitted = false; + HttpSession session = request.getSession(); - if (session.getAttribute("ampAdmin") != null) { - String key = (String) session.getAttribute("ampAdmin"); - if (key.equalsIgnoreCase("yes")) { - permitted = true; - } else { - if (session.getAttribute("teamLeadFlag") != null) { - key = (String) session.getAttribute("teamLeadFlag"); - if (key.equalsIgnoreCase("true")) { - permitted = true; - } - } - } - } + boolean permitted = AuditLoggerUtil.checkPermission(request); if (!permitted) { return mapping.findForward("index"); } @@ -53,73 +40,17 @@ public ActionForward modePrepare(ActionMapping mapping, ActionForm form, TeamMember tm = (TeamMember) session.getAttribute("currentMember"); teamname = tm.getTeamName(); } - + TeamAuditForm vForm = (TeamAuditForm) form; - - Collection logs=AuditLoggerUtil.getTeamLogObjects(teamname); - - if (request.getParameter("sortBy")!=null){ - vForm.setSortBy(request.getParameter("sortBy")); - } - if(vForm.getSortBy() == null){ - vForm.setSortBy("changedatedesc"); - } - if("nameasc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerNameComparator()) ; - } - else if("namedesc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerNameComparator()); - Collections.reverse((List)logs); - } - else if("typeasc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerTypeComparator()); - } - else if("typedesc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerTypeComparator()); - Collections.reverse((List)logs); - } - else if("teamasc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerTeamComparator()); - } - else if("teamdesc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerTeamComparator()); - Collections.reverse((List)logs); - } - else if("authorasc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerAuthorComparator()); - } - else if("authordesc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerAuthorComparator()); - Collections.reverse((List)logs); - } - else if("creationdateasc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerCreationDateComparator()); - } - else if("creationdatedesc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerCreationDateComparator()); - Collections.reverse((List)logs); - } - else if("editorasc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerEditorNameComparator()); - } - else if("editordesc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerEditorNameComparator()); - Collections.reverse((List)logs); - } - else if("actionasc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerActionComparator()); - } - else if("actiondesc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerActionComparator()); - Collections.reverse((List)logs); - } - else if("changedateasc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerActionComparator()); - } - else if("changedatedesc".equalsIgnoreCase(vForm.getSortBy())){ - Collections.sort((List)logs, new AuditLoggerUtil.HelperAuditloggerActionComparator()); - Collections.reverse((List)logs); - } + vForm.setUserList(AuditLoggerUtil.getEditorNameFromLog()); + vForm.setTeamName(teamname); + vForm.populateEffectiveFilters(); + + Collection logs = AuditLoggerUtil.getLogObjects(false, + vForm.getEffectiveSelectedUser(), teamname, vForm.getEffectiveDateFrom(), + vForm.getEffectiveDateTo()); + + applySortBy(request, vForm, (List) logs); vForm.setPagesToShow(10); int totalrecords=20; @@ -134,45 +65,89 @@ else if("changedatedesc".equalsIgnoreCase(vForm.getSortBy())){ Collection tempCol = new ArrayList(); AmpAuditLogger[] tmplogs = (AmpAuditLogger[])logs.toArray(new AmpAuditLogger[0]); for (int i = (stIndex - 1); i < edIndex; i++) { - if (logs.size() > i){ + if (logs.size() > i) { tempCol.add(tmplogs[i]); - } - else{ + } else { break; } - } - + } + Collection pages = null; int numpages; numpages = logs.size() / totalrecords; numpages += (logs.size() % totalrecords != 0) ? 1 : 0; - + if ((numpages) >= 1) { pages = new ArrayList(); for (int i = 0; i < (numpages); i++) { - Integer pageNum = new Integer(i + 1); - pages.add(pageNum); + Integer pageNum = new Integer(i + 1); + pages.add(pageNum); } - }else{ - pages = new ArrayList(); - } - - vForm.setPages(pages); + } else { + pages = new ArrayList(); + } + + vForm.setPages(pages); vForm.setCurrentPage(new Integer(page)); vForm.setLogs(tempCol); vForm.setPagesSize(pages.size()); - + return modeSelect(mapping, form, request, response); } - public ActionForward modeSelect(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { - // TODO Auto-generated method stub - //return modeNew(mapping, form, request, response); - if(request.getParameter("action")!=null) - { -// if(request.getParameter("action").compareTo("add")==0) return modeAddTemplate(mapping, form, request, response); - } + private void applySortBy(HttpServletRequest request, TeamAuditForm vForm, List logs) { + if (request.getParameter("sortBy") != null) { + vForm.setSortBy(request.getParameter("sortBy")); + } + if (vForm.getSortBy() == null) { + vForm.setSortBy("changedatedesc"); + } + if ("nameasc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerNameComparator()); + } else if ("namedesc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerNameComparator()); + Collections.reverse(logs); + } else if ("typeasc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerTypeComparator()); + } else if ("typedesc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerTypeComparator()); + Collections.reverse(logs); + } else if ("teamasc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerTeamComparator()); + } else if ("teamdesc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerTeamComparator()); + Collections.reverse(logs); + } else if ("authorasc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerAuthorComparator()); + } else if ("authordesc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerAuthorComparator()); + Collections.reverse(logs); + } else if ("creationdateasc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerCreationDateComparator()); + } else if ("creationdatedesc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerCreationDateComparator()); + Collections.reverse(logs); + } else if ("editorasc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerEditorNameComparator()); + } else if ("editordesc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerEditorNameComparator()); + Collections.reverse(logs); + } else if ("actionasc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerActionComparator()); + } else if ("actiondesc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerActionComparator()); + Collections.reverse(logs); + } else if ("changedateasc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerChangeDateComparator()); + } else if ("changedatedesc".equalsIgnoreCase(vForm.getSortBy())) { + Collections.sort(logs, new AuditLoggerUtil.HelperAuditloggerChangeDateComparator()); + Collections.reverse(logs); + } + } + + public ActionForward modeSelect(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { return mapping.findForward("forward"); } - -} + +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/dbentity/AmpFunding.java b/amp/WEB-INF/src/org/digijava/module/aim/dbentity/AmpFunding.java index a7660d8f348..4e6b47996d7 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/dbentity/AmpFunding.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/dbentity/AmpFunding.java @@ -183,7 +183,10 @@ public Object getValue() { if (auxDetail.getContract() != null) ret.append("-" + auxDetail.getContract().getId()); ret.append("-" + auxDetail.getExpCategory()); ret.append("-" + auxDetail.getDisbursementOrderRejected()); - if (auxDetail.getRecipientOrg() != null) ret.append("- recipient " + auxDetail.getRecipientOrg().getAmpOrgId() + " with role of " + auxDetail.getRecipientRole().getAmpRoleId()); + if (auxDetail.getRecipientOrg() != null && auxDetail.getRecipientRole() != null) { + ret.append("- recipient " + auxDetail.getRecipientOrg().getAmpOrgId() + + " with role of " + auxDetail.getRecipientRole().getAmpRoleId()); + } } // Compare fields from AmpFundingMTEFProjection. @@ -355,7 +358,10 @@ public Output getOutput() { } if (!error) { String recipientInfo = ""; - if (auxDetail.getRecipientOrg() != null) recipientInfo = String.format(" to %s as %s", auxDetail.getRecipientOrg().getName(), auxDetail.getRecipientRole().getName()); + if (auxDetail.getRecipientOrg() != null && auxDetail.getRecipientRole() != null) { + recipientInfo = String.format(" to %s as %s", auxDetail.getRecipientOrg().getName(), + auxDetail.getRecipientRole().getName()); + } String adjustment = auxDetail.getAdjustmentType().getValue(); auxOutDetail = out.getOutputs().get(out.getOutputs().size() - 1); auxOutDetail.getOutputs().add(new Output(null, new String[]{""}, new Object[]{adjustment, " - ", auxDetail.getTransactionAmount(), " ", auxDetail.getAmpCurrencyId(), " - ", auxDetail.getTransactionDate(), extraValues + recipientInfo})); diff --git a/amp/WEB-INF/src/org/digijava/module/aim/dbentity/AmpIssues.java b/amp/WEB-INF/src/org/digijava/module/aim/dbentity/AmpIssues.java index e445c04fe6f..97a02242d68 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/dbentity/AmpIssues.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/dbentity/AmpIssues.java @@ -105,12 +105,11 @@ public Output getOutput() { int i = 0; while (it2.hasNext()) { AmpActor actor = (AmpActor) it2.next(); - if (actor.getName() != null){ - actors[i] = actor.getName(); - if (it2.hasNext()) - actors[i] += ", "; - i++; + actors[i] = actor.getName() != null ? actor.getName() : " "; + if (it2.hasNext()) { + actors[i] += ", "; } + i++; } Output out1 = new Output(new ArrayList(), new String[] {"Actors"}, actors); diff --git a/amp/WEB-INF/src/org/digijava/module/aim/form/AuditLoggerManagerForm.java b/amp/WEB-INF/src/org/digijava/module/aim/form/AuditLoggerManagerForm.java index 072c19340b4..568adac1fca 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/form/AuditLoggerManagerForm.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/form/AuditLoggerManagerForm.java @@ -1,105 +1,38 @@ package org.digijava.module.aim.form; import java.io.Serializable; -import java.util.Collection; +import java.util.List; -import org.apache.struts.action.ActionForm; +public class AuditLoggerManagerForm extends FilterAuditLoggerForm implements Serializable { -public class AuditLoggerManagerForm extends ActionForm implements Serializable{ - private static final long serialVersionUID = -2614366966871314200L; - - private Collection logs; - private String sortBy; - private int pagesToShow; - private Integer currentPage; - private int pagesSize; - private Collection pages = null; - private int offset; - private String useraction; - private String frecuency; - private boolean withLogin; - - public String getUseraction() { - return useraction; - } - public void setUseraction(String useraction) { - this.useraction = useraction; - } + private boolean withLogin; + private List userId; + private List teamList; - public String getFrecuency() { - return frecuency; + public boolean isWithLogin() { + return withLogin; } - public void setFrecuency(String frecuency) { - this.frecuency = frecuency; + public void setWithLogin(boolean withLogin) { + this.withLogin = withLogin; } - public int getOffset() { - int value; - if (getCurrentPage()> (this.getPagesToShow()/2)){ - value = (this.getCurrentPage() - (this.getPagesToShow()/2))-1; - } - else { - value = 0; - } - setOffset(value); - return offset; + public List getTeamList() { + return teamList; } - public void setOffset(int offset) { - this.offset = offset; - } - - public Collection getPages() { - return pages; - } - public void setPages(Collection pages) { - this.pages = pages; - if(pages!=null) - { - this.pagesSize=pages.size(); - } - } - - public int getPagesToShow() { - return pagesToShow; - } - public void setPagesToShow(int pagesToShow) { - this.pagesToShow = pagesToShow; - } - public Integer getCurrentPage() { - return currentPage; - } - public void setCurrentPage(Integer currentPage) { - this.currentPage = currentPage; - } - public int getPagesSize() { - return pagesSize; - } - public void setPagesSize(int pagesSize) { - this.pagesSize = pagesSize; - } - public Collection getLogs() { - return logs; - } - public void setLogs(Collection logs) { - this.logs = logs; - } - public String getSortBy() { - return sortBy; - } - public void setSortBy(String sortBy) { - this.sortBy = sortBy; + public void setTeamList(List teamList) { + this.teamList = teamList; } - public boolean isWithLogin() { - return withLogin; + public List getUserId() { + return userId; } - public void setWithLogin(boolean withLogin) { - this.withLogin = withLogin; + public void setUserId(List userId) { + this.userId = userId; } -} +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/form/CompareActivityVersionsForm.java b/amp/WEB-INF/src/org/digijava/module/aim/form/CompareActivityVersionsForm.java index 16d48d2762f..eb475f320a5 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/form/CompareActivityVersionsForm.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/form/CompareActivityVersionsForm.java @@ -4,12 +4,11 @@ import java.util.Map; import java.util.Set; -import org.apache.struts.action.ActionForm; import org.digijava.module.aim.annotations.activityversioning.CompareOutput; -import org.digijava.module.aim.dbentity.AmpActivity; import org.digijava.module.aim.dbentity.AmpActivityVersion; +import org.digijava.module.aim.util.versioning.ActivityComparisonResult; -public class CompareActivityVersionsForm extends ActionForm { +public class CompareActivityVersionsForm extends FilterAuditLoggerForm { private Long activityOneId; @@ -30,11 +29,32 @@ public class CompareActivityVersionsForm extends ActionForm { private String[] mergedValues = new String[] {}; private Long ampActivityId; - + private boolean advancemode; private Map> outputCollectionGrouped; + + private List activityComparisonResultList; + + private String activityName; + + public String getActivityName() { + return activityName; + } + + public void setActivityName(String activityName) { + this.activityName = activityName; + } + + public List getActivityComparisonResultList() { + return this.activityComparisonResultList; + } + + public void setActivityComparisonResultList(List activityComparisonResultList) { + this.activityComparisonResultList = activityComparisonResultList; + } + public Long getActivityOneId() { return activityOneId; } @@ -134,4 +154,5 @@ public void setOutputCollectionGrouped(Map> outputCo public Set>> getOutputCollectionGroupedAsSet() { return this.outputCollectionGrouped.entrySet(); } -} + +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/form/FilterAuditLoggerForm.java b/amp/WEB-INF/src/org/digijava/module/aim/form/FilterAuditLoggerForm.java new file mode 100644 index 00000000000..f7c63a9aeff --- /dev/null +++ b/amp/WEB-INF/src/org/digijava/module/aim/form/FilterAuditLoggerForm.java @@ -0,0 +1,215 @@ +package org.digijava.module.aim.form; + +import org.apache.struts.action.ActionForm; +import org.digijava.module.aim.helper.DateConversion; +import org.joda.time.DateTime; + +import java.util.Collection; +import java.util.Date; +import java.util.List; + + +public class FilterAuditLoggerForm extends ActionForm { + + public static final Integer LAST_HOUR_OF_DAY = 30; + public static final Integer LAST_MINUTE_OF_HOUR = 59; + public static final Integer LAST_SECOND_OF_MINUTE = 59; + private String selectedUser; + private String selectedTeam; + private String selectedDateFrom; + private String selectedDateTo; + private String effectiveSelectedUser; + private String effectiveSelectedTeam; + private Date effectiveDateFrom; + private Date effectiveDateTo; + private List userList; + + private Collection logs; + private String sortBy; + private int pagesToShow; + private Integer currentPage; + private int pagesSize; + private Collection pages = null; + private int offset; + private String useraction; + private String frecuency; + + public String getUseraction() { + return useraction; + } + + public void setUseraction(String useraction) { + this.useraction = useraction; + } + + public String getFrecuency() { + return frecuency; + } + + public void setFrecuency(String frecuency) { + this.frecuency = frecuency; + } + + public int getOffset() { + int value; + if (getCurrentPage() > (this.getPagesToShow() / 2)) { + value = (this.getCurrentPage() - (this.getPagesToShow() / 2)) - 1; + } else { + value = 0; + } + setOffset(value); + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public Collection getPages() { + return pages; + } + + public void setPages(Collection pages) { + this.pages = pages; + if (pages != null) { + this.pagesSize = pages.size(); + } + } + + public int getPagesToShow() { + return pagesToShow; + } + + public void setPagesToShow(int pagesToShow) { + this.pagesToShow = pagesToShow; + } + + public Integer getCurrentPage() { + return currentPage; + } + + public void setCurrentPage(Integer currentPage) { + this.currentPage = currentPage; + } + + public int getPagesSize() { + return pagesSize; + } + + public void setPagesSize(int pagesSize) { + this.pagesSize = pagesSize; + } + + public Collection getLogs() { + return logs; + } + + public void setLogs(Collection logs) { + this.logs = logs; + } + + public String getSortBy() { + return sortBy; + } + + public void setSortBy(String sortBy) { + this.sortBy = sortBy; + } + + + public List getUserList() { + return userList; + } + + public void setUserList(List userList) { + this.userList = userList; + } + + public FilterAuditLoggerForm() { + super(); + + } + + public String getSelectedDateFrom() { + return selectedDateFrom; + } + + public void setSelectedDateFrom(String selectedDateFrom) { + this.selectedDateFrom = selectedDateFrom; + } + + public String getSelectedDateTo() { + return selectedDateTo; + } + + public void setSelectedDateTo(String selectedDateTo) { + this.selectedDateTo = selectedDateTo; + } + + public String getSelectedUser() { + return selectedUser; + } + + public void setSelectedUser(String selectedUser) { + this.selectedUser = selectedUser; + } + + public String getSelectedTeam() { + return selectedTeam; + } + + public void setSelectedTeam(String selectedTeam) { + this.selectedTeam = selectedTeam; + } + + public String getEffectiveSelectedUser() { + return effectiveSelectedUser; + } + + public void setEffectiveSelectedUser(String effectiveSelectedUser) { + this.effectiveSelectedUser = effectiveSelectedUser; + } + + public String getEffectiveSelectedTeam() { + return effectiveSelectedTeam; + } + + public void setEffectiveSelectedTeam(String effectiveSelectedTeam) { + this.effectiveSelectedTeam = effectiveSelectedTeam; + } + + public Date getEffectiveDateFrom() { + return effectiveDateFrom; + } + + public void setEffectiveDateFrom(Date effectiveDateFrom) { + this.effectiveDateFrom = effectiveDateFrom; + } + + public Date getEffectiveDateTo() { + return effectiveDateTo; + } + + public void setEffectiveDateTo(Date effectiveDateTo) { + this.effectiveDateTo = effectiveDateTo; + } + + public void populateEffectiveFilters() { + effectiveSelectedUser = this.getSelectedUser() != null && !this.getSelectedUser().equals("-1") + ? this.getSelectedUser() : null; + effectiveSelectedTeam = this.getSelectedTeam() != null && !this.getSelectedTeam().equals("-1") + ? this.getSelectedTeam() : null; + if (effectiveSelectedTeam == null) { + this.setSelectedTeam(null); + } + effectiveDateFrom = DateConversion.getDate(this.getSelectedDateFrom()); + if (this.getSelectedDateTo() != null && !this.getSelectedDateTo().trim().equals("")) { + + effectiveDateTo = new DateTime(DateConversion.getDate(this.getSelectedDateTo())). + plusHours(LAST_HOUR_OF_DAY).plusMinutes(LAST_MINUTE_OF_HOUR). + plusSeconds(LAST_SECOND_OF_MINUTE).toDate(); + } else { + this.setEffectiveDateTo(null); + } + } +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/form/TeamAuditForm.java b/amp/WEB-INF/src/org/digijava/module/aim/form/TeamAuditForm.java index b72187a670e..2b3b732a5cf 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/form/TeamAuditForm.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/form/TeamAuditForm.java @@ -1,98 +1,21 @@ package org.digijava.module.aim.form; import java.io.Serializable; -import java.util.Collection; -import org.apache.struts.action.ActionForm; - -public class TeamAuditForm extends ActionForm implements Serializable{ +public class TeamAuditForm extends FilterAuditLoggerForm implements Serializable { /** - * + * */ private static final long serialVersionUID = -2614366966871314200L; - - private Collection logs; - private String sortBy; - private int pagesToShow; - private Integer currentPage; - private int pagesSize; - private Collection pages = null; - private int offset; - private String useraction; - private String frecuency; - - public String getUseraction() { - return useraction; - } - - public void setUseraction(String useraction) { - this.useraction = useraction; - } - - public String getFrecuency() { - return frecuency; - } - public void setFrecuency(String frecuency) { - this.frecuency = frecuency; - } + private String teamName; - public int getOffset() { - int value; - if (getCurrentPage()> (this.getPagesToShow()/2)){ - value = (this.getCurrentPage() - (this.getPagesToShow()/2))-1; - } - else { - value = 0; - } - setOffset(value); - return offset; + public String getTeamName() { + return teamName; } - public void setOffset(int offset) { - this.offset = offset; - } - - public Collection getPages() { - return pages; - } - public void setPages(Collection pages) { - this.pages = pages; - if(pages!=null) - { - this.pagesSize=pages.size(); - } - } - - public int getPagesToShow() { - return pagesToShow; - } - public void setPagesToShow(int pagesToShow) { - this.pagesToShow = pagesToShow; - } - public Integer getCurrentPage() { - return currentPage; - } - public void setCurrentPage(Integer currentPage) { - this.currentPage = currentPage; - } - public int getPagesSize() { - return pagesSize; - } - public void setPagesSize(int pagesSize) { - this.pagesSize = pagesSize; - } - public Collection getLogs() { - return logs; - } - public void setLogs(Collection logs) { - this.logs = logs; - } - public String getSortBy() { - return sortBy; - } - public void setSortBy(String sortBy) { - this.sortBy = sortBy; + public void setTeamName(String teamname) { + this.teamName = teamname; } -} +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/helper/Constants.java b/amp/WEB-INF/src/org/digijava/module/aim/helper/Constants.java index 24d48b42e15..9534f1a6163 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/helper/Constants.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/helper/Constants.java @@ -448,4 +448,5 @@ public static class GlobalSettings { public static final String AUTOMATIC_VALIDATION_JOB_CLASS_NAME = "org.digijava.module.message.jobs.ActivityAutomaticValidationJob" ; + public static final Integer AUDIT_LOGGER_BATCH_SIZE = 10; } diff --git a/amp/WEB-INF/src/org/digijava/module/aim/services/auditcleaner/AuditCleanerJob.java b/amp/WEB-INF/src/org/digijava/module/aim/services/auditcleaner/AuditCleanerJob.java index ce6bcf93eb5..97c73b49d38 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/services/auditcleaner/AuditCleanerJob.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/services/auditcleaner/AuditCleanerJob.java @@ -11,22 +11,26 @@ import org.quartz.JobExecutionException; /** - * + * * @author Diego Dimunzio - * + * */ public class AuditCleanerJob extends ConnectionCleaningJob { private static Logger logger = Logger.getLogger(AuditCleanerJob.class); - + /** - * + * */ @Override public void executeInternal(JobExecutionContext contex) throws JobExecutionException { String deletetime = FeaturesUtil.getGlobalSettingValue(GlobalSettingsConstants.AUTOMATIC_AUDIT_LOGGER_CLEANUP); - logger.info("Starting to delete audit logs older than " + deletetime + " days............................."); - AuditLoggerUtil.deleteLogsByPeriod(deletetime); - logger.info("Delete Audit logs finished..................................................."); + if (deletetime.equals("-1")) { + logger.info("Delete Audit Logs Option Disabled :: Please select another option"); + } else { + logger.info("Starting to delete audit logs older than " + deletetime + " days..........................."); + AuditLoggerUtil.deleteLogsByPeriod(deletetime); + logger.info("Delete Audit logs finished................................................."); + } } -} +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/util/ActivityUtil.java b/amp/WEB-INF/src/org/digijava/module/aim/util/ActivityUtil.java index 87ca27de84f..4b507b278ac 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/util/ActivityUtil.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/util/ActivityUtil.java @@ -2021,14 +2021,13 @@ public static AmpActivityVersion getPreviousVersion(AmpActivityVersion activity) Session session = PersistenceManager.getRequestDBSession(); Query qry = session.createQuery(String.format("SELECT act FROM " + AmpActivityVersion.class.getName() + " act WHERE approval_status in ( '%s','%s' ) and act.ampActivityGroup.ampActivityGroupId = ? " - + " and act.ampActivityId <> ? " + + " and act.ampActivityId < ? " + " ORDER BY act.ampActivityId DESC", Constants.APPROVED_STATUS, Constants.STARTED_APPROVED_STATUS)) .setMaxResults(1); qry.setParameter(0, activity.getAmpActivityGroup().getAmpActivityGroupId()); qry.setParameter(1, activity.getAmpActivityId()); return (qry.list().size() > 0 ? (AmpActivityVersion) qry.list().get(0) : null); } - /** * @param a * @param activityDisbursements diff --git a/amp/WEB-INF/src/org/digijava/module/aim/util/ActivityVersionUtil.java b/amp/WEB-INF/src/org/digijava/module/aim/util/ActivityVersionUtil.java index 699c85e5af7..7b326b97c9c 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/util/ActivityVersionUtil.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/util/ActivityVersionUtil.java @@ -1,40 +1,58 @@ package org.digijava.module.aim.util; - import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.sql.Timestamp; import java.text.NumberFormat; +import java.util.ArrayList; import java.util.Collection; +import java.util.Comparator; import java.util.Date; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; +import java.util.stream.Collectors; -import javax.servlet.http.HttpServletRequest; - +import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.apache.wicket.util.string.Strings; import org.digijava.kernel.exception.DgException; import org.digijava.kernel.persistence.PersistenceManager; import org.digijava.kernel.persistence.WorkerException; -import org.digijava.kernel.request.Site; +import org.digijava.kernel.request.TLSUtils; import org.digijava.kernel.translator.TranslatorWorker; -import org.digijava.kernel.util.RequestUtils; +import org.digijava.module.aim.annotations.activityversioning.CompareOutput; +import org.digijava.module.aim.annotations.activityversioning.VersionableCollection; +import org.digijava.module.aim.annotations.activityversioning.VersionableFieldSimple; +import org.digijava.module.aim.annotations.activityversioning.VersionableFieldTextEditor; import org.digijava.module.aim.dbentity.AmpActivityFields; import org.digijava.module.aim.dbentity.AmpActivityVersion; import org.digijava.module.aim.dbentity.AmpTeamMember; import org.digijava.module.aim.dbentity.Versionable; +import org.digijava.module.aim.helper.ActivityHistory; import org.digijava.module.aim.helper.DateConversion; import org.digijava.module.aim.helper.FormatHelper; import org.digijava.module.aim.helper.GlobalSettingsConstants; +import org.digijava.module.aim.util.versioning.ActivitiesToBeCompared; +import org.digijava.module.aim.util.versioning.ActivityComparisonContext; +import org.digijava.module.aim.util.versioning.ActivityComparisonResult; import org.digijava.module.aim.version.exception.CannotGetLastVersionForVersionException; +import org.digijava.module.editor.util.DbUtil; +import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.Session; +import static org.digijava.module.aim.helper.Constants.AUDIT_LOGGER_BATCH_SIZE; + public class ActivityVersionUtil { + private static final Integer AUDIT_LOGGER_ID = 4; private static Logger logger = Logger.getLogger(ActivityVersionUtil.class); @@ -70,14 +88,11 @@ public static boolean implementsVersionable(Class[] array) { return ret; } - public static String generateFormattedOutput(HttpServletRequest request, Output out) throws WorkerException { - return generateFormattedOutput(request, out, null); + public static String generateFormattedOutput(Output out, ActivityComparisonContext context) { + return generateFormattedOutput(out, null, context); } - public static String generateFormattedOutput(HttpServletRequest request, Output out, Output out1) throws WorkerException { - Site site = RequestUtils.getSite(request); - String langCode = RequestUtils.getNavigationLanguage(request).getCode(); - + public static String generateFormattedOutput(Output out, Output out1, ActivityComparisonContext context) { StringBuilder ret = new StringBuilder(); if (out.getOutputs() != null) { // First level. @@ -94,10 +109,14 @@ public static String generateFormattedOutput(HttpServletRequest request, Output existsInOtherVersion = out1.getOutputByTitle(title) != null; } if (!title.trim().isEmpty()) { - if (!existsInOtherVersion) ret.append(""); - ret.append("
").append(TranslatorWorker.translateText(auxOutput.getTitle()[i], langCode, site.getId())). - append(": "); - if (!existsInOtherVersion) ret.append("
"); + if (!existsInOtherVersion) { + ret.append(""); + } + ret.append("
").append(TranslatorWorker.translateText(auxOutput.getTitle()[i], + context.getLang(), context.getSiteId())).append(": "); + if (!existsInOtherVersion) { + ret.append("
"); + } } } for (int i = 0; i < auxOutput.getValue().length; i++) { @@ -106,15 +125,21 @@ public static String generateFormattedOutput(HttpServletRequest request, Output * date = DateConversion.ConvertDateToString((Date) * auxOutput.getValue()[i]); ret += date; } else { */ - if (auxOutput.getValue()[i]!=null){ + if (auxOutput.getValue()[i] != null) { String text = auxOutput.getValue()[i].toString(); - if (auxOutput.getTranslateValue()) - text = TranslatorWorker.translateText(text, langCode, site.getId()); - if (!existsInOtherVersion) ret.append(""); - ret.append(DbUtil.filter(text)); - if (!existsInOtherVersion) ret.append(""); + if (auxOutput.getTranslateValue()) { + text = TranslatorWorker.translateText(text, context.getLang(), context.getSiteId()); + } + if (!existsInOtherVersion) { + ret.append(""); + } + ret.append(org.digijava.module.aim.util.DbUtil.filter(text)); + + if (!existsInOtherVersion) { + ret.append(""); + } } - // } + } if (auxOutput.getOutputs() != null) { @@ -138,7 +163,8 @@ public static String generateFormattedOutput(HttpServletRequest request, Output ret.append(tabs); for (int i = 0; i < auxOutput2.getTitle().length; i++) { ret.append(""). - append(TranslatorWorker.translateText(auxOutput2.getTitle()[i], langCode, site.getId())). + append(TranslatorWorker.translateText(auxOutput2.getTitle()[i], context.getLang(), + context.getSiteId())). append(""); } for (int i = 0; i < auxOutput2.getValue().length; i++) { @@ -147,12 +173,12 @@ public static String generateFormattedOutput(HttpServletRequest request, Output markAsDifferent = true; ret.append(""); } - + if (auxOutput2.getValue()[i] instanceof Timestamp) { String date = DateConversion.convertDateToString(new Date(((Timestamp) auxOutput2.getValue()[i]).getTime())); ret.append(date); - } else if (auxOutput2.getValue()[i] instanceof BigDecimal - || auxOutput2.getValue()[i] instanceof Double + } else if (auxOutput2.getValue()[i] instanceof BigDecimal + || auxOutput2.getValue()[i] instanceof Double || auxOutput2.getValue()[i] instanceof Float) { NumberFormat formatter = FormatHelper.getDecimalFormat(); formatter.setMaximumFractionDigits(0); @@ -160,8 +186,8 @@ public static String generateFormattedOutput(HttpServletRequest request, Output } else { String text = auxOutput2.getValue()[i].toString(); if (auxOutput2.getTranslateValue()) - text = TranslatorWorker.translateText(text, langCode, site.getId()); - ret.append(DbUtil.filter(text)); + text = TranslatorWorker.translateText(text, context.getLang(), context.getSiteId()); + ret.append(org.digijava.module.aim.util.DbUtil.filter(text)); } if (markAsDifferent) ret.append(""); @@ -194,11 +220,11 @@ public static int numberOfVersions() { } return aux; } - + public static boolean isVersioningEnabled(){ return (numberOfVersions() > 0); } - + public static Long getLastVersionForVersion(Long oldActivity) throws CannotGetLastVersionForVersionException { try { Session session = PersistenceManager.getSession(); @@ -215,10 +241,11 @@ public static Long getLastVersionForVersion(Long oldActivity) throws CannotGetLa } } + /** * Create a copy of the {@link AmpActivityVersion} with all Collections linked with * it and ready to save. - * + * * @param in * @param member * @return @@ -226,9 +253,9 @@ public static Long getLastVersionForVersion(Long oldActivity) throws CannotGetLa */ public static AmpActivityVersion cloneActivity(AmpActivityVersion in, AmpTeamMember member) throws CloneNotSupportedException { AmpActivityVersion out = (AmpActivityVersion) in.clone(); - + Class clazz = AmpActivityFields.class; - + Field[] fields = clazz.getDeclaredFields();//clazz.getFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; @@ -242,7 +269,7 @@ public static AmpActivityVersion cloneActivity(AmpActivityVersion in, AmpTeamMem out.setModifiedBy(member); return out; } - + /** * for the definition of this function, please see JavaDoc for {@link #initSet(AmpActivityVersion, Field)} * @param obj @@ -255,11 +282,11 @@ private static Object prepareMerge(Object obj, AmpActivityVersion newActivity) t else return obj; } - + /** * out.field = new Set[prepareMerge(out.field.each)] * f(X) = ((Versionable) X.prepareMerge()), if X instanceof Versionable. - * f(X) = X, otherwise + * f(X) = X, otherwise * @param out * @param field */ @@ -274,7 +301,7 @@ private static void initSet(AmpActivityVersion out, Field field){ returnSet = new HashSet<>(); for(Object obj:set) returnSet.add(prepareMerge(obj, out)); - } + } if (Set.class.isAssignableFrom(field.getType())) method = clazz.getMethod("set" + setName, Set.class); else @@ -289,7 +316,7 @@ private static void initSet(AmpActivityVersion out, Field field){ /** * Initialize all collections (up to level 2) for an {@link AmpActivityVersion} * object. Use it to prevent exceptions with lazy collections. - * + * * @param act * @return * @throws DgException @@ -327,4 +354,469 @@ public static AmpActivityVersion initializeActivity(AmpActivityVersion act) thro } return act; } -} + + + public static ActivityComparisonResult compareActivities(Long activityOneId) throws Exception { + ActivityComparisonContext context = new ActivityComparisonContext(TLSUtils.getSite().getId(), + TLSUtils.getSite().getName(), TLSUtils.getEffectiveLangCode()); + + Session session = PersistenceManager.getRequestDBSession(); + AmpActivityVersion ampActivityOne = (AmpActivityVersion) session.load(AmpActivityVersion.class, activityOneId); + AmpActivityVersion ampActivityTwo = ActivityUtil.getPreviousVersion(ampActivityOne); + + return (ampActivityTwo == null) ? null + : new ActivityComparisonResult(activityOneId, ampActivityOne.getAmpId() + " " + + ampActivityOne.getName(), compareActivities(activityOneId, + ampActivityTwo.getAmpActivityId(), context)); + } + + + public static Map> compareActivities(Long activityOneId, Long activityTwoId, + ActivityComparisonContext context) + throws Exception { + Session session = PersistenceManager.getRequestDBSession(); + AmpActivityVersion ampActivityOne = (AmpActivityVersion) session.load(AmpActivityVersion.class, activityOneId); + + Hibernate.initialize(ampActivityOne); + ActivityVersionUtil.initializeActivity(ampActivityOne); + + AmpActivityVersion ampActivityTwo = (AmpActivityVersion) session.load(AmpActivityVersion.class, activityTwoId); + + Hibernate.initialize(ampActivityTwo); + ActivityVersionUtil.initializeActivity(ampActivityTwo); + + List outputCollection = new ArrayList<>(); + ActivityHistory auditHistoryOne = ActivityVersionUtil.getAuditHistory(ampActivityOne); + ActivityHistory auditHistoryTwo = ActivityVersionUtil.getAuditHistory(ampActivityTwo); + ActivitiesToBeCompared activitiesToBeCompared = new ActivitiesToBeCompared(ampActivityOne, ampActivityTwo, + auditHistoryOne, auditHistoryTwo); + // Retrieve annotated for versioning fields. + Field[] fields = AmpActivityFields.class.getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + // logger.info(fields[i]); + CompareOutput output = new CompareOutput(); + if (fields[i].isAnnotationPresent(VersionableFieldSimple.class)) { + processVersionableSimple(activitiesToBeCompared, outputCollection, fields[i], output, context); + } + if (fields[i].isAnnotationPresent(VersionableFieldTextEditor.class)) { + processVersionableTextEditor(activitiesToBeCompared, outputCollection, fields[i], output, context); + } + if (fields[i].isAnnotationPresent(VersionableCollection.class)) { + processVersionableCollection(activitiesToBeCompared, outputCollection, fields, i, output, context); + } + } + return ActivityVersionUtil.groupOutputCollection(outputCollection); + } + + private static void processVersionableCollection(ActivitiesToBeCompared activitiesToBeCompared, + List outputCollection, Field[] fields, + int i, CompareOutput output, ActivityComparisonContext context) + throws Exception { + Method auxMethod = ActivityVersionUtil.getMethodFromFieldName(fields[i].getName(), + AmpActivityVersion.class, "get"); + // Get values from 2 versions. + // Sometimes I have a problem with lazy collections and + // apparently closed session. + // Delete these lines if there are problems when saving: two + // sessions problem. + Object auxResult1 = auxMethod.invoke(activitiesToBeCompared.getActivityOne(), null); + Hibernate.initialize(auxResult1); + Object auxResult2 = auxMethod.invoke(activitiesToBeCompared.getActivityTwo(), null); + Hibernate.initialize(auxResult2); + // Obtain annotation object. + VersionableCollection auxAnnotation = fields[i].getAnnotation(VersionableCollection.class); + // Create list of differences. + List differences = new ArrayList(); + Collection auxCollection1 = (Collection) auxResult1; + Collection auxCollection2 = (Collection) auxResult2; + // Evaluate the type of objects stored in the collection. + // TODO: Assuming everything is a Collection, later to implement + // other types. + if ((auxCollection1 == null && auxCollection2 == null) + || (auxCollection1 == null && auxCollection2.size() == 0) + || (auxCollection1.size() == 0 && auxCollection2 == null) + || (auxCollection1.size() == 0 && auxCollection2.size() == 0)) { + // Collections are equal. + return; + } + Class auxReturnType = null; + if (auxCollection1 != null && auxCollection1.size() != 0) { + auxReturnType = auxCollection1.toArray()[0].getClass(); + } else { + auxReturnType = auxCollection2.toArray()[0].getClass(); + } + if (isOfSimpleType(auxReturnType)) { + // Wrappers don't have IDs then we can't detect "updates". + // Iterate each collection and show as different the values + // not present in the other. + addAsDifferentIfNnoPresent(outputCollection, fields, i, auxAnnotation, auxCollection2, + auxCollection1.iterator()); + addAsDifferentIfNnoPresent(outputCollection, fields, i, auxAnnotation, auxCollection2, + auxCollection2.iterator()); + } else if (ActivityVersionUtil.implementsVersionable(auxReturnType.getInterfaces())) { + List auxList = new ArrayList<>(); + Iterator iter1 = auxCollection1.iterator(); + while (iter1.hasNext()) { + int coincidence = 0; + Object auxObject1 = iter1.next(); + Versionable auxVersionable1 = (Versionable) auxObject1; + Iterator iter2 = auxCollection2.iterator(); + while (iter2.hasNext()) { + Object auxObject2 = iter2.next(); + Versionable auxVersionable2 = (Versionable) auxObject2; + if (auxVersionable1.equalsForVersioning(auxVersionable2)) { + coincidence++; + Object auxValue1 = auxVersionable1.getValue() != null ? auxVersionable1.getValue() : ""; + Object auxValue2 = auxVersionable2.getValue() != null ? auxVersionable2.getValue() : ""; + if (!auxValue1.equals(auxValue2)) { + CompareOutput auxOutput = null; + if (auxVersionable1.getClass().getName() + .equals("org.digijava.module.aim.dbentity.AmpFunding") + && auxVersionable2.getClass().getName() + .equals("org.digijava.module.aim.dbentity.AmpFunding")) { + auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), new String[] { + ActivityVersionUtil.generateFormattedOutput(auxVersionable1.getOutput(), + auxVersionable2.getOutput(), context), + ActivityVersionUtil.generateFormattedOutput(auxVersionable2.getOutput(), + auxVersionable1.getOutput(), context) }, fields[i], + new Object[] { auxObject1, auxObject2 }, false, + false); + } else { + String activityOneFormattedOutput = ActivityVersionUtil + .generateFormattedOutput(auxVersionable1.getOutput(), context); + String activityTwoFormattedOutput = ActivityVersionUtil.generateFormattedOutput( + auxVersionable2.getOutput(), context); + auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), + new String[]{activityOneFormattedOutput, activityTwoFormattedOutput + }, fields[i], new Object[]{auxObject1, auxObject2}, + false, false); + } + outputCollection.add(auxOutput); + auxList.add(auxVersionable1); + auxList.add(auxVersionable2); + } + } + } + if (coincidence == 0) { + CompareOutput auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), new String[] { + ActivityVersionUtil.generateFormattedOutput(auxVersionable1.getOutput(), context), "" }, + fields[i], new Object[] { auxObject1, null }, false, false); + outputCollection.add(auxOutput); + auxList.add(auxVersionable1); + } + } + iter1 = auxCollection2.iterator(); + while (iter1.hasNext()) { + int coincidence = 0; + Object auxObject2 = iter1.next(); + Versionable auxVersionable2 = (Versionable) auxObject2; + Iterator iter2 = auxCollection1.iterator(); + while (iter2.hasNext()) { + Object auxObject1 = iter2.next(); + Versionable auxVersionable1 = (Versionable) auxObject1; + if (auxVersionable2.equalsForVersioning(auxVersionable1)) { + coincidence++; + Object auxValue1 = auxVersionable1.getValue() != null ? auxVersionable1.getValue() : ""; + Object auxValue2 = auxVersionable2.getValue() != null ? auxVersionable2.getValue() : ""; + if (!auxValue2.equals(auxValue1)) { + // Check if the object was added in the + // previous iteration. + if (!auxList.contains(auxVersionable2)) { + CompareOutput auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), + new String[] { + ActivityVersionUtil + .generateFormattedOutput(auxVersionable1.getOutput(), context), + ActivityVersionUtil + .generateFormattedOutput(auxVersionable2.getOutput(), context)}, + fields[i], new Object[] { auxObject1, auxObject2 }, false, + false); + outputCollection.add(auxOutput); + } + } + } + } + if (coincidence == 0) { + // Check if the object was added in the + // previous iteration. + if (!auxList.contains(auxVersionable2)) { + CompareOutput auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), + new String[] { "", + ActivityVersionUtil + .generateFormattedOutput(auxVersionable2.getOutput(), context) }, + fields[i], new Object[] { null, auxObject2 }, false, false); + outputCollection.add(auxOutput); + } + } + } + } else { + output.setStringOutput(new String[] { auxResult1 != null ? auxResult1.toString() : "", + auxResult2 != null ? auxResult2.toString() : "" }); + output.setDescriptionOutput(auxAnnotation.fieldTitle()); + outputCollection.add(output); + } + } + + private static boolean isOfSimpleType(Class auxReturnType) { + return auxReturnType.getName().equals("java.util.Date") || auxReturnType.getName().equals("java.sql.Date") + || auxReturnType.getName().equals("java.lang.String") + || auxReturnType.getName().equals("java.lang.Double") + || auxReturnType.getName().equals("java.lang.Integer") + || auxReturnType.getName().equals("java.lang.Long") + || auxReturnType.getName().equals("java.lang.Short") + || auxReturnType.getName().equals("java.lang.Float") + || auxReturnType.getName().equals("java.lang.Boolean") + || auxReturnType.getName().equals("java.math.BigDecimal"); + } + + private static void processVersionableTextEditor(ActivitiesToBeCompared activitiesToBeCompared, + List outputCollection, Field field, + CompareOutput output, ActivityComparisonContext context) + throws Exception { + // Obtain "get" method from field. + Method auxMethod = ActivityVersionUtil.getMethodFromFieldName(field.getName(), + AmpActivityVersion.class, "get"); + // Compare values from 2 versions. + String auxResult1 = (String) auxMethod.invoke(activitiesToBeCompared.getActivityOne(), null); + String auxResult2 = (String) auxMethod.invoke(activitiesToBeCompared.getActivityTwo(), null); + // Obtain annotation object. + VersionableFieldTextEditor auxAnnotation = field.getAnnotation(VersionableFieldTextEditor.class); + // Compare values, if both are null then they are considered + // equal. + if (!(auxResult1 == null && auxResult2 == null)) { + if ((auxResult1 != null && auxResult2 == null) || (auxResult1 == null && auxResult2 != null) + || (!auxResult1.equals(auxResult2))) { + output.setFieldOutput(field); + output.setBlockSingleChangeOutput(false); + output.setMandatoryForSingleChangeOutput(false); + output.setDescriptionOutput(auxAnnotation.fieldTitle()); + String auxBody1 = DbUtil.getEditorBody(context.getSiteName(), auxResult1, context.getLang()); + String auxBody2 = DbUtil.getEditorBody(context.getSiteName(), auxResult2, context.getLang()); + auxBody1 = auxBody1 != null ? auxBody1 : ""; + auxBody2 = auxBody2 != null ? auxBody2 : ""; + if (!auxBody1.trim().equals(auxBody2.trim())) { + output.setStringOutput(new String[] { auxBody1, auxBody2 }); + output.setOriginalValueOutput(new String[] { auxResult1, auxResult2 }); + outputCollection.add(output); + } + } + } + } + + private static void processVersionableSimple(ActivitiesToBeCompared activitiesToBeCompared, + List outputCollection, Field field, + CompareOutput output, ActivityComparisonContext context) + throws Exception { + // Obtain "get" method from field. + Method auxMethod = ActivityVersionUtil.getMethodFromFieldName(field.getName(), + AmpActivityVersion.class, "get"); + // Compare values from 2 versions. + Object auxResult1 = auxMethod.invoke(activitiesToBeCompared.getActivityOne(), null); + Object auxResult2 = auxMethod.invoke(activitiesToBeCompared.getActivityTwo(), null); + // Obtain annotation object. + VersionableFieldSimple auxAnnotation = field.getAnnotation(VersionableFieldSimple.class); + // Sanitize String values. + if (auxMethod.getReturnType().getName().equals("java.lang.String")) { + if (auxResult1 != null && auxResult1.toString().trim().equals("")) { + auxResult1 = null; + } + if (auxResult2 != null && auxResult2.toString().trim().equals("")) { + auxResult2 = null; + } + } + // AMP-25074 - retrieve information about who and when modified the activity + // from amp_audit_logger (if it is empty in the activity object) + if (StringUtils.equals(field.getName(), "modifiedBy")) { + auxResult1 = ActivityUtil.getModifiedByUserName(activitiesToBeCompared.getActivityOne(), + activitiesToBeCompared.getAuditHistoryOne()); + auxResult2 = ActivityUtil.getModifiedByUserName(activitiesToBeCompared.getActivityTwo(), + activitiesToBeCompared.getAuditHistoryTwo()); + } else if (StringUtils.equals(field.getName(), "updatedDate")) { + auxResult1 = ActivityUtil.getModifiedByDate(activitiesToBeCompared.getActivityOne(), + activitiesToBeCompared.getAuditHistoryOne()); + auxResult2 = ActivityUtil.getModifiedByDate(activitiesToBeCompared.getActivityTwo(), + activitiesToBeCompared.getAuditHistoryTwo()); + } + // Compare values, if both are null then they are considered equal. + if (!(auxResult1 == null && auxResult2 == null)) { + if ((auxResult1 != null && auxResult2 == null) || (auxResult1 == null && auxResult2 != null) + || (!auxResult1.equals(auxResult2))) { + logger.warn(field.getName() + ": " + auxResult1 + "-" + auxResult2); + output.setDescriptionOutput(auxAnnotation.fieldTitle()); + output.setFieldOutput(field); + // Identity "read-value" and "mandatory" fields. + // TODO: If needed do the same for + // @VersionableFieldTextEditor and + // @VersionableCollection. + output.setBlockSingleChangeOutput(auxAnnotation.blockSingleChange()); + output.setMandatoryForSingleChangeOutput(auxAnnotation.mandatoryForSingleChange()); + // Differentiate Wrappers from Classes that implements Versionable. + Class auxReturnType = auxMethod.getReturnType(); + if (isOfSimpleType(auxReturnType)) { + String aux1String = ActivityVersionUtil.getStringOrEmpty(auxResult1); + String aux2String = ActivityVersionUtil.getStringOrEmpty(auxResult2); + output.setStringOutput(new String[] { aux1String, aux2String }); + output.setOriginalValueOutput(new Object[] { auxResult1, auxResult2 }); + } else if (ActivityVersionUtil.implementsVersionable(auxReturnType.getInterfaces())) { + Versionable auxVersionable1 = Versionable.class + .cast(auxMethod.invoke(activitiesToBeCompared.getActivityOne(), null)); + Versionable auxVersionable2 = Versionable.class + .cast(auxMethod.invoke(activitiesToBeCompared.getActivityTwo(), null)); + String output1 = (auxVersionable1 != null) + ? ActivityVersionUtil.generateFormattedOutput(auxVersionable1.getOutput(), context) + : null; + String output2 = (auxVersionable2 != null) + ? ActivityVersionUtil.generateFormattedOutput(auxVersionable2.getOutput(), context) + : null; + output.setStringOutput(new String[] { output1, output2 }); + output.setOriginalValueOutput(new Object[] { auxResult1, auxResult2 }); + } else { + if ("modifiedBy".equals(field.getName())) { + // this field cannot be used in merging + output.setBlockSingleChangeOutput(true); + } + output.setStringOutput( + new String[] { getStringOrEmpty(auxResult1), getStringOrEmpty(auxResult2) }); + output.setOriginalValueOutput(new Object[] { auxResult1, auxResult2 }); + } + outputCollection.add(output); + } + } + } + + public static List getOutputCollectionGrouped(String editorName, String team, + Date fromDate, Date toDate) { + List activitiesFromAuditLogger; + List activityComparisonResults = new ArrayList<>(); + + + activitiesFromAuditLogger = AuditLoggerUtil. + getListOfActivitiesFromAuditLogger(editorName, team, fromDate, toDate); + + for (int startIndex = 0; startIndex < activitiesFromAuditLogger.size(); startIndex += AUDIT_LOGGER_BATCH_SIZE) { + + int endIndex = Math.min(activitiesFromAuditLogger.size(), startIndex + AUDIT_LOGGER_BATCH_SIZE); + + List activityComparisonResultsSubList = activitiesFromAuditLogger.subList(startIndex, endIndex); + + ActivityComparisonContext context = new ActivityComparisonContext(TLSUtils.getSite().getId(), + TLSUtils.getSite().getSiteId(), TLSUtils.getEffectiveLangCode()); + + List> projectsToBePosted = + activityComparisonResultsSubList.stream() + .map(activityObj -> processComparison(activityObj, context)).collect(Collectors.toList()); + + List result = + projectsToBePosted.stream() + .map(CompletableFuture::join) + .collect(Collectors.toList()); + + activityComparisonResults.addAll(result); + } + + activityComparisonResults.sort(new Comparator() { + + @Override + public int compare(ActivityComparisonResult o1, ActivityComparisonResult o2) { + return o1.getAmpAuditLoggerId().compareTo(o2.getAmpAuditLoggerId()); + } + }); + + return activityComparisonResults; + + } + public static CompletableFuture processComparison(Object[] activityObject, + ActivityComparisonContext context) { + + CompletableFuture futureComparisonResult = + CompletableFuture.supplyAsync(new Supplier() { + //TODO this can be replaced with a lambda expresion leaving the full for clarify + //TODO before finishing the whole task we can replace with Lambda + @Override + public ActivityComparisonResult get() { + Long currentActivityId = Long.valueOf(activityObject[0].toString()); + Long previousActivityId = Long.valueOf(activityObject[1].toString()); + String name = activityObject[2].toString(); + Long auditLoggerId = Long.valueOf(activityObject[AUDIT_LOGGER_ID].toString()); + Map> compareOutput = null; + try { + compareOutput = compareActivities(currentActivityId, previousActivityId, context); + } catch (Exception e) { + //TODO PROPERLY NOTIFY AN ERROR AND DO NOT SWALLOW EXCEPTIONS + e.printStackTrace(); + PersistenceManager.rollbackCurrentSessionTx(); + } finally { + PersistenceManager.endSessionLifecycle(); + } + return new ActivityComparisonResult(currentActivityId, compareOutput, name, auditLoggerId); + } + }); + return futureComparisonResult; + } + + + + + + private static void addAsDifferentIfNnoPresent(List outputCollection, Field[] fields, int i, + VersionableCollection auxAnnotation, Collection auxCollection2, + Iterator iter1) { + while (iter1.hasNext()) { + int coincidence = 0; + Object auxObject1 = iter1.next(); + String auxValue1 = auxObject1.toString(); + Iterator iter2 = auxCollection2.iterator(); + while (iter2.hasNext()) { + if (auxValue1.equals((String) iter2.next())) { + coincidence++; + } + } + if (coincidence == 0) { + CompareOutput auxOutput = new CompareOutput(auxAnnotation.fieldTitle(), new String[]{ + auxValue1, ""}, fields[i], new Object[]{auxObject1, null}, false, false); + outputCollection.add(auxOutput); + } + } + } + + private static ActivityHistory getAuditHistory(AmpActivityVersion activity) { + ActivityHistory auditHistory = null; + if (activity.getModifiedBy() == null + || (activity.getUpdatedDate() == null && activity.getModifiedDate() == null)) { + auditHistory = ActivityUtil.getModifiedByInfoFromAuditLogger(activity.getAmpActivityId()); + } + return auditHistory; + } + private static String getStringOrEmpty(Object o) { + if (o != null) { + if (o instanceof Date || o instanceof java.sql.Date) { + return FormatHelper.formatDate((Date) o); + } + return o.toString(); + } + return ""; + } + private static Map> groupOutputCollection(List outputCollection) { + Map> retVal = new HashMap>(); + int idx = 0; + for (CompareOutput obj : outputCollection) { + if (!obj.getBlockSingleChangeOutput()) { + obj.setIndex(idx); + idx++; + } else { + obj.setIndex(-1); // skip from merge process + } + if (!retVal.containsKey(obj.getDescriptionOutput())) { + retVal.put(obj.getDescriptionOutput(), new ArrayList<>()); + } + retVal.get(obj.getDescriptionOutput()).add(obj); + } + return retVal; + } + //TODO this code is dupe from xls we should merge them once we merge the code + public static String sanitizeHtmlForExport(String stringToFormat) { + String newValue = stringToFormat.toString().replaceAll("\\<.*?>", ""); + String newValues = newValue.replaceAll(" ", "\n"); + String newVal = newValues.replaceAll("
", ""); + return newVal; + } +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/util/AuditLoggerUtil.java b/amp/WEB-INF/src/org/digijava/module/aim/util/AuditLoggerUtil.java index d2b4213da92..25e282b6c9e 100644 --- a/amp/WEB-INF/src/org/digijava/module/aim/util/AuditLoggerUtil.java +++ b/amp/WEB-INF/src/org/digijava/module/aim/util/AuditLoggerUtil.java @@ -22,7 +22,6 @@ import org.apache.log4j.Logger; import org.digijava.kernel.exception.DgException; import org.digijava.kernel.persistence.PersistenceManager; -import org.digijava.kernel.persistence.WorkerException; import org.digijava.kernel.translator.TranslatorWorker; import org.digijava.kernel.user.User; import org.digijava.module.aim.dbentity.AmpActivityVersion; @@ -31,42 +30,44 @@ import org.digijava.module.aim.helper.TeamMember; import org.hibernate.HibernateException; import org.hibernate.Query; +import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.type.DateType; import org.hibernate.type.StringType; +import org.hibernate.type.TimestampType; + /** * ActivityUtil is the persister class for all activity related * entities * * @author Priyajith */ -public class AuditLoggerUtil { +public final class AuditLoggerUtil { + private static String query; private static Logger logger = Logger.getLogger(AuditLoggerUtil.class); - //can't we get session from request? why passing it as parameter? + private static final Integer DAYS_IN_YEAR = 365; + private AuditLoggerUtil() { + + } public static void logObject(HttpServletRequest request, - LoggerIdentifiable o, String action,String additionalDetails) throws DgException { + LoggerIdentifiable o, String action, String additionalDetails) throws DgException { - Session session = null; - Transaction tx = null; - HttpSession hsession=request.getSession(); - TeamMember tm = (TeamMember) hsession.getAttribute(Constants.CURRENT_MEMBER); - String objId; - objId = o.getIdentifier().toString(); + Session session; + TeamMember tm = (TeamMember) request.getSession().getAttribute(Constants.CURRENT_MEMBER); + String objId = o.getIdentifier().toString(); String objType = (String) o.getObjectType(); String browser=request.getHeader("user-agent"); try { session = PersistenceManager.getRequestDBSession(); - -//beginTransaction(); AmpAuditLogger aal = new AmpAuditLogger(); long time = System.currentTimeMillis(); Timestamp ts = new Timestamp(time); if ("update".compareTo(action) == 0) { Collection col = getAudits(session, objId, objType); if (col != null && col.size() == 1) { - AmpAuditLogger existentLoggerObj = (AmpAuditLogger) col.iterator().next(); + AmpAuditLogger existentLoggerObj = col.iterator().next(); aal.setAuthorEmail(existentLoggerObj.getAuthorEmail()); aal.setAuthorName(existentLoggerObj.getAuthorName()); aal.setLoggedDate(existentLoggerObj.getLoggedDate()); @@ -77,53 +78,41 @@ public static void logObject(HttpServletRequest request, aal.setLoggedDate(ts); } - aal.setEditorEmail(tm.getEmail()); aal.setEditorName(tm.getMemberName()); aal.setAction(action); aal.setModifyDate(ts); aal.setBrowser(browser); aal.setIp(request.getRemoteAddr()); - aal.setObjectId((String) o.getIdentifier().toString()); + aal.setObjectId(o.getIdentifier().toString()); aal.setObjectType((String) o.getObjectType()); aal.setTeamName(tm.getTeamName()); aal.setObjectName(o.getObjectName()); aal.setDetail(additionalDetails); - + session.save(aal); - //tx.commit(); } catch (Exception ex) { - ex.printStackTrace(); - logger.error("Cannot save audit logger :", ex); -// if (tx!=null){ -// try { -// tx.rollback(); -// } catch (Exception e1) { -// logger.error("Release session failed :", e1); -// throw new DgException("Cannot rallback",e1); -// } -// } throw new DgException("Cannot save audit logger",ex); - } + } return; } - - - public static void logObject(HttpSession hsession,HttpServletRequest request, - LoggerIdentifiable o, String action) throws DgException { - logObject(request,o, action,null); + + + public static void logObject(HttpSession hsession, HttpServletRequest request, + LoggerIdentifiable o, String action) throws DgException { + logObject(request, o, action, null); } private static Collection getAudits(Session session, - String objId, String objType) { + String objId, String objType) { String qryStr; Query qry; try { String addAction = "add"; qryStr = "select f from " - + AmpAuditLogger.class.getName() - + " f where f.objectType=:objectType and f.action=:actionObj and f.objectId=:objectId "; + + AmpAuditLogger.class.getName() + + " f where f.objectType=:objectType and f.action=:actionObj and f.objectId=:objectId "; qry = session.createQuery(qryStr); qry.setParameter("objectType", objType.toString(), StringType.INSTANCE); @@ -137,8 +126,8 @@ private static Collection getAudits(Session session, } return null; } - - public static void logUserLogin(HttpServletRequest request,User currentUser,String action){ + + public static void logUserLogin(HttpServletRequest request, User currentUser, String action) { Session session = null; Transaction tx = null; HttpSession hsession = request.getSession(); @@ -164,18 +153,17 @@ public static void logUserLogin(HttpServletRequest request,User currentUser,Stri aal.setTeamName(""); aal.setObjectName(Constants.LOGIN_ACTION); aal.setDetail(""); - + session.save(aal); }catch (Exception ex) { ex.printStackTrace(); logger.error("Cannot save audit logger :", ex); - } + } } - - public static void logSentReminderEmails(Session session,User user){ + + public static void logSentReminderEmails(Session session, User user) { try { -//beginTransaction(); AmpAuditLogger aal = new AmpAuditLogger(); long time = System.currentTimeMillis(); Timestamp ts = new Timestamp(time); @@ -193,27 +181,28 @@ public static void logSentReminderEmails(Session session,User user){ aal.setTeamName(""); aal.setObjectName(""); aal.setDetail(Constants.SENT_REMINDER); - + session.save(aal); }catch (Exception ex) { - ex.printStackTrace(); logger.error("Cannot save audit logger :", ex); - } + } } - - public static void logActivityUpdate(HttpServletRequest request, AmpActivityVersion activity, List details){ + + public static void logActivityUpdate(HttpServletRequest request, AmpActivityVersion activity, + List details) { logActivityUpdate(request, activity, details, null); } /** - * This method was changed to simulate an update that happened in the past. Will be removed once donorscore card testing is done - * @deprecated Do not use this method use {@link AuditLoggerUtil.logActivityUpdate(HttpServletRequest request, AmpActivityVersion activity, List details)} + * This method was changed to simulate an update that happened in the past. Will be removed once donorscore + * card testing is done + * @deprecated Do not use this method use AuditLoggerUtil.logActivityUpdate(HttpServletRequest request, + * AmpActivityVersion activity, List details) * @param request * @param activity * @param details */ public static void logActivityUpdate(HttpServletRequest request, AmpActivityVersion activity, List details, Date dateUpdated){ Session session = null; - Transaction tx = null; HttpSession hsession = request.getSession(); TeamMember tm = (TeamMember) hsession.getAttribute(Constants.CURRENT_MEMBER); String objId; @@ -223,8 +212,6 @@ public static void logActivityUpdate(HttpServletRequest request, AmpActivityVers try { session = PersistenceManager.getSession(); -//beginTransaction(); - long time = System.currentTimeMillis(); Timestamp ts; if(dateUpdated!=null){ @@ -233,56 +220,112 @@ public static void logActivityUpdate(HttpServletRequest request, AmpActivityVers }else{ ts= new Timestamp(time); } - - StringBuilder message=new StringBuilder(); + AmpAuditLogger existentLoggerObj = null; + + Collection col = getAudits(session, objId, objType); + if (col != null && col.size() == 1) { + existentLoggerObj = (AmpAuditLogger) col + .iterator().next(); + } + + StringBuilder message = new StringBuilder(); for(String detail:details){ message.append(detail+" "); } - AmpAuditLogger aal = new AmpAuditLogger(); - aal.setAuthorEmail(activity.getActivityCreator().getUser().getEmail()); - aal.setAuthorName(activity.getActivityCreator().getUser().getName()); - aal.setLoggedDate(new Timestamp(activity.getCreatedDate().getTime())); - aal.setUserid(DbUtil.getUser(tm.getEmail()).getId()); - aal.setEditorEmail(tm.getEmail()); - aal.setEditorName(tm.getMemberName()); - aal.setAction("update"); - aal.setModifyDate(ts); - aal.setBrowser(browser); - aal.setIp(request.getRemoteAddr()); - aal.setObjectId((String) activity.getIdentifier().toString()); - aal.setObjectType((String) activity.getObjectType()); - aal.setTeamName(tm.getTeamName()); - aal.setObjectName(activity.getObjectName()); - aal.setDetail(message.toString()); - session.save(aal); - - - //tx.commit(); + AmpAuditLogger aal = new AmpAuditLogger(); + if (existentLoggerObj != null) { + aal.setAuthorEmail(existentLoggerObj.getAuthorEmail()); + aal.setAuthorName(existentLoggerObj.getAuthorName()); + aal.setLoggedDate(existentLoggerObj.getLoggedDate()); + } else { + aal.setAuthorName(tm.getMemberName()); + aal.setAuthorEmail(tm.getEmail()); + aal.setLoggedDate(ts); + } + aal.setUserid(DbUtil.getUser(tm.getEmail()).getId()); + aal.setEditorEmail(tm.getEmail()); + aal.setEditorName(tm.getMemberName()); + aal.setAction("update"); + aal.setModifyDate(ts); + aal.setBrowser(browser); + aal.setIp(request.getRemoteAddr()); + aal.setObjectId((String) activity.getIdentifier().toString()); + aal.setObjectType((String) activity.getObjectType()); + aal.setTeamName(tm.getTeamName()); + aal.setObjectName(activity.getObjectName()); + aal.setDetail(message.toString()); + session.save(aal); } catch (Exception ex) { logger.error("Exception : ", ex); } } - + /** * @author dan */ - public static Collection getLogObjects(boolean withLogin) { + public static Collection getLogObjects(boolean withLogin, String editorName, String teamToFilter, + Date dateFrom, Date dateTo) { try { - String qryStr = null; - if (!withLogin){ - qryStr = "select f from " + AmpAuditLogger.class.getName() + " f where action<>'" - + Constants.LOGIN_ACTION + "' order by modifyDate desc"; - } else { - qryStr = "select f from " + AmpAuditLogger.class.getName() + " f order by modifyDate desc"; + StringBuffer qryStr = new StringBuffer(); + //TODO this comments will be removed + //I added 1 = 1 in order to be able to concat the ands with out thinking if i added a condidtion before + List filters = new ArrayList(); + + qryStr.append("select f from " + AmpAuditLogger.class.getName() + " f where 1 = 1 "); + + if (!withLogin) { + filters.add(new HibernateFilterParam("action", null, Constants.LOGIN_ACTION, + StringType.INSTANCE, "<>")); + + } + if (editorName != null) { + filters.add(new HibernateFilterParam("editorName", null, editorName, + StringType.INSTANCE)); } - return PersistenceManager.getSession().createQuery(qryStr).list(); + if (teamToFilter != null) { + filters.add(new HibernateFilterParam("teamname", null, teamToFilter, + StringType.INSTANCE)); + } + if (dateFrom != null) { + filters.add(new HibernateFilterParam("modifyDate", "modifyDateFrom", + dateFrom, TimestampType.INSTANCE, ">=")); + } + if (dateTo != null) { + filters.add(new HibernateFilterParam("modifyDate", "modifyDateTo", + dateTo, TimestampType.INSTANCE, "<=")); + } + + HibernateFilterParam.getQueryStringFromFilterParam(filters, qryStr); + Query auditLoggerQuery = PersistenceManager.getSession().createQuery(qryStr.toString() + + " order by loggedDate desc"); + HibernateFilterParam.setQueryParams(filters, auditLoggerQuery); + + return auditLoggerQuery.list(); } catch (Exception ex) { throw new RuntimeException(ex); } } - + public static List getTeamFromLog() { + String query = "select distinct teamname from amp_audit_logger " + + "where teamname <> '' " + + "order by teamname asc"; + return getStringsFromQuery(query); + } + public static List getEditorNameFromLog() { + String query = "select distinct editorname from amp_audit_logger " + + "where editorname <> '' " + + "order by editorname asc"; + return getStringsFromQuery(query); + } + + private static List getStringsFromQuery(String query) { + Session session = PersistenceManager.getSession(); + SQLQuery sqlQuery = session.createSQLQuery(query); + return sqlQuery.list(); + } + /** - * + * * @return */ public static Collection getTeamLogObjects(String teamname) { @@ -290,14 +333,14 @@ public static Collection getTeamLogObjects(String teamname) { Collection col = new ArrayList(); String qryStr = null; Query qry = null; - + try { session = PersistenceManager.getSession(); - qryStr = "select f from " - + AmpAuditLogger.class.getName() - + " f where f.teamName=:teamname"; + qryStr = "select f from " + + AmpAuditLogger.class.getName() + + " f where f.teamName=:teamname"; qry = session.createQuery(qryStr); - qry.setString("teamname", teamname); + qry.setString("teamname", teamname); col = qry.list(); } catch (Exception ex) { logger.error("Exception : " + ex.getMessage()); @@ -335,10 +378,10 @@ public static List getActivityLogObjects(String activityId) { List col = new ArrayList(); String qryStr = null; Query qry = null; - + try { session = PersistenceManager.getSession(); - + qryStr = "select f from " + AmpAuditLogger.class.getName() + " f where f.objectType=:objectType and f.objectId=:objectId order by f.modifyDate desc"; @@ -353,7 +396,7 @@ public static List getActivityLogObjects(String activityId) { } public static List generateLogs(AmpActivityVersion activity, - Long activityId) { + Long activityId) { List auditTrail = new ArrayList(); Session session = null; try { @@ -372,8 +415,8 @@ public static List generateLogs(AmpActivityVersion activity, } return auditTrail; - } - + } + private static Date getDateRange(int interval) { GregorianCalendar cal = new GregorianCalendar(); cal.add(Calendar.DATE, -interval); @@ -390,12 +433,12 @@ public static Collection getLogByPeriod(int interval) { Collection col = new ArrayList(); String qryStr = null; Query qry = null; - + try { session = PersistenceManager.getSession(); - qryStr = "select f from " + - AmpAuditLogger.class.getName() - + " f where f.modifyDate >= :dateParam order by loggedDate desc"; + qryStr = "select f from " + + AmpAuditLogger.class.getName() + + " f where f.modifyDate >= :dateParam order by loggedDate desc"; qry = session.createQuery(qryStr); qry.setParameter("dateParam",getDateRange(interval),DateType.INSTANCE); col = qry.list(); @@ -404,13 +447,13 @@ public static Collection getLogByPeriod(int interval) { } return col; } - - + + /** * @author Diego Dimunzio * Delete all records whose date is less than the interval * @param interval - */ + */ public static void deleteLogsByPeriod(String interval) { try { String qryStr = "delete from " + AmpAuditLogger.class.getName() @@ -424,7 +467,63 @@ public static void deleteLogsByPeriod(String interval) { throw new RuntimeException(e); } } - + + public static List getListOfActivitiesFromAuditLogger(String editorName, String team, Date fromDate, + Date toDate) { + SQLQuery sqlQuery; + Session session = PersistenceManager.getSession(); + + StringBuffer query = new StringBuffer(); + query.append("select * from ( "); + query.append(" select aav.amp_activity_id current_id , "); + query.append(" lead(aav.amp_activity_id, 1) "); + query.append(" over(partition by aav.amp_activity_group_id order by aav.amp_activity_id desc) previous_id, "); + query.append(" aal.objectname, aav.amp_activity_group_id, "); + query.append(" aal.id from amp_activity_version aav "); + query.append(" left join amp_audit_logger aal on "); + query.append(" (aal.objecttype ='org.digijava.module.aim.dbentity.AmpActivityVersion' "); + query.append(" and cast (aal.objectId AS INTEGER) = aav.amp_activity_id"); + query.append(" and aal.modifyDate > :yearToDate"); + //query.append(" AND modifydate > :year) "); + if (editorName != null) { + query.append(" and aal.editorName=:editorName "); + } + if (fromDate != null) { + query.append(" and modifydate>:fromDate "); + } + if (toDate != null) { + query.append(" and modifydate<:toDate "); + + } + if (team != null) { + query.append(" and aal.teamname=:team "); + } + query.append(" and trim(aal.detail) ='approved') "); + query.append(" and aav.approval_status in ('approved','startedapproved') "); + query.append(" order by amp_activity_group_id desc "); + query.append(" ) t where t.id is not null"); + query.append(" and t.previous_id is not null"); + + sqlQuery = session.createSQLQuery(query.toString()); + sqlQuery.setParameter("yearToDate", getDateRange(DAYS_IN_YEAR)); + if (editorName != null) { + sqlQuery.setParameter("editorName", editorName); + } + if (fromDate != null) { + sqlQuery.setParameter("fromDate", fromDate); + } + if (toDate != null) { + sqlQuery.setParameter("toDate", toDate); + } + if (team != null) { + sqlQuery.setParameter("team", team); + } + + + return sqlQuery.list(); + } + + /** * This class is used for sorting by name. * @author Diego Dimunzio @@ -445,12 +544,12 @@ public HelperAuditloggerNameComparator(String iso) { public int compare(AmpAuditLogger o1, AmpAuditLogger o2) { collator = Collator.getInstance(locale); collator.setStrength(Collator.TERTIARY); - + int result = (o1.getObjectName()==null || o2.getObjectName()==null)?0:collator.compare(o1.getObjectName().toLowerCase(), o2.getObjectName().toLowerCase()); return result; } } - + /** * This class is used for sorting by Object type. * @author Diego Dimunzio @@ -471,12 +570,12 @@ public HelperAuditloggerTypeComparator(String iso) { public int compare(AmpAuditLogger o1, AmpAuditLogger o2) { collator = Collator.getInstance(locale); collator.setStrength(Collator.TERTIARY); - + int result = (o1.getObjectTypeTrimmed()==null || o2.getObjectName()==null)?0:collator.compare(o1.getObjectTypeTrimmed().toLowerCase(), o2.getObjectTypeTrimmed().toLowerCase()); return result; } } - + /** * This class is used for sorting by Team Name. * @author Diego Dimunzio @@ -497,12 +596,12 @@ public HelperAuditloggerTeamComparator(String iso) { public int compare(AmpAuditLogger o1, AmpAuditLogger o2) { collator = Collator.getInstance(locale); collator.setStrength(Collator.TERTIARY); - + int result = (o1.getTeamName()==null || o2.getTeamName()==null)?0:collator.compare(o1.getTeamName().toLowerCase(), o2.getTeamName().toLowerCase()); return result; } } - + /** * This class is used for sorting by Author Name. * @author Diego Dimunzio @@ -523,12 +622,12 @@ public HelperAuditloggerAuthorComparator(String iso) { public int compare(AmpAuditLogger o1, AmpAuditLogger o2) { collator = Collator.getInstance(locale); collator.setStrength(Collator.TERTIARY); - + int result = (o1.getAuthorName()==null || o2.getAuthorName()==null)?0:collator.compare(o1.getAuthorName().toLowerCase(), o2.getAuthorName().toLowerCase()); return result; } } - + /** * This class is used for sorting by Creation Date. * @author Diego Dimunzio @@ -540,19 +639,19 @@ public int compare(AmpAuditLogger o1, AmpAuditLogger o2) { return result; } } - + /** * This class is used for sorting by Change Date. * @author Diego Dimunzio * */ public static class HelperAuditloggerChangeDateComparator implements Comparator { - public int compare(AmpAuditLogger o1, AmpAuditLogger o2) { + public int compare(AmpAuditLogger o1, AmpAuditLogger o2) { int result = (o1.getModifyDate()==null || o2.getModifyDate()==null)?0:o1.getModifyDate().compareTo(o2.getModifyDate()); return result; } } - + /** * This class is used for sorting by Editor Name. * @author Diego Dimunzio @@ -573,7 +672,7 @@ public HelperAuditloggerEditorNameComparator(String iso) { public int compare(AmpAuditLogger o1, AmpAuditLogger o2) { collator = Collator.getInstance(locale); collator.setStrength(Collator.TERTIARY); - + int result = (o1.getEditorName()==null || o2.getEditorName()==null)?0:collator.compare(o1.getEditorName(), o2.getEditorName()); return result; } @@ -598,7 +697,7 @@ public HelperAuditloggerActionComparator(String iso) { public int compare(AmpAuditLogger o1, AmpAuditLogger o2) { collator = Collator.getInstance(locale); collator.setStrength(Collator.TERTIARY); - + int result = (o1.getAction()==null || o2.getAction()==null)?0:collator.compare(o1.getAction(), o2.getAction()); return result; } @@ -634,4 +733,23 @@ public int compare(AmpAuditLogger o1, AmpAuditLogger o2) { return result; } } -} + + public static boolean checkPermission(HttpServletRequest request) { + boolean permitted = false; + HttpSession session = request.getSession(); + if (session.getAttribute("ampAdmin") != null) { + String key = (String) session.getAttribute("ampAdmin"); + if (key.equalsIgnoreCase("yes")) { + permitted = true; + } else { + if (session.getAttribute("teamLeadFlag") != null) { + key = (String) session.getAttribute("teamLeadFlag"); + if (key.equalsIgnoreCase("true")) { + permitted = true; + } + } + } + } + return permitted; + } +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/util/HibernateFilterParam.java b/amp/WEB-INF/src/org/digijava/module/aim/util/HibernateFilterParam.java new file mode 100644 index 00000000000..c22619068c6 --- /dev/null +++ b/amp/WEB-INF/src/org/digijava/module/aim/util/HibernateFilterParam.java @@ -0,0 +1,92 @@ +package org.digijava.module.aim.util; + +import org.hibernate.Query; +import org.hibernate.type.AbstractSingleColumnStandardBasicType; + +import java.util.List; + +/** + * Class to generalize setting values for hibernate filters + * if FilterName is null the same as fieldName will be used + */ +public class HibernateFilterParam { + private String fieldName; + private String filterName; + private Object value; + private AbstractSingleColumnStandardBasicType hibernateType; + private String operator; + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public String getFilterName() { + return filterName; + } + + public void setFilterName(String filterName) { + this.filterName = filterName; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + public AbstractSingleColumnStandardBasicType getHibernateType() { + return hibernateType; + } + + public void setHibernateType(AbstractSingleColumnStandardBasicType hibernateType) { + this.hibernateType = hibernateType; + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + public HibernateFilterParam(String fieldName, String filterName, Object value, + AbstractSingleColumnStandardBasicType hibernateType) { + this(fieldName, filterName, value, hibernateType, "="); + } + + public HibernateFilterParam(String fieldName, String filterName, Object value, + AbstractSingleColumnStandardBasicType hibernateType, String operator) { + this.fieldName = fieldName; + this.filterName = filterName; + this.value = value; + this.hibernateType = hibernateType; + this.operator = operator; + + } + + private static String getFilterName(HibernateFilterParam filterParam) { + return filterParam.getFilterName() != null ? filterParam.getFilterName() + : filterParam.getFieldName(); + } + + public static void getQueryStringFromFilterParam(List paramList, StringBuffer hqlQuery) { + paramList.forEach(filterParam -> { + String filterName = getFilterName(filterParam); + hqlQuery.append(" and " + filterParam.getFieldName() + " " + filterParam.getOperator() + ":" + filterName); + }); + } + + public static void setQueryParams(List paramList, Query query) { + paramList.forEach(filterParam -> { + String filterName = getFilterName(filterParam); + query.setParameter(filterName, filterParam.getValue(), filterParam.getHibernateType()); + }); + } +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/util/versioning/ActivitiesToBeCompared.java b/amp/WEB-INF/src/org/digijava/module/aim/util/versioning/ActivitiesToBeCompared.java new file mode 100644 index 00000000000..8841eaa8951 --- /dev/null +++ b/amp/WEB-INF/src/org/digijava/module/aim/util/versioning/ActivitiesToBeCompared.java @@ -0,0 +1,51 @@ +package org.digijava.module.aim.util.versioning; + +import org.digijava.module.aim.dbentity.AmpActivityVersion; +import org.digijava.module.aim.helper.ActivityHistory; + +public class ActivitiesToBeCompared { + private AmpActivityVersion activityOne; + private AmpActivityVersion activityTwo; + private ActivityHistory auditHistoryOne; + private ActivityHistory auditHistoryTwo; + + public ActivitiesToBeCompared(AmpActivityVersion activityOne, AmpActivityVersion activityTwo, + ActivityHistory auditHistoryOne, ActivityHistory auditHistoryTwo) { + this.activityOne = activityOne; + this.activityTwo = activityTwo; + this.auditHistoryOne = auditHistoryOne; + this.auditHistoryTwo = auditHistoryTwo; + } + + public AmpActivityVersion getActivityOne() { + return activityOne; + } + + public void setActivityOne(AmpActivityVersion activityOne) { + this.activityOne = activityOne; + } + + public AmpActivityVersion getActivityTwo() { + return activityTwo; + } + + public void setActivityTwo(AmpActivityVersion activityTwo) { + this.activityTwo = activityTwo; + } + + public ActivityHistory getAuditHistoryOne() { + return auditHistoryOne; + } + + public void setAuditHistoryOne(ActivityHistory auditHistoryOne) { + this.auditHistoryOne = auditHistoryOne; + } + + public ActivityHistory getAuditHistoryTwo() { + return auditHistoryTwo; + } + + public void setAuditHistoryTwo(ActivityHistory auditHistoryTwo) { + this.auditHistoryTwo = auditHistoryTwo; + } +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/util/versioning/ActivityComparisonContext.java b/amp/WEB-INF/src/org/digijava/module/aim/util/versioning/ActivityComparisonContext.java new file mode 100644 index 00000000000..b722a57fca7 --- /dev/null +++ b/amp/WEB-INF/src/org/digijava/module/aim/util/versioning/ActivityComparisonContext.java @@ -0,0 +1,37 @@ +package org.digijava.module.aim.util.versioning; + +public class ActivityComparisonContext { + + private String siteName; + private String lang; + private Long siteId; + + public ActivityComparisonContext(Long siteId, String siteName, String lang) { + this.siteId = siteId; + this.siteName = siteName; + this.lang = lang; + } + public Long getSiteId() { + return siteId; + } + + public void setSiteId(Long siteId) { + this.siteId = siteId; + } + + public String getSiteName() { + return siteName; + } + + public void setSiteName(String siteName) { + this.siteName = siteName; + } + + public String getLang() { + return lang; + } + + public void setLang(String lang) { + this.lang = lang; + } +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/aim/util/versioning/ActivityComparisonResult.java b/amp/WEB-INF/src/org/digijava/module/aim/util/versioning/ActivityComparisonResult.java new file mode 100644 index 00000000000..bd50e740f8b --- /dev/null +++ b/amp/WEB-INF/src/org/digijava/module/aim/util/versioning/ActivityComparisonResult.java @@ -0,0 +1,58 @@ +package org.digijava.module.aim.util.versioning; + +import org.digijava.module.aim.annotations.activityversioning.CompareOutput; + +import java.util.List; +import java.util.Map; + +public class ActivityComparisonResult { + + private Long activityId; + private String name; + private Long ampAuditLoggerId; + private Map> compareOutput; + + public ActivityComparisonResult(Long activityId, String name, Map> compareOutput) { + this.activityId = activityId; + this.name = name; + this.compareOutput = compareOutput; + } + + public ActivityComparisonResult(Long activityId, Map> compareOutput, String name, + Long ampAuditLoggerId) { + this(activityId, name, compareOutput); + this.ampAuditLoggerId = ampAuditLoggerId; + } + + public Long getActivityId() { + return activityId; + } + + public void setActivityId(Long activityId) { + this.activityId = activityId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map> getCompareOutput() { + return compareOutput; + } + + public void setCompareOutput(Map> compareOutput) { + this.compareOutput = compareOutput; + } + + public Long getAmpAuditLoggerId() { + return ampAuditLoggerId; + } + + public void setAmpAuditLoggerId(Long ampAuditLoggerId) { + this.ampAuditLoggerId = ampAuditLoggerId; + } +} \ No newline at end of file diff --git a/amp/WEB-INF/src/org/digijava/module/dataExchange/engine/DEImportBuilder.java b/amp/WEB-INF/src/org/digijava/module/dataExchange/engine/DEImportBuilder.java index 70077eda081..ab185e7dfb6 100644 --- a/amp/WEB-INF/src/org/digijava/module/dataExchange/engine/DEImportBuilder.java +++ b/amp/WEB-INF/src/org/digijava/module/dataExchange/engine/DEImportBuilder.java @@ -1484,7 +1484,7 @@ private String setEditorFreeTextType(List list , AmpActivity activ ed.setBody(obj.getValue()); try { org.digijava.module.editor.util.DbUtil.saveEditor(ed); - } catch (EditorException e) { + } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -2376,7 +2376,7 @@ private void fixEmptyEditorFields(AmpActivityVersion ampActivity, HttpServletReq ed.setBody(""); try { org.digijava.module.editor.util.DbUtil.saveEditor(ed); - } catch (EditorException e) { + } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } diff --git a/amp/WEB-INF/src/org/digijava/module/dataExchange/engine/IatiActivityWorker.java b/amp/WEB-INF/src/org/digijava/module/dataExchange/engine/IatiActivityWorker.java index d3379cc580d..6d881a1b058 100644 --- a/amp/WEB-INF/src/org/digijava/module/dataExchange/engine/IatiActivityWorker.java +++ b/amp/WEB-INF/src/org/digijava/module/dataExchange/engine/IatiActivityWorker.java @@ -1570,7 +1570,7 @@ private String setEditorDescription(Description obj , String key){ ed.setBody(value); try { org.digijava.module.editor.util.DbUtil.saveEditor(ed); - } catch (EditorException e) { + } catch (Exception e) { e.printStackTrace(); } return key; diff --git a/amp/WEB-INF/src/org/digijava/module/editor/action/admin/AddEditor.java b/amp/WEB-INF/src/org/digijava/module/editor/action/admin/AddEditor.java index 80209a7e8ad..2b8ce78df27 100644 --- a/amp/WEB-INF/src/org/digijava/module/editor/action/admin/AddEditor.java +++ b/amp/WEB-INF/src/org/digijava/module/editor/action/admin/AddEditor.java @@ -74,7 +74,7 @@ public ActionForward execute(ActionMapping mapping, DbUtil.saveEditor(ed); - } catch (EditorException ex1) { + } catch (Exception ex1) { /**@todo exception handling */ } } diff --git a/amp/WEB-INF/src/org/digijava/module/editor/util/DbUtil.java b/amp/WEB-INF/src/org/digijava/module/editor/util/DbUtil.java index 9f8db038447..4267b3b0c9e 100644 --- a/amp/WEB-INF/src/org/digijava/module/editor/util/DbUtil.java +++ b/amp/WEB-INF/src/org/digijava/module/editor/util/DbUtil.java @@ -60,8 +60,8 @@ public class DbUtil { private static Logger logger = Logger.getLogger(DbUtil.class); - - /** + + /** * Get editor item by key from database * * @param key @@ -75,9 +75,9 @@ public static List getEditorList(Site site, String editorKey, String lan List items = new ArrayList(); try { session = PersistenceManager.getRequestDBSession(); - Query q = session.createQuery("from " + - Editor.class.getName() + - " e where (e.siteId=:siteId) and (e.editorKey=:editorKey) and (e.language!=:language)"); + Query q = session.createQuery("from " + + Editor.class.getName() + + " e where (e.siteId=:siteId) and (e.editorKey=:editorKey) and (e.language!=:language)"); q.setString("siteId", site.getSiteId()); q.setString("editorKey", editorKey); @@ -88,7 +88,7 @@ public static List getEditorList(Site site, String editorKey, String lan catch (Exception ex) { logger.debug("Unable to get editor item from database ", ex); throw new EditorException("Unable to get editor item from database", - ex); + ex); } return items; @@ -110,8 +110,8 @@ public static List getEditorList(String editorKey, Site site) throws Edi try { session = PersistenceManager.getRequestDBSession(); Query q = session.createQuery("from " - + Editor.class.getName() - + " e where (e.siteId=:siteId) and (e.editorKey=:editorKey)"); + + Editor.class.getName() + + " e where (e.siteId=:siteId) and (e.editorKey=:editorKey)"); q.setString("siteId", site.getSiteId()); q.setString("editorKey", editorKey); @@ -124,8 +124,8 @@ public static List getEditorList(String editorKey, Site site) throws Edi } return items; - } - + } + public static List getEditorList(String editorKey, Site site, Session session) throws EditorException { List items = new ArrayList(); try { @@ -141,10 +141,10 @@ public static List getEditorList(String editorKey, Site site, Session se } return items; - } - + } + public static void deleteEditor(Editor ed) throws - EditorException { + EditorException { Transaction tx = null; Session session = null; try { @@ -158,7 +158,7 @@ public static void deleteEditor(Editor ed) throws logger.debug("Unable to delete editor", ex); throw new EditorException( - "Unable to delete editor", ex); + "Unable to delete editor", ex); } } @@ -169,16 +169,16 @@ public static void deleteEditor(Editor ed) throws * @return * @throws EditorException */ - + public static List getSiteEditorList(Site site) throws - EditorException { + EditorException { Session session = null; List items = new ArrayList(); try { session = PersistenceManager.getRequestDBSession(); Query q = session.createQuery("from " + Editor.class.getName() + - " e where (e.siteId=:siteId) order by e.orderIndex"); + " e where (e.siteId=:siteId) order by e.orderIndex"); q.setString("siteId", site.getSiteId()); @@ -194,7 +194,7 @@ public static List getSiteEditorList(Site site) throws catch (Exception ex) { logger.debug("Unable to get editor list from database ", ex); throw new EditorException("Unable to get editor item from database", - ex); + ex); } return items; @@ -206,11 +206,11 @@ public static List getSiteEditorList(Site site, String lang,String group List items = new ArrayList(); try { session = PersistenceManager.getRequestDBSession(); - Query q = session.createQuery("from " + - Editor.class.getName() + - " e where e.siteId=:siteId and e.groupName=:groupName " + - "and e.language=:language " + - "order by e.orderIndex"); + Query q = session.createQuery("from " + + Editor.class.getName() + + " e where e.siteId=:siteId and e.groupName=:groupName " + + "and e.language=:language " + + "order by e.orderIndex"); q.setString("siteId", site.getSiteId()); q.setString("groupName", groupName); @@ -248,18 +248,18 @@ public static Editor getEditor(Site site, String editorKey,String language) thro session = PersistenceManager.getRequestDBSession(); try { Query q = session.createQuery("from " + Editor.class.getName() +" e where e.siteId=:siteId and e.editorKey=:editorKey"); - q.setString("siteId", site.getSiteId()); - q.setString("editorKey", editorKey); - //q.setString("language", language); - @SuppressWarnings("unchecked") - Collection edits=q.list(); - for (Iterator iterator = edits.iterator(); iterator.hasNext();) { - Editor editor = (Editor) iterator.next(); - if (editor.getLanguage().equalsIgnoreCase(language) && !"".equalsIgnoreCase(editor.getBody())){ - item = editor; - break; - } + q.setString("siteId", site.getSiteId()); + q.setString("editorKey", editorKey); + //q.setString("language", language); + @SuppressWarnings("unchecked") + Collection edits = q.list(); + for (Iterator iterator = edits.iterator(); iterator.hasNext();) { + Editor editor = (Editor) iterator.next(); + if (editor.getLanguage().equalsIgnoreCase(language) && !"".equalsIgnoreCase(editor.getBody())) { + item = editor; + break; } + } } catch (ObjectNotFoundException ex1) { logger.error("DbUtil:getEditor:Unable to get Editor item", ex1); @@ -271,7 +271,7 @@ public static Editor getEditor(Site site, String editorKey,String language) thro } return item; } - + public static Editor getEditorForUpdate(String siteId, String editorKey,String language) throws EditorException { Session session = null; @@ -280,10 +280,10 @@ public static Editor getEditorForUpdate(String siteId, String editorKey,String l session = PersistenceManager.getRequestDBSession(); try { Query q = session.createQuery("from " + Editor.class.getName() +" e where e.siteId=:siteId and e.editorKey=:editorKey and e.language=:language"); - q.setString("siteId", siteId); - q.setString("editorKey", editorKey); - q.setString("language", language); - item = (Editor)q.uniqueResult(); + q.setString("siteId", siteId); + q.setString("editorKey", editorKey); + q.setString("language", language); + item = (Editor) q.uniqueResult(); } catch (ObjectNotFoundException ex1) { logger.error("DbUtil:getEditor:Unable to get Editor item", ex1); @@ -303,10 +303,10 @@ public static Editor getEditor(Site site, int orderIndex) throws EditorException Editor item = new Editor(); try { session = PersistenceManager.getRequestDBSession(); - Query q = session.createQuery("from " + - Editor.class.getName() + - " e where (e.siteId=:siteId) and " + - "(e.orderIndex=:orderIndex)"); + Query q = session.createQuery("from " + + Editor.class.getName() + + " e where (e.siteId=:siteId) and " + + "(e.orderIndex=:orderIndex)"); q.setString("siteId", site.getSiteId()); q.setInteger("orderIndex", new Integer(orderIndex)); @@ -344,8 +344,8 @@ public static Editor getEditor(String editorKey, String language) throws EditorE Editor item = new Editor(); try { session = PersistenceManager.getRequestDBSession(); - Query q = session.createQuery("from " + Editor.class.getName() + - " e where (e.editorKey=:editorKey) and (e.language=:language)"); + Query q = session.createQuery("from " + Editor.class.getName() + + " e where (e.editorKey=:editorKey) and (e.language=:language)"); q.setString("editorKey", editorKey); q.setString("language", language); @@ -366,9 +366,9 @@ public static Editor getEditor(String editorKey, String language) throws EditorE return item; } - - - + + + /** * Update editor * @@ -398,12 +398,12 @@ public static void updateEditor(Editor editor) throws EditorException { } } throw new EditorException( - "Unable to update editor information into database", ex); + "Unable to update editor information into database", ex); } } public static void updateEditorList(Collection editors) throws - EditorException { + EditorException { Session session = null; Transaction tx = null; @@ -420,7 +420,7 @@ public static void updateEditorList(Collection editors) throws logger.debug("Unable to update editor information into database", ex); throw new EditorException( - "Unable to update editor information into database", ex); + "Unable to update editor information into database", ex); } } @@ -429,9 +429,8 @@ public static void updateEditorList(Collection editors) throws * Save editor * * @param editor - * @throws EditorException */ - public static void saveEditor(Editor editor) throws EditorException { + public static void saveEditor(Editor editor) { PersistenceManager.getSession().save(editor); } @@ -457,7 +456,7 @@ public static Editor createEditor(User user, String languageCode, // get module instance ModuleInstance moduleInstance = RequestUtils.getRealModuleInstance(request); - // TODO: not sure if moduleInstance is now always false and we can simply replace with TLSUtils.getSite() + // TODO: not sure if moduleInstance is now always false and we can simply replace with TLSUtils.getSite() Site site = moduleInstance == null ? TLSUtils.getSite() : moduleInstance.getSite(); editor.setSite(site); @@ -477,31 +476,44 @@ public static Editor createEditor(User user, String languageCode, } /** - * Retrieves editor body text. Gives priority to chosen language, else returns English, else returns any, else returns null + * + * @param site Site object for the current deployed amp + * @param editorKey editor key to fetch the body for + * @param language lanaguage of the body + * @return the body for the given parameters + * @throws EditorException + */ + public static String getEditorBody(Site site, String editorKey, String language) throws EditorException { + return getEditorBody(site.getSiteId(), editorKey, language); + } + + /** + * Retrieves editor body text. Gives priority to chosen language, else returns English, else returns any, + * else returns null * @param siteId - * @param editorKey - * @param language - * @return + * @param editorKey editor key to fetch the body for + * @param language language of the body + * @return the body for the given parameters * @throws EditorException */ - public static String getEditorBody(Site site, String editorKey, String language) throws EditorException - { + public static String getEditorBody(String siteId, String editorKey, String language) throws EditorException { String bodyEn = null; // translation in English String bodyOther = null; // translation in any language which is not English and is not the requested one - - String stat = String.format("SELECT body, language FROM dg_editor WHERE site_id = '%s' AND editor_key = '%s'", site.getSiteId(), editorKey); - List res = PersistenceManager.getSession().createSQLQuery(stat).list(); + + String stat = String.format("SELECT body, language FROM dg_editor WHERE site_id = '%s' AND editor_key = '%s'", + siteId, editorKey); + List res = PersistenceManager.getRequestDBSession().createSQLQuery(stat).list(); for(Object[] entry:res) { String editorBody = PersistenceManager.getString(entry[0]); String editorLanguage = PersistenceManager.getString(entry[1]); - + if ("".equals(editorBody)) continue; // ignore this one - + if (editorLanguage.equalsIgnoreCase(language)) return editorBody; - + if (editorLanguage.equalsIgnoreCase("en")) bodyEn = editorBody; else @@ -511,7 +523,7 @@ public static String getEditorBody(Site site, String editorKey, String language) return bodyEn; return bodyOther; } - + /** * Retrieves editor body text. * @param siteId @@ -528,9 +540,9 @@ public static String getEditorBodyEmptyInclude(Site site, String editorKey, Stri try { session = PersistenceManager.getRequestDBSession(); Query q = session.createQuery( - "select e.body from " + Editor.class.getName() + " e " + - " where (e.siteId=:siteId) and (e.editorKey=:editorKey) and e.language=:language"); - // q.setCacheable(true); + "select e.body from " + Editor.class.getName() + " e " + + " where (e.siteId=:siteId) and (e.editorKey=:editorKey) and e.language=:language"); + // q.setCacheable(true); q.setString("siteId", site.getSiteId()); q.setString("editorKey", editorKey); q.setString("language", language); @@ -543,15 +555,15 @@ public static String getEditorBodyEmptyInclude(Site site, String editorKey, Stri return body; } - + /** * Returns editor body text but strips out all HTML tags. - * Uses {@link #getEditorBody(String, String, String)} method to + * Uses {@link #getEditorBody(String, String, String)} method to * retrieve initial body text and then uses regexps to strip tags. - * Note that to strip all possible HTML tags batch processing is used to + * Note that to strip all possible HTML tags batch processing is used to * avoid stack overflow problems which happens when processing too huge regexp. * Solution copied from AMP v2 Help+Lucene integration solution. - * Check AMP-9328 for more details. + * Check AMP-9328 for more details. * @param siteId * @param editorKey * @param language @@ -580,9 +592,9 @@ public static String getEditorTitle(Site site, String editorKey,String language) session = PersistenceManager.getRequestDBSession(); Query q = session.createQuery( - "select e.title from " + - Editor.class.getName() + " e, " + - " where (e.siteId=:siteId) and (e.editorKey=:editorKey) and (e.language=:language)"); + "select e.title from " + + Editor.class.getName() + " e, " + + " where (e.siteId=:siteId) and (e.editorKey=:editorKey) and (e.language=:language)"); q.setCacheable(true); q.setString("siteId", site.getSiteId()); @@ -611,10 +623,10 @@ public static String getEditorTitle(Site site, String editorKey,String language) catch (Exception ex) { logger.debug("Unable to get editor title from database", ex); throw new EditorException( - "Unable to get editor title from database", ex); + "Unable to get editor title from database", ex); } return title; } -} +} \ No newline at end of file diff --git a/amp/repository/aim/view/allVisibilityTags.jsp b/amp/repository/aim/view/allVisibilityTags.jsp index d2420ff5fac..7b2588b574b 100644 --- a/amp/repository/aim/view/allVisibilityTags.jsp +++ b/amp/repository/aim/view/allVisibilityTags.jsp @@ -112,7 +112,7 @@ - + diff --git a/amp/repository/aim/view/auditLoggerManager.jsp b/amp/repository/aim/view/auditLoggerManager.jsp index 68f6c9fdcfb..2fa5c10c21f 100644 --- a/amp/repository/aim/view/auditLoggerManager.jsp +++ b/amp/repository/aim/view/auditLoggerManager.jsp @@ -6,42 +6,14 @@ <%@ taglib uri="/taglib/digijava" prefix="digi" %> <%@ taglib uri="/taglib/jstl-core" prefix="c" %> <%@ taglib uri="/taglib/jstl-functions" prefix="fn" %> - +<%@page import="org.digijava.module.aim.util.FeaturesUtil"%> <%@page import="org.digijava.module.aim.services.auditcleaner.AuditCleaner"%> - - - - +<% if (FeaturesUtil.isVisibleFeature("Activity Diferrence") ){%> + +<%}%> + + -

Audit Logger Manager

+

Audit Logger Manager

@@ -176,12 +172,12 @@ function exportScorecard () {
- Admin Home + Admin Home  >  - Audit Logger Manager - + Audit Logger Manager + @@ -191,7 +187,7 @@ function exportScorecard () { <%if(AuditCleaner.getInstance().isRunning()){%> <%if (AuditCleaner.getInstance().getRemainingdays()!= null){%> - The automatic cleanup of the audit trail will occur in + The automatic cleanup of the audit trail will occur in <%=AuditCleaner.getInstance().getRemainingdays()%> Days <%} @@ -206,9 +202,9 @@ function exportScorecard () { ${loginTr} - - Show cleanup options >> -  
+ + Show cleanup options >>
+   - +
- - - + + + + +
+ + + + + + Show Filter options + + + + + Hide Filter options + + + + +  
+
background-color:#ffffff;padding:2px; width: 100%" id="currentFilterSettings" > +
+
+
+
User:
+
+ Select User + +
+
+
+
Team:
+
+ Select Team + +
+
+ + Date + + +
+
From:
+
+
+ + + Click to View Calendar + + + + +
+ +
+
+
+
To:
+ +
+
+ + + Click to View Calendar + + + + + +
+
+
+
+
+
+
+
+
+
+
+
- + -
@@ -263,116 +345,121 @@ function exportScorecard () { + + + @@ -388,10 +475,10 @@ function exportScorecard () { + + + + + + + + + + +
- - - Name + + Name - + - - Name + + Name - - Object Type + + Object Type - - Object Type + + Object Type - - Team Name + + Team Name - - Team Name + + Team Name - - Author Name + + Author Name - - Author Name + + Author Name - - Creation Date + + Creation Date - - Creation Date + + Creation Date - - Editor Name + + Editor Name - - Editor Name + + Editor Name - - Change Date + + Change Date - - Change Date + + Change Date - - Action + + Action - - Action + + Action - + Additional Details - + Additional Details - + + View Differences +
- + - + ')" style="text-decoration: none" title="${log.authorName}"> @@ -403,7 +490,7 @@ function exportScorecard () { - + @@ -416,10 +503,10 @@ function exportScorecard () { - + - + @@ -430,7 +517,7 @@ function exportScorecard () { Update Login - + @@ -440,14 +527,27 @@ function exportScorecard () { No Data +  
- +
@@ -457,16 +557,20 @@ function exportScorecard () { + + First Page - << + << + + Previous Page | @@ -474,26 +578,30 @@ function exportScorecard () { Previous -   +   | - + <%=pages%> + + + + <%=pages%> - | + | Click here to go to Next Page - - <%=pages%> + + <%=pages%> | @@ -503,45 +611,57 @@ function exportScorecard () { + + + + Next Page - + Next | - + + + + + - + + + + + Last Page - + >> -   +   of  - + Back to Top - +
+ - + diff --git a/amp/repository/aim/view/scripts/auditFilter.jsp b/amp/repository/aim/view/scripts/auditFilter.jsp new file mode 100644 index 00000000000..bea67f4a2be --- /dev/null +++ b/amp/repository/aim/view/scripts/auditFilter.jsp @@ -0,0 +1,65 @@ +<%@ taglib uri="/taglib/digijava" prefix="digi" %> + + + + + + + + + + + + + + \ No newline at end of file diff --git a/amp/repository/aim/view/scripts/compareAcivity.js b/amp/repository/aim/view/scripts/compareAcivity.js new file mode 100644 index 00000000000..51ddd3ea018 --- /dev/null +++ b/amp/repository/aim/view/scripts/compareAcivity.js @@ -0,0 +1,33 @@ +function toggleFilterSettings(){ + var currentFilterSettings = $('#currentFilterSettings'); + var displayFilterButton = $('#displayFilterButton'); + if(currentFilterSettings.css('display') == "inline-flex"){ + currentFilterSettings.hide(); + $('#exportScorecard').hide(); + displayFilterButton.html('Show Filter options'+ ' >>'); + } + else + { + currentFilterSettings.css('display', 'inline-flex'); + $('#exportScorecard').css('display','inline-flex'); + displayFilterButton.html('Hide Filter options'+ ' <<'); + } +} + +function viewDifferences(activityOneId) { + document.aimCompareActivityVersionsForm.method.value = "viewDifferences"; + document.aimCompareActivityVersionsForm.activityOneId.value = activityOneId; + document.aimCompareActivityVersionsForm.submit(); +} + +function compareAll(){ + document.getElementById("compPrevForm").target = "_blank"; + var user = document.getElementById("userId").value; + var team = document.getElementById("teamId").value; + document.aimCompareActivityVersionsForm.selectedUser.value = user; + document.aimCompareActivityVersionsForm.selectedTeam.value = team; + document.aimCompareActivityVersionsForm.selectedDateFrom.value = document.getElementById("selectedDateFromText").value; + document.aimCompareActivityVersionsForm.selectedDateTo.value = document.getElementById("selectedDateToText").value; + document.aimCompareActivityVersionsForm.method.value = "compareAll"; + document.aimCompareActivityVersionsForm.submit(); +} \ No newline at end of file diff --git a/amp/repository/aim/view/teamAuditList.jsp b/amp/repository/aim/view/teamAuditList.jsp index 8aef42312d4..03e94467224 100644 --- a/amp/repository/aim/view/teamAuditList.jsp +++ b/amp/repository/aim/view/teamAuditList.jsp @@ -1,13 +1,17 @@ -<%@ page pageEncoding="UTF-8" %> -<%@ taglib uri="/taglib/struts-bean" prefix="bean" %> -<%@ taglib uri="/taglib/struts-logic" prefix="logic" %> -<%@ taglib uri="/taglib/struts-tiles" prefix="tiles" %> -<%@ taglib uri="/taglib/struts-html" prefix="html" %> +<%@ page import="org.digijava.module.aim.util.FeaturesUtil" %> +<%@ page pageEncoding="UTF-8"%> +<%@ taglib uri="/taglib/struts-bean" prefix="bean"%> +<%@ taglib uri="/taglib/struts-logic" prefix="logic"%> +<%@ taglib uri="/taglib/struts-tiles" prefix="tiles"%> +<%@ taglib uri="/taglib/struts-html" prefix="html"%> <%@ taglib uri="/taglib/digijava" prefix="digi" %> <%@ taglib uri="/taglib/jstl-core" prefix="c" %> <%@ taglib uri="/taglib/jstl-functions" prefix="fn" %> - - + +<% if (FeaturesUtil.isVisibleFeature("Activity Diferrence") ){%> + +<%}%> + @@ -64,12 +82,87 @@ function showUser(email){ -
- +
- + + + + + + Show Filter options + + + + + Hide Filter options + + - + +  
+
background-color:#ffffff;padding:2px; width: 100%" id="currentFilterSettings" > +
+
+
+
User:
+
+ Select User + + +
+
+
+
Team:
+
+
+
+ + Date + +
+
From:
+
+ +
+
+
+
To:
+
+ +
+
+
+
+
+
+
+
+
+ +
+ + + +
+ + + - - - + + + + +
@@ -215,10 +308,15 @@ function showUser(email){ View differences +
@@ -276,6 +374,14 @@ function showUser(email){ Update +
+ +
+
diff --git a/amp/repository/aim/view/viewActivityDifferences.jsp b/amp/repository/aim/view/viewActivityDifferences.jsp index 49b5cf09b15..fbd9e366155 100644 --- a/amp/repository/aim/view/viewActivityDifferences.jsp +++ b/amp/repository/aim/view/viewActivityDifferences.jsp @@ -10,11 +10,12 @@ <%@ taglib uri="/taglib/featureVisibility" prefix="feature" %> <%@ taglib uri="/taglib/moduleVisibility" prefix="module" %> <%@ taglib uri="/taglib/jstl-functions" prefix="fn" %> - +<%@page import="org.digijava.module.aim.util.FeaturesUtil"%> + - +<% if (FeaturesUtil.isVisibleFeature("Activity Diferrence") ){%> + +<%}%> @@ -45,15 +54,48 @@ - -
+ + + + The activity you chose is the latest and has no previous version. + + + +
+ +
+ Activity: +
+
@@ -90,99 +132,32 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - <%-- - - - - - - - - - - - + - - - --%> + + + + + + + +
- -
-
-   - -
-
- - - - -
 
-
- - - - -
-   - -
-
- - -
-   - -
-
- - -
 
-
- - -
-   - + <%-- Iterate through the list of output collections for compareAll method... --%> + + <%int count = 0; %> + +
+ +
"> + <%out.print("
["+(++count)+"]. "); %>
+ +

- - + + @@ -192,8 +167,21 @@ \ No newline at end of file diff --git a/amp/repository/aim/view/viewGlobalSettings.jsp b/amp/repository/aim/view/viewGlobalSettings.jsp index 4928de392a1..8726f629330 100644 --- a/amp/repository/aim/view/viewGlobalSettings.jsp +++ b/amp/repository/aim/view/viewGlobalSettings.jsp @@ -469,6 +469,17 @@ var enterBinder = new EnterHitBinder('gsSaveAllBtn'); + <% + if (!globalSett.getGlobalSettingsValue().equalsIgnoreCase("-1") && globalSett.getGlobalSettingsName() + .equals(GlobalSettingsConstants.AUTOMATIC_AUDIT_LOGGER_CLEANUP)) { + String sdate = org.digijava.module.common.util.DateTimeUtil + .formatDate(AuditCleaner.getInstance().getNextcleanup()); + %> +
+ Next Audit Cleanup:<%=" " + sdate%> + <% + } + %> <% } %> @@ -713,54 +724,6 @@ var enterBinder = new EnterHitBinder('gsSaveAllBtn'); %> - - <% - String peridiodvalues = globalSett - .getGlobalSettingsValue(); - int selected = Integer - .parseInt(peridiodvalues); - %> - - <% - if (!globalSett - .getGlobalSettingsValue() - .equalsIgnoreCase("-1")) { - String sdate = org.digijava.module.common.util.DateTimeUtil - .formatDate(AuditCleaner - .getInstance() - .getNextcleanup()); - %> -
- Next Audit Cleanup: - <%=" " + sdate%> - <% - } - %> -
diff --git a/amp/repository/aim/view/viewGroupedOutput.jsp b/amp/repository/aim/view/viewGroupedOutput.jsp new file mode 100644 index 00000000000..fc216b34e47 --- /dev/null +++ b/amp/repository/aim/view/viewGroupedOutput.jsp @@ -0,0 +1,75 @@ +<%-- + Created by IntelliJ IDEA. + User: Wessi + Date: 08-Mar-19 + Time: 10:23 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> +<%@ page trimDirectiveWhitespaces="true"%> +<%@ taglib uri="/taglib/jstl-core" prefix="c" %> +<%@ taglib uri="/taglib/struts-bean" prefix="bean" %> +<%@ taglib uri="/taglib/struts-logic" prefix="logic" %> +<%@ taglib uri="/taglib/digijava" prefix="digi" %> + + + + + + + + + + + + + + + + +
+   + +
+ + + + + + + + + +
 
+ + + + + + + + + +
+ + +
+   + +
+ + + + + + +
+ + + +
+
\ No newline at end of file diff --git a/amp/xmlpatches/2.z13.01.12/AMPET-148-audit-logger-cleaner.xml b/amp/xmlpatches/2.z13.01.12/AMPET-148-audit-logger-cleaner.xml new file mode 100644 index 00000000000..516205a505e --- /dev/null +++ b/amp/xmlpatches/2.z13.01.12/AMPET-148-audit-logger-cleaner.xml @@ -0,0 +1,35 @@ + + + AMPET-148 + Global settings for Automatic Audit Logger Cleanup + Wessi + Add possible values, insert into amp_global_settings + + + + \ No newline at end of file diff --git a/amp/xmlpatches/general/views/v_g_settings_audit_logger_cleanup.xml b/amp/xmlpatches/general/views/v_g_settings_audit_logger_cleanup.xml new file mode 100644 index 00000000000..03e127fe565 --- /dev/null +++ b/amp/xmlpatches/general/views/v_g_settings_audit_logger_cleanup.xml @@ -0,0 +1,29 @@ + + + AMPET-148 + Views + Wessi + recreate view at every server startup + + + + val.equalsIgnoreCase("true") + + + + + + \ No newline at end of file