Example usage for java.util Calendar PM

List of usage examples for java.util Calendar PM

Introduction

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

Prototype

int PM

To view the source code for java.util Calendar PM.

Click Source Link

Document

Value of the #AM_PM field indicating the period of the day from noon to just before midnight.

Usage

From source file:org.kuali.kfs.pdp.service.impl.FormatServiceImpl.java

/**
 * @see org.kuali.kfs.pdp.service.FormatService#startFormatProcess(org.kuali.rice.kim.bo.Person, java.lang.String,
 *      java.util.List, java.util.Date, java.lang.String)
 *//*from ww  w  .jav a  2 s  .  co m*/
@Override
public FormatProcessSummary startFormatProcess(Person user, String campus, List<CustomerProfile> customers,
        Date paydate, String paymentTypes) {
    LOG.debug("startFormatProcess() started");

    for (CustomerProfile element : customers) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("startFormatProcess() Customer: " + element);
        }
    }

    // Create the process
    Date d = new Date();
    PaymentProcess paymentProcess = new PaymentProcess();
    paymentProcess.setCampusCode(campus);
    paymentProcess.setProcessUser(user);
    paymentProcess.setProcessTimestamp(new Timestamp(d.getTime()));

    this.businessObjectService.save(paymentProcess);

    // add an entry in the format process table (to lock the format process)
    FormatProcess formatProcess = new FormatProcess();

    formatProcess.setPhysicalCampusProcessCode(campus);
    formatProcess.setBeginFormat(dateTimeService.getCurrentTimestamp());
    formatProcess.setPaymentProcIdentifier(paymentProcess.getId().intValue());

    this.businessObjectService.save(formatProcess);

    Timestamp now = new Timestamp((new Date()).getTime());
    java.sql.Date sqlDate = new java.sql.Date(paydate.getTime());
    Calendar c = Calendar.getInstance();
    c.setTime(sqlDate);
    c.set(Calendar.HOUR, 11);
    c.set(Calendar.MINUTE, 59);
    c.set(Calendar.SECOND, 59);
    c.set(Calendar.MILLISECOND, 59);
    c.set(Calendar.AM_PM, Calendar.PM);
    Timestamp paydateTs = new Timestamp(c.getTime().getTime());

    if (LOG.isDebugEnabled()) {
        LOG.debug("startFormatProcess() last update = " + now);
        LOG.debug("startFormatProcess() entered paydate = " + paydate);
        LOG.debug("startFormatProcess() actual paydate = " + paydateTs);
    }
    PaymentStatus format = this.businessObjectService.findBySinglePrimaryKey(PaymentStatus.class,
            PdpConstants.PaymentStatusCodes.FORMAT);

    List customerIds = new ArrayList();
    for (Iterator iter = customers.iterator(); iter.hasNext();) {
        CustomerProfile element = (CustomerProfile) iter.next();
        customerIds.add(element.getId());
    }

    // Mark all of them ready for format
    Iterator groupIterator = formatPaymentDao.markPaymentsForFormat(customerIds, paydateTs, paymentTypes);

    while (groupIterator.hasNext()) {
        PaymentGroup paymentGroup = (PaymentGroup) groupIterator.next();
        paymentGroup.setLastUpdate(paydateTs);// delete this one
        paymentGroup.setPaymentStatus(format);
        paymentGroup.setProcess(paymentProcess);
        businessObjectService.save(paymentGroup);
    }

    // summarize them
    FormatProcessSummary preFormatProcessSummary = new FormatProcessSummary();
    Iterator<PaymentGroup> iterator = this.paymentGroupService.getByProcess(paymentProcess);

    while (iterator.hasNext()) {
        PaymentGroup paymentGroup = iterator.next();
        preFormatProcessSummary.add(paymentGroup);
    }

    // if no payments found for format clear the format process
    if (preFormatProcessSummary.getProcessSummaryList().size() == 0) {
        LOG.debug("startFormatProcess() No payments to process.  Format process ending");
        clearUnfinishedFormat(paymentProcess.getId().intValue());// ?? maybe call end format process
    }

    return preFormatProcessSummary;
}

From source file:com.versobit.weatherdoge.WeatherUtil.java

private static String convertYahooCode(String code, String weatherTime, String sunrise, String sunset) {
    Date weatherDate = new Date();
    try {// w  w w  .  j a  va 2s  . c om
        weatherDate = YAHOO_DATE_FORMAT.parse(weatherTime);
    } catch (ParseException ex) {
        Log.e(TAG, "Yahoo date format failed!", ex);
    }
    Calendar weatherCal = new GregorianCalendar();
    Calendar sunriseCal = new GregorianCalendar();
    Calendar sunsetCal = new GregorianCalendar();
    weatherCal.setTime(weatherDate);
    sunriseCal.setTime(weatherDate);
    sunsetCal.setTime(weatherDate);

    Matcher sunriseMatch = YAHOO_TIME.matcher(sunrise);
    Matcher sunsetMatch = YAHOO_TIME.matcher(sunset);
    if (!sunriseMatch.matches() || !sunsetMatch.matches()) {
        Log.e(TAG, "Failed to find sunrise/sunset. Using defaults.");
        sunriseMatch = YAHOO_TIME.matcher("6:00 am");
        sunsetMatch = YAHOO_TIME.matcher("6:00 pm");
        sunriseMatch.matches();
        sunsetMatch.matches();
    }
    // Set the sunrise to the correct hour and minute of the same day
    sunriseCal.set(Calendar.HOUR, Integer.parseInt(sunriseMatch.group(1)));
    sunriseCal.set(Calendar.MINUTE, Integer.parseInt(sunriseMatch.group(2)));
    sunriseCal.set(Calendar.SECOND, 0);
    sunriseCal.set(Calendar.MILLISECOND, 0);
    sunriseCal.set(Calendar.AM_PM, "am".equals(sunriseMatch.group(3)) ? Calendar.AM : Calendar.PM);

    // Set the sunset to the correct hour and minute of the same day
    sunsetCal.set(Calendar.HOUR, Integer.parseInt(sunsetMatch.group(1)));
    sunsetCal.set(Calendar.MINUTE, Integer.parseInt(sunsetMatch.group(2)));
    sunsetCal.set(Calendar.SECOND, 0);
    sunsetCal.set(Calendar.MILLISECOND, 0);
    sunsetCal.set(Calendar.AM_PM, "am".equals(sunsetMatch.group(3)) ? Calendar.AM : Calendar.PM);

    boolean isDaytime = true;
    if (weatherCal.before(sunriseCal) || weatherCal.after(sunsetCal)) {
        isDaytime = false;
    }

    String owmCode = "01";
    switch (Integer.parseInt(code)) {
    // Thunderstorms
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 17:
    case 37:
    case 38:
    case 39:
    case 45:
    case 47:
        owmCode = "11";
        break;
    // Snow
    case 5:
    case 7:
    case 13:
    case 14:
    case 15:
    case 16:
    case 18:
    case 41:
    case 42:
    case 43:
    case 46:
        owmCode = "13";
        break;
    // Rain
    case 6:
    case 10:
    case 35:
        owmCode = "09";
        break;
    // Light-ish Rain
    case 8:
    case 9:
    case 11:
    case 12:
    case 40:
        owmCode = "10";
        break;
    // Fog
    case 19:
    case 20:
    case 21:
    case 22:
        owmCode = "50";
        break;
    // Cloudy
    case 27:
    case 28:
        owmCode = "04";
        break;
    // (Other) Cloudy
    case 26:
        owmCode = "03";
        break;
    // Partly Cloudy
    case 23:
    case 24:
    case 25:
    case 29:
    case 30:
    case 44:
        owmCode = "02";
        break;
    // Clear
    case 31:
    case 32:
    case 33:
    case 34:
    case 36:
        owmCode = "01";
        break;
    }
    return owmCode + (isDaytime ? "d" : "n");
}

From source file:eionet.util.Util.java

/**
 * A method for calculating time difference in MILLISECONDS, between a date-time specified in input parameters and the current
 * date-time. <BR>/* w ww .  jav a2  s  . c  om*/
 * This should be useful for calculating sleep time for code that has a certain schedule for execution.
 *
 * @param hour
 *            An integer from 0 to 23. If less than 0 or more than 23, then the closest next hour to current hour is taken.
 * @param date
 *            An integer from 1 to 31. If less than 1 or more than 31, then the closest next date to current date is taken.
 * @param month
 *            An integer from Calendar.JANUARY to Calendar.DECEMBER. If out of those bounds, the closest next month to current
 *            month is taken.
 * @param wday
 *            An integer from 1 to 7. If out of those bounds, the closest next weekday to weekday month is taken.
 * @param zone
 *            A String specifying the time-zone in which the calculations should be done. Please see Java documentation an
 *            allowable time-zones and formats.
 * @return Time difference in milliseconds.
 */
public static long timeDiff(int hour, int date, int month, int wday, String zone) {

    GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone(zone));
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    cal.setFirstDayOfWeek(Calendar.MONDAY);

    /*
     * here we force the hour to be one of the defualts if (hour < 0) hour = 0; if (hour > 23) hour = 23;
     */
    int cur_hour = cal.get(Calendar.HOUR);

    if (cal.get(Calendar.AM_PM) == Calendar.PM) {
        cur_hour = 12 + cur_hour;
    }

    // here we assume that every full hour is accepted
    /*
     * if (hour < 0 || hour > 23) { hour = cur_hour>=23 ? 0 : cur_hour + 1; }
     */

    if (wday >= 1 && wday <= 7) {

        int cur_wday = cal.get(Calendar.DAY_OF_WEEK);
        if (hour < 0 || hour > 23) {
            if (cur_wday != wday) {
                hour = 0;
            } else {
                hour = cur_hour >= 23 ? 0 : cur_hour + 1;
            }
        }

        int amount = wday - cur_wday;
        if (amount < 0) {
            amount = 7 + amount;
        }
        if (amount == 0 && cur_hour >= hour) {
            amount = 7;
        }
        cal.add(Calendar.DAY_OF_WEEK, amount);
    } else if (month >= Calendar.JANUARY && month <= Calendar.DECEMBER) { // do something about when every date is accepted
        if (date < 1) {
            date = 1;
        }
        if (date > 31) {
            date = 31;
        }
        int cur_month = cal.get(Calendar.MONTH);
        int amount = month - cur_month;
        if (amount < 0) {
            amount = 12 + amount;
        }
        if (amount == 0) {
            if (cal.get(Calendar.DATE) > date) {
                amount = 12;
            } else if (cal.get(Calendar.DATE) == date) {
                if (cur_hour >= hour) {
                    amount = 12;
                }
            }
        }
        // cal.set(Calendar.DATE, date);
        cal.add(Calendar.MONTH, amount);
        if (date > cal.getActualMaximum(Calendar.DATE)) {
            date = cal.getActualMaximum(Calendar.DATE);
        }
        cal.set(Calendar.DATE, date);
    } else if (date >= 1 && date <= 31) {
        int cur_date = cal.get(Calendar.DATE);
        if (cur_date > date) {
            cal.add(Calendar.MONTH, 1);
        } else if (cur_date == date) {
            if (cur_hour >= hour) {
                cal.add(Calendar.MONTH, 1);
            }
        }
        cal.set(Calendar.DATE, date);
    } else {
        if (hour < 0 || hour > 23) {
            hour = cur_hour >= 23 ? 0 : cur_hour + 1;
        }
        if (cur_hour >= hour) {
            cal.add(Calendar.DATE, 1);
        }
    }

    if (hour >= 12) {
        cal.set(Calendar.HOUR, hour - 12);
        cal.set(Calendar.AM_PM, Calendar.PM);
    } else {
        cal.set(Calendar.HOUR, hour);
        cal.set(Calendar.AM_PM, Calendar.AM);
    }

    Date nextDate = cal.getTime();
    Date currDate = new Date();

    long nextTime = cal.getTime().getTime();
    long currTime = (new Date()).getTime();

    return nextTime - currTime;
}

From source file:com.panet.imeta.job.entries.special.JobEntrySpecial.java

private long getNextMonthlyExecutionTime() {
    Calendar calendar = Calendar.getInstance();

    long nowMillis = calendar.getTimeInMillis();
    int amHour = hour;
    if (amHour > 12) {
        amHour = amHour - 12;// ww  w . ja  v a2 s  .c  o  m
        calendar.set(Calendar.AM_PM, Calendar.PM);
    } else {
        calendar.set(Calendar.AM_PM, Calendar.AM);
    }
    calendar.set(Calendar.HOUR, amHour);
    calendar.set(Calendar.MINUTE, minutes);
    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    if (calendar.getTimeInMillis() <= nowMillis) {
        calendar.add(Calendar.MONTH, 1);
    }
    return calendar.getTimeInMillis() - nowMillis;
}

From source file:com.panet.imeta.job.entries.special.JobEntrySpecial.java

private long getNextWeeklyExecutionTime() {
    Calendar calendar = Calendar.getInstance();

    long nowMillis = calendar.getTimeInMillis();
    int amHour = hour;
    if (amHour > 12) {
        amHour = amHour - 12;/*from ww  w  .  j  a  va 2  s.  co  m*/
        calendar.set(Calendar.AM_PM, Calendar.PM);
    } else {
        calendar.set(Calendar.AM_PM, Calendar.AM);
    }
    calendar.set(Calendar.HOUR, amHour);
    calendar.set(Calendar.MINUTE, minutes);
    calendar.set(Calendar.DAY_OF_WEEK, weekDay + 1);
    if (calendar.getTimeInMillis() <= nowMillis) {
        calendar.add(Calendar.WEEK_OF_YEAR, 1);
    }
    return calendar.getTimeInMillis() - nowMillis;
}

From source file:org.kuali.ole.sys.batch.service.impl.SchedulerServiceImpl.java

protected boolean isPastScheduleCutoffTime(Calendar dateTime, boolean log) {
    try {/*from   www .ja v  a  2  s.  co  m*/
        Date scheduleCutoffTimeTemp = scheduler.getTriggersOfJob(SCHEDULE_JOB_NAME, SCHEDULED_GROUP)[0]
                .getPreviousFireTime();
        Calendar scheduleCutoffTime;
        if (scheduleCutoffTimeTemp == null) {
            scheduleCutoffTime = dateTimeService.getCurrentCalendar();
        } else {
            scheduleCutoffTime = dateTimeService.getCalendar(scheduleCutoffTimeTemp);
        }
        String cutoffParameter = parameterService.getParameterValueAsString(ScheduleStep.class,
                OLEConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME);
        String[] scheduleStepCutoffTime = StringUtils.split(cutoffParameter, ":");
        if (scheduleStepCutoffTime.length != 3 && scheduleStepCutoffTime.length != 4) {
            throw new IllegalArgumentException(
                    "Error! The " + OLEConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME
                            + " parameter had an invalid value: " + cutoffParameter);
        }
        // if there are 4 components, then we have an AM/PM delimiter
        // otherwise, assume 24-hour time
        if (scheduleStepCutoffTime.length == 4) {
            int hour = Integer.parseInt(scheduleStepCutoffTime[0]);
            // need to adjust for meaning of hour
            if (hour == 12) {
                hour = 0;
            } else {
                hour--;
            }
            scheduleCutoffTime.set(Calendar.HOUR, hour);
            if (StringUtils.containsIgnoreCase(scheduleStepCutoffTime[3], "AM")) {
                scheduleCutoffTime.set(Calendar.AM_PM, Calendar.AM);
            } else {
                scheduleCutoffTime.set(Calendar.AM_PM, Calendar.PM);
            }
        } else {
            scheduleCutoffTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(scheduleStepCutoffTime[0]));
        }
        scheduleCutoffTime.set(Calendar.MINUTE, Integer.parseInt(scheduleStepCutoffTime[1]));
        scheduleCutoffTime.set(Calendar.SECOND, Integer.parseInt(scheduleStepCutoffTime[2]));
        if (parameterService.getParameterValueAsBoolean(ScheduleStep.class,
                OLEConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME_IS_NEXT_DAY)) {
            scheduleCutoffTime.add(Calendar.DAY_OF_YEAR, 1);
        }
        boolean isPastScheduleCutoffTime = dateTime.after(scheduleCutoffTime);
        if (log) {
            LOG.info(new StringBuilder("isPastScheduleCutoffTime=").append(isPastScheduleCutoffTime)
                    .append(" : ").append(dateTimeService.toDateTimeString(dateTime.getTime())).append(" / ")
                    .append(dateTimeService.toDateTimeString(scheduleCutoffTime.getTime())));
        }
        return isPastScheduleCutoffTime;
    } catch (NumberFormatException e) {
        throw new RuntimeException(
                "Caught exception while checking whether we've exceeded the schedule cutoff time", e);
    } catch (SchedulerException e) {
        throw new RuntimeException(
                "Caught exception while checking whether we've exceeded the schedule cutoff time", e);
    }
}

From source file:org.kuali.kfs.sys.batch.service.impl.SchedulerServiceImpl.java

protected boolean isPastScheduleCutoffTime(Calendar dateTime, boolean log) {
    try {//from  w  w  w.  ja  v a  2  s .c  o  m
        Date scheduleCutoffTimeTemp = scheduler.getTriggersOfJob(SCHEDULE_JOB_NAME, SCHEDULED_GROUP)[0]
                .getPreviousFireTime();
        Calendar scheduleCutoffTime;
        if (scheduleCutoffTimeTemp == null) {
            scheduleCutoffTime = dateTimeService.getCurrentCalendar();
        } else {
            scheduleCutoffTime = dateTimeService.getCalendar(scheduleCutoffTimeTemp);
        }
        String cutoffParameter = parameterService.getParameterValueAsString(ScheduleStep.class,
                KFSConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME);
        String[] scheduleStepCutoffTime = StringUtils.split(cutoffParameter, ":");
        if (scheduleStepCutoffTime.length != 3 && scheduleStepCutoffTime.length != 4) {
            throw new IllegalArgumentException(
                    "Error! The " + KFSConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME
                            + " parameter had an invalid value: " + cutoffParameter);
        }
        // if there are 4 components, then we have an AM/PM delimiter
        // otherwise, assume 24-hour time
        if (scheduleStepCutoffTime.length == 4) {
            int hour = Integer.parseInt(scheduleStepCutoffTime[0]);
            // need to adjust for meaning of hour
            if (hour == 12) {
                hour = 0;
            } else {
                hour--;
            }
            scheduleCutoffTime.set(Calendar.HOUR, hour);
            if (StringUtils.containsIgnoreCase(scheduleStepCutoffTime[3], "AM")) {
                scheduleCutoffTime.set(Calendar.AM_PM, Calendar.AM);
            } else {
                scheduleCutoffTime.set(Calendar.AM_PM, Calendar.PM);
            }
        } else {
            scheduleCutoffTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(scheduleStepCutoffTime[0]));
        }
        scheduleCutoffTime.set(Calendar.MINUTE, Integer.parseInt(scheduleStepCutoffTime[1]));
        scheduleCutoffTime.set(Calendar.SECOND, Integer.parseInt(scheduleStepCutoffTime[2]));
        if (parameterService.getParameterValueAsBoolean(ScheduleStep.class,
                KFSConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME_IS_NEXT_DAY)) {
            scheduleCutoffTime.add(Calendar.DAY_OF_YEAR, 1);
        }
        boolean isPastScheduleCutoffTime = dateTime.after(scheduleCutoffTime);
        if (log) {
            LOG.info(new StringBuilder("isPastScheduleCutoffTime=").append(isPastScheduleCutoffTime)
                    .append(" : ").append(dateTimeService.toDateTimeString(dateTime.getTime())).append(" / ")
                    .append(dateTimeService.toDateTimeString(scheduleCutoffTime.getTime())));
        }
        return isPastScheduleCutoffTime;
    } catch (NumberFormatException e) {
        throw new RuntimeException(
                "Caught exception while checking whether we've exceeded the schedule cutoff time", e);
    } catch (SchedulerException e) {
        throw new RuntimeException(
                "Caught exception while checking whether we've exceeded the schedule cutoff time", e);
    }
}

From source file:com.panet.imeta.job.entries.special.JobEntrySpecial.java

private long getNextDailyExecutionTime() {
    Calendar calendar = Calendar.getInstance();

    long nowMillis = calendar.getTimeInMillis();
    int amHour = hour;
    if (amHour > 12) {
        amHour = amHour - 12;/*from www .  j av a 2  s.  co  m*/
        calendar.set(Calendar.AM_PM, Calendar.PM);
    } else {
        calendar.set(Calendar.AM_PM, Calendar.AM);
    }
    calendar.set(Calendar.HOUR, amHour);
    calendar.set(Calendar.MINUTE, minutes);
    if (calendar.getTimeInMillis() <= nowMillis) {
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
    return calendar.getTimeInMillis() - nowMillis;
}

From source file:gr.open.loglevelsmanager.loglevel.LogLevelsManager.java

private LogLevel getLogLevelFromRequest(PortletRequest request) {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
    LogLevelImpl logLevel = new LogLevelImpl();
    try {/* w w w  .  j  av a2 s  . c  o m*/
        logLevel.setLogLevelId(ParamUtil.getLong(request, "LogLevelId"));
    } catch (Exception nfe) {
        // Controled en Validator
    }
    logLevel.setLogLevelDescription(ParamUtil.getString(request, "logLevelDescription"));
    logLevel.setLogLevelPriority(ParamUtil.getString(request, "logLevelPriority"));

    logLevel.setActivateOnStartup(ParamUtil.getBoolean(request, "activateOnStartup"));
    logLevel.setLogLevelScheduled(ParamUtil.getBoolean(request, "logLevelScheduled"));
    logLevel.setLogLevelCategory(ParamUtil.getString(request, "logLevelCategory"));
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    logLevel.setLogLevelEndDate(ParamUtil.getDate(request, "logLevelEndDate", sdf));

    int LogLevelStartDateTimeAno = ParamUtil.getInteger(request, "logLevelStartDateYear");
    int LogLevelStartDateTimeMes = ParamUtil.getInteger(request, "logLevelStartDateMonth") + 1;
    int LogLevelStartDateTimeDia = ParamUtil.getInteger(request, "logLevelStartDateDay");
    int LogLevelStartDateTimeHora = ParamUtil.getInteger(request, "logLevelStartDateHour");
    int LogLevelStartDateTimeMinuto = ParamUtil.getInteger(request, "logLevelStartDateMinute");
    int LogLevelStartDateTimeAmPm = ParamUtil.getInteger(request, "logLevelStartDateAmPm");

    if (LogLevelStartDateTimeAmPm == Calendar.PM) {
        LogLevelStartDateTimeHora += 12;
    }
    try {
        SimpleDateFormat formatterDateTime = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        logLevel.setLogLevelStartDate(formatterDateTime.parse(
                LogLevelStartDateTimeAno + "/" + LogLevelStartDateTimeMes + "/" + LogLevelStartDateTimeDia + " "
                        + LogLevelStartDateTimeHora + ":" + LogLevelStartDateTimeMinuto));
    } catch (ParseException e) {
        logLevel.setLogLevelStartDate(new Date());
    }

    int LogLevelEndDateTimeAno = ParamUtil.getInteger(request, "logLevelEndDateYear");
    int LogLevelEndDateTimeMes = ParamUtil.getInteger(request, "logLevelEndDateMonth") + 1;
    int LogLevelEndDateTimeDia = ParamUtil.getInteger(request, "logLevelEndDateDay");
    int LogLevelEndDateTimeHora = ParamUtil.getInteger(request, "logLevelEndDateHour");
    int LogLevelEndDateTimeMinuto = ParamUtil.getInteger(request, "logLevelEndDateMinute");
    int LogLevelEndDateTimeAmPm = ParamUtil.getInteger(request, "logLevelEndDateAmPm");

    if (LogLevelEndDateTimeAmPm == Calendar.PM) {
        LogLevelEndDateTimeHora += 12;
    }
    try {
        SimpleDateFormat formatterDateTime = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        logLevel.setLogLevelEndDate(formatterDateTime
                .parse(LogLevelEndDateTimeAno + "/" + LogLevelEndDateTimeMes + "/" + LogLevelEndDateTimeDia
                        + " " + LogLevelEndDateTimeHora + ":" + LogLevelEndDateTimeMinuto));
    } catch (ParseException e) {
        logLevel.setLogLevelEndDate(new Date());
    }

    try {
        logLevel.setPrimaryKey(ParamUtil.getLong(request, "resourcePrimKey"));
    } catch (NumberFormatException nfe) {
        // Controled en Validator
    }

    logLevel.setCompanyId(themeDisplay.getCompanyId());
    logLevel.setGroupId(themeDisplay.getScopeGroupId());
    logLevel.setUserId(themeDisplay.getUserId());

    logger.debug("GOT FROM REQUEST:" + logLevel);

    return logLevel;
}

From source file:com.liferay.portlet.journal.lar.JournalPortletDataHandlerImpl.java

public static void importArticle(PortletDataContext portletDataContext, Element articleElement)
        throws Exception {

    String path = articleElement.attributeValue("path");

    if (!portletDataContext.isPathNotProcessed(path)) {
        return;//from  ww w .j  ava 2s  . co  m
    }

    JournalArticle article = (JournalArticle) portletDataContext.getZipEntryAsObject(path);

    prepareLanguagesForImport(article);

    long userId = portletDataContext.getUserId(article.getUserUuid());

    JournalCreationStrategy creationStrategy = JournalCreationStrategyFactory.getInstance();

    long authorId = creationStrategy.getAuthorUserId(portletDataContext, article);

    if (authorId != JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) {
        userId = authorId;
    }

    User user = UserLocalServiceUtil.getUser(userId);

    String articleId = article.getArticleId();
    boolean autoArticleId = false;

    Map<String, String> articleIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalArticle.class + ".articleId");

    String newArticleId = articleIds.get(articleId);

    // ======= Start of change ============
    if (Validator.isNotNull(newArticleId)) {

        // A sibling of a different version was already assigned a new
        // article id

        articleId = newArticleId;
    }
    // =======end of change================

    String content = article.getContent();

    content = importDLFileEntries(portletDataContext, articleElement, content);

    Group group = GroupLocalServiceUtil.getGroup(portletDataContext.getScopeGroupId());

    content = StringUtil.replace(content, "@data_handler_group_friendly_url@", group.getFriendlyURL());

    content = importLinksToLayout(portletDataContext, content);

    article.setContent(content);

    String newContent = creationStrategy.getTransformedContent(portletDataContext, article);

    if (!StringUtils.equals(JournalCreationStrategy.ARTICLE_CONTENT_UNCHANGED, newContent)) {
        article.setContent(newContent);
    }

    Map<String, String> structureIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalStructure.class);

    String parentStructureId = MapUtil.getString(structureIds, article.getStructureId(),
            article.getStructureId());

    Map<String, String> templateIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalTemplate.class);

    String parentTemplateId = MapUtil.getString(templateIds, article.getTemplateId(), article.getTemplateId());

    Date displayDate = article.getDisplayDate();

    int displayDateMonth = 0;
    int displayDateDay = 0;
    int displayDateYear = 0;
    int displayDateHour = 0;
    int displayDateMinute = 0;

    if (displayDate != null) {
        Calendar displayCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        displayCal.setTime(displayDate);

        displayDateMonth = displayCal.get(Calendar.MONTH);
        displayDateDay = displayCal.get(Calendar.DATE);
        displayDateYear = displayCal.get(Calendar.YEAR);
        displayDateHour = displayCal.get(Calendar.HOUR);
        displayDateMinute = displayCal.get(Calendar.MINUTE);

        if (displayCal.get(Calendar.AM_PM) == Calendar.PM) {
            displayDateHour += 12;
        }
    }

    Date expirationDate = article.getExpirationDate();

    int expirationDateMonth = 0;
    int expirationDateDay = 0;
    int expirationDateYear = 0;
    int expirationDateHour = 0;
    int expirationDateMinute = 0;
    boolean neverExpire = true;

    if (expirationDate != null) {
        Calendar expirationCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        expirationCal.setTime(expirationDate);

        expirationDateMonth = expirationCal.get(Calendar.MONTH);
        expirationDateDay = expirationCal.get(Calendar.DATE);
        expirationDateYear = expirationCal.get(Calendar.YEAR);
        expirationDateHour = expirationCal.get(Calendar.HOUR);
        expirationDateMinute = expirationCal.get(Calendar.MINUTE);
        neverExpire = false;

        if (expirationCal.get(Calendar.AM_PM) == Calendar.PM) {
            expirationDateHour += 12;
        }
    }

    Date reviewDate = article.getReviewDate();

    int reviewDateMonth = 0;
    int reviewDateDay = 0;
    int reviewDateYear = 0;
    int reviewDateHour = 0;
    int reviewDateMinute = 0;
    boolean neverReview = true;

    if (reviewDate != null) {
        Calendar reviewCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        reviewCal.setTime(reviewDate);

        reviewDateMonth = reviewCal.get(Calendar.MONTH);
        reviewDateDay = reviewCal.get(Calendar.DATE);
        reviewDateYear = reviewCal.get(Calendar.YEAR);
        reviewDateHour = reviewCal.get(Calendar.HOUR);
        reviewDateMinute = reviewCal.get(Calendar.MINUTE);
        neverReview = false;

        if (reviewCal.get(Calendar.AM_PM) == Calendar.PM) {
            reviewDateHour += 12;
        }
    }

    long structurePrimaryKey = 0;

    if (Validator.isNotNull(article.getStructureId())) {
        String structureUuid = articleElement.attributeValue("structure-uuid");

        JournalStructure existingStructure = JournalStructureUtil.fetchByUUID_G(structureUuid,
                portletDataContext.getScopeGroupId());

        if (existingStructure == null) {
            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

            long companyGroupId = companyGroup.getGroupId();

            existingStructure = JournalStructureUtil.fetchByUUID_G(structureUuid, companyGroupId);
        }

        if (existingStructure == null) {
            String newStructureId = structureIds.get(article.getStructureId());

            if (Validator.isNotNull(newStructureId)) {
                existingStructure = JournalStructureUtil.fetchByG_S(portletDataContext.getScopeGroupId(),
                        String.valueOf(newStructureId));
            }

            if (existingStructure == null) {
                if (_log.isWarnEnabled()) {
                    StringBundler sb = new StringBundler();

                    sb.append("Structure ");
                    sb.append(article.getStructureId());
                    sb.append(" is missing for article ");
                    sb.append(article.getArticleId());
                    sb.append(", skipping this article.");

                    _log.warn(sb.toString());
                }

                return;
            }
        }

        structurePrimaryKey = existingStructure.getPrimaryKey();

        parentStructureId = existingStructure.getStructureId();
    }

    if (Validator.isNotNull(article.getTemplateId())) {
        String templateUuid = articleElement.attributeValue("template-uuid");

        JournalTemplate existingTemplate = JournalTemplateUtil.fetchByUUID_G(templateUuid,
                portletDataContext.getScopeGroupId());

        if (existingTemplate == null) {
            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

            long companyGroupId = companyGroup.getGroupId();

            existingTemplate = JournalTemplateUtil.fetchByUUID_G(templateUuid, companyGroupId);
        }

        if (existingTemplate == null) {
            String newTemplateId = templateIds.get(article.getTemplateId());

            if (Validator.isNotNull(newTemplateId)) {
                existingTemplate = JournalTemplateUtil.fetchByG_T(portletDataContext.getScopeGroupId(),
                        newTemplateId);
            }

            if (existingTemplate == null) {
                if (_log.isWarnEnabled()) {
                    StringBundler sb = new StringBundler();

                    sb.append("Template ");
                    sb.append(article.getTemplateId());
                    sb.append(" is missing for article ");
                    sb.append(article.getArticleId());
                    sb.append(", skipping this article.");

                    _log.warn(sb.toString());
                }

                return;
            }
        }

        parentTemplateId = existingTemplate.getTemplateId();
    }

    File smallFile = null;

    String smallImagePath = articleElement.attributeValue("small-image-path");

    if (article.isSmallImage() && Validator.isNotNull(smallImagePath)) {
        byte[] bytes = portletDataContext.getZipEntryAsByteArray(smallImagePath);

        smallFile = FileUtil.createTempFile(article.getSmallImageType());

        FileUtil.write(smallFile, bytes);
    }

    Map<String, byte[]> images = new HashMap<String, byte[]>();

    String imagePath = articleElement.attributeValue("image-path");

    if (portletDataContext.getBooleanParameter(_NAMESPACE, "images") && Validator.isNotNull(imagePath)) {

        List<String> imageFiles = portletDataContext.getZipFolderEntries(imagePath);

        for (String imageFile : imageFiles) {
            String fileName = imageFile;

            if (fileName.contains(StringPool.SLASH)) {
                fileName = fileName.substring(fileName.lastIndexOf(CharPool.SLASH) + 1);
            }

            if (fileName.endsWith(".xml")) {
                continue;
            }

            int pos = fileName.lastIndexOf(CharPool.PERIOD);

            if (pos != -1) {
                fileName = fileName.substring(0, pos);
            }

            images.put(fileName, portletDataContext.getZipEntryAsByteArray(imageFile));
        }
    }

    String articleURL = null;

    boolean addGroupPermissions = creationStrategy.addGroupPermissions(portletDataContext, article);
    boolean addGuestPermissions = creationStrategy.addGuestPermissions(portletDataContext, article);

    ServiceContext serviceContext = portletDataContext.createServiceContext(articleElement, article,
            _NAMESPACE);

    serviceContext.setAddGroupPermissions(addGroupPermissions);
    serviceContext.setAddGuestPermissions(addGuestPermissions);
    serviceContext.setAttribute("imported", Boolean.TRUE.toString());

    if (article.getStatus() != WorkflowConstants.STATUS_APPROVED) {
        serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
    }

    JournalArticle importedArticle = null;

    String articleResourceUuid = articleElement.attributeValue("article-resource-uuid");

    if (portletDataContext.isDataStrategyMirror()) {
        JournalArticleResource articleResource = JournalArticleResourceUtil.fetchByUUID_G(articleResourceUuid,
                portletDataContext.getScopeGroupId());

        if (articleResource == null) {
            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

            long companyGroupId = companyGroup.getGroupId();

            articleResource = JournalArticleResourceUtil.fetchByUUID_G(articleResourceUuid, companyGroupId);
        }
        //Modification start
        if (articleResource == null) {
            articleResource = JournalArticleResourceUtil.fetchByG_A(portletDataContext.getScopeGroupId(),
                    articleId);
        }
        //Modification end
        serviceContext.setUuid(articleResourceUuid);

        JournalArticle existingArticle = null;

        if (articleResource != null) {
            try {
                existingArticle = JournalArticleLocalServiceUtil.getLatestArticle(
                        articleResource.getResourcePrimKey(), WorkflowConstants.STATUS_ANY, false);
            } catch (NoSuchArticleException nsae) {
            }
        }

        if (existingArticle == null) {
            existingArticle = JournalArticleUtil.fetchByG_A_V(portletDataContext.getScopeGroupId(),
                    newArticleId, article.getVersion());
        }

        if (existingArticle == null) {
            importedArticle = JournalArticleLocalServiceUtil.addArticle(userId,
                    portletDataContext.getScopeGroupId(), article.getClassNameId(), structurePrimaryKey,
                    articleId, autoArticleId, article.getVersion(), article.getTitleMap(),
                    article.getDescriptionMap(), article.getContent(), article.getType(), parentStructureId,
                    parentTemplateId, article.getLayoutUuid(), displayDateMonth, displayDateDay,
                    displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay,
                    expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth,
                    reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute, neverReview,
                    article.isIndexable(), article.isSmallImage(), article.getSmallImageURL(), smallFile,
                    images, articleURL, serviceContext);
        } else {
            importedArticle = JournalArticleLocalServiceUtil.updateArticle(userId, existingArticle.getGroupId(),
                    existingArticle.getArticleId(), existingArticle.getVersion(), article.getTitleMap(),
                    article.getDescriptionMap(), article.getContent(), article.getType(), parentStructureId,
                    parentTemplateId, article.getLayoutUuid(), displayDateMonth, displayDateDay,
                    displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay,
                    expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth,
                    reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute, neverReview,
                    article.isIndexable(), article.isSmallImage(), article.getSmallImageURL(), smallFile,
                    images, articleURL, serviceContext);
        }
    } else {
        importedArticle = JournalArticleLocalServiceUtil.addArticle(userId,
                portletDataContext.getScopeGroupId(), article.getClassNameId(), structurePrimaryKey, articleId,
                autoArticleId, article.getVersion(), article.getTitleMap(), article.getDescriptionMap(),
                article.getContent(), article.getType(), parentStructureId, parentTemplateId,
                article.getLayoutUuid(), displayDateMonth, displayDateDay, displayDateYear, displayDateHour,
                displayDateMinute, expirationDateMonth, expirationDateDay, expirationDateYear,
                expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth, reviewDateDay,
                reviewDateYear, reviewDateHour, reviewDateMinute, neverReview, article.isIndexable(),
                article.isSmallImage(), article.getSmallImageURL(), smallFile, images, articleURL,
                serviceContext);
    }

    if (smallFile != null) {
        smallFile.delete();
    }

    portletDataContext.importClassedModel(article, importedArticle, _NAMESPACE);

    if (Validator.isNull(newArticleId)) {
        articleIds.put(article.getArticleId(), importedArticle.getArticleId());
    }

    Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

    if (importedArticle.getGroupId() == companyGroup.getGroupId()) {
        portletDataContext.addCompanyReference(JournalArticle.class, articleId);
    }

    if (!articleId.equals(importedArticle.getArticleId())) {
        if (_log.isWarnEnabled()) {
            _log.warn("An article with the ID " + articleId + " already " + "exists. The new generated ID is "
                    + importedArticle.getArticleId());
        }
    }
}