Example usage for java.util Calendar clear

List of usage examples for java.util Calendar clear

Introduction

In this page you can find the example usage for java.util Calendar clear.

Prototype

public final void clear() 

Source Link

Document

Sets all the calendar field values and the time value (millisecond offset from the Epoch) of this Calendar undefined.

Usage

From source file:org.apache.flume.sink.customhdfs.TestHDFSEventSink.java

@Test
public void testSimpleAppend()
        throws InterruptedException, LifecycleException, EventDeliveryException, IOException {

    LOG.debug("Starting...");
    final String fileName = "FlumeData";
    final long rollCount = 5;
    final long batchSize = 2;
    final int numBatches = 4;
    String newPath = testPath + "/singleBucket";
    int totalEvents = 0;
    int i = 1, j = 1;

    // clear the test directory
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    Path dirPath = new Path(newPath);
    fs.delete(dirPath, true);//from   w w w.  j av a  2 s . c o m
    fs.mkdirs(dirPath);

    Context context = new Context();

    context.put("hdfs.path", newPath);
    context.put("hdfs.filePrefix", fileName);
    context.put("hdfs.rollCount", String.valueOf(rollCount));
    context.put("hdfs.batchSize", String.valueOf(batchSize));

    Configurables.configure(sink, context);

    Channel channel = new MemoryChannel();
    Configurables.configure(channel, context);

    sink.setChannel(channel);
    sink.start();

    Calendar eventDate = Calendar.getInstance();
    List<String> bodies = Lists.newArrayList();

    // push the event batches into channel
    for (i = 1; i < numBatches; i++) {
        Transaction txn = channel.getTransaction();
        txn.begin();
        for (j = 1; j <= batchSize; j++) {
            Event event = new SimpleEvent();
            eventDate.clear();
            eventDate.set(2011, i, i, i, 0); // yy mm dd
            event.getHeaders().put("timestamp", String.valueOf(eventDate.getTimeInMillis()));
            event.getHeaders().put("hostname", "Host" + i);
            String body = "Test." + i + "." + j;
            event.setBody(body.getBytes());
            bodies.add(body);
            channel.put(event);
            totalEvents++;
        }
        txn.commit();
        txn.close();

        // execute sink to process the events
        sink.process();
    }

    sink.stop();

    // loop through all the files generated and check their contains
    FileStatus[] dirStat = fs.listStatus(dirPath);
    Path fList[] = FileUtil.stat2Paths(dirStat);

    // check that the roll happened correctly for the given data
    long expectedFiles = totalEvents / rollCount;
    if (totalEvents % rollCount > 0)
        expectedFiles++;
    Assert.assertEquals("num files wrong, found: " + Lists.newArrayList(fList), expectedFiles, fList.length);
    verifyOutputSequenceFiles(fs, conf, dirPath.toUri().getPath(), fileName, bodies);
}

From source file:org.apache.flume.sink.customhdfs.TestHDFSEventSink.java

@Test
public void testBadSimpleAppend()
        throws InterruptedException, LifecycleException, EventDeliveryException, IOException {

    LOG.debug("Starting...");
    final String fileName = "FlumeData";
    final long rollCount = 5;
    final long batchSize = 2;
    final int numBatches = 4;
    String newPath = testPath + "/singleBucket";
    int totalEvents = 0;
    int i = 1, j = 1;

    HDFSTestWriterFactory badWriterFactory = new HDFSTestWriterFactory();
    sink = new HDFSEventSink(badWriterFactory);

    // clear the test directory
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    Path dirPath = new Path(newPath);
    fs.delete(dirPath, true);/*from w  w w .j av  a 2  s .c  o  m*/
    fs.mkdirs(dirPath);

    Context context = new Context();

    context.put("hdfs.path", newPath);
    context.put("hdfs.filePrefix", fileName);
    context.put("hdfs.rollCount", String.valueOf(rollCount));
    context.put("hdfs.batchSize", String.valueOf(batchSize));
    context.put("hdfs.fileType", HDFSTestWriterFactory.TestSequenceFileType);

    Configurables.configure(sink, context);

    Channel channel = new MemoryChannel();
    Configurables.configure(channel, context);

    sink.setChannel(channel);
    sink.start();

    Calendar eventDate = Calendar.getInstance();

    List<String> bodies = Lists.newArrayList();
    // push the event batches into channel
    for (i = 1; i < numBatches; i++) {
        Transaction txn = channel.getTransaction();
        txn.begin();
        for (j = 1; j <= batchSize; j++) {
            Event event = new SimpleEvent();
            eventDate.clear();
            eventDate.set(2011, i, i, i, 0); // yy mm dd
            event.getHeaders().put("timestamp", String.valueOf(eventDate.getTimeInMillis()));
            event.getHeaders().put("hostname", "Host" + i);

            String body = "Test." + i + "." + j;
            event.setBody(body.getBytes());
            bodies.add(body);
            // inject fault
            if ((totalEvents % 30) == 1) {
                event.getHeaders().put("fault-once", "");
            }
            channel.put(event);
            totalEvents++;
        }
        txn.commit();
        txn.close();

        LOG.info("Process events: " + sink.process());
    }
    LOG.info("Process events to end of transaction max: " + sink.process());
    LOG.info("Process events to injected fault: " + sink.process());
    LOG.info("Process events remaining events: " + sink.process());
    sink.stop();
    verifyOutputSequenceFiles(fs, conf, dirPath.toUri().getPath(), fileName, bodies);

}

From source file:org.apache.flume.sink.customhdfs.TestHDFSEventSink.java

private void slowAppendTestHelper(long appendTimeout)
        throws InterruptedException, IOException, LifecycleException, EventDeliveryException, IOException {
    final String fileName = "FlumeData";
    final long rollCount = 5;
    final long batchSize = 2;
    final int numBatches = 2;
    String newPath = testPath + "/singleBucket";
    int totalEvents = 0;
    int i = 1, j = 1;

    // clear the test directory
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    Path dirPath = new Path(newPath);
    fs.delete(dirPath, true);/*from   w w  w  .  j  a  v  a  2s.co  m*/
    fs.mkdirs(dirPath);

    // create HDFS sink with slow writer
    HDFSTestWriterFactory badWriterFactory = new HDFSTestWriterFactory();
    sink = new HDFSEventSink(badWriterFactory);

    Context context = new Context();
    context.put("hdfs.path", newPath);
    context.put("hdfs.filePrefix", fileName);
    context.put("hdfs.rollCount", String.valueOf(rollCount));
    context.put("hdfs.batchSize", String.valueOf(batchSize));
    context.put("hdfs.fileType", HDFSTestWriterFactory.TestSequenceFileType);
    context.put("hdfs.appendTimeout", String.valueOf(appendTimeout));
    Configurables.configure(sink, context);

    Channel channel = new MemoryChannel();
    Configurables.configure(channel, context);

    sink.setChannel(channel);
    sink.start();

    Calendar eventDate = Calendar.getInstance();
    List<String> bodies = Lists.newArrayList();
    // push the event batches into channel
    for (i = 0; i < numBatches; i++) {
        Transaction txn = channel.getTransaction();
        txn.begin();
        for (j = 1; j <= batchSize; j++) {
            Event event = new SimpleEvent();
            eventDate.clear();
            eventDate.set(2011, i, i, i, 0); // yy mm dd
            event.getHeaders().put("timestamp", String.valueOf(eventDate.getTimeInMillis()));
            event.getHeaders().put("hostname", "Host" + i);
            event.getHeaders().put("slow", "1500");
            String body = "Test." + i + "." + j;
            event.setBody(body.getBytes());
            bodies.add(body);
            channel.put(event);
            totalEvents++;
        }
        txn.commit();
        txn.close();

        // execute sink to process the events
        sink.process();
    }

    sink.stop();

    // loop through all the files generated and check their contains
    FileStatus[] dirStat = fs.listStatus(dirPath);
    Path fList[] = FileUtil.stat2Paths(dirStat);

    // check that the roll happened correctly for the given data
    // Note that we'll end up with two files with only a head
    long expectedFiles = totalEvents / rollCount;
    if (totalEvents % rollCount > 0)
        expectedFiles++;
    Assert.assertEquals("num files wrong, found: " + Lists.newArrayList(fList), expectedFiles, fList.length);
    verifyOutputSequenceFiles(fs, conf, dirPath.toUri().getPath(), fileName, bodies);
}

From source file:org.apache.flume.sink.customhdfs.TestHDFSEventSink.java

@Test
public void testSimpleAppendLocalTime()
        throws InterruptedException, LifecycleException, EventDeliveryException, IOException {
    final long currentTime = System.currentTimeMillis();
    Clock clk = new Clock() {
        @Override//w w  w . ja v a  2s.  c om
        public long currentTimeMillis() {
            return currentTime;
        }
    };

    LOG.debug("Starting...");
    final String fileName = "FlumeData";
    final long rollCount = 5;
    final long batchSize = 2;
    final int numBatches = 4;
    String newPath = testPath + "/singleBucket/%s";
    String expectedPath = testPath + "/singleBucket/" + String.valueOf(currentTime / 1000);
    int totalEvents = 0;
    int i = 1, j = 1;

    // clear the test directory
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    Path dirPath = new Path(expectedPath);
    fs.delete(dirPath, true);
    fs.mkdirs(dirPath);

    Context context = new Context();

    context.put("hdfs.path", newPath);
    context.put("hdfs.filePrefix", fileName);
    context.put("hdfs.rollCount", String.valueOf(rollCount));
    context.put("hdfs.batchSize", String.valueOf(batchSize));
    context.put("hdfs.useLocalTimeStamp", String.valueOf(true));

    Configurables.configure(sink, context);

    Channel channel = new MemoryChannel();
    Configurables.configure(channel, context);

    sink.setChannel(channel);
    sink.setBucketClock(clk);
    sink.start();

    Calendar eventDate = Calendar.getInstance();
    List<String> bodies = Lists.newArrayList();

    // push the event batches into channel
    for (i = 1; i < numBatches; i++) {
        Transaction txn = channel.getTransaction();
        txn.begin();
        for (j = 1; j <= batchSize; j++) {
            Event event = new SimpleEvent();
            eventDate.clear();
            eventDate.set(2011, i, i, i, 0); // yy mm dd
            event.getHeaders().put("timestamp", String.valueOf(eventDate.getTimeInMillis()));
            event.getHeaders().put("hostname", "Host" + i);
            String body = "Test." + i + "." + j;
            event.setBody(body.getBytes());
            bodies.add(body);
            channel.put(event);
            totalEvents++;
        }
        txn.commit();
        txn.close();

        // execute sink to process the events
        sink.process();
    }

    sink.stop();

    // loop through all the files generated and check their contains
    FileStatus[] dirStat = fs.listStatus(dirPath);
    Path fList[] = FileUtil.stat2Paths(dirStat);

    // check that the roll happened correctly for the given data
    long expectedFiles = totalEvents / rollCount;
    if (totalEvents % rollCount > 0)
        expectedFiles++;
    Assert.assertEquals("num files wrong, found: " + Lists.newArrayList(fList), expectedFiles, fList.length);
    verifyOutputSequenceFiles(fs, conf, dirPath.toUri().getPath(), fileName, bodies);
    // The clock in bucketpath is static, so restore the real clock
    sink.setBucketClock(new SystemClock());
}

From source file:freemarker.ext.dump.DumpDirectiveTest.java

private Employee getEmployee() {

    Calendar c = Calendar.getInstance();
    c.set(1982, Calendar.MAY, 5);
    c = DateUtils.truncate(c, Calendar.DATE);
    Employee jdoe = new Employee("John", "Doe", 34523, c.getTime());
    jdoe.setFavoriteColors("blue", "green");
    jdoe.setSalary(65000);/*from   w w w.  java  2s  .c o m*/

    //        Map<String, String> degrees = new HashMap<String, String>();
    //        degrees.put("BA", "Mathematics");
    //        degrees.put("MS", "Computer Science");
    //        jdoe.setDegrees(degrees);

    c.clear();
    c.set(1975, Calendar.OCTOBER, 25);
    c = DateUtils.truncate(c, Calendar.DATE);
    Employee jsmith = new Employee("Jane", "Smith", 78234, c.getTime());
    jsmith.setFavoriteColors("red", "orange");

    jdoe.setSupervisor(jsmith);

    return jdoe;
}

From source file:org.apache.flume.sink.customhdfs.TestHDFSEventSink.java

public void doTestTextBatchAppend(boolean useRawLocalFileSystem) throws Exception {
    LOG.debug("Starting...");

    final long rollCount = 10;
    final long batchSize = 2;
    final String fileName = "FlumeData";
    String newPath = testPath + "/singleTextBucket";
    int totalEvents = 0;
    int i = 1, j = 1;

    // clear the test directory
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    Path dirPath = new Path(newPath);
    fs.delete(dirPath, true);/*from   w ww .j a  v  a 2  s . c  o m*/
    fs.mkdirs(dirPath);

    Context context = new Context();

    // context.put("hdfs.path", testPath + "/%Y-%m-%d/%H");
    context.put("hdfs.path", newPath);
    context.put("hdfs.filePrefix", fileName);
    context.put("hdfs.rollCount", String.valueOf(rollCount));
    context.put("hdfs.rollInterval", "0");
    context.put("hdfs.rollSize", "0");
    context.put("hdfs.batchSize", String.valueOf(batchSize));
    context.put("hdfs.writeFormat", "Text");
    context.put("hdfs.useRawLocalFileSystem", Boolean.toString(useRawLocalFileSystem));
    context.put("hdfs.fileType", "DataStream");

    Configurables.configure(sink, context);

    Channel channel = new MemoryChannel();
    Configurables.configure(channel, context);

    sink.setChannel(channel);
    sink.start();

    Calendar eventDate = Calendar.getInstance();
    List<String> bodies = Lists.newArrayList();

    // push the event batches into channel to roll twice
    for (i = 1; i <= (rollCount * 10) / batchSize; i++) {
        Transaction txn = channel.getTransaction();
        txn.begin();
        for (j = 1; j <= batchSize; j++) {
            Event event = new SimpleEvent();
            eventDate.clear();
            eventDate.set(2011, i, i, i, 0); // yy mm dd
            String body = "Test." + i + "." + j;
            event.setBody(body.getBytes());
            bodies.add(body);
            channel.put(event);
            totalEvents++;
        }
        txn.commit();
        txn.close();

        // execute sink to process the events
        sink.process();
    }

    sink.stop();

    // loop through all the files generated and check their contains
    FileStatus[] dirStat = fs.listStatus(dirPath);
    Path fList[] = FileUtil.stat2Paths(dirStat);

    // check that the roll happened correctly for the given data
    long expectedFiles = totalEvents / rollCount;
    if (totalEvents % rollCount > 0)
        expectedFiles++;
    Assert.assertEquals("num files wrong, found: " + Lists.newArrayList(fList), expectedFiles, fList.length);
    // check the contents of the all files
    verifyOutputTextFiles(fs, conf, dirPath.toUri().getPath(), fileName, bodies);
}

From source file:com.square.core.service.implementations.ActionServiceImplementation.java

/**
 * Mthode prive qui crer un objet action  partir d'un objet actionDto.
 * @param actionDto l'action dto Source//from   w  w w . j  a  v a  2  s.  co m
 * @param action l'action resultante
 */
private void mapperAction(ActionCreationDto actionCreationDto, Action action, ActionNature natureAction,
        ActionType typeAction, ActionObjet objetAction, ActionSousObjet sousObjetAction,
        ActionPriorite prioriteAction, Campagne campagne, ActionDuree dureeAction) {
    action.setDate(actionCreationDto.getDateAction());
    // Nature Action
    if (natureAction != null) {
        action.setNature(natureAction);
    }
    // Type
    if (typeAction != null) {
        action.setType(typeAction);
    }
    // Objet
    if (objetAction != null) {
        action.setObjet(objetAction);
    }
    // Sous objet
    if (sousObjetAction != null) {
        action.setSousObjet(sousObjetAction);
    }
    // Priorit
    if (prioriteAction != null) {
        action.setPriorite(prioriteAction);
    } else {
        action.setPriorite(actionPrioriteDao
                .rechercherPrioriteActionParId(squareMappingService.getIdActionPrioriteParDefaut()));
    }
    // Campagne
    if (campagne != null) {
        action.setCampagne(campagne);
    }
    // Dure
    if (dureeAction != null) {
        action.setDuree(dureeAction);
    }
    // Enregistrement de la date de notification
    if (actionCreationDto.getRappel() != null && actionCreationDto.getRappel()) {
        if (actionCreationDto.getIdNotificationList() != null) {
            final ActionNotificationInfosDto notification = squareMappingService
                    .getActionNotificationParId(actionCreationDto.getIdNotificationList());
            final Calendar soustraction = Calendar.getInstance();
            soustraction.clear();
            final Long dateTime = -notification.getNotification().getTimeInMillis()
                    + actionCreationDto.getDateAction().getTimeInMillis();
            soustraction.setTimeInMillis(dateTime);
            action.setDateNotification(soustraction);
        }
    } else {
        action.setDateNotification(null);
    }
    // Rclamation
    if (actionCreationDto.getReclamation() != null) {
        action.setReclamation(actionCreationDto.getReclamation());
    } else {
        action.setReclamation(false);
    }
    // Mail notification
    if (actionCreationDto.getMePrevenirParMail() != null) {
        action.setMailNotification(actionCreationDto.getMePrevenirParMail());
    } else {
        action.setMailNotification(false);
    }
    // Date d'affichage
    if (actionCreationDto.getDateAffichageAction() != null) {
        action.setDateAffichage(actionCreationDto.getDateAffichageAction());
    }
    // Date de cration
    action.setDateCreation(Calendar.getInstance());
}

From source file:de.csdev.ebus.command.datatypes.ext.EBusTypeTime.java

@Override
public byte[] encodeInt(Object data) throws EBusTypeException {

    IEBusType<BigDecimal> bcdType = types.getType(EBusTypeBCD.TYPE_BCD);
    IEBusType<BigDecimal> wordType = types.getType(EBusTypeWord.TYPE_WORD);
    IEBusType<BigDecimal> charType = types.getType(EBusTypeChar.TYPE_CHAR);

    Calendar calendar = null;
    byte[] result = new byte[this.getTypeLength()];

    if (data instanceof EBusDateTime) {
        calendar = ((EBusDateTime) data).getCalendar();

    } else if (data instanceof Calendar) {
        calendar = (Calendar) data;
    }//from  w w  w.j a  v  a2s . c om

    // set date to 01.01.1970
    calendar = (Calendar) calendar.clone();
    calendar.set(1970, 0, 1);

    if (calendar != null) {
        if (StringUtils.equals(variant, DEFAULT)) {

            result = new byte[] { bcdType.encode(calendar.get(Calendar.SECOND))[0],
                    bcdType.encode(calendar.get(Calendar.MINUTE))[0],
                    bcdType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, SHORT)) {

            result = new byte[] { bcdType.encode(calendar.get(Calendar.MINUTE))[0],
                    bcdType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, HEX)) {

            result = new byte[] { charType.encode(calendar.get(Calendar.SECOND))[0],
                    charType.encode(calendar.get(Calendar.MINUTE))[0],
                    charType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, HEX_SHORT)) {

            result = new byte[] { charType.encode(calendar.get(Calendar.MINUTE))[0],
                    charType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, MINUTES) || StringUtils.equals(variant, MINUTES_SHORT)) {

            long millis = calendar.getTimeInMillis();

            calendar.clear();
            calendar.set(1970, 0, 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            long millisMidnight = calendar.getTimeInMillis();

            BigDecimal minutes = new BigDecimal(millis - millisMidnight);

            // milliseconds to minutes
            minutes = minutes.divide(BigDecimal.valueOf(1000 * 60), 0, RoundingMode.HALF_UP);

            // xxx
            minutes = minutes.divide(minuteMultiplier, 0, RoundingMode.HALF_UP);

            if (StringUtils.equals(variant, MINUTES_SHORT)) {
                result = charType.encode(minutes);
            } else {
                result = wordType.encode(minutes);
            }

        }
    }

    return result;
}

From source file:org.exoplatform.addon.pulse.service.ws.RestActivitiesStatistic.java

private ChartData buildStatisticByFilter(String maxColumn, String filter, Date fromDate) throws Exception {

    int totalDataCoulumn = 5;
    try {/*from   w  w  w  .j  a v  a 2s  .  com*/
        totalDataCoulumn = Integer.parseInt(maxColumn);
    } catch (Exception e) {
        //do nothing
    }

    if (filter.equalsIgnoreCase(FILTER_BY_DAY)) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(fromDate);
        calendar.add(Calendar.DATE, totalDataCoulumn - 1);
        Date toDate = calendar.getTime();

        List<ActivityStatisticBean> list = service.getListActivityStatisticByDate(fromDate, toDate);
        TreeMap<Date, ActivityStatisticBean> dateData = new TreeMap<Date, ActivityStatisticBean>();
        //init empty-data
        for (int i = 0; i < totalDataCoulumn; i++) {
            calendar.clear();
            calendar.setTime(fromDate);
            calendar.add(Calendar.DATE, i);
            Date nextDate = parseDate(partString(calendar.getTime(), "dd/MM/yyyy"), "dd/MM/yyyy");
            dateData.put(nextDate, null);
        }

        List<String> listTitle = new ArrayList<String>();
        List<Long> newUsersData = new ArrayList<Long>();
        List<Long> loginCountData = new ArrayList<Long>();
        List<Long> forumActiveUsersData = new ArrayList<Long>();
        List<Long> newForumPostsData = new ArrayList<Long>();

        List<Long> userConnectionData = new ArrayList<Long>();
        List<Long> socialPostData = new ArrayList<Long>();
        List<Long> emailNotificationData = new ArrayList<Long>();

        ChartData chartData = new ChartData();

        for (ActivityStatisticBean bean : list) {
            dateData.put(parseDate(partString(bean.getCreatedDate(), "dd/MM/yyyy"), "dd/MM/yyyy"), bean);
        }

        for (Date key : dateData.keySet()) {
            ActivityStatisticBean bean = dateData.get(key);
            if (bean != null) {
                listTitle.add(partString(bean.getCreatedDate(), "dd-MM-yyyy"));
                newUsersData.add(bean.getNewUserToday());
                loginCountData.add(bean.getLoginCountToday());
                forumActiveUsersData.add(bean.getForumActiveUserToday());
                newForumPostsData.add(bean.getForumPostToday());

                userConnectionData.add(bean.getUserConnectionCountToday());
                socialPostData.add(bean.getSocialPostCountToday());
                emailNotificationData.add(bean.getEmailNotificationCountToday());
            } else {
                listTitle.add(partString(key, "dd-MM-yyyy"));
                newUsersData.add(0L);
                loginCountData.add(0L);
                forumActiveUsersData.add(0L);
                newForumPostsData.add(0L);
                userConnectionData.add(0L);
                socialPostData.add(0L);
                emailNotificationData.add(0L);
            }
        }

        chartData.setListTitle(listTitle);
        chartData.setNewUsersData(newUsersData);
        chartData.setLoginCountData(loginCountData);
        chartData.setForumActiveUsersData(forumActiveUsersData);
        chartData.setNewForumPostsData(newForumPostsData);

        chartData.setUserConnectionData(userConnectionData);
        chartData.setSocialPostData(socialPostData);
        chartData.setEmailNotificationData(emailNotificationData);
        return chartData;
    }

    if (filter.equalsIgnoreCase(FILTER_BY_WEEK)) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setTime(fromDate);
        calendar.add(Calendar.WEEK_OF_YEAR, totalDataCoulumn - 1);
        Date nextFewWeek = calendar.getTime();

        List<ActivityStatisticBean> list = service.getListActivityStatisticByDate(fromDate, nextFewWeek);

        List<String> listTitle = new ArrayList<String>();
        List<Long> newUsersData = new ArrayList<Long>();
        List<Long> loginCountData = new ArrayList<Long>();
        List<Long> forumActiveUsersData = new ArrayList<Long>();
        List<Long> newForumPostsData = new ArrayList<Long>();

        List<Long> userConnectionData = new ArrayList<Long>();
        List<Long> socialPostData = new ArrayList<Long>();
        List<Long> emailNotificationData = new ArrayList<Long>();

        ChartData chartData = new ChartData();

        TreeMap<String, List<ActivityStatisticBean>> weekData = new TreeMap<String, List<ActivityStatisticBean>>();
        //init empty-data
        for (int i = 0; i < totalDataCoulumn; i++) {
            calendar.clear();
            calendar.setTime(fromDate);
            calendar.add(Calendar.WEEK_OF_YEAR, i);
            int weekIndex = calendar.get(Calendar.WEEK_OF_YEAR);
            int monthIndex = calendar.get(Calendar.MONTH);
            if (monthIndex == Calendar.DECEMBER && weekIndex == 1)
                weekIndex = 53;
            int year = calendar.get(Calendar.YEAR);
            //goto begin of week
            calendar.clear();
            calendar.set(Calendar.WEEK_OF_YEAR, weekIndex);
            calendar.set(Calendar.YEAR, year);
            //goto end of week
            calendar.add(Calendar.DATE, 6);

            String week = "";
            if (calendar.get(Calendar.MONTH) == Calendar.DECEMBER && calendar.get(Calendar.WEEK_OF_YEAR) == 1) {
                week = 53 + "-" + calendar.get(Calendar.YEAR);
            } else {
                week = calendar.get(Calendar.WEEK_OF_YEAR) + "-" + calendar.get(Calendar.YEAR);
            }
            week = week.length() < 7 ? calendar.get(Calendar.YEAR) + "-" + "0" + week
                    : calendar.get(Calendar.YEAR) + "-" + week;
            weekData.put(week, new ArrayList<ActivityStatisticBean>());
        }

        for (ActivityStatisticBean bean : list) {
            calendar.clear();
            calendar.setTime(bean.getCreatedDate());

            int weekIndex = calendar.get(Calendar.WEEK_OF_YEAR);
            int monthIndex = calendar.get(Calendar.MONTH);
            if (monthIndex == Calendar.DECEMBER && weekIndex == 1)
                weekIndex = 53;
            int year = calendar.get(Calendar.YEAR);
            //goto begin of week
            calendar.clear();
            calendar.set(Calendar.WEEK_OF_YEAR, weekIndex);
            calendar.set(Calendar.YEAR, year);
            //goto end of week
            calendar.add(Calendar.DATE, 6);

            String week = "";
            if (calendar.get(Calendar.MONTH) == Calendar.DECEMBER && calendar.get(Calendar.WEEK_OF_YEAR) == 1) {
                week = 53 + "-" + calendar.get(Calendar.YEAR);
            } else {
                week = calendar.get(Calendar.WEEK_OF_YEAR) + "-" + calendar.get(Calendar.YEAR);
            }
            week = week.length() < 7 ? calendar.get(Calendar.YEAR) + "-" + "0" + week
                    : calendar.get(Calendar.YEAR) + "-" + week;

            if (weekData.containsKey(week)) {
                List<ActivityStatisticBean> listValueOfNode = weekData.get(week);
                listValueOfNode.add(bean);
            } else {
                List<ActivityStatisticBean> listValueOfNode = new ArrayList<ActivityStatisticBean>();
                listValueOfNode.add(bean);
                weekData.put(week, listValueOfNode);
            }
        }

        for (String key : weekData.keySet()) {
            List<ActivityStatisticBean> listValueOfNode = weekData.get(key);
            Long weekNewUsersValue = 0L;
            Long weekLoginCountValue = 0L;
            Long weekForumActiveUsersValue = 0L;
            Long weekNewForumPostsValue = 0L;

            Long weekUserConnectionValue = 0L;
            Long weekSocialPostsValue = 0L;
            Long weekEmailNotificationValue = 0L;

            for (ActivityStatisticBean obj : listValueOfNode) {
                weekNewUsersValue = weekNewUsersValue + obj.getNewUserToday();
                weekLoginCountValue = weekLoginCountValue + obj.getLoginCountToday();
                weekForumActiveUsersValue = weekForumActiveUsersValue + obj.getForumActiveUserToday();
                weekNewForumPostsValue = weekNewForumPostsValue + obj.getForumPostToday();

                weekUserConnectionValue = weekUserConnectionValue + obj.getUserConnectionCountToday();
                weekSocialPostsValue = weekSocialPostsValue + obj.getSocialPostCountToday();
                weekEmailNotificationValue = weekEmailNotificationValue + obj.getEmailNotificationCountToday();
            }

            String weekTitle = "W" + key.substring(5, key.length());
            listTitle.add(weekTitle);
            newUsersData.add(weekNewUsersValue);
            loginCountData.add(weekLoginCountValue);
            forumActiveUsersData.add(
                    weekForumActiveUsersValue > 0 ? (Long) (weekForumActiveUsersValue / listValueOfNode.size())
                            : 0L);
            newForumPostsData.add(weekNewForumPostsValue);

            userConnectionData.add(weekUserConnectionValue);
            socialPostData.add(weekSocialPostsValue);
            emailNotificationData.add(weekEmailNotificationValue);
        }
        chartData.setListTitle(listTitle);
        chartData.setNewUsersData(newUsersData);
        chartData.setLoginCountData(loginCountData);
        chartData.setForumActiveUsersData(forumActiveUsersData);
        chartData.setNewForumPostsData(newForumPostsData);

        chartData.setUserConnectionData(userConnectionData);
        chartData.setSocialPostData(socialPostData);
        chartData.setEmailNotificationData(emailNotificationData);

        return chartData;
    }

    if (filter.equalsIgnoreCase(FILTER_BY_MONTH)) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setTime(fromDate);
        calendar.add(Calendar.MONTH, totalDataCoulumn - 1);
        Date nextFewMonth = calendar.getTime();

        List<ActivityStatisticBean> list = service.getListActivityStatisticByDate(fromDate, nextFewMonth);

        List<String> listTitle = new ArrayList<String>();
        List<Long> newUsersData = new ArrayList<Long>();
        List<Long> loginCountData = new ArrayList<Long>();
        List<Long> forumActiveUsersData = new ArrayList<Long>();
        List<Long> newForumPostsData = new ArrayList<Long>();

        List<Long> userConnectionData = new ArrayList<Long>();
        List<Long> socialPostData = new ArrayList<Long>();
        List<Long> emailNotificationData = new ArrayList<Long>();

        ChartData chartData = new ChartData();

        TreeMap<String, List<ActivityStatisticBean>> monthData = new TreeMap<String, List<ActivityStatisticBean>>();

        //init empty-data
        for (int i = 0; i < totalDataCoulumn; i++) {
            calendar.clear();
            calendar.setTime(fromDate);
            calendar.add(Calendar.MONTH, i);
            String month = calendar.get(Calendar.YEAR) + "-" + partString(calendar.getTime(), "MM") + "-"
                    + partString(calendar.getTime(), "MMM") + "-" + calendar.get(Calendar.YEAR); //get name of Month
            monthData.put(month, new ArrayList<ActivityStatisticBean>());
        }

        for (ActivityStatisticBean bean : list) {
            calendar.clear();
            calendar.setTime(bean.getCreatedDate());
            String month = calendar.get(Calendar.YEAR) + "-" + partString(calendar.getTime(), "MM") + "-"
                    + partString(calendar.getTime(), "MMM") + "-" + calendar.get(Calendar.YEAR); //get name of Month

            if (monthData.containsKey(month)) {
                List<ActivityStatisticBean> listValueOfNode = monthData.get(month);
                listValueOfNode.add(bean);
            } else {
                List<ActivityStatisticBean> listValueOfNode = new ArrayList<ActivityStatisticBean>();
                listValueOfNode.add(bean);
                monthData.put(month, listValueOfNode);
            }
        }

        for (String key : monthData.keySet()) {
            List<ActivityStatisticBean> listValueOfNode = monthData.get(key);
            Long monthNewUsersValue = 0L;
            Long monthLoginCountValue = 0L;
            Long monthForumActiveUsersValue = 0L;
            Long monthNewForumPostsValue = 0L;

            Long monthUserConnectionValue = 0L;
            Long monthSocialPostsValue = 0L;
            Long monthEmailNotificationValue = 0L;

            for (ActivityStatisticBean obj : listValueOfNode) {
                monthNewUsersValue = monthNewUsersValue + obj.getNewUserToday();
                monthLoginCountValue = monthLoginCountValue + obj.getLoginCountToday();
                monthForumActiveUsersValue = monthForumActiveUsersValue + obj.getForumActiveUserToday();
                monthNewForumPostsValue = monthNewForumPostsValue + obj.getForumPostToday();

                monthUserConnectionValue = monthUserConnectionValue + obj.getUserConnectionCountToday();
                monthSocialPostsValue = monthSocialPostsValue + obj.getSocialPostCountToday();
                monthEmailNotificationValue = +monthEmailNotificationValue
                        + obj.getEmailNotificationCountToday();
            }

            listTitle.add(key.substring(8, key.length()));
            newUsersData.add(monthNewUsersValue);
            loginCountData.add(monthLoginCountValue);
            forumActiveUsersData.add(monthForumActiveUsersValue > 0
                    ? (Long) (monthForumActiveUsersValue / listValueOfNode.size())
                    : 0L);
            newForumPostsData.add(monthNewForumPostsValue);

            userConnectionData.add(monthUserConnectionValue);
            socialPostData.add(monthSocialPostsValue);
            emailNotificationData.add(monthEmailNotificationValue);
        }
        chartData.setListTitle(listTitle);
        chartData.setNewUsersData(newUsersData);
        chartData.setLoginCountData(loginCountData);
        chartData.setForumActiveUsersData(forumActiveUsersData);
        chartData.setNewForumPostsData(newForumPostsData);

        chartData.setUserConnectionData(userConnectionData);
        chartData.setSocialPostData(socialPostData);
        chartData.setEmailNotificationData(emailNotificationData);

        return chartData;
    }
    return null;
}

From source file:com.square.core.service.implementations.ActionServiceImplementation.java

@Override
public ActionResultatDto modifierAction(ActionModificationDto actionModificationDto) {
    // Dto null/*  w  w  w .  j av  a  2 s.com*/
    if (actionModificationDto == null) {
        throw new BusinessException(messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_DTO_NULL));
    }

    // Identifiant de l'action null
    if (actionModificationDto.getIdAction() == null) {
        throw new BusinessException(messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_IDACTION_NULL));
    }

    // Rcupration de l'action correspondant
    final Action actionAModifier = actionDao.rechercherActionParId(actionModificationDto.getIdAction());
    if (actionAModifier == null) {
        throw new BusinessException(messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_INEXISTANTE));
    }
    if (logger.isDebugEnabled()) {
        logger.debug("bug 0008864 : modifierAction(ActionModificationDto)");
        logger.debug("recuperation de l'action : " + actionModificationDto.getIdAction());
        logger.debug("dateCreation = " + (actionAModifier.getDateCreation() != null
                ? SDF.format(actionAModifier.getDateCreation().getTime())
                : "null"));
    }

    Agence agence = null;
    if (actionModificationDto.getAgence() != null
            && actionModificationDto.getAgence().getIdentifiant() != null) {
        agence = agenceDao.rechercheAgenceParId(actionModificationDto.getAgence().getIdentifiant());
        if (agence == null) {
            logger.error(
                    "L'agence id = " + actionModificationDto.getAgence().getIdentifiant() + "n'existe pas.");
            throw new TechnicalException(
                    messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_AGENCE_INEXISTANTE));
        }
    }

    // Rcupration de la ressource correspondant au commercial (on permet dsormais le changement de ressource mme si existant)
    Ressource commercial = null;
    if (actionAModifier.getActionAttribution() != null && actionModificationDto.getRessource() != null
            && actionModificationDto.getRessource().getIdentifiant() != null) {
        commercial = ressourceDao
                .rechercherRessourceParId(actionModificationDto.getRessource().getIdentifiant());
        if (commercial == null) {
            logger.error(
                    "La ressource " + actionModificationDto.getRessource().getIdentifiant() + " n'existe pas");
            throw new BusinessException(
                    messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_COMMERCIAL_INEXISTANTE));
        }
    }

    // Rcupration de la dure
    ActionDuree dureeAction = null;
    if (actionModificationDto.getIdDuree() != null) {
        dureeAction = actionDureeDao.rechercherDureeActionParId(actionModificationDto.getIdDuree());
        if (dureeAction == null) {
            throw new BusinessException(
                    messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_DUREE_INEXISTANTE));
        }
    }

    final RapportDto rapport = new RapportDto();

    // Vrification de la nature
    if (actionModificationDto.getNatureAction() == null
            || actionModificationDto.getNatureAction().getIdentifiant() == null) {
        rapport.ajoutRapport(ActionModificationDto.class.getSimpleName() + ".nature",
                messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_NATURE_ACTION_NULL), true);
    }

    // Pour une action de nature "tlphone sortant" passant au statut "termin"
    if (actionModificationDto.getNatureAction() != null
            && squareMappingService.getIdNatureActionTelephoneSortant()
                    .equals(actionModificationDto.getNatureAction().getIdentifiant())
            && actionModificationDto.getStatut() != null && squareMappingService.getIdStatutActionTermine()
                    .equals(actionModificationDto.getStatut().getIdentifiant())) {
        // On vrifie que le rsultat de la nature est renseign
        if (actionModificationDto.getNatureResultat() == null
                || actionModificationDto.getNatureResultat().getIdentifiant() == null) {
            rapport.ajoutRapport(ActionModificationDto.class.getSimpleName() + ".natureResultat",
                    messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_NATURE_RESULTAT_ACTION_NULL),
                    true);
        }
    }

    // vrification que la nature de resultat est selectionne pour la nature d'action visite sortante si on demande la vrification
    if (!BooleanUtils.isFalse(actionModificationDto.getVerifierResultatNatureAction())
            && actionModificationDto.getNatureAction() != null
            && squareMappingService.getIdNatureActionVisiteSortante()
                    .equals(actionModificationDto.getNatureAction().getIdentifiant())
            && actionModificationDto.getNatureResultat() == null && squareMappingService
                    .getIdStatutActionTermine().equals(actionModificationDto.getStatut().getIdentifiant())) {
        throw new BusinessException(
                messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_NATURE_RESULTAT_VISITE_SORTANTE));
    }

    // Contrle du statut
    final ValidationExpressionProp[] propsAction = new ValidationExpressionProp[] {
            new ValidationExpressionProp("statut", null,
                    messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_STATUT_NULL)),
            new ValidationExpressionProp("dateAction", null,
                    messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_DATE_ACTION_NULL)) };

    validationExpressionUtil.verifierSiVide(rapport, actionModificationDto, propsAction);

    if (actionModificationDto.getDateAction() != null) {
        // On copie la date de l'action enregistre en base
        final Calendar ancienneDateAction = DateUtils.truncate((Calendar) actionAModifier.getDate().clone(),
                Calendar.HOUR);
        // On copie la nouvelle date d'action
        final Calendar nouvelleDateAction = DateUtils
                .truncate((Calendar) actionModificationDto.getDateAction().clone(), Calendar.HOUR);
        // Si la date de l'action est modifie
        if (!ancienneDateAction.equals(nouvelleDateAction)) {
            // On vrifie que la date d'action est postrieure  la date courante
            if (DateUtils.truncate(nouvelleDateAction, Calendar.DAY_OF_MONTH)
                    .before(DateUtils.truncate(Calendar.getInstance(), Calendar.DAY_OF_MONTH))) {
                rapport.ajoutRapport(actionModificationDto.getClass().getSimpleName() + ".dateAction",
                        messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_DATE_ACTION_INVALIDE), true);
            }
        }
    }

    // Une action ne peut tre termine sans tre attribue
    if (actionModificationDto.getStatut() != null
            && squareMappingService.getIdStatutActionTermine()
                    .equals(actionModificationDto.getStatut().getIdentifiant())
            && (actionModificationDto.getRessource() == null
                    || actionModificationDto.getRessource().getIdentifiant() == null)) {
        rapport.ajoutRapport(ActionModificationDto.class.getSimpleName() + ".statut",
                messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_TERMINEE_SANS_ATTRIBUTION), true);
    }

    // On ne peut rendre visible une action dans l'agenda que si elle a une date de dbut, une dure
    if (actionModificationDto.getVisibleAgenda() != null
            && actionModificationDto.getVisibleAgenda().booleanValue()
            && (actionModificationDto.getDateAction() == null || actionModificationDto.getIdDuree() == null)) {
        rapport.ajoutRapport(actionModificationDto.getClass().getSimpleName() + ".isVisibleAgenda",
                messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_IMPOSSIBLE_VISIBLE_AGENDA), true);
    }

    // Prsence d'erreurs empchant la modification de l'action
    if (rapport.getEnErreur()) {
        // On retourne le rapport d'erreur
        RapportUtil.logRapport(rapport, logger);
        throw new ControleIntegriteException(rapport);
    }

    // Vrification de l'existance des nouveaux champs
    verificationExistanceModification(actionModificationDto, actionAModifier);

    // Vrification de la rgle de gestion de l'opportunit en cours
    if (Boolean.TRUE.equals(actionModificationDto.getVerifierRegleGestionOpportuniteEnCours())) {
        verifierRegleGestionOpportuniteOuverte(actionModificationDto, actionAModifier);
    }

    // Modification de l'action
    if (actionModificationDto.getNatureAction() != null
            && actionModificationDto.getNatureAction().getIdentifiant() != null) {
        final ActionNature nature = actionNatureDao
                .rechercherNatureActionParId(actionModificationDto.getNatureAction().getIdentifiant());
        if (nature == null) {
            throw new TechnicalException(
                    messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_NATURE_ACTION_INEXISTANT));
        }
        actionAModifier.setNature(nature);
    }
    // modification du type d'action
    final IdentifiantLibelleDto typeAction = actionModificationDto.getTypeAction();
    if (actionModificationDto.getTypeAction() != null && typeAction.getIdentifiant() != null) {
        actionAModifier.setType(actionTypeDao.rechercherTypeActionParId(typeAction.getIdentifiant()));
    }

    // modificatio de l'objet d'action
    final IdentifiantLibelleDto objetAction = actionModificationDto.getObjetAction();
    if (actionModificationDto.getObjetAction() != null && objetAction.getIdentifiant() != null) {
        actionAModifier.setObjet(actionObjetDao.rechercherObjetActionParId(objetAction.getIdentifiant()));
    }
    // affectation au pot commun
    if (actionModificationDto.getAffectationPotCommun() != null
            && actionModificationDto.getAffectationPotCommun()) {
        actionAModifier.getActionAttribution()
                .setAgence(agenceDao.rechercheAgenceParId(squareMappingService.getIdentifiantAgenceFrance()));
        actionAModifier.getActionAttribution().setRessource(null);
    }
    if (actionModificationDto.getRappelMail() != null) {
        actionAModifier.setMailNotification(actionModificationDto.getRappelMail());
    }
    // action tlphone sortant ou visite sortante
    if (actionModificationDto.getNatureAction() != null
            && (squareMappingService.getIdNatureActionTelephoneSortant()
                    .equals(actionModificationDto.getNatureAction().getIdentifiant())
                    || squareMappingService.getIdNatureActionVisiteSortante()
                            .equals(actionModificationDto.getNatureAction().getIdentifiant()))) {
        if (actionModificationDto.getNatureResultat() != null
                && actionModificationDto.getNatureResultat().getIdentifiant() != null) {
            actionAModifier.setNatureResultat(actionNatureResultatDao.rechercherNatureResultatActionById(
                    actionModificationDto.getNatureResultat().getIdentifiant()));
        } else {
            actionAModifier.setNatureResultat(null);
        }
    }

    if (agence != null) {
        // si on affecte une action de relance (qui n'avait pas d'agence)  une agence, on affecte aussi l'opp  l'agence
        if (actionAModifier.getActionAttribution().getAgence() == null
                && actionAModifier.getType().getId().equals(squareMappingService.getIdTypeActionRelance())
                && actionAModifier.getActionAffectation().getOpportunite() != null) {
            actionAModifier.getActionAffectation().getOpportunite().getOpportuniteAttribution()
                    .setAgence(agence);
        }
        actionAModifier.getActionAttribution().setAgence(agence);
    }

    if (commercial != null) {
        // si on affecte une action de relance (qui n'avait pas de ressource)  une ressource, on affecte aussi l'opp  la ressource
        if (actionAModifier.getActionAttribution().getRessource() == null
                && actionAModifier.getType().getId().equals(squareMappingService.getIdTypeActionRelance())
                && actionAModifier.getActionAffectation().getOpportunite() != null) {
            actionAModifier.getActionAffectation().getOpportunite().getOpportuniteAttribution()
                    .setRessource(commercial);
        }
        actionAModifier.getActionAttribution().setRessource(commercial);
    }

    final Long idStatutTermine = squareMappingService.getIdStatutTerminer();

    // Rsultat
    // Cration d'une opportunit si le rsultat passe  opportunit
    OpportuniteDto opportuniteCree = null;
    if (actionAModifier.getResultat() == null) {
        if (actionModificationDto.getResultat() != null && actionModificationDto.getResultat().getIdentifiant()
                .equals(squareMappingService.getIdResultatOpportunite())) {
            actionAModifier.setStatut(actionStatutDao.rechercherStatutActionParId(idStatutTermine));
            opportuniteCree = creationOpportunite(actionAModifier);
        } else if (actionModificationDto.getResultat() != null && actionModificationDto.getResultat()
                .getIdentifiant().equals(squareMappingService.getIdResultatRelance())) {
            actionAModifier.setStatut(actionStatutDao.rechercherStatutActionParId(idStatutTermine));
        } else {
            actionAModifier.setStatut(actionStatutDao
                    .rechercherStatutActionParId(actionModificationDto.getStatut().getIdentifiant()));
        }
        if (actionModificationDto.getResultat() != null) {
            actionAModifier.setResultat(actionResultatDao
                    .rechercherActionResultatParId(actionModificationDto.getResultat().getIdentifiant()));
        }
    } else {
        if (actionModificationDto.getResultat() != null && actionModificationDto.getResultat().getIdentifiant()
                .equals(squareMappingService.getIdResultatOpportunite())) {
            if (!actionAModifier.getResultat().getId()
                    .equals(squareMappingService.getIdResultatOpportunite())) {
                actionAModifier.setStatut(actionStatutDao.rechercherStatutActionParId(idStatutTermine));
                opportuniteCree = creationOpportunite(actionAModifier);
            }
        } else if (actionModificationDto.getResultat() != null && actionModificationDto.getResultat()
                .getIdentifiant().equals(squareMappingService.getIdResultatRelance())) {
            actionAModifier.setStatut(actionStatutDao.rechercherStatutActionParId(idStatutTermine));
        } else {
            actionAModifier.setStatut(actionStatutDao
                    .rechercherStatutActionParId(actionModificationDto.getStatut().getIdentifiant()));
        }
        if (actionModificationDto.getResultat() != null) {
            actionAModifier.setResultat(actionResultatDao
                    .rechercherActionResultatParId(actionModificationDto.getResultat().getIdentifiant()));
        }
    }

    // Mise  jour de la date de l'action
    if (idStatutTermine.equals(actionModificationDto.getStatut().getIdentifiant())) {
        // Si l'action passe au statut "termin", on met  jour la date termine de l'action en prenant la date courante
        actionAModifier.setDateTerminee(Calendar.getInstance());
    } else {
        actionAModifier.setDate(actionModificationDto.getDateAction());
    }

    // Priorit
    if (actionModificationDto.getPriorite() != null
            && actionModificationDto.getPriorite().getIdentifiant() != null) {
        // Rcupration de la priorit
        final ActionPriorite priorite = actionPrioriteDao
                .rechercherPrioriteActionParId(actionModificationDto.getPriorite().getIdentifiant());
        if (priorite != null) {
            actionAModifier.setPriorite(priorite);
        }
    }

    // Dure de l'action
    if (dureeAction != null) {
        actionAModifier.setDuree(dureeAction);
    }

    // Action visible ou non dans l'agenda
    actionAModifier.setVisibleAgenda(actionModificationDto.getVisibleAgenda() != null
            && actionModificationDto.getVisibleAgenda().booleanValue());

    // Construction de la date de notification
    if (actionModificationDto.getRappel() != null && actionModificationDto.getRappel()) {
        if (actionModificationDto.getIdNotification() != null) {
            final ActionNotificationInfosDto notification = squareMappingService
                    .getActionNotificationParId(actionModificationDto.getIdNotification());
            final Calendar soustraction = Calendar.getInstance();
            soustraction.clear();
            final Long dateTime = -notification.getNotification().getTimeInMillis()
                    + actionAModifier.getDate().getTimeInMillis();
            soustraction.setTimeInMillis(dateTime);
            actionAModifier.setDateNotification(soustraction);
        } else {
            actionAModifier.setDateNotification(null);
        }
    } else {
        actionAModifier.setDateNotification(null);
    }
    // Constuction du commentaire
    if (actionModificationDto.getCommentaire() != null) {
        final Commentaire commentaire = mapperDozerBean.map(actionModificationDto.getCommentaire(),
                Commentaire.class);
        if (actionModificationDto.getCommentaire().getRessource() != null) {
            final Ressource ressource = ressourceDao
                    .rechercherRessourceParId(actionModificationDto.getCommentaire().getRessource().getId());
            commentaire.setRessource(ressource);
        }
        if (actionAModifier.getCommentaires() == null) {
            final List<Commentaire> list = new ArrayList<Commentaire>();
            list.add(commentaire);
            actionAModifier.setCommentaires(list);
        } else {
            actionAModifier.getCommentaires().add(commentaire);
        }
    }

    // Envoi d'un email si demand
    if (actionAModifier.isMailNotification()
            && squareMappingService.getIdStatutActionTermine().equals(actionAModifier.getStatut().getId())) {
        if (actionAModifier.getRessource() != null) {
            final Ressource createur = actionAModifier.getRessource();
            if (createur.getEmail() == null || "".equals(createur.getEmail())) {
                throw new BusinessException(
                        messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_EMAIL_CREATEUR_ACTION_VIDE));
            }
            final List<String> listeDestinataires = new ArrayList<String>();
            listeDestinataires.add(createur.getEmail());
            final String titre = messageSourceUtil.get(ActionKeyUtil.TITRE_EMAIL_FIN_ACTION);
            String personneAction = "";
            String type = "";
            String objet = "";
            String sousObjet = "";
            String nature = "";
            String campagne = "";
            if (actionAModifier.getActionAffectation() != null
                    && actionAModifier.getActionAffectation().getPersonne() != null) {
                final Personne personne = actionAModifier.getActionAffectation().getPersonne();
                if (personne instanceof PersonnePhysique) {
                    final PersonnePhysique personnePhysique = (PersonnePhysique) actionAModifier
                            .getActionAffectation().getPersonne();
                    personneAction = personnePhysique.getNom() + ESPACE + personnePhysique.getPrenom();
                } else if (personne instanceof PersonneMorale) {
                    final PersonneMorale personneMorale = (PersonneMorale) actionAModifier
                            .getActionAffectation().getPersonne();
                    personneAction = personneMorale.getRaisonSociale();
                }
            }
            if (actionAModifier.getType() != null) {
                type = actionAModifier.getType().getLibelle();
            }
            if (actionAModifier.getObjet() != null) {
                objet = actionAModifier.getObjet().getLibelle();
            }
            if (actionAModifier.getSousObjet() != null) {
                sousObjet = actionAModifier.getSousObjet().getLibelle();
            }
            if (actionAModifier.getNature() != null) {
                nature = actionAModifier.getNature().getLibelle();
            }
            if (actionAModifier.getCampagne() != null) {
                campagne = actionAModifier.getCampagne().getLibelle();
            }
            final String message = messageSourceUtil.get(ActionKeyUtil.MESSAGE_EMAIL_FIN_ACTION,
                    new String[] { personneAction, type, objet, sousObjet, nature, campagne });
            final MailDto mailDto = new MailDto(expediteurNoReply, listeDestinataires, titre, message, null,
                    false);
            emailSquarePlugin.envoyerEmail(mailDto);
        }
    }
    // Renseignement de la date de modification
    actionAModifier.setDateModification(Calendar.getInstance());

    final ActionResultatDto resultat = new ActionResultatDto();
    if (opportuniteCree != null) {
        resultat.setIdOpportunite(opportuniteCree.getIdOpportunite());
    }
    return resultat;
}