Example usage for java.text SimpleDateFormat applyPattern

List of usage examples for java.text SimpleDateFormat applyPattern

Introduction

In this page you can find the example usage for java.text SimpleDateFormat applyPattern.

Prototype

public void applyPattern(String pattern) 

Source Link

Document

Applies the given pattern string to this date format.

Usage

From source file:org.openmrs.util.OpenmrsUtilTest.java

/**
 * @see OpenmrsUtil#getDateFormat(Locale)
 *//*from w  w  w. j  a v a2  s  . com*/
@Test
public void getDateFormat_shouldNotAllowTheReturnedSimpleDateFormatToBeModified() {
    // start with a locale that is not currently cached by getDateFormat()
    Locale locale = new Locale("hk");
    Assert.assertTrue("default locale is potentially already cached", !Context.getLocale().equals(locale));

    // get the initially built dateformat from getDateFormat()
    SimpleDateFormat sdf = OpenmrsUtil.getDateFormat(locale);
    Assert.assertNotSame("initial dateFormatCache entry is modifiable", OpenmrsUtil.getDateFormat(locale), sdf);

    // verify changing the pattern on our variable does not affect the cache
    sdf.applyPattern("yyyymmdd");
    Assert.assertTrue("initial dateFormatCache pattern is modifiable",
            !OpenmrsUtil.getDateFormat(locale).toPattern().equals(sdf.toPattern()));

    // the dateformat cache now contains the format for this locale; checking
    // a second time will guarantee we are looking at cached data and not the
    // initially built dateformat
    sdf = OpenmrsUtil.getDateFormat(locale);
    Assert.assertNotSame("cached dateFormatCache entry is modifiable", OpenmrsUtil.getDateFormat(locale), sdf);

    // verify changing the pattern on our variable does not affect the cache
    sdf.applyPattern("yyyymmdd");
    Assert.assertTrue("cached dateFormatCache pattern is modifiable",
            !OpenmrsUtil.getDateFormat(locale).toPattern().equals(sdf.toPattern()));
}

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 * List all available timeformats, read from the jspwiki.properties
 * /*  w w w  .  jav a2  s. co m*/
 * @param pageContext
 * @return map of TimeFormats
 * @since 2.7.x
 */
public Map listTimeFormats(PageContext pageContext) {
    WikiContext context = WikiContext.findContext(pageContext);
    Properties props = m_engine.getWikiProperties();
    ArrayList<String> tfArr = new ArrayList<String>(40);
    LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>();

    /* filter timeformat properties */
    for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();

        if (name.startsWith(TIMEFORMATPROPERTIES)) {
            tfArr.add(name);
        }
    }

    /* fetch actual formats */
    if (tfArr.size() == 0) /*
                             * no props found - make sure some default
                             * formats are avail
                             */
    {
        tfArr.add("dd-MMM-yy");
        tfArr.add("d-MMM-yyyy");
        tfArr.add("EEE, dd-MMM-yyyy, zzzz");
    } else {
        Collections.sort(tfArr);

        for (int i = 0; i < tfArr.size(); i++) {
            tfArr.set(i, props.getProperty(tfArr.get(i)));
        }
    }

    String prefTimeZone = Preferences.getPreference(context, "TimeZone");
    //TimeZone tz = TimeZone.getDefault();
    TimeZone tz = TimeZone.getTimeZone(prefTimeZone);
    /*try
    {
    tz.setRawOffset(Integer.parseInt(prefTimeZone));
    }
    catch (Exception e)
    {
    }*/

    Date d = new Date(); // current date
    try {
        // dummy format pattern
        SimpleDateFormat fmt = Preferences.getDateFormat(context, TimeFormat.DATETIME);
        fmt.setTimeZone(tz);

        for (int i = 0; i < tfArr.size(); i++) {
            try {
                String f = tfArr.get(i);
                fmt.applyPattern(f);

                resultMap.put(f, fmt.format(d));
            } catch (IllegalArgumentException e) {
            } // skip parameter
        }
    } catch (IllegalArgumentException e) {
    } // skip parameter

    return resultMap;
}

From source file:nl.b3p.gis.writers.B3pOgcSqlWriter.java

private String formatDate(String olddate, String oldtime, String newdate, String newtime, String parse_date)
        throws ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat(olddate + " " + oldtime);
    Date date = null;//from   w w w.  j  a  va 2  s  . co m
    // first try date + time
    try {
        date = dateFormat.parse(parse_date);
        dateFormat = new SimpleDateFormat(newdate + " " + newtime);
    } catch (ParseException e) {
        // second try date
        try {
            dateFormat.applyPattern(olddate);
            date = dateFormat.parse(parse_date);
            dateFormat = new SimpleDateFormat(newdate);
        } catch (ParseException e2) {
            // third try time
            dateFormat.applyPattern(oldtime);
            date = dateFormat.parse(parse_date);
            dateFormat = new SimpleDateFormat(newtime);
        }
    }
    return dateFormat.format(date);
}

From source file:com.panet.imeta.job.entries.zipfile.JobEntryZipFile.java

public String getFullFilename(String filename, boolean add_date, boolean add_time, boolean specify_format,
        String datetime_folder) {
    String retval = "";
    if (Const.isEmpty(filename))
        return null;

    // Replace possible environment variables...
    String realfilename = environmentSubstitute(filename);
    int lenstring = realfilename.length();
    int lastindexOfDot = realfilename.lastIndexOf('.');
    if (lastindexOfDot == -1)
        lastindexOfDot = lenstring;//from  w ww .ja va  2s .co m

    retval = realfilename.substring(0, lastindexOfDot);

    SimpleDateFormat daf = new SimpleDateFormat();
    Date now = new Date();

    if (specify_format && !Const.isEmpty(datetime_folder)) {
        daf.applyPattern(datetime_folder);
        String dt = daf.format(now);
        retval += dt;
    } else {
        if (add_date) {
            daf.applyPattern("yyyyMMdd");
            String d = daf.format(now);
            retval += "_" + d;
        }
        if (add_time) {
            daf.applyPattern("HHmmssSSS");
            String t = daf.format(now);
            retval += "_" + t;
        }
    }
    retval += realfilename.substring(lastindexOfDot, lenstring);
    return retval;

}

From source file:org.pentaho.di.trans.steps.sqlfileoutput.SQLFileOutputMeta.java

public String buildFilename(String fileName, int stepnr, int splitnr) {
    SimpleDateFormat daf = new SimpleDateFormat();

    // Replace possible environment variables...
    String retval = fileName;/* ww  w.  ja  v a2s  .  c o m*/

    Date now = new Date();

    if (dateInFilename) {
        daf.applyPattern("yyyMMdd");
        String d = daf.format(now);
        retval += "_" + d;
    }
    if (timeInFilename) {
        daf.applyPattern("HHmmss");
        String t = daf.format(now);
        retval += "_" + t;
    }
    if (stepNrInFilename) {
        retval += "_" + stepnr;
    }

    if (splitEvery > 0) {
        retval += "_" + splitnr;
    }

    if (extension != null && extension.length() != 0) {
        retval += "." + extension;
    }

    return retval;
}

From source file:com.rr.generic.ui.importexport.importExportController.java

/**
 * //from   w ww .  j a v a  2  s  .c o m
 * @param surveyId
 * @param session
 * @param request
 * @return
 * @throws Exception 
 */
@RequestMapping(value = "/saveParticipantExport.do", method = RequestMethod.POST)
public ModelAndView saveExport(@ModelAttribute(value = "exportDetails") savedExports exportDetails,
        @RequestParam List<Integer> selectedSites, BindingResult errors, HttpSession session,
        HttpServletRequest request) throws Exception {

    if (errors.hasErrors()) {
        for (ObjectError error : errors.getAllErrors()) {
            System.out.println(error.getDefaultMessage());
        }
    }

    User userDetails = (User) session.getAttribute("userDetails");

    SimpleDateFormat datesearchFormat = new SimpleDateFormat("MM/dd/yyyy");
    Date startDate = datesearchFormat.parse(exportDetails.getStartDate());
    Date endDate = datesearchFormat.parse(exportDetails.getEndDate());

    datesearchFormat.applyPattern("yyyy-MM-dd");

    String realStartDate = datesearchFormat.format(startDate);
    String realEndDate = datesearchFormat.format(endDate);

    String exportFileName = "";

    String registryName = programmanager.getProgramById(programId).getProgramName().replaceAll(" ", "-")
            .toLowerCase();

    /* Get the client engagements */
    List<engagements> engagements = engagementmanager.getEngagementByMultipleEntity(programId, selectedSites,
            realStartDate, realEndDate);

    Integer exportId = 0;

    /* Loop through sessions here */
    if (engagements != null && engagements.size() > 0) {

        exportDetails.setProgramId(programId);
        exportDetails.setSystemUserId(userDetails.getId());
        exportDetails.setSelectedDateRange(exportDetails.getStartDate() + " - " + exportDetails.getEndDate());
        exportDetails.setDownloadType(1);

        exportId = exportManager.saveExport(exportDetails);

        if (selectedSites != null && !"".equals(selectedSites)) {
            StringBuilder selectedSiteNames = new StringBuilder();
            for (Integer site : selectedSites) {
                programHierarchyDetails siteDetails = hierarchymanager.getProgramHierarchyItemDetails(site);

                savedExportSites exportSite = new savedExportSites();
                exportSite.setExportId(exportId);
                exportSite.setSiteName(siteDetails.getName());
                exportSite.setSiteId(site);

                exportManager.saveExportSite(exportSite);
            }
        }

        progressBar newProgressBar = new progressBar();
        newProgressBar.setExportId(exportDetails.getUniqueId());
        newProgressBar.setPercentComplete(0);

        exportManager.saveProgessBar(newProgressBar);

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
        Date date = new Date();
        String fileName = "";
        String delimiter = ",";

        if (exportDetails.getExportType() == 1) {
            fileName = new StringBuilder().append("participantExport").append(dateFormat.format(date))
                    .append(".csv").toString();
            delimiter = ",";
        } else if (exportDetails.getExportType() == 2) {
            fileName = new StringBuilder().append("participantExport").append(dateFormat.format(date))
                    .append(".txt").toString();
            delimiter = ",";
        } else if (exportDetails.getExportType() == 3) {
            fileName = new StringBuilder().append("participantExport").append(dateFormat.format(date))
                    .append(".txt").toString();
            delimiter = "|";
        } else if (exportDetails.getExportType() == 4) {
            fileName = new StringBuilder().append("participantExport").append(dateFormat.format(date))
                    .append(".txt").toString();
            delimiter = "\t";
        }

        /* Create new export file */
        InputStream inputStream = null;
        OutputStream outputStream = null;

        fileSystem dir = new fileSystem();
        dir.setDir(registryName, "exportFiles");

        File newFile = new File(dir.getDir() + fileName);

        /* Create the empty file in the correct location */
        try {

            if (newFile.exists()) {
                int i = 1;
                while (newFile.exists()) {
                    int iDot = fileName.lastIndexOf(".");
                    newFile = new File(dir.getDir() + fileName.substring(0, iDot) + "_(" + ++i + ")"
                            + fileName.substring(iDot));
                }
                fileName = newFile.getName();
                newFile.createNewFile();
            } else {
                newFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        /* Read in the file */
        FileInputStream fileInput = null;
        File file = new File(dir.getDir() + fileName);
        fileInput = new FileInputStream(file);

        exportFileName = fileName;

        FileWriter fw = null;

        try {
            fw = new FileWriter(file, true);
        } catch (IOException ex) {
            Logger.getLogger(exportManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        exportDetails.setExportFile(exportFileName);
        exportManager.saveExport(exportDetails);

        StringBuilder exportRow = new StringBuilder();
        exportRow.append("ORGCODE").append(delimiter);
        exportRow.append("PARTICIP").append(delimiter);
        exportRow.append("STATE").append(delimiter);
        exportRow.append("GLUCTEST").append(delimiter);
        exportRow.append("GDM").append(delimiter); /* P */
        exportRow.append("RISKTEST").append(delimiter); /* P */
        exportRow.append("AGE").append(delimiter); /* P */
        exportRow.append("ETHNIC").append(delimiter); /* P */
        exportRow.append("AIAN").append(delimiter); /* P */
        exportRow.append("ASIAN").append(delimiter); /* P */
        exportRow.append("BLACK").append(delimiter); /* P */
        exportRow.append("NHOPI").append(delimiter); /* P */
        exportRow.append("WHITE").append(delimiter); /* P */
        exportRow.append("SEX").append(delimiter); /* P */
        exportRow.append("HEIGHT").append(delimiter);
        exportRow.append("DATE").append(delimiter);
        exportRow.append("WEIGHT").append(delimiter);
        exportRow.append("PA").append(delimiter);

        exportRow.append(System.getProperty("line.separator"));

        fw.write(exportRow.toString());

        Integer participantId = 0;

        List<programExportFields> exportFields = programmanager.getProgramExportFields(programId);

        List<String> tableinfo = new ArrayList<String>();

        Integer fieldId = 0;
        Integer customFieldId = 0;
        Integer validationValue = 0;
        String fieldTypeValue = "";
        Integer crosswalkId = 0;

        for (programExportFields field : exportFields) {

            if (field.getFieldType() == 1) {
                fieldTypeValue = "1";
                programClientFields fieldDetails = clientmanager.getClientFieldDetails(programId,
                        field.getFieldId());
                fieldId = fieldDetails.getFieldId();
                customFieldId = fieldDetails.getCustomfieldId();
                validationValue = fieldDetails.getValidationId();
                crosswalkId = fieldDetails.getCrosswalkId();
            } else {
                fieldTypeValue = "2";
                programEngagementFields fieldDetails = engagementmanager.getEngagementFieldDetails(programId,
                        field.getFieldId());
                fieldId = fieldDetails.getFieldId();
                customFieldId = fieldDetails.getCustomfieldId();
                validationValue = fieldDetails.getValidationId();
                crosswalkId = fieldDetails.getCrosswalkId();
            }

            if (fieldId > 0) {
                dataElements fieldDetails = clientmanager.getFieldDetails(fieldId);
                tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTableName() + "-"
                        + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId);
            }

            else if (customFieldId > 0) {
                customProgramFields fieldDetails = clientmanager.getCustomFieldDetails(customFieldId);
                tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTable() + "-"
                        + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId);
            }
        }

        Integer totalDone = 0;
        float percentComplete;

        progressBar exportProgressBar = exportManager.getProgressBar(exportDetails.getUniqueId());

        for (engagements engagement : engagements) {

            exportRow = new StringBuilder();

            programHierarchyDetails hierarchyDetails = hierarchymanager.getProgramHierarchyItemDetails(
                    clientmanager.getClientEntities(engagement.getProgramPatientId()).getEntity3Id());

            String siteDisplayId = "";

            if (hierarchyDetails.getDisplayId() != null) {
                siteDisplayId = hierarchyDetails.getDisplayId();
            }

            exportRow.append(siteDisplayId).append(delimiter);

            if (tableinfo != null & tableinfo.size() > 0) {
                for (String table : tableinfo) {
                    String[] tableInfoArray = table.split("-");
                    String fieldValue = "";
                    String fieldType = tableInfoArray[0];
                    String tablename = tableInfoArray[1];
                    String tableCol = tableInfoArray[2];
                    String validation = tableInfoArray[3];
                    String crosswalk = tableInfoArray[4];

                    if ("1".equals(fieldType)) {
                        fieldValue = clientmanager.getTableData(tablename, tableCol,
                                engagement.getProgramPatientId());
                    } else {
                        fieldValue = engagementmanager.getTableData(tablename, tableCol, engagement.getId(),
                                engagement.getProgramPatientId());
                    }

                    if ("55".equals(crosswalk) && "0".equals(fieldValue)) {
                        fieldValue = "2";
                    }

                    /* If date format to correct display format */
                    if ("4".equals(validation)) {
                        if ("dob".equals(tableCol)) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            Date dob = format.parse(fieldValue);
                            Date today = new Date();

                            format.applyPattern("yyyy");
                            String dobAsString = format.format(dob);
                            String todayAsString = format.format(today);

                            Integer age = Integer.parseInt(todayAsString) - Integer.parseInt(dobAsString);
                            exportRow.append(age).append(delimiter);
                        } else {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            Date formatedDate = format.parse(fieldValue);
                            format.applyPattern("MM/dd/yy");
                            exportRow.append(format.format(formatedDate)).append(delimiter);
                        }
                    } else {
                        exportRow.append(fieldValue).append(delimiter);
                    }
                }
            }

            exportRow.append(System.getProperty("line.separator"));
            fw.write(exportRow.toString());

            //Update progress bar
            totalDone = totalDone + 1;
            percentComplete = ((float) totalDone) / engagements.size();
            exportProgressBar.setPercentComplete(Math.round(percentComplete * 100));
            exportManager.saveProgessBar(exportProgressBar);

        }

        fw.close();
    }

    ModelAndView mav = new ModelAndView();

    /* If no results are found */
    if (exportFileName.isEmpty()) {
        mav.setViewName("/importExport/exportModal");

        savedExports newexportDetails = new savedExports();
        exportDetails.setExportType(1);

        programOrgHierarchy level1 = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId);
        programOrgHierarchy level2 = hierarchymanager.getProgramOrgHierarchyBydspPos(2, programId);
        programOrgHierarchy level3 = hierarchymanager.getProgramOrgHierarchyBydspPos(3, programId);

        List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(),
                userDetails.getId());
        mav.addObject("level1Items", level1Items);

        mav.addObject("level1Name", level1.getName());
        mav.addObject("level2Name", level2.getName());
        mav.addObject("level3Name", level3.getName());

        mav.addObject("exportDetails", newexportDetails);
        mav.addObject("showDateRange", true);
        mav.addObject("noresults", true);
    } else {
        if (exportDetails.getUniqueId() > 0) {
            /* Delete progress bar entry */
            exportManager.deleteProgressBar(exportDetails.getUniqueId());
        }

        mav.setViewName("/importExport/exportDownloadModal");
        mav.addObject("exportFileName", exportFileName);
    }

    return mav;
}

From source file:org.sakaiproject.contentreview.vericite.ContentReviewServiceVeriCite.java

public void createAssignment(final String contextId, final String assignmentRef, final Map opts)
        throws SubmissionException, TransientSubmissionException {
    new Thread() {
        public void run() {
            boolean isA2 = isA2(null, assignmentRef);
            String assignmentId = getAssignmentId(assignmentRef, isA2);
            Map<String, ContentResource> attachmentsMap = new HashMap<String, ContentResource>();
            if (assignmentId != null) {
                AssignmentData assignmentData = new AssignmentData();
                if (opts != null) {
                    if (opts.containsKey("title")) {
                        assignmentData.setAssignmentTitle(opts.get("title").toString());
                    } else if (!isA2) {
                        //we can find the title from the assignment ref for A1
                        String assignmentTitle = getAssignmentTitle(assignmentRef);
                        if (assignmentTitle != null) {
                            assignmentData.setAssignmentTitle(assignmentTitle);
                        }/*from w w w  .j a  v a 2s .  co  m*/
                    }
                    if (opts.containsKey("instructions")) {
                        assignmentData.setAssignmentInstructions(opts.get("instructions").toString());
                    }
                    if (opts.containsKey("exclude_quoted")) {
                        assignmentData
                                .setAssignmentExcludeQuotes("1".equals(opts.get("exclude_quoted").toString()));
                    }
                    if (opts.containsKey("exclude_self_plag")) {
                        assignmentData.setAssignmentExcludeSelfPlag(
                                "1".equals(opts.get("exclude_self_plag").toString()));
                    }
                    if (opts.containsKey("store_inst_index")) {
                        assignmentData
                                .setAssignmentStoreInIndex("1".equals(opts.get("store_inst_index").toString()));
                    }
                    if (opts.containsKey("dtdue")) {
                        SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance());
                        dform.applyPattern("yyyy-MM-dd HH:mm:ss");
                        try {
                            Date dueDate = dform.parse(opts.get("dtdue").toString());
                            if (dueDate != null) {
                                assignmentData.setAssignmentDueDate(dueDate.getTime());
                            }
                        } catch (ParseException e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                    //Pass in 0 to delete a grade, otherwise, set the grade.
                    assignmentData.setAssignmentGrade(0);
                    if (opts.containsKey("points")) {
                        //points are stored as integers and multiplied by 100 (i.e. 5.5 = 550; 1 = 100, etc)
                        try {
                            Integer points = Integer.parseInt(opts.get("points").toString()) / 100;
                            assignmentData.setAssignmentGrade(points);
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                    if (opts.containsKey("attachments") && opts.get("attachments") instanceof List) {
                        SecurityAdvisor yesMan = new SecurityAdvisor() {
                            public SecurityAdvice isAllowed(String arg0, String arg1, String arg2) {
                                return SecurityAdvice.ALLOWED;
                            }
                        };
                        securityService.pushAdvisor(yesMan);
                        try {
                            List<ExternalContentData> attachments = new ArrayList<ExternalContentData>();
                            for (String refStr : (List<String>) opts.get("attachments")) {
                                try {
                                    Reference ref = entityManager.newReference(refStr);
                                    ContentResource res = (ContentResource) ref.getEntity();
                                    if (res != null) {
                                        ExternalContentData attachment = new ExternalContentData();
                                        String fileName = res.getProperties()
                                                .getProperty(ResourceProperties.PROP_DISPLAY_NAME);
                                        attachment.setFileName(FilenameUtils.getBaseName(fileName));
                                        attachment.setExternalContentID(getAssignmentAttachmentId(consumer,
                                                contextId, assignmentId, res.getId()));
                                        attachment.setUploadContentLength((int) res.getContentLength());
                                        attachment.setUploadContentType(FilenameUtils.getExtension(fileName));
                                        attachments.add(attachment);
                                        attachmentsMap.put(attachment.getExternalContentID(), res);
                                    }
                                } catch (Exception e) {
                                    log.error(e.getMessage(), e);
                                }
                            }
                            if (attachments.size() > 0) {
                                assignmentData.setAssignmentAttachmentExternalContent(attachments);
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        } finally {
                            securityService.popAdvisor(yesMan);
                        }
                    }
                }
                DefaultApi vericiteApi = getVeriCiteAPI();
                try {
                    List<ExternalContentUploadInfo> uploadInfo = vericiteApi
                            .assignmentsContextIDAssignmentIDPost(contextId, assignmentId, consumer,
                                    consumerSecret, assignmentData);
                    //see if there are any attachment presigned urls to upload to
                    if (uploadInfo != null) {
                        //see if this attachment needs uploaded:
                        for (ExternalContentUploadInfo info : uploadInfo) {
                            if (attachmentsMap.containsKey(info.getExternalContentId())) {
                                //upload this attachment
                                ContentResource res = attachmentsMap.get(info.getExternalContentId());
                                try {
                                    uploadExternalContent(info.getUrlPost(), res.getContent());
                                } catch (ServerOverloadException e) {
                                    log.error(e.getMessage(), e);
                                }
                            }
                        }
                    }
                } catch (ApiException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }.start();
}

From source file:com.rr.generic.ui.reports.reportController.java

/**
 * /*w ww.  j a  v  a 2  s.co m*/
 * @param surveyId
 * @param session
 * @param request
 * @return
 * @throws Exception 
 */
@RequestMapping(value = "/saveParticipantReport.do", method = RequestMethod.POST)
public ModelAndView saveReport(@ModelAttribute(value = "reportDetails") reportRequest reportDetails,
        @RequestParam List<Integer> selectedSites, BindingResult errors, HttpSession session,
        HttpServletRequest request) throws Exception {

    if (errors.hasErrors()) {
        for (ObjectError error : errors.getAllErrors()) {
            System.out.println(error.getDefaultMessage());
        }
    }

    User userDetails = (User) session.getAttribute("userDetails");

    SimpleDateFormat datesearchFormat = new SimpleDateFormat("MM/dd/yyyy");
    Date startDate = datesearchFormat.parse(reportDetails.getStartDate());
    Date endDate = datesearchFormat.parse(reportDetails.getEndDate());

    datesearchFormat.applyPattern("yyyy-MM-dd");

    String realStartDate = datesearchFormat.format(startDate);
    String realEndDate = datesearchFormat.format(endDate);

    String reportFileName = "";

    String registryName = programmanager.getProgramById(programId).getProgramName().replaceAll(" ", "-")
            .toLowerCase();

    /* Get the client engagements */
    List<engagements> engagements = engagementmanager.getEngagementByMultipleEntity(programId, selectedSites,
            realStartDate, realEndDate);

    Integer reportRequestId = 0;

    /* Loop through sessions here */
    if (engagements != null && engagements.size() > 0) {

        reportDetails.setProgramId(programId);
        reportDetails.setSystemUserId(userDetails.getId());
        reportDetails.setSelectedDateRange(reportDetails.getStartDate() + " - " + reportDetails.getEndDate());
        reportDetails.setStartDateTime(startDate);
        reportDetails.setEndDateTime(endDate);

        reportRequestId = reportmanager.saveReportRequest(reportDetails);

        if (selectedSites != null && !"".equals(selectedSites)) {
            StringBuilder selectedSiteNames = new StringBuilder();
            for (Integer site : selectedSites) {
                programHierarchyDetails siteDetails = hierarchymanager.getProgramHierarchyItemDetails(site);

                reportRequestEntity reportSite = new reportRequestEntity();
                reportSite.setSiteName(siteDetails.getName());
                reportSite.setReportRequestId(reportRequestId);
                reportSite.setEntity3Id(site);

                reportmanager.saveReportRequestEntity(reportSite);
            }
        }

        progressBar newProgressBar = new progressBar();
        newProgressBar.setExportId(reportDetails.getUniqueId());
        newProgressBar.setPercentComplete(0);

        reportmanager.saveProgessBar(newProgressBar);

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
        Date date = new Date();
        String fileName = "";
        String delimiter = ",";

        if (reportDetails.getFileTypeId() == 1) {
            fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date))
                    .append(".csv").toString();
            delimiter = ",";
        } else if (reportDetails.getFileTypeId() == 2) {
            fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date))
                    .append(".txt").toString();
            delimiter = ",";
        } else if (reportDetails.getFileTypeId() == 3) {
            fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date))
                    .append(".txt").toString();
            delimiter = "|";
        } else if (reportDetails.getFileTypeId() == 4) {
            fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date))
                    .append(".txt").toString();
            delimiter = "\t";
        }

        /* Create new export file */
        InputStream inputStream = null;
        OutputStream outputStream = null;

        fileSystem dir = new fileSystem();
        dir.setDir(registryName, "reports");

        File newFile = new File(dir.getDir() + fileName);

        /* Create the empty file in the correct location */
        try {

            if (newFile.exists()) {
                int i = 1;
                while (newFile.exists()) {
                    int iDot = fileName.lastIndexOf(".");
                    newFile = new File(dir.getDir() + fileName.substring(0, iDot) + "_(" + ++i + ")"
                            + fileName.substring(iDot));
                }
                fileName = newFile.getName();
                newFile.createNewFile();
            } else {
                newFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        /* Read in the file */
        FileInputStream fileInput = null;
        File file = new File(dir.getDir() + fileName);
        fileInput = new FileInputStream(file);

        reportFileName = fileName;

        FileWriter fw = null;

        try {
            fw = new FileWriter(file, true);
        } catch (IOException ex) {
            Logger.getLogger(exportManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        reportDetails.setReportFileName(reportFileName);
        reportmanager.updateReportRequest(reportDetails);

        StringBuilder reportRow = new StringBuilder();
        reportRow.append("ORGCODE").append(delimiter);
        reportRow.append("PARTICIP").append(delimiter);
        reportRow.append("STATE").append(delimiter);
        reportRow.append("GLUCTEST").append(delimiter);
        reportRow.append("GDM").append(delimiter); /* P */
        reportRow.append("RISKTEST").append(delimiter); /* P */
        reportRow.append("AGE").append(delimiter); /* P */
        reportRow.append("ETHNIC").append(delimiter); /* P */
        reportRow.append("AIAN").append(delimiter); /* P */
        reportRow.append("ASIAN").append(delimiter); /* P */
        reportRow.append("BLACK").append(delimiter); /* P */
        reportRow.append("NHOPI").append(delimiter); /* P */
        reportRow.append("WHITE").append(delimiter); /* P */
        reportRow.append("SEX").append(delimiter); /* P */
        reportRow.append("HEIGHT").append(delimiter);
        reportRow.append("DATE").append(delimiter);
        reportRow.append("WEIGHT").append(delimiter);
        reportRow.append("PA").append(delimiter);

        reportRow.append(System.getProperty("line.separator"));

        fw.write(reportRow.toString());

        Integer participantId = 0;

        List<programExportFields> exportFields = programmanager.getProgramExportFields(programId);

        List<String> tableinfo = new ArrayList<String>();

        Integer fieldId = 0;
        Integer customFieldId = 0;
        Integer validationValue = 0;
        String fieldTypeValue = "";
        Integer crosswalkId = 0;

        for (programExportFields field : exportFields) {

            if (field.getFieldType() == 1) {
                fieldTypeValue = "1";
                programClientFields fieldDetails = clientmanager.getClientFieldDetails(programId,
                        field.getFieldId());
                fieldId = fieldDetails.getFieldId();
                customFieldId = fieldDetails.getCustomfieldId();
                validationValue = fieldDetails.getValidationId();
                crosswalkId = fieldDetails.getCrosswalkId();
            } else {
                fieldTypeValue = "2";
                programEngagementFields fieldDetails = engagementmanager.getEngagementFieldDetails(programId,
                        field.getFieldId());
                fieldId = fieldDetails.getFieldId();
                customFieldId = fieldDetails.getCustomfieldId();
                validationValue = fieldDetails.getValidationId();
                crosswalkId = fieldDetails.getCrosswalkId();
            }

            if (fieldId > 0) {
                dataElements fieldDetails = clientmanager.getFieldDetails(fieldId);
                tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTableName() + "-"
                        + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId);
            }

            else if (customFieldId > 0) {
                customProgramFields fieldDetails = clientmanager.getCustomFieldDetails(customFieldId);
                tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTable() + "-"
                        + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId);
            }
        }

        Integer totalDone = 0;
        float percentComplete;

        progressBar reportProgressBar = reportmanager.getProgressBar(reportDetails.getUniqueId());

        for (engagements engagement : engagements) {

            reportRow = new StringBuilder();

            programHierarchyDetails hierarchyDetails = hierarchymanager.getProgramHierarchyItemDetails(
                    clientmanager.getClientEntities(engagement.getProgramPatientId()).getEntity3Id());

            String siteDisplayId = "";

            if (hierarchyDetails.getDisplayId() != null) {
                siteDisplayId = hierarchyDetails.getDisplayId();
            }

            reportRow.append(siteDisplayId).append(delimiter);

            if (tableinfo != null & tableinfo.size() > 0) {
                for (String table : tableinfo) {
                    String[] tableInfoArray = table.split("-");
                    String fieldValue = "";
                    String fieldType = tableInfoArray[0];
                    String tablename = tableInfoArray[1];
                    String tableCol = tableInfoArray[2];
                    String validation = tableInfoArray[3];
                    String crosswalk = tableInfoArray[4];

                    if ("1".equals(fieldType)) {
                        fieldValue = clientmanager.getTableData(tablename, tableCol,
                                engagement.getProgramPatientId());
                    } else {
                        fieldValue = engagementmanager.getTableData(tablename, tableCol, engagement.getId(),
                                engagement.getProgramPatientId());
                    }

                    if (!"".equals(crosswalk) && !"0".equals(crosswalk)) {
                        crosswalkData cwData = clientmanager
                                .getCrosswalkDataByTarget(Integer.parseInt(crosswalk), fieldValue);
                        if (cwData != null) {
                            fieldValue = cwData.getDescValue();
                        } else {
                            fieldValue = "";
                        }
                    }

                    /* If date format to correct display format */
                    if ("4".equals(validation)) {
                        if ("dob".equals(tableCol)) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            Date dob = format.parse(fieldValue);
                            Date today = new Date();

                            format.applyPattern("yyyy");
                            String dobAsString = format.format(dob);
                            String todayAsString = format.format(today);

                            Integer age = Integer.parseInt(todayAsString) - Integer.parseInt(dobAsString);
                            reportRow.append(age).append(delimiter);
                        } else {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            Date formatedDate = format.parse(fieldValue);
                            format.applyPattern("MM/dd/yy");
                            reportRow.append(format.format(formatedDate)).append(delimiter);
                        }
                    } else {
                        reportRow.append(fieldValue).append(delimiter);
                    }
                }
            }

            reportRow.append(System.getProperty("line.separator"));
            fw.write(reportRow.toString());

            //Update progress bar
            totalDone = totalDone + 1;
            percentComplete = ((float) totalDone) / engagements.size();
            reportProgressBar.setPercentComplete(Math.round(percentComplete * 100));
            reportmanager.saveProgessBar(reportProgressBar);

        }

        fw.close();
    }

    ModelAndView mav = new ModelAndView();

    /* If no results are found */
    if (reportFileName.isEmpty()) {
        mav.setViewName("/reports/reportModal");

        savedExports newexportDetails = new savedExports();
        reportDetails.setFileTypeId(1);

        programOrgHierarchy level1 = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId);
        programOrgHierarchy level2 = hierarchymanager.getProgramOrgHierarchyBydspPos(2, programId);
        programOrgHierarchy level3 = hierarchymanager.getProgramOrgHierarchyBydspPos(3, programId);

        List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(),
                userDetails.getId());
        mav.addObject("level1Items", level1Items);

        mav.addObject("level1Name", level1.getName());
        mav.addObject("level2Name", level2.getName());
        mav.addObject("level3Name", level3.getName());

        mav.addObject("exportDetails", newexportDetails);
        mav.addObject("showDateRange", true);
        mav.addObject("noresults", true);
    } else {
        if (reportDetails.getUniqueId() > 0) {
            /* Delete progress bar entry */
            reportmanager.deleteProgressBar(reportDetails.getUniqueId());
        }

        mav.setViewName("/reports/reportDownloadModal");
        mav.addObject("reportFileName", reportFileName);
    }

    return mav;
}

From source file:com.rr.wabshs.ui.importexport.importExportController.java

/**
 * //from   w w  w .  j  a v  a2 s. c o  m
 * @param surveyId
 * @param session
 * @param request
 * @return
 * @throws Exception 
 */
@RequestMapping(value = "/saveParticipantExport.do", method = RequestMethod.POST)
public ModelAndView saveExport(@ModelAttribute(value = "exportDetails") savedExports exportDetails,
        @RequestParam List<Integer> selectedSites, BindingResult errors, HttpSession session,
        HttpServletRequest request) throws Exception {

    if (errors.hasErrors()) {
        for (ObjectError error : errors.getAllErrors()) {
            System.out.println(error.getDefaultMessage());
        }
    }

    User userDetails = (User) session.getAttribute("userDetails");

    SimpleDateFormat datesearchFormat = new SimpleDateFormat("MM/dd/yyyy");
    Date startDate = datesearchFormat.parse(exportDetails.getStartDate());
    Date endDate = datesearchFormat.parse(exportDetails.getEndDate());

    datesearchFormat.applyPattern("yyyy-MM-dd");

    String realStartDate = datesearchFormat.format(startDate);
    String realEndDate = datesearchFormat.format(endDate);

    String exportFileName = "";

    String registryName = programmanager.getProgramById(programId).getProgramName().replaceAll(" ", "-")
            .toLowerCase();

    /* Get the client engagements */
    List<engagements> engagements = engagementmanager.getEngagementByMultipleEntity(programId, selectedSites,
            realStartDate, realEndDate);

    Integer exportId = 0;

    /* Loop through sessions here */
    if (engagements != null && engagements.size() > 0) {

        exportDetails.setProgramId(programId);
        exportDetails.setSystemUserId(userDetails.getId());
        exportDetails.setSelectedDateRange(exportDetails.getStartDate() + " - " + exportDetails.getEndDate());
        exportDetails.setDownloadType(1);
        exportDetails.setTotalRecords(engagements.size());

        exportId = exportManager.saveExport(exportDetails);

        if (selectedSites != null && !"".equals(selectedSites)) {
            StringBuilder selectedSiteNames = new StringBuilder();
            for (Integer site : selectedSites) {
                programHierarchyDetails siteDetails = hierarchymanager.getProgramHierarchyItemDetails(site);

                savedExportSites exportSite = new savedExportSites();
                exportSite.setExportId(exportId);
                exportSite.setSiteName(siteDetails.getName());
                exportSite.setSiteId(site);

                exportManager.saveExportSite(exportSite);
            }
        }

        progressBar newProgressBar = new progressBar();
        newProgressBar.setExportId(exportDetails.getUniqueId());
        newProgressBar.setPercentComplete(0);

        exportManager.saveProgessBar(newProgressBar);

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
        Date date = new Date();
        String fileName = "";
        String delimiter = ",";

        if (exportDetails.getExportType() == 1) {
            fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".csv")
                    .toString();
            delimiter = ",";
        } else if (exportDetails.getExportType() == 2) {
            fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".txt")
                    .toString();
            delimiter = ",";
        } else if (exportDetails.getExportType() == 3) {
            fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".txt")
                    .toString();
            delimiter = "|";
        } else if (exportDetails.getExportType() == 4) {
            fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".txt")
                    .toString();
            delimiter = "\t";
        }

        /* Create new export file */
        InputStream inputStream = null;
        OutputStream outputStream = null;

        fileSystem dir = new fileSystem();
        dir.setDir(registryName, "exportFiles");

        File newFile = new File(dir.getDir() + fileName);

        /* Create the empty file in the correct location */
        try {

            if (newFile.exists()) {
                int i = 1;
                while (newFile.exists()) {
                    int iDot = fileName.lastIndexOf(".");
                    newFile = new File(dir.getDir() + fileName.substring(0, iDot) + "_(" + ++i + ")"
                            + fileName.substring(iDot));
                }
                fileName = newFile.getName();
                newFile.createNewFile();
            } else {
                newFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        /* Read in the file */
        FileInputStream fileInput = null;
        File file = new File(dir.getDir() + fileName);
        fileInput = new FileInputStream(file);

        exportFileName = fileName;

        FileWriter fw = null;

        try {
            fw = new FileWriter(file, true);
        } catch (IOException ex) {
            Logger.getLogger(exportManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        exportDetails.setExportFile(exportFileName);
        exportManager.saveExport(exportDetails);

        StringBuilder exportRow = new StringBuilder();
        exportRow.append("PATIENT NUMBER").append(delimiter);
        exportRow.append("FIRST NAME").append(delimiter);
        exportRow.append("LAST NAME").append(delimiter);
        exportRow.append("DOB").append(delimiter);
        exportRow.append("GENDER").append(delimiter); /* P */
        exportRow.append("VISIT DATE").append(delimiter); /* P */
        exportRow.append("WEIGHT").append(delimiter); /* P */
        exportRow.append("HEIGHT").append(delimiter); /* P */
        exportRow.append("BP SYSTOLIC").append(delimiter); /* P */
        exportRow.append("BP DIASTOLIC").append(delimiter); /* P */

        exportRow.append(System.getProperty("line.separator"));

        fw.write(exportRow.toString());

        Integer participantId = 0;

        List<programExportFields> exportFields = programmanager.getProgramExportFields(programId);

        List<String> tableinfo = new ArrayList<String>();

        Integer fieldId = 0;
        Integer customFieldId = 0;
        Integer validationValue = 0;
        String fieldTypeValue = "";
        Integer crosswalkId = 0;

        for (programExportFields field : exportFields) {

            if (field.getFieldType() == 1) {
                fieldTypeValue = "1";
                programClientFields fieldDetails = clientmanager.getClientFieldDetails(programId,
                        field.getFieldId());
                fieldId = fieldDetails.getFieldId();
                customFieldId = fieldDetails.getCustomfieldId();
                validationValue = fieldDetails.getValidationId();
                crosswalkId = fieldDetails.getCrosswalkId();
            } else {
                fieldTypeValue = "2";
                programEngagementFields fieldDetails = engagementmanager.getEngagementFieldDetails(programId,
                        field.getFieldId());
                fieldId = fieldDetails.getFieldId();
                customFieldId = fieldDetails.getCustomfieldId();
                validationValue = fieldDetails.getValidationId();
                crosswalkId = fieldDetails.getCrosswalkId();
            }

            if (fieldId > 0) {
                dataElements fieldDetails = clientmanager.getFieldDetails(fieldId);
                tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTableName() + "-"
                        + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId);
            }

            else if (customFieldId > 0) {
                customProgramFields fieldDetails = clientmanager.getCustomFieldDetails(customFieldId);
                tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTable() + "-"
                        + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId);
            }
        }

        Integer totalDone = 0;
        float percentComplete;

        progressBar exportProgressBar = exportManager.getProgressBar(exportDetails.getUniqueId());

        for (engagements engagement : engagements) {

            exportRow = new StringBuilder();

            programHierarchyDetails hierarchyDetails = hierarchymanager.getProgramHierarchyItemDetails(
                    clientmanager.getClientEntities(engagement.getProgramPatientId()).getEntity3Id());

            String siteDisplayId = "";

            if (hierarchyDetails.getDisplayId() != null) {
                siteDisplayId = hierarchyDetails.getDisplayId();
            }

            //exportRow.append(siteDisplayId).append(delimiter);

            if (tableinfo != null & tableinfo.size() > 0) {
                for (String table : tableinfo) {
                    String[] tableInfoArray = table.split("-");
                    String fieldValue = "";
                    String fieldType = tableInfoArray[0];
                    String tablename = tableInfoArray[1];
                    String tableCol = tableInfoArray[2];
                    String validation = tableInfoArray[3];
                    String crosswalk = tableInfoArray[4];

                    if ("1".equals(fieldType)) {
                        fieldValue = clientmanager.getTableData(tablename, tableCol,
                                engagement.getProgramPatientId());
                    } else {
                        fieldValue = engagementmanager.getTableData(tablename, tableCol, engagement.getId(),
                                engagement.getProgramPatientId());
                    }

                    if ("55".equals(crosswalk) && "0".equals(fieldValue)) {
                        fieldValue = "2";
                    }

                    /* If date format to correct display format */
                    if ("4".equals(validation)) {
                        if ("dob".equals(tableCol)) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            Date dob = format.parse(fieldValue);
                            Date today = new Date();

                            format.applyPattern("yyyy");
                            String dobAsString = format.format(dob);
                            String todayAsString = format.format(today);

                            Integer age = Integer.parseInt(todayAsString) - Integer.parseInt(dobAsString);
                            exportRow.append(age).append(delimiter);
                        } else {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            Date formatedDate = format.parse(fieldValue);
                            format.applyPattern("MM/dd/yy");
                            exportRow.append(format.format(formatedDate)).append(delimiter);
                        }
                    } else {
                        exportRow.append(fieldValue).append(delimiter);
                    }
                }
            }

            exportRow.append(System.getProperty("line.separator"));
            fw.write(exportRow.toString());

            //Update progress bar
            totalDone = totalDone + 1;
            percentComplete = ((float) totalDone) / engagements.size();
            exportProgressBar.setPercentComplete(Math.round(percentComplete * 100));
            exportManager.saveProgessBar(exportProgressBar);

        }

        fw.close();
    }

    ModelAndView mav = new ModelAndView();

    /* If no results are found */
    if (exportFileName.isEmpty()) {
        mav.setViewName("/importExport/exportModal");

        savedExports newexportDetails = new savedExports();
        exportDetails.setExportType(1);

        programOrgHierarchy level1 = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId);
        programOrgHierarchy level2 = hierarchymanager.getProgramOrgHierarchyBydspPos(2, programId);
        programOrgHierarchy level3 = hierarchymanager.getProgramOrgHierarchyBydspPos(3, programId);

        Integer userId;
        if (userDetails.getRoleId() == 2) {
            userId = 0;
        } else {
            userId = userDetails.getId();
        }

        List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(),
                userId);
        mav.addObject("level1Items", level1Items);

        mav.addObject("level1Name", level1.getName());
        mav.addObject("level2Name", level2.getName());
        mav.addObject("level3Name", level3.getName());

        mav.addObject("exportDetails", newexportDetails);
        mav.addObject("showDateRange", true);
        mav.addObject("noresults", true);
    } else {
        if (exportDetails.getUniqueId() > 0) {
            /* Delete progress bar entry */
            exportManager.deleteProgressBar(exportDetails.getUniqueId());
        }

        mav.setViewName("/importExport/exportDownloadModal");
        mav.addObject("exportFileName", exportFileName);
    }

    return mav;
}

From source file:org.sakaiproject.contentreview.impl.compilatio.CompilatioReviewServiceImpl.java

@SuppressWarnings({ "deprecation" })
@Override/*from  w  w  w  . j av  a 2  s . com*/
public void checkForReports() {
    SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance());
    dform.applyPattern(COMPILATIO_DATETIME_FORMAT);

    log.info("Fetching reports from Compilatio");

    // get the list of all items that are waiting for reports
    Search search = new Search();
    search.setConjunction(false); //OR clauses
    search.addRestriction(new Restriction("status", ContentReviewItem.SUBMITTED_AWAITING_REPORT_CODE));
    search.addRestriction(new Restriction("status", ContentReviewItem.REPORT_ERROR_RETRY_CODE));
    List<ContentReviewItem> awaitingReport = dao.findBySearch(ContentReviewItem.class, search);

    Iterator<ContentReviewItem> listIterator = awaitingReport.iterator();

    log.debug("There are " + awaitingReport.size() + " submissions awaiting reports");

    int errors = 0;
    int success = 0;
    int inprogress = 0;
    ContentReviewItem currentItem;
    while (listIterator.hasNext()) {
        currentItem = (ContentReviewItem) listIterator.next();

        // has the item reached its next retry time?
        if (currentItem.getNextRetryTime() == null) {
            currentItem.setNextRetryTime(new Date());
        }

        if (currentItem.getNextRetryTime().after(new Date())) {
            // we haven't reached the next retry time
            log.info("checkForReports :: next retry time not yet reached for item: " + currentItem.getId());
            dao.update(currentItem);
            continue;
        }

        if (!processItem(currentItem)) {
            errors++;
            continue;
        }

        //back to analysis (this should not happen)
        if (StringUtils.isBlank(currentItem.getExternalId())) {
            currentItem.setStatus(Long.valueOf(ContentReviewItem.SUBMISSION_ERROR_RETRY_CODE));
            dao.update(currentItem);
            errors++;
            continue;
        }

        // get the list from compilatio and see if the review is
        // available

        log.debug("Attempting to update hashtable with reports for site " + currentItem.getSiteId());

        Map<String, String> params = CompilatioAPIUtil.packMap("action", "getDocument", "idDocument",
                currentItem.getExternalId());

        Document document = null;
        try {
            document = compilatioConn.callCompilatioReturnDocument(params);
        } catch (TransientSubmissionException | SubmissionException e) {
            log.warn("Update failed : " + e.toString(), e);
            processError(currentItem, ContentReviewItem.REPORT_ERROR_RETRY_CODE, e.getMessage(), null);
            errors++;
            continue;
        }

        Element root = document.getDocumentElement();
        if (root.getElementsByTagName("documentStatus").item(0) != null) {
            log.debug("Report list returned successfully");

            NodeList objects = root.getElementsByTagName("documentStatus");
            log.debug(objects.getLength() + " objects in the returned list");

            String status = getNodeValue("status", root);

            if ("ANALYSE_NOT_STARTED".equals(status)) {
                //send back to the process queue, we need no analyze it again
                processError(currentItem, ContentReviewItem.SUBMISSION_ERROR_RETRY_CODE, "ANALYSE_NOT_STARTED",
                        null);
                errors++;
                continue;
            } else if ("ANALYSE_COMPLETE".equals(status)) {
                String reportVal = getNodeValue("indice", root);
                currentItem.setReviewScore((int) Math.round(Double.parseDouble(reportVal)));
                currentItem.setStatus(ContentReviewItem.SUBMITTED_REPORT_AVAILABLE_CODE);
                success++;
            } else {
                String progression = getNodeValue("progression", root);
                if (StringUtils.isNotBlank(progression)) {
                    currentItem.setReviewScore((int) Double.parseDouble(progression));
                    inprogress++;
                }
            }
            currentItem.setDateReportReceived(new Date());
            dao.update(currentItem);
            log.debug("new report received: " + currentItem.getExternalId() + " -> "
                    + currentItem.getReviewScore());

        } else {
            log.debug("Report list request not successful");
            log.debug(document.getTextContent());

        }
    }

    log.info("Finished fetching reports from Compilatio : " + success + " success items, " + inprogress
            + " in progress, " + errors + " errors");
}