Example usage for org.joda.time DateTime getMonthOfYear

List of usage examples for org.joda.time DateTime getMonthOfYear

Introduction

In this page you can find the example usage for org.joda.time DateTime getMonthOfYear.

Prototype

public int getMonthOfYear() 

Source Link

Document

Get the month of year field value.

Usage

From source file:org.ecocean.servlet.importer.ImportSRGD.java

License:Open Source License

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String context = "context0";
    context = ServletUtilities.getContext(request);
    Shepherd myShepherd = new Shepherd(context);
    myShepherd.setAction("ImportSRGD");
    System.out.println("\n\nStarting ImportSRGD servlet...");

    //setup data dir
    String rootWebappPath = getServletContext().getRealPath("/");
    File webappsDir = new File(rootWebappPath).getParentFile();
    File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName(context));
    if (!shepherdDataDir.exists()) {
        shepherdDataDir.mkdirs();/*from  w w  w. j a v  a2  s  .c  o  m*/
    }
    File tempSubdir = new File(webappsDir, "temp");
    if (!tempSubdir.exists()) {
        tempSubdir.mkdirs();
    }
    System.out.println("\n\n     Finished directory creation...");

    //set up for response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    boolean locked = false;

    String fileName = "None";

    StringBuffer messages = new StringBuffer();

    boolean successfullyWroteFile = false;

    File finalFile = new File(tempSubdir, "temp.csv");

    try {
        MultipartParser mp = new MultipartParser(request,
                (CommonConfiguration.getMaxMediaSizeInMegabytes(context) * 1048576));
        Part part;
        while ((part = mp.readNextPart()) != null) {
            String name = part.getName();
            if (part.isParam()) {

                // it's a parameter part
                ParamPart paramPart = (ParamPart) part;
                String value = paramPart.getStringValue();

            }

            if (part.isFile()) {
                FilePart filePart = (FilePart) part;
                fileName = ServletUtilities.cleanFileName(filePart.getFileName());
                if (fileName != null) {
                    System.out.println("     Trying to upload file: " + fileName);
                    //File thisSharkDir = new File(encountersDir.getAbsolutePath() +"/"+ encounterNumber);
                    //if(!thisSharkDir.exists()){thisSharkDir.mkdirs();}
                    finalFile = new File(tempSubdir, fileName);
                    filePart.writeTo(finalFile);
                    successfullyWroteFile = true;
                    System.out.println("\n\n     I successfully uploaded the file!");
                }
            }
        }

        try {
            if (successfullyWroteFile) {

                System.out.println("\n\n     Starting CSV content import...");

                //OK, we have our CSV file
                //let's import
                CSVReader reader = new CSVReader(new FileReader(finalFile));
                List<String[]> allLines = reader.readAll();
                System.out.println("\n\n     Read in the CSV file!");

                //let's detect the size of this array by reading the number of header columns in row 0
                String[] headerNames = allLines.get(0);
                int numColumns = headerNames.length;
                int numRows = allLines.size();

                //determine the Occurrence_ID column as it is at the end
                int occurrenceIDColumnNumber = -1;
                for (int g = 0; g < numColumns; g++) {
                    if (headerNames[g].equals("Occurrence_ID")) {
                        occurrenceIDColumnNumber = g;
                    }
                }

                for (int i = 1; i < numRows; i++) {

                    System.out.println("\n\n     Processing row " + i);
                    boolean newEncounter = true;
                    boolean newShark = true;
                    String[] line = allLines.get(i);

                    boolean ok2import = true;

                    Encounter enc = new Encounter();

                    myShepherd.beginDBTransaction();

                    //line[0] is the sample_ID
                    String encNumber = line[0].trim();
                    if ((encNumber != null) && (!encNumber.equals(""))) {
                        if (myShepherd.isEncounter(encNumber)) {
                            enc = myShepherd.getEncounter(encNumber);
                            newEncounter = false;
                        } else {
                            enc.setCatalogNumber(encNumber);
                            enc.setState("approved");
                        }
                    } else {
                        ok2import = false;
                        messages.append("<li>Row " + i
                                + ": could not find sample/encounter ID in the first column of row " + i
                                + ".</li>");
                        System.out.println(
                                "          Could not find sample/encounter ID in the first column of row " + i
                                        + ".");
                    }

                    //line[1] is the IndividualID
                    String individualID = line[1].trim();
                    if (individualID != null) {

                        enc.addComments("<p><em>" + request.getRemoteUser() + " on "
                                + (new java.util.Date()).toString() + "</em><br>"
                                + "Import SRGD process set marked individual to " + individualID + ".</p>");

                        //enc.setIndividualID(individualID);
                        System.out.println(
                                "          Setting Individual ID for row " + i + ". Value: " + individualID);

                    }

                    //line[2] is the latitude
                    String latitude = line[2].trim();
                    if ((latitude != null) && (!latitude.equals(""))) {
                        try {

                            enc.addComments("<p><em>" + request.getRemoteUser() + " on "
                                    + (new java.util.Date()).toString() + "</em><br>"
                                    + "Import SRGD process set latitude to " + latitude + ".</p>");

                            Double lat = new Double(latitude);
                            enc.setDecimalLatitude(lat);
                            System.out.println(
                                    "          Setting latitude for row " + i + ". Value: " + latitude);

                        } catch (NumberFormatException nfe) {
                            messages.append("<li>Row " + i + " for sample ID " + enc.getCatalogNumber()
                                    + ": Latitude hit a NumberFormatException in row " + i
                                    + " and could not be imported. The listed value was: " + latitude
                                    + "</li>");
                        }
                    }

                    //line[3] is the latitude
                    String longitude = line[3].trim();
                    if ((longitude != null) && (!longitude.equals(""))) {
                        try {

                            enc.addComments("<p><em>" + request.getRemoteUser() + " on "
                                    + (new java.util.Date()).toString() + "</em><br>"
                                    + "Import SRGD process set longitude to " + longitude + ".</p>");

                            Double longie = new Double(longitude);
                            enc.setDecimalLongitude(longie);
                            System.out.println(
                                    "          Setting longitude for row " + i + ". Value: " + longitude);

                        } catch (NumberFormatException nfe) {
                            nfe.printStackTrace();
                            messages.append("<li>Row " + i + " for sample ID " + enc.getCatalogNumber()
                                    + ": Longitude hit a NumberFormatException in row " + i
                                    + " and could not be imported. The listed value was: " + longitude
                                    + "</li>");
                        }
                    }

                    //line[4] is the date_time
                    String isoDate = line[4].trim();
                    if ((isoDate != null) && (!isoDate.equals(""))) {

                        StringTokenizer tks = new StringTokenizer(isoDate, "-");
                        int numTokens = tks.countTokens();
                        DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeParser();

                        enc.setMonth(-1);
                        enc.setDay(-1);
                        enc.setYear(-1);
                        enc.setHour(-1);
                        enc.setMinutes("00");

                        try {
                            DateTime time = parser2.parseDateTime(isoDate);
                            enc.setYear(time.getYear());

                            if (numTokens >= 2) {
                                enc.setMonth(time.getMonthOfYear());
                            }
                            if (numTokens >= 3) {
                                enc.setDay(time.getDayOfMonth());
                            }

                            if (isoDate.indexOf("T") != -1) {
                                int minutes = time.getMinuteOfHour();
                                String minutes2 = (new Integer(minutes)).toString();
                                if ((time.getHourOfDay() != 0) && (minutes != 0)) {
                                    enc.setHour(time.getHourOfDay());
                                    if (isoDate.indexOf(":") != -1) {
                                        enc.setMinutes(minutes2);
                                    }
                                }
                            }

                            enc.addComments("<p><em>" + request.getRemoteUser() + " on "
                                    + (new java.util.Date()).toString() + "</em><br>"
                                    + "Import SRGD process set date to " + enc.getDate() + ".</p>");

                            System.out.println("          Set date for encounter: " + enc.getDate());

                        } catch (IllegalArgumentException iae) {
                            iae.printStackTrace();
                            messages.append("<li>Row " + i + ": could not import the date and time for row: "
                                    + i + ". Cancelling the import for this row.</li>");
                            ok2import = false;

                        }
                    }

                    //line[5] get locationID
                    String locationID = line[5].trim();
                    if (line.length >= 6) {
                        if ((locationID != null) && (!locationID.equals(""))) {
                            enc.setLocationID(locationID);
                            enc.addComments("<p><em>" + request.getRemoteUser() + " on "
                                    + (new java.util.Date()).toString() + "</em><br>"
                                    + "Import SRGD process set location ID to " + locationID + ".</p>");

                            System.out.println(
                                    "          Setting location ID for row " + i + ". Value: " + locationID);
                        }
                    }

                    //line[6] get sex
                    String sex = line[6].trim();
                    if (line.length >= 7) {
                        if ((sex != null) && (!sex.equals(""))) {

                            if (sex.equals("M")) {
                                enc.setSex("male");
                            } else if (sex.equals("F")) {
                                enc.setSex("female");
                            } else {
                                enc.setSex("unknown");
                            }

                            System.out.println("          Setting sex for row " + i + ". Value: " + sex);
                            enc.addComments("<p><em>" + request.getRemoteUser() + " on "
                                    + (new java.util.Date()).toString() + "</em><br>"
                                    + "Import SRGD process set sex to " + enc.getSex() + ".</p>");

                        }

                        //line[occurrenceIDColumnNumber] get Occurrence_ID
                        Occurrence occur = new Occurrence();
                        if (occurrenceIDColumnNumber != -1) {
                            String occurID = line[occurrenceIDColumnNumber];

                            if (myShepherd.isOccurrence(occurID)) {
                                occur = myShepherd.getOccurrence(occurID);
                                boolean isNew = occur.addEncounter(enc);
                                if (isNew) {
                                    occur.addComments("<p><em>" + request.getRemoteUser() + " on "
                                            + (new java.util.Date()).toString() + "</em><br>"
                                            + "Import SRGD process added encounter " + enc.getCatalogNumber()
                                            + ".</p>");
                                }

                            } else {
                                occur = new Occurrence(occurID, enc);
                                occur.addComments("<p><em>" + request.getRemoteUser() + " on "
                                        + (new java.util.Date()).toString() + "</em><br>"
                                        + "Import SRGD process added encounter " + enc.getCatalogNumber()
                                        + ".</p>");

                                myShepherd.getPM().makePersistent(occur);

                            }
                        }

                    }

                    if (ok2import) {

                        System.out.println("          ok2import");

                        myShepherd.commitDBTransaction();
                        if (newEncounter) {
                            myShepherd.storeNewEncounter(enc, enc.getCatalogNumber());
                        }

                        //before proceeding with haplotype and loci importing, we need to create the tissue sample
                        myShepherd.beginDBTransaction();
                        Encounter enc3 = myShepherd.getEncounter(encNumber);
                        TissueSample ts = new TissueSample(encNumber, ("sample_" + encNumber));

                        if (myShepherd.isTissueSample(("sample_" + encNumber), encNumber)) {
                            ts = myShepherd.getTissueSample(("sample_" + encNumber), encNumber);
                        } else {
                            myShepherd.getPM().makePersistent(ts);
                            enc3.addTissueSample(ts);
                        }
                        System.out.println("          Added TissueSample.");

                        //let's set genetic Sex
                        if ((sex != null) && (!sex.equals(""))) {
                            SexAnalysis sexDNA = new SexAnalysis(
                                    ("analysis_" + enc3.getCatalogNumber() + "_sex"), sex,
                                    enc3.getCatalogNumber(), ("sample_" + enc3.getCatalogNumber()));
                            if (myShepherd.isGeneticAnalysis(ts.getSampleID(), encNumber,
                                    ("analysis_" + enc3.getCatalogNumber() + "_sex"), "SexAnalysis")) {
                                sexDNA = myShepherd.getSexAnalysis(ts.getSampleID(), encNumber,
                                        ("analysis_" + enc3.getCatalogNumber() + "_sex"));
                                sexDNA.setSex(sex);
                            } else {
                                ts.addGeneticAnalysis(sexDNA);
                                myShepherd.getPM().makePersistent(sexDNA);
                            }
                            enc3.addComments("<p><em>" + request.getRemoteUser() + " on "
                                    + (new java.util.Date()).toString() + "</em><br />"
                                    + "Import SRGD process added or updated genetic sex analysis "
                                    + sexDNA.getAnalysisID() + " for tissue sample " + ts.getSampleID()
                                    + ".<br />" + sexDNA.getHTMLString());
                        }
                        System.out.println("          Added genetic sex.");

                        //line[7] get haplotype
                        if (line.length >= 8) {
                            String haplo = line[7].trim();
                            if ((haplo != null) && (!haplo.equals(""))) {
                                //TBD check id this analysis already exists
                                System.out.println("          Starting haplotype.");

                                MitochondrialDNAAnalysis mtDNA = new MitochondrialDNAAnalysis(
                                        ("analysis_" + enc3.getCatalogNumber()), haplo, enc3.getCatalogNumber(),
                                        ("sample_" + enc3.getCatalogNumber()));
                                if (myShepherd.isGeneticAnalysis(ts.getSampleID(), encNumber,
                                        ("analysis_" + enc3.getCatalogNumber()), "MitochondrialDNA")) {
                                    mtDNA = myShepherd.getMitochondrialDNAAnalysis(ts.getSampleID(), encNumber,
                                            ("analysis_" + enc3.getCatalogNumber()));
                                    mtDNA.setHaplotype(haplo);
                                    System.out.println("                  Haplotype reset.");

                                } else {
                                    ts.addGeneticAnalysis(mtDNA);
                                    myShepherd.getPM().makePersistent(mtDNA);
                                    System.out.println("          Added new haplotype.");

                                }
                                enc3.addComments("<p><em>" + request.getRemoteUser() + " on "
                                        + (new java.util.Date()).toString() + "</em><br />"
                                        + "Import SRGD process added or updated mitochondrial DNA analysis (haplotype) "
                                        + mtDNA.getAnalysisID() + " for tissue sample " + ts.getSampleID()
                                        + ".<br />" + mtDNA.getHTMLString());
                                System.out.println("          Added haplotype.");
                            } else {
                                System.out.println("          Did NOT add haplotype.");
                            }
                        }

                        ArrayList<Locus> loci = new ArrayList<Locus>();

                        //loci value import       
                        if (line.length >= 9) {

                            for (int f = 8; f < numColumns; f++) {
                                if (line.length > (f + 2)) {
                                    String l1 = line[f].trim();
                                    String l2 = line[f + 1].trim();
                                    String locusName = headerNames[f].replaceAll("L_", "");

                                    System.out.println("          Loaded loci name.");

                                    //verify that we're looking at the right loci and everything matches up nicely
                                    if ((l1 != null) && (l2 != null) && (!l1.equals("")) && (!l2.equals(""))
                                            && (!locusName.equals(""))
                                            && (headerNames[f].trim().toLowerCase().startsWith("l_"))
                                            && (headerNames[f + 1].trim().toLowerCase().startsWith("l_"))
                                            && (headerNames[f].trim().toLowerCase()
                                                    .equals(headerNames[f + 1].trim().toLowerCase()))) {

                                        //get allele values
                                        Integer intA = new Integer(l1);
                                        Integer intB = new Integer(l2);

                                        Locus myLocus = new Locus(locusName, intA, intB);
                                        loci.add(myLocus);

                                    }

                                    f++;
                                }
                            }
                        }

                        //TBD check if this analysis already exists
                        if (loci.size() > 0) {

                            System.out.println("          Found msMarkers!!!!!!!!!!!!1");

                            MicrosatelliteMarkersAnalysis microAnalysis = new MicrosatelliteMarkersAnalysis(
                                    (ts.getSampleID() + "_msMarkerAnalysis"), ts.getSampleID(),
                                    enc.getCatalogNumber(), loci);

                            if (myShepherd.isGeneticAnalysis(ts.getSampleID(), encNumber,
                                    (ts.getSampleID() + "_msMarkerAnalysis"), "MicrosatelliteMarkers")) {
                                microAnalysis = myShepherd.getMicrosatelliteMarkersAnalysis(ts.getSampleID(),
                                        encNumber, (ts.getSampleID() + "_msMarkerAnalysis"));
                                microAnalysis.setLoci(loci);
                            } else {
                                ts.addGeneticAnalysis(microAnalysis);
                                myShepherd.getPM().makePersistent(microAnalysis);
                            }
                            System.out.println("          Added ms markers.");

                            enc3.addComments("<p><em>" + request.getRemoteUser() + " on "
                                    + (new java.util.Date()).toString() + "</em><br />"
                                    + "Import SRGD process added or updated microsatellite markers of analysis "
                                    + microAnalysis.getAnalysisID() + " for tissue sample " + ts.getSampleID()
                                    + ".<br />" + microAnalysis.getHTMLString());

                        }

                        myShepherd.commitDBTransaction();

                        if (!individualID.equals("")) {
                            MarkedIndividual indie = new MarkedIndividual();
                            myShepherd.beginDBTransaction();

                            Encounter enc2 = myShepherd.getEncounter(encNumber);

                            if (myShepherd.isMarkedIndividual(individualID)) {
                                indie = myShepherd.getMarkedIndividual(individualID);
                                newShark = false;
                            } else {
                                //indie.setIndividualID(individualID);
                            }

                            //OK to generically add it as the addEncounter() method will ignore it if already added to marked individual
                            indie.addEncounter(enc2);

                            if ((indie.getSex() == null)
                                    || ((enc2.getSex() != null) && (indie.getSex() != enc2.getSex()))) {
                                indie.setSex(enc2.getSex());
                                indie.addComments("<p><em>" + request.getRemoteUser() + " on "
                                        + (new java.util.Date()).toString() + "</em><br>"
                                        + "Import SRGD process set sex to " + enc2.getSex() + ".</p>");

                            }

                            if ((indie.getHaplotype() == null) && (enc2.getHaplotype() != null)) {
                                indie.doNotSetLocalHaplotypeReflection(enc2.getHaplotype());
                            }

                            indie.refreshDependentProperties();
                            indie.addComments("<p><em>" + request.getRemoteUser() + " on "
                                    + (new java.util.Date()).toString() + "</em><br>"
                                    + "Import SRGD process added encounter " + enc2.getCatalogNumber()
                                    + ".</p>");

                            myShepherd.commitDBTransaction();
                            if (newShark) {
                                myShepherd.storeNewMarkedIndividual(indie);
                            }
                        }

                    } else {
                        myShepherd.rollbackDBTransaction();
                    }

                    //out.println("Imported row: "+line);

                }

            } else {
                locked = true;
                System.out.println("ImportSRGD: For some reason the import failed without exception.");
            }

        } catch (Exception le) {
            locked = true;
            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            le.printStackTrace();
        }

        if (!locked) {
            myShepherd.commitDBTransaction();
            myShepherd.closeDBTransaction();
            out.println(ServletUtilities.getHeader(request));
            out.println(
                    "<p><strong>Success!</strong> I have successfully uploaded and imported your SRGD CSV file.</p>");

            if (messages.toString().equals("")) {
                messages.append("None");
            }
            out.println("<p>The following error messages were reported during the import process:<br /><ul>"
                    + messages + "</ul></p>");

            out.println("<p><a href=\"appadmin/import.jsp\">Return to the import page</a></p>");

            out.println(ServletUtilities.getFooter(context));
        }

    } catch (IOException lEx) {
        lEx.printStackTrace();
        out.println(ServletUtilities.getHeader(request));
        out.println(
                "<strong>Error:</strong> I was unable to upload your SRGD CSV. Please contact the webmaster about this message.");
        out.println(ServletUtilities.getFooter(context));
    } catch (NullPointerException npe) {
        npe.printStackTrace();
        out.println(ServletUtilities.getHeader(request));
        out.println("<strong>Error:</strong> I was unable to import SRGD data as no file was specified.");
        out.println(ServletUtilities.getFooter(context));
    }
    out.close();
}

From source file:org.efaps.admin.datamodel.attributetype.DateTimeType.java

License:Apache License

/**
 * {@inheritDoc}//from  ww  w.  j  av  a  2s  .c  o m
 * @throws EFapsException
 */
@Override
public Object readValue(final Attribute _attribute, final List<Object> _objectList) throws EFapsException {
    // reads the Value from "Admin_Common_DataBaseTimeZone"
    final String timezoneID = EFapsSystemConfiguration.get().getAttributeValue(KernelSettings.DBTIMEZONE);
    final ISOChronology chron;
    if (timezoneID != null) {
        final DateTimeZone timezone = DateTimeZone.forID(timezoneID);
        chron = ISOChronology.getInstance(timezone);
    } else {
        chron = ISOChronology.getInstanceUTC();
    }

    final List<DateTime> ret = new ArrayList<DateTime>();
    for (final Object object : _objectList) {
        if (object instanceof Timestamp || object instanceof Date) {
            // to avoid the automatic "correction" of the timezone first a local date must be made
            // and than a new Date with the correct timezone must be created
            final DateTime dateTime = new DateTime(object);
            final DateTime unlocalized = new DateTime(dateTime.getYear(), dateTime.getMonthOfYear(),
                    dateTime.getDayOfMonth(), dateTime.getHourOfDay(), dateTime.getMinuteOfHour(),
                    dateTime.getSecondOfMinute(), dateTime.getMillisOfSecond(), chron);
            ret.add(unlocalized);
        } else if (object != null) {
            ret.add(new DateTime());
        } else {
            ret.add(null);
        }
    }
    return _objectList.size() > 0 ? ret.size() > 1 ? ret : ret.get(0) : null;
}

From source file:org.efaps.admin.datamodel.attributetype.DateTimeType.java

License:Apache License

/**
 * The value that can be set is a Date, a DateTime or a String
 * yyyy-MM-dd'T'HH:mm:ss.SSSZZ. It will be normalized to ISO Calender with
 * TimeZone from SystemAttribute Admin_Common_DataBaseTimeZone. In case that
 * the SystemAttribute is missing UTC will be used.
 *
 * @param _value value to evaluate/*  ww  w.jav  a 2  s .com*/
 * @return evaluated value
 * @throws EFapsException on error
 */
protected Timestamp eval(final Object[] _value) throws EFapsException {
    final Timestamp ret;
    if (_value == null || _value.length == 0 || _value[0] == null) {
        ret = null;
    } else {
        final DateTime dateTime = DateTimeUtil.translateFromUI(_value[0]);
        // until now we have a time that depends on the timezone of the application server
        // to convert it in a timestamp for the efaps database the timezone information (mainly the offset)
        // must be removed. This is done by creating a local date with the same, date and time.
        // this guarantees that the datetime inserted into the database depends on the setting
        // in the configuration and not on the timezone for the application server.
        final DateTime localized = new DateTime(dateTime.getYear(), dateTime.getMonthOfYear(),
                dateTime.getDayOfMonth(), dateTime.getHourOfDay(), dateTime.getMinuteOfHour(),
                dateTime.getSecondOfMinute(), dateTime.getMillisOfSecond());
        ret = localized != null ? new Timestamp(localized.getMillis()) : null;
    }
    return ret;
}

From source file:org.efaps.admin.datamodel.attributetype.DateType.java

License:Apache License

/**
 * The value that can be set is a Date, a DateTime or a String
 * yyyy-MM-dd'T'HH:mm:ss.SSSZZ. It will be normalized to ISO Calender with
 * TimeZone from SystemAttribute Admin_Common_DataBaseTimeZone. In case that
 * the SystemAttribute is missing UTC will be used.
 * For storing the value in the database the time is set to 00:00;
 *
 * @param _value value to evaluate/* w  w w.  ja v  a2s  .co  m*/
 * @return evaluated value
 * @throws EFapsException on error
 */
@Override
protected Timestamp eval(final Object[] _value) throws EFapsException {
    final Timestamp ret;
    if (_value == null || _value.length == 0 || _value[0] == null) {
        ret = null;
    } else {
        DateTime dateTime = new DateTime();
        if (_value[0] instanceof Date) {
            dateTime = new DateTime(_value[0]);
        } else if (_value[0] instanceof DateTime) {
            dateTime = (DateTime) _value[0];
        } else if (_value[0] instanceof String) {
            dateTime = ISODateTimeFormat.dateTime().withOffsetParsed().parseDateTime((String) _value[0]);
        }
        // until now we have a time that depends on the timezone of the application server
        // to convert it in a timestamp for the efaps database the timezone information (mainly the offset)
        // must be removed. This is done by creating a local date with the same, date and time.
        // this guarantees that the datetime inserted into the database depends on the setting
        // in the configuration and not on the timezone for the application server.
        final DateTime localized = new DateTime(dateTime.getYear(), dateTime.getMonthOfYear(),
                dateTime.getDayOfMonth(), 0, 0, 0, 0);
        ret = localized != null ? new Timestamp(localized.getMillis()) : null;
    }
    return ret;
}

From source file:org.efaps.admin.index.Indexer.java

License:Apache License

/**
 * Index or reindex a given list of instances. The given instances m,ust be
 * all of the same type!//ww  w .j av a 2 s.  c  o  m
 *
 * @param _context the _context
 * @param _instances the instances
 * @throws EFapsException the e faps exception
 */
public static void index(final IndexContext _context, final List<Instance> _instances) throws EFapsException {
    if (CollectionUtils.isNotEmpty(_instances)) {
        final Company currentCompany = Context.getThreadContext().getCompany();
        final String currentLanguage = Context.getThreadContext().getLanguage();

        Context.getThreadContext().setCompany(Company.get(_context.getCompanyId()));
        Context.getThreadContext().setLanguage(_context.getLanguage());
        final IndexWriterConfig config = new IndexWriterConfig(_context.getAnalyzer());
        try (IndexWriter writer = new IndexWriter(_context.getDirectory(), config);
                TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(_context.getTaxonomyDirectory());) {

            final IndexDefinition def = IndexDefinition.get(_instances.get(0).getType().getUUID());
            final MultiPrintQuery multi = new MultiPrintQuery(_instances);
            for (final IndexField field : def.getFields()) {
                multi.addSelect(field.getSelect());
            }
            Attribute createdAttr = null;
            if (!_instances.get(0).getType().getAttributes(CreatedType.class).isEmpty()) {
                createdAttr = _instances.get(0).getType().getAttributes(CreatedType.class).iterator().next();
                multi.addAttribute(createdAttr);
            }
            multi.addMsgPhrase(def.getMsgPhrase());
            multi.executeWithoutAccessCheck();
            while (multi.next()) {
                final String oid = multi.getCurrentInstance().getOid();
                final String type = multi.getCurrentInstance().getType().getLabel();
                final DateTime created;
                if (createdAttr == null) {
                    created = new DateTime();
                } else {
                    created = multi.getAttribute(createdAttr);
                }

                final Document doc = new Document();
                doc.add(new FacetField(Dimension.DIMTYPE.name(), type));
                doc.add(new FacetField(Dimension.DIMCREATED.name(), String.valueOf(created.getYear()),
                        String.format("%02d", created.getMonthOfYear())));
                doc.add(new StringField(Key.OID.name(), oid, Store.YES));
                doc.add(new TextField(DBProperties.getProperty("index.Type"), type, Store.YES));
                doc.add(new NumericDocValuesField(Key.CREATED.name(), created.getMillis()));
                doc.add(new StringField(Key.CREATEDSTR.name(),
                        DateTools.dateToString(created.toDate(), DateTools.Resolution.DAY), Store.NO));

                final StringBuilder allBldr = new StringBuilder().append(type).append(" ");

                for (final IndexField field : def.getFields()) {
                    final String name = DBProperties.getProperty(field.getKey());
                    Object value = multi.getSelect(field.getSelect());
                    if (value != null) {
                        if (StringUtils.isNoneEmpty(field.getTransform())) {
                            final Class<?> clazz = Class.forName(field.getTransform(), false,
                                    EFapsClassLoader.getInstance());
                            final ITransformer transformer = (ITransformer) clazz.newInstance();
                            value = transformer.transform(value);
                        }
                        switch (field.getFieldType()) {
                        case LONG:
                            long val = 0;
                            if (value instanceof String) {
                                val = NumberUtils.toLong((String) value);
                            } else if (value instanceof Number) {
                                val = ((Number) value).longValue();
                            }
                            doc.add(new LongField(name, val, Store.YES));
                            allBldr.append(value).append(" ");
                            break;
                        case SEARCHLONG:
                            long val2 = 0;
                            if (value instanceof String) {
                                val2 = NumberUtils.toLong((String) value);
                            } else if (value instanceof Number) {
                                val2 = ((Number) value).longValue();
                            }
                            doc.add(new LongField(name, val2, Store.NO));
                            allBldr.append(value).append(" ");
                            break;
                        case STRING:
                            doc.add(new StringField(name, String.valueOf(value), Store.YES));
                            allBldr.append(value).append(" ");
                            break;
                        case SEARCHSTRING:
                            doc.add(new StringField(name, String.valueOf(value), Store.NO));
                            allBldr.append(value).append(" ");
                            break;
                        case TEXT:
                            doc.add(new TextField(name, String.valueOf(value), Store.YES));
                            allBldr.append(value).append(" ");
                            break;
                        case SEARCHTEXT:
                            doc.add(new TextField(name, String.valueOf(value), Store.NO));
                            allBldr.append(value).append(" ");
                            break;
                        case STORED:
                            doc.add(new StoredField(name, String.valueOf(value)));
                            allBldr.append(value).append(" ");
                            break;
                        default:
                            break;
                        }
                    }
                }
                doc.add(new StoredField(Key.MSGPHRASE.name(), multi.getMsgPhrase(def.getMsgPhrase())));
                doc.add(new TextField(Key.ALL.name(), allBldr.toString(), Store.NO));
                writer.updateDocument(new Term(Key.OID.name(), oid),
                        Index.getFacetsConfig().build(taxonomyWriter, doc));
                LOG.debug("Add Document: {}", doc);
            }
            writer.close();
            taxonomyWriter.close();
        } catch (final IOException | ClassNotFoundException | InstantiationException
                | IllegalAccessException e) {
            throw new EFapsException(Indexer.class, "IOException", e);
        } finally {
            Context.getThreadContext().setCompany(currentCompany);
            Context.getThreadContext().setLanguage(currentLanguage);
        }
    }
}

From source file:org.efaps.esjp.accounting.report.PurchaseRecordReport_Base.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/* www . ja v  a2  s.  c  om*/
public void init(final JasperReport _jasperReport, final Parameter _parameter, final JRDataSource _parentSource,
        final Map<String, Object> _jrParameters) throws EFapsException {
    QueryCache.cleanByKey(PurchaseRecordReport_Base.CACHEDQUERYKEY);

    final List<Map<String, Object>> values = new ArrayList<>();
    final List<Instance> instances = getInstances(_parameter);

    if (instances.size() > 0) {
        final Map<Instance, PosSum4Doc> posSums = getPosSums(_parameter);

        final SelectBuilder selRel = new SelectBuilder().linkto(CIAccounting.PurchaseRecord2Document.ToLink);
        final SelectBuilder selRelDocType = new SelectBuilder(selRel).type();
        final SelectBuilder selRelDocInst = new SelectBuilder(selRel).instance();
        final SelectBuilder selRelDocName = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Name);
        final SelectBuilder selRelDocRevision = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Revision);
        final SelectBuilder selRelDocDate = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Date);
        final SelectBuilder selRelDocDueDate = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.DueDate);
        final SelectBuilder selRelDocNTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.NetTotal);
        final SelectBuilder selRelDocCTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.CrossTotal);
        final SelectBuilder selRelDocRNTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateNetTotal);
        final SelectBuilder selRelDocRCTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateCrossTotal);
        final SelectBuilder selRelDocRateLabel = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Rate).label();

        final SelectBuilder selRelDocCurInst = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.CurrencyId).instance();
        final SelectBuilder selRelDocRCurInst = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateCurrencyId).instance();

        final SelectBuilder selRelDocContact = new SelectBuilder(selRel)
                .linkto(CISales.DocumentSumAbstract.Contact);
        final SelectBuilder selRelDocContactName = new SelectBuilder(selRelDocContact)
                .attribute(CIContacts.Contact.Name);
        final SelectBuilder selRelDocContactTax = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassOrganisation).attribute(CIContacts.ClassOrganisation.TaxNumber);
        final SelectBuilder selRelDocContactIdenityCard = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassPerson).attribute(CIContacts.ClassPerson.IdentityCard);
        final SelectBuilder selRelDocContactDOIType = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassPerson).linkto(CIContacts.ClassPerson.DOITypeLink)
                .attribute(CIContacts.AttributeDefinitionDOIType.MappingKey);

        final SelectBuilder selRelTypeLink = new SelectBuilder()
                .linkto(CIAccounting.PurchaseRecord2Document.TypeLink);
        final SelectBuilder selRelTypeLinkName = new SelectBuilder(selRelTypeLink)
                .attribute(CIERP.DocumentType.Name);

        final MultiPrintQuery multi = new MultiPrintQuery(instances);
        multi.addSelect(selRelDocType, selRelDocInst, selRelDocName, selRelDocRevision, selRelDocDate,
                selRelDocDueDate, selRelDocNTotal, selRelDocCTotal, selRelDocRNTotal, selRelDocRCTotal,
                selRelDocRateLabel, selRelDocCurInst, selRelDocRCurInst, selRelDocContactName,
                selRelDocContactTax, selRelTypeLinkName, selRelDocContactIdenityCard, selRelDocContactDOIType);
        multi.addAttribute(CIAccounting.PurchaseRecord2Document.DetractionDate,
                CIAccounting.PurchaseRecord2Document.DetractionName,
                CIAccounting.PurchaseRecord2Document.DetractionAmount,
                CIAccounting.PurchaseRecord2Document.Taxed);
        multi.execute();

        while (multi.next()) {
            final Map<String, Object> map = new HashMap<>();
            final Type docType = multi.<Type>getSelect(selRelDocType);
            final Instance instDoc = multi.<Instance>getSelect(selRelDocInst);
            final String docName = multi.<String>getSelect(selRelDocName);
            final DateTime docDate = multi.<DateTime>getSelect(selRelDocDate);
            final DateTime docDueDate = multi.<DateTime>getSelect(selRelDocDueDate);
            final String contactName = multi.<String>getSelect(selRelDocContactName);
            final String contactTaxNum = multi.<String>getSelect(selRelDocContactTax);
            final BigDecimal rateTmp = multi.<BigDecimal>getSelect(selRelDocRateLabel);
            final String typeLinkName = multi.<String>getSelect(selRelTypeLinkName);
            final String docRevision = multi.<String>getSelect(selRelDocRevision);
            final String docContactIdenityCard = multi.<String>getSelect(selRelDocContactIdenityCard);
            final String docContactDOIType = multi.<String>getSelect(selRelDocContactDOIType);
            final Taxed4PurchaseRecord taxed = multi.getAttribute(CIAccounting.PurchaseRecord2Document.Taxed);

            final String detractionName = multi
                    .<String>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionName);
            final BigDecimal detractionAmount = multi
                    .<BigDecimal>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionAmount);
            final DateTime detractionDate = multi
                    .<DateTime>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionDate);
            final Instance docDerivatedRel = getDocumentDerivated(instDoc, true) == null
                    ? getDocumentDerivated(instDoc, false)
                    : getDocumentDerivated(instDoc, true);

            BigDecimal netTotal = multi.<BigDecimal>getSelect(selRelDocNTotal);
            BigDecimal crossTotal = multi.<BigDecimal>getSelect(selRelDocCTotal);

            final PosSum4Doc posSum = posSums.get(instDoc);
            BigDecimal taxfree;
            if (posSum != null) {
                taxfree = posSum.getTaxFree(_parameter);
            } else {
                taxfree = BigDecimal.ZERO;
            }
            BigDecimal igv = crossTotal.subtract(netTotal);
            netTotal = netTotal.subtract(taxfree);

            if (crossTotal.compareTo(netTotal) == 0) {
                taxfree = netTotal;
                netTotal = BigDecimal.ZERO;
            }

            if (CISales.IncomingCreditNote.getType().equals(docType)) {
                netTotal = netTotal.negate();
                crossTotal = crossTotal.negate();
                igv = igv.negate();
                taxfree = taxfree.negate();
            }

            PurchaseRecordReport_Base.LOG.debug("Document OID '{}'", instDoc.getOid());
            PurchaseRecordReport_Base.LOG.debug("Document name '{}'", docName);

            map.put(PurchaseRecordReport_Base.Field.DOC_RATE.getKey(), rateTmp);
            map.put(PurchaseRecordReport_Base.Field.DOC_DATE.getKey(), docDate);
            map.put(PurchaseRecordReport_Base.Field.DOC_DUEDATE.getKey(), docDueDate);
            map.put(PurchaseRecordReport_Base.Field.DOC_NAME.getKey(), docName);
            map.put(PurchaseRecordReport_Base.Field.DOC_CONTACT.getKey(), contactName);
            Boolean isDOI = false;
            String taxNum = contactTaxNum;
            if (taxNum == null || taxNum != null && taxNum.isEmpty()) {
                if (docContactIdenityCard != null && !docContactIdenityCard.isEmpty()) {
                    taxNum = docContactIdenityCard;
                    isDOI = true;
                }
            }
            map.put(PurchaseRecordReport_Base.Field.DOC_TAXNUM.getKey(), taxNum);

            switch (taxed) {
            case TAXED:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALTAXED.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVTAXED.getKey(), igv);
                break;
            case EXPORT:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALEXPORT.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVEXPORT.getKey(), igv);
                break;
            case UNTAXED:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALUNTAXED.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVUNTAXED.getKey(), igv);
                break;
            default:
                break;
            }

            map.put(PurchaseRecordReport_Base.Field.DOC_CROSSTOTAL.getKey(), crossTotal);
            map.put(PurchaseRecordReport_Base.Field.DOC_VALUENOTAX.getKey(), taxfree);

            final String[] nameAr = docName.split("\\W");

            if (nameAr.length == 2 && nameAr[0].length() < nameAr[1].length()) {
                map.put(PurchaseRecordReport_Base.Field.DOC_SN.getKey(), nameAr[0]);
                map.put(PurchaseRecordReport_Base.Field.DOC_NUMBER.getKey(), nameAr[1]);
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_SN.getKey(), "");
                map.put(PurchaseRecordReport_Base.Field.DOC_NUMBER.getKey(), docName);
            }

            map.put(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey(), typeLinkName);
            map.put(PurchaseRecordReport_Base.Field.DOC_REVISION.getKey(), docRevision);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_NAME.getKey(), detractionName);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_AMOUNT.getKey(), detractionAmount);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_DATE.getKey(),
                    detractionAmount == null ? null : detractionDate);

            if (docDerivatedRel != null && docDerivatedRel.isValid()) {
                final SelectBuilder selLinkName = new SelectBuilder()
                        .linkfrom(CISales.Document2DocumentType, CISales.Document2DocumentType.DocumentLink)
                        .linkto(CISales.Document2DocumentType.DocumentTypeLink)
                        .attribute(CIERP.DocumentType.Name);

                final PrintQuery printDocRel = new PrintQuery(docDerivatedRel);
                printDocRel.addAttribute(CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name);
                printDocRel.addSelect(selLinkName);
                printDocRel.execute();

                final DateTime docRelDate = printDocRel
                        .<DateTime>getAttribute(CISales.DocumentSumAbstract.Date);
                final String docRelName = printDocRel.<String>getAttribute(CISales.DocumentSumAbstract.Name);

                map.put(PurchaseRecordReport_Base.Field.DOCREL_DATE.getKey(), docRelDate);
                map.put(PurchaseRecordReport_Base.Field.DOCREL_PREFNAME.getKey(),
                        docRelName.split("-").length == 2 ? docRelName.split("-")[0] : "");
                map.put(PurchaseRecordReport_Base.Field.DOCREL_SUFNAME.getKey(),
                        docRelName.split("-").length == 2 ? docRelName.split("-")[1] : docRelName);
                map.put(PurchaseRecordReport_Base.Field.DOCREL_TYPE.getKey(),
                        printDocRel.<String>getSelect(selLinkName));
            }

            // TODO falta implementar
            map.put(PurchaseRecordReport_Base.Field.DUA_YEAR.getKey(), "0");
            map.put(PurchaseRecordReport_Base.Field.RETENCION_APPLIES.getKey(), false);

            if (isDOI) {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), docContactDOIType);
            } else if (contactTaxNum.length() == 11) {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), "6");
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), "0");
            }

            final DateTime purchaseDate = getDate4Purchase(_parameter);
            final Integer diff = purchaseDate.getMonthOfYear() - docDate.getMonthOfYear();

            if (Math.abs(diff) > 12) {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.OUSIDE.getKey());
            } else if (Math.abs(diff) > 0) {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.INSIDE.getKey());
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.NORMAL.getKey());
            }

            values.add(map);
        }
    }
    final ComparatorChain chain = new ComparatorChain();
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final String val1 = (String) _o1.get(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey());
            final String val2 = (String) _o2.get(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey());
            return val1.compareTo(val2);
        }
    });
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final DateTime date1 = (DateTime) _o1.get(PurchaseRecordReport_Base.Field.DOC_DATE.getKey());
            final DateTime date2 = (DateTime) _o2.get(PurchaseRecordReport_Base.Field.DOC_DATE.getKey());
            return date1.compareTo(date2);
        }
    });
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final String val1 = (String) _o1.get(PurchaseRecordReport_Base.Field.DOC_NAME.getKey());
            final String val2 = (String) _o2.get(PurchaseRecordReport_Base.Field.DOC_NAME.getKey());
            return val1.compareTo(val2);
        }
    });

    Collections.sort(values, chain);
    getValues().addAll(values);
}

From source file:org.efaps.esjp.accounting.SubJournal_Base.java

License:Apache License

/**
 * Insert post trigger./*from ww  w. j a  v a 2s .co  m*/
 *
 * @param _parameter the parameter
 * @return the return
 * @throws EFapsException the e faps exception
 */
public Return insertPostTrigger(final Parameter _parameter) throws EFapsException {
    final PrintQuery print = new PrintQuery(_parameter.getInstance());
    final SelectBuilder selRepInst = SelectBuilder.get()
            .linkto(CIAccounting.ReportSubJournal2Transaction.FromLink).instance();
    final SelectBuilder selRepName = SelectBuilder.get()
            .linkto(CIAccounting.ReportSubJournal2Transaction.FromLink)
            .attribute(CIAccounting.ReportSubJournal.Name);
    final SelectBuilder selTransDate = SelectBuilder.get()
            .linkto(CIAccounting.ReportSubJournal2Transaction.ToLink).attribute(CIAccounting.Transaction.Date);
    print.addSelect(selRepInst, selRepName, selTransDate);
    print.executeWithoutAccessCheck();
    final Instance repInst = print.<Instance>getSelect(selRepInst);
    final String repName = print.<String>getSelect(selRepName);
    final DateTime transDate = print.<DateTime>getSelect(selTransDate);

    final QueryBuilder attrQueryBldr = new QueryBuilder(CIAccounting.Transaction);
    attrQueryBldr.addWhereAttrGreaterValue(CIAccounting.Transaction.Date,
            transDate.withDayOfMonth(1).withTimeAtStartOfDay().minusSeconds(1));
    attrQueryBldr.addWhereAttrLessValue(CIAccounting.Transaction.Date,
            transDate.withDayOfMonth(1).withTimeAtStartOfDay().plusMonths(1));
    final AttributeQuery attrQuery = attrQueryBldr.getAttributeQuery(CIAccounting.Transaction.ID);

    final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.ReportSubJournal2Transaction);
    queryBldr.addWhereAttrEqValue(CIAccounting.ReportSubJournal2Transaction.FromLink, repInst);
    queryBldr.addWhereAttrInQuery(CIAccounting.ReportSubJournal2Transaction.ToLink, attrQuery);
    queryBldr.addWhereAttrNotEqValue(CIAccounting.ReportSubJournal2Transaction.ID, _parameter.getInstance());
    queryBldr.addOrderByAttributeDesc(CIAccounting.ReportSubJournal2Transaction.Number);
    final MultiPrintQuery multi = queryBldr.getPrint();
    multi.setEnforceSorted(true);
    multi.addAttribute(CIAccounting.ReportSubJournal2Transaction.Number);
    multi.executeWithoutAccessCheck();
    String numberStr = "";
    if (multi.next()) {
        numberStr = multi.<String>getAttribute(CIAccounting.ReportSubJournal2Transaction.Number);
    }
    final int month = transDate.getMonthOfYear();

    Integer curr = 0;
    try {
        final Pattern pattern = Pattern.compile("\\d*$");
        final Matcher matcher = pattern.matcher(numberStr.trim());
        if (matcher.find()) {
            curr = Integer.parseInt(matcher.group());
        }
    } catch (final NumberFormatException e) {
        SubJournal_Base.LOG.warn("Catched NumberFormatException");
    }
    curr = curr + 1;

    numberStr = String.format("%s/%02d/%04d", repName, month, curr);

    final Update update = new Update(_parameter.getInstance());
    update.add(CIAccounting.ReportSubJournal2Transaction.Number, numberStr);
    update.executeWithoutTrigger();
    return new Return();
}

From source file:org.egov.adtax.service.AdvertisementDemandService.java

License:Open Source License

private int noOfMonths(final Date startDate, final Date endDate) {
    DateTime sDate = new DateTime(startDate);
    DateTime eDate = new DateTime(endDate);
    final int yearDiff = eDate.getYear() - sDate.getYear();
    int noOfMonths = yearDiff * 12 + eDate.getMonthOfYear() - sDate.getMonthOfYear();
    return noOfMonths;

}

From source file:org.egov.eventnotification.service.ScheduleDetailsService.java

License:Open Source License

/**
 * This method take a cron expression from properties file and replace the hour,minute,day and month into the placeholder to
 * make dynamic cron expression.//from  w ww  .j  av a  2 s. c  o  m
 *
 * @param notificationschedule
 * @return
 */
private String getCronExpression(Schedule notificationschedule) {
    String cronExpression = null;
    DateTime calendar = new DateTime(notificationschedule.getStartDate());
    int hours = calendar.getHourOfDay();
    int minutes = calendar.getMinuteOfHour();

    switch (notificationschedule.getScheduleRepeat().getName().toLowerCase()) {
    case "day":
        cronExpression = appProperties.getDailyCron().replace(MINUTES_CRON, String.valueOf(minutes));
        cronExpression = cronExpression.replace(HOURS_CRON, String.valueOf(hours));
        break;
    case "month":
        cronExpression = appProperties.getMonthlyCron().replace(MINUTES_CRON, String.valueOf(minutes));
        cronExpression = cronExpression.replace(HOURS_CRON, String.valueOf(hours));
        cronExpression = cronExpression.replace(DAY_CRON, String.valueOf(calendar.getDayOfMonth()));
        break;
    case "year":
        cronExpression = appProperties.getYearlyCron().replace(MINUTES_CRON, String.valueOf(minutes));
        cronExpression = cronExpression.replace(HOURS_CRON, String.valueOf(hours));
        cronExpression = cronExpression.replace(DAY_CRON, String.valueOf(calendar.getDayOfMonth()));
        cronExpression = cronExpression.replace(MONTH_CRON, String.valueOf(calendar.getMonthOfYear()));
        break;
    default:
        break;
    }
    return cronExpression;
}

From source file:org.egov.pgr.elasticsearch.repository.ComplaintIndexRepositoryImpl.java

License:Open Source License

@Override
public Map<String, SearchResponse> findAllGrievanceByFilter(
        final ComplaintDashBoardRequest complaintDashBoardRequest, final BoolQueryBuilder query,
        final String grouByField) {
    /**/*from ww  w .j  a  va2s. com*/
     * For Current day's complaint count if dates are sent in the request, consider the toDate, else take date range between
     * current date +1 day
     */
    DateTime fromDate = new DateTime();
    if (isNotBlank(complaintDashBoardRequest.getFromDate())
            && isNotBlank(complaintDashBoardRequest.getToDate()))
        fromDate = new DateTime(complaintDashBoardRequest.getFromDate());

    // This is size used to fetch those many number of documents
    int size = 120;
    if (complaintDashBoardRequest.getSize() >= 0)
        size = complaintDashBoardRequest.getSize();

    DateTime currentYearFromDate = new DateTime();
    if (fromDate.getMonthOfYear() < 4)
        currentYearFromDate = currentYearFromDate.minusYears(1).withMonthOfYear(4).dayOfMonth()
                .withMinimumValue();
    else
        currentYearFromDate = currentYearFromDate.withMonthOfYear(4).dayOfMonth().withMinimumValue();

    final SearchResponse consolidatedResponse = elasticsearchTemplate.getClient().prepareSearch(PGR_INDEX_NAME)
            .setQuery(query).setSize(0).addAggregation(getCount("countAggregation", "crn"))
            .addAggregation(getCountWithGrouping("closedCount", IF_CLOSED, 2))
            .addAggregation(getCountWithGrouping("slaCount", IF_SLA, 2))
            .addAggregation(getAverageWithFilter(IF_CLOSED, 1, "AgeingInWeeks", COMPLAINT_AGEINGDAYS_FROM_DUE))
            .addAggregation(getAverageWithExclusion(SATISFACTION_AVERAGE, SATISFACTION_INDEX))
            .addAggregation(getCountBetweenSpecifiedDates("currentYear", CREATED_DATE,
                    currentYearFromDate.toString(formatter), new DateTime().plusDays(1).toString(formatter)))
            .addAggregation(getCountBetweenSpecifiedDates(TODAY_COMPLAINT_COUNT, CREATED_DATE,
                    new DateTime().toString(formatter), new DateTime().plusDays(1).toString(formatter)))
            .execute().actionGet();

    SearchResponse tableResponse;
    if (complaintDashBoardRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_ALL_WARDS))
        tableResponse = elasticsearchTemplate.getClient().prepareSearch(PGR_INDEX_NAME).setQuery(query)
                .setSize(0)
                .addAggregation(getCountWithGroupingAndOrder(COMPLAINT_TYPE_WISE, COMPLAINT_TYPE_NAME, size,
                        complaintDashBoardRequest.getSortField(), complaintDashBoardRequest.getSortDirection())
                                .subAggregation(getAverageWithExclusion(COMPLAINT_TYPE_SATISFACTION_AVERAGE,
                                        SATISFACTION_INDEX))
                                .subAggregation(getCountWithGrouping(COMPLAINT_TYPE_WISE_OPEN_AND_CLOSED_COUNT,
                                        IF_CLOSED, 2)
                                                .subAggregation(AggregationBuilders.range(COMPLAINT_TYPE_AGEING)
                                                        .field(COMPLAINT_AGEINGDAYS_FROM_DUE)
                                                        .addRange(ONE_WEEK, 0, 8).addRange(ONE_MONTH, 8, 32)
                                                        .addRange(THREE_MONTHS, 32, 91)
                                                        .addUnboundedFrom(REMAINING_MONTHS, 91))
                                                .subAggregation(AggregationBuilders
                                                        .range(HOURWISE_COMPLAINT_TYPE_AGEING)
                                                        .field(COMPLAINT_AGEING_FROM_DUE)
                                                        .addRange(TWELVE_HOURS, 0, 13).addRange("1day", 13, 25)
                                                        .addRange(ONE_WEEK, 25, 169)
                                                        .addUnboundedFrom(REMAINING_HOURS, 169))
                                                .subAggregation(
                                                        getCountWithGrouping(COMPLAINT_TYPE_SLA, IF_SLA, 2))))
                .addAggregation(AggregationBuilders.terms(ULBWISE).field(CITY_CODE).size(120)
                        .subAggregation(getCountWithGroupingAndOrder(GROUP_BY_FIELD, grouByField, size,
                                complaintDashBoardRequest.getSortField(),
                                complaintDashBoardRequest.getSortDirection())
                                        .subAggregation(getAverageWithExclusion(
                                                GROUP_BY_FIELD_SATISFACTION_AVERAGE, SATISFACTION_INDEX))
                                        .subAggregation(AggregationBuilders.topHits(COMPLAINT_RECORD)
                                                .addField(CITY_CODE).addField(DISTRICT_NAME).addField(CITY_NAME)
                                                .addField(WARD_NAME).setSize(1))
                                        .subAggregation(
                                                getCountWithGrouping(GROUP_FIELD_WISE_OPEN_AND_CLOSED_COUNT,
                                                        IF_CLOSED, 2).subAggregation(
                                                                AggregationBuilders.range(GROUP_BY_FIELD_AGEING)
                                                                        .field(COMPLAINT_AGEINGDAYS_FROM_DUE)
                                                                        .addRange(ONE_WEEK, 0, 8)
                                                                        .addRange(ONE_MONTH, 8, 32)
                                                                        .addRange(THREE_MONTHS, 32, 91)
                                                                        .addUnboundedFrom(REMAINING_MONTHS, 91))
                                                                .subAggregation(AggregationBuilders
                                                                        .range(GROUP_BY_FIELD_AGEING_FOR_HOURS)
                                                                        .field(COMPLAINT_AGEING_FROM_DUE)
                                                                        .addRange(TWELVE_HOURS, 0, 13)
                                                                        .addRange("1day", 13, 25)
                                                                        .addRange(ONE_WEEK, 25, 169)
                                                                        .addUnboundedFrom(REMAINING_HOURS, 169))
                                                                .subAggregation(getCountWithGrouping(
                                                                        GROUP_BY_FIELD_SLA, IF_SLA, 2)))))

                .execute().actionGet();
    else if (complaintDashBoardRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_ALL_LOCALITIES))
        tableResponse = elasticsearchTemplate.getClient().prepareSearch(PGR_INDEX_NAME).setQuery(query)
                .setSize(0)
                .addAggregation(getCountWithGroupingAndOrder(COMPLAINT_TYPE_WISE, COMPLAINT_TYPE_NAME, size,
                        complaintDashBoardRequest.getSortField(), complaintDashBoardRequest.getSortDirection())
                                .subAggregation(getAverageWithExclusion(COMPLAINT_TYPE_SATISFACTION_AVERAGE,
                                        SATISFACTION_INDEX))
                                .subAggregation(getCountWithGrouping(COMPLAINT_TYPE_WISE_OPEN_AND_CLOSED_COUNT,
                                        IF_CLOSED, 2)
                                                .subAggregation(AggregationBuilders.range(COMPLAINT_TYPE_AGEING)
                                                        .field(COMPLAINT_AGEINGDAYS_FROM_DUE)
                                                        .addRange(ONE_WEEK, 0, 8).addRange(ONE_MONTH, 8, 32)
                                                        .addRange(THREE_MONTHS, 32, 91)
                                                        .addUnboundedFrom(REMAINING_MONTHS, 91))
                                                .subAggregation(AggregationBuilders
                                                        .range(HOURWISE_COMPLAINT_TYPE_AGEING)
                                                        .field(COMPLAINT_AGEING_FROM_DUE)
                                                        .addRange(TWELVE_HOURS, 0, 13).addRange("1day", 13, 25)
                                                        .addRange(ONE_WEEK, 25, 169)
                                                        .addUnboundedFrom(REMAINING_HOURS, 169))
                                                .subAggregation(
                                                        getCountWithGrouping(COMPLAINT_TYPE_SLA, IF_SLA, 2))))
                .addAggregation(AggregationBuilders.terms(ULBWISE).field(CITY_CODE).size(120)
                        .subAggregation(AggregationBuilders.terms(WARDWISE).field(WARD_NUMBER).size(size)
                                .subAggregation(getCountWithGroupingAndOrder(GROUP_BY_FIELD, grouByField, size,
                                        complaintDashBoardRequest.getSortField(),
                                        complaintDashBoardRequest.getSortDirection()).subAggregation(
                                                getAverageWithExclusion(GROUP_BY_FIELD_SATISFACTION_AVERAGE,
                                                        SATISFACTION_INDEX))
                                                .subAggregation(AggregationBuilders.topHits(COMPLAINT_RECORD)
                                                        .addField(CITY_CODE).addField(CITY_DISTRICT_NAME)
                                                        .addField(CITY_NAME).addField(WARD_NAME)
                                                        .addField(LOCALITY_NAME).setSize(1))
                                                .subAggregation(getCountWithGrouping(
                                                        GROUP_FIELD_WISE_OPEN_AND_CLOSED_COUNT, IF_CLOSED, 2)
                                                                .subAggregation(AggregationBuilders
                                                                        .range(GROUP_BY_FIELD_AGEING).field(
                                                                                COMPLAINT_AGEINGDAYS_FROM_DUE)
                                                                        .addRange(ONE_WEEK, 0, 8)
                                                                        .addRange(ONE_MONTH, 8, 32)
                                                                        .addRange(THREE_MONTHS, 32, 91)
                                                                        .addUnboundedFrom(REMAINING_MONTHS, 91))
                                                                .subAggregation(AggregationBuilders
                                                                        .range(GROUP_BY_FIELD_AGEING_FOR_HOURS)
                                                                        .field(COMPLAINT_AGEING_FROM_DUE)
                                                                        .addRange(TWELVE_HOURS, 0, 13)
                                                                        .addRange("1day", 13, 25)
                                                                        .addRange(ONE_WEEK, 25, 169)
                                                                        .addUnboundedFrom(REMAINING_HOURS, 169))
                                                                .subAggregation(getCountWithGrouping(
                                                                        GROUP_BY_FIELD_SLA, IF_SLA, 2))))))
                .execute().actionGet();
    else if (complaintDashBoardRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_ALL_FUNCTIONARY))
        tableResponse = elasticsearchTemplate.getClient().prepareSearch(PGR_INDEX_NAME).setQuery(query)
                .setSize(0)
                .addAggregation(getCountWithGroupingAndOrder(COMPLAINT_TYPE_WISE, COMPLAINT_TYPE_NAME, size,
                        complaintDashBoardRequest.getSortField(), complaintDashBoardRequest.getSortDirection())
                                .subAggregation(getAverageWithExclusion(COMPLAINT_TYPE_SATISFACTION_AVERAGE,
                                        SATISFACTION_INDEX))
                                .subAggregation(getCountWithGrouping(COMPLAINT_TYPE_WISE_OPEN_AND_CLOSED_COUNT,
                                        IF_CLOSED, 2)
                                                .subAggregation(AggregationBuilders.range(COMPLAINT_TYPE_AGEING)
                                                        .field(COMPLAINT_AGEINGDAYS_FROM_DUE)
                                                        .addRange(ONE_WEEK, 0, 8).addRange(ONE_MONTH, 8, 32)
                                                        .addRange(THREE_MONTHS, 32, 91)
                                                        .addUnboundedFrom(REMAINING_MONTHS, 91))
                                                .subAggregation(AggregationBuilders
                                                        .range(HOURWISE_COMPLAINT_TYPE_AGEING)
                                                        .field(COMPLAINT_AGEING_FROM_DUE)
                                                        .addRange(TWELVE_HOURS, 0, 13).addRange("1day", 13, 25)
                                                        .addRange(ONE_WEEK, 25, 169)
                                                        .addUnboundedFrom(REMAINING_HOURS, 169))
                                                .subAggregation(
                                                        getCountWithGrouping(COMPLAINT_TYPE_SLA, IF_SLA, 2))))
                .addAggregation(AggregationBuilders.terms(ULBWISE).field(CITY_CODE).size(120)
                        .subAggregation(AggregationBuilders.terms(DEPARTMENTWISE).field(DEPARTMENT_CODE)
                                .size(size)
                                .subAggregation(getCountWithGroupingAndOrder(GROUP_BY_FIELD, grouByField, size,
                                        complaintDashBoardRequest.getSortField(),
                                        complaintDashBoardRequest.getSortDirection()).subAggregation(
                                                getAverageWithExclusion(GROUP_BY_FIELD_SATISFACTION_AVERAGE,
                                                        SATISFACTION_INDEX))
                                                .subAggregation(AggregationBuilders.topHits(COMPLAINT_RECORD)
                                                        .addField(CITY_CODE).addField(CITY_DISTRICT_NAME)
                                                        .addField(CITY_NAME).addField(DEPARTMENT_NAME)
                                                        .addField(INITIAL_FUNCTIONARY_MOBILE_NUMBER).setSize(1))
                                                .subAggregation(getCountWithGrouping(
                                                        GROUP_FIELD_WISE_OPEN_AND_CLOSED_COUNT, IF_CLOSED, 2)
                                                                .subAggregation(AggregationBuilders
                                                                        .range(GROUP_BY_FIELD_AGEING).field(
                                                                                COMPLAINT_AGEINGDAYS_FROM_DUE)
                                                                        .addRange(ONE_WEEK, 0, 8)
                                                                        .addRange(ONE_MONTH, 8, 32)
                                                                        .addRange(THREE_MONTHS, 32, 91)
                                                                        .addUnboundedFrom(REMAINING_MONTHS, 91))
                                                                .subAggregation(AggregationBuilders
                                                                        .range(GROUP_BY_FIELD_AGEING_FOR_HOURS)
                                                                        .field(COMPLAINT_AGEING_FROM_DUE)
                                                                        .addRange(TWELVE_HOURS, 0, 13)
                                                                        .addRange("1day", 13, 25)
                                                                        .addRange(ONE_WEEK, 25, 169)
                                                                        .addUnboundedFrom(REMAINING_HOURS, 169))
                                                                .subAggregation(getCountWithGrouping(
                                                                        GROUP_BY_FIELD_SLA, IF_SLA, 2))))))
                .execute().actionGet();
    else
        tableResponse = elasticsearchTemplate.getClient().prepareSearch(PGR_INDEX_NAME).setQuery(query)
                .setSize(0)
                .addAggregation(getCountWithGroupingAndOrder(COMPLAINT_TYPE_WISE, COMPLAINT_TYPE_NAME, size,
                        complaintDashBoardRequest.getSortField(), complaintDashBoardRequest.getSortDirection())
                                .subAggregation(getAverageWithExclusion(COMPLAINT_TYPE_SATISFACTION_AVERAGE,
                                        SATISFACTION_INDEX))
                                .subAggregation(getCountWithGrouping(COMPLAINT_TYPE_WISE_OPEN_AND_CLOSED_COUNT,
                                        IF_CLOSED, 2)
                                                .subAggregation(AggregationBuilders.range(COMPLAINT_TYPE_AGEING)
                                                        .field(COMPLAINT_AGEINGDAYS_FROM_DUE)
                                                        .addRange(ONE_WEEK, 0, 8).addRange(ONE_MONTH, 8, 32)
                                                        .addRange(THREE_MONTHS, 32, 91)
                                                        .addUnboundedFrom(REMAINING_MONTHS, 91))
                                                .subAggregation(AggregationBuilders
                                                        .range(HOURWISE_COMPLAINT_TYPE_AGEING)
                                                        .field(COMPLAINT_AGEING_FROM_DUE)
                                                        .addRange(TWELVE_HOURS, 0, 13).addRange("1day", 13, 25)
                                                        .addRange(ONE_WEEK, 25, 169)
                                                        .addUnboundedFrom(REMAINING_HOURS, 169))
                                                .subAggregation(
                                                        getCountWithGrouping(COMPLAINT_TYPE_SLA, IF_SLA, 2))))
                .addAggregation(getCountWithGroupingAndOrder(GROUP_BY_FIELD, grouByField, size,
                        complaintDashBoardRequest.getSortField(), complaintDashBoardRequest.getSortDirection())
                                .subAggregation(getAverageWithExclusion(GROUP_BY_FIELD_SATISFACTION_AVERAGE,
                                        SATISFACTION_INDEX))
                                .subAggregation(getCountWithGrouping(GROUP_FIELD_WISE_OPEN_AND_CLOSED_COUNT,
                                        IF_CLOSED, 2)
                                                .subAggregation(AggregationBuilders.range(GROUP_BY_FIELD_AGEING)
                                                        .field(COMPLAINT_AGEINGDAYS_FROM_DUE)
                                                        .addRange(ONE_WEEK, 0, 8).addRange(ONE_MONTH, 8, 32)
                                                        .addRange(THREE_MONTHS, 32, 91)
                                                        .addUnboundedFrom(REMAINING_MONTHS, 91))
                                                .subAggregation(AggregationBuilders
                                                        .range(GROUP_BY_FIELD_AGEING_FOR_HOURS)
                                                        .field(COMPLAINT_AGEING_FROM_DUE)
                                                        .addRange(TWELVE_HOURS, 0, 13).addRange("1day", 13, 25)
                                                        .addRange(ONE_WEEK, 25, 169)
                                                        .addUnboundedFrom(REMAINING_HOURS, 169))
                                                .subAggregation(
                                                        getCountWithGrouping(GROUP_BY_FIELD_SLA, IF_SLA, 2))))
                .execute().actionGet();

    final HashMap<String, SearchResponse> result = new HashMap<>();
    if (grouByField.equals(LOCALITY_NAME)) {
        final SearchResponse localityMissingResponse = elasticsearchTemplate.getClient()
                .prepareSearch(PGR_INDEX_NAME).setQuery(query).setSize(0)
                .addAggregation(AggregationBuilders.missing(NOLOCALITY).field(LOCALITY_NAME)
                        .subAggregation(getAverageWithExclusion(GROUP_BY_FIELD_SATISFACTION_AVERAGE,
                                SATISFACTION_INDEX))
                        .subAggregation(
                                getCountWithGrouping(GROUP_FIELD_WISE_OPEN_AND_CLOSED_COUNT, IF_CLOSED, 2)
                                        .subAggregation(AggregationBuilders.range(GROUP_BY_FIELD_AGEING)
                                                .field(COMPLAINT_AGEINGDAYS_FROM_DUE).addRange(ONE_WEEK, 0, 8)
                                                .addRange(ONE_MONTH, 8, 32).addRange(THREE_MONTHS, 32, 91)
                                                .addUnboundedFrom(REMAINING_MONTHS, 91))
                                        .subAggregation(AggregationBuilders
                                                .range(GROUP_BY_FIELD_AGEING_FOR_HOURS)
                                                .field(COMPLAINT_AGEING_FROM_DUE).addRange(TWELVE_HOURS, 0, 13)
                                                .addRange("1day", 13, 25).addRange(ONE_WEEK, 25, 169)
                                                .addUnboundedFrom(REMAINING_HOURS, 169))
                                        .subAggregation(getCountWithGrouping(GROUP_BY_FIELD_SLA, IF_SLA, 2))))
                .execute().actionGet();
        result.put("noLocality", localityMissingResponse);
    }

    result.put("consolidatedResponse", consolidatedResponse);
    result.put("tableResponse", tableResponse);

    return result;
}