Example usage for org.joda.time Period Period

List of usage examples for org.joda.time Period Period

Introduction

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

Prototype

public Period(Object period) 

Source Link

Document

Creates a period by converting or copying from another object.

Usage

From source file:net.longfalcon.newsj.Binaries.java

License:Open Source License

public void updateAllGroups() {
    // get all groups
    Collection<Group> groups = groupDAO.getActiveGroups();

    // get site config TODO: use config service
    Site site = siteDAO.getDefaultSite();

    newGroupScanByDays = site.getNewGroupsScanMethod() == 1; // TODO: create constants/enum
    compressedHeaders = site.isCompressedHeaders();
    messageBuffer = site.getMaxMessages();
    newGroupDaysToScan = site.getNewGroupDaysToScan();
    newGroupMsgsToScan = site.getNewGroupMsgsToScan();

    if (!groups.isEmpty()) {
        long startTime = System.currentTimeMillis();

        System.out.printf("Updating: %s groups - Using compression? %s%n", groups.size(),
                compressedHeaders ? "Yes" : "No");

        //get nntp client
        NewsClient nntpClient = nntpConnectionFactory.getNntpClient();
        if (nntpClient == null) {
            throw new RuntimeException("Connection error. Please check NNTP settings and try again.");
        }/*from  w w  w . j a va 2  s.com*/

        for (Group group : groups) {
            updateGroup(nntpClient, group);
            if (nntpClient == null) {
                nntpClient = nntpConnectionFactory.getNntpClient();
            } else if (!nntpClient.isConnected() || !nntpClient.isAvailable()) {
                try {
                    nntpClient.disconnect();
                } catch (IOException e) {
                    _log.error(e.toString(), e);
                }
                nntpClient = nntpConnectionFactory.getNntpClient();
            }
        }
        try {
            nntpClient.logout();
            nntpClient.disconnect();
        } catch (IOException e) {
            _log.error(e.toString(), e);
        }
        long endTime = System.currentTimeMillis();

        String duration = _periodFormatter.print(new Period(endTime - startTime));
        System.out.println("Updating completed in " + duration);
    } else {
        System.out.println("No groups specified. Ensure groups are added to newznab's database for updating.");
    }
}

From source file:net.longfalcon.web.AdminJobConfigController.java

License:Open Source License

private JobConfigView getJobConfigView(JobConfig jobConfig) {
    JobConfigView jobConfigView = new JobConfigView();
    jobConfigView.setJobKey(jobConfig.getJobName());
    String jobFrequency = jobConfig.getJobFrequency();
    jobConfigView.setFrequencyType(jobFrequency);

    if (JobConfigKeys.FREQ_PERIODIC.equals(jobFrequency)) {
        int periodMillis = Integer.parseInt(jobConfig.getFrequencyConfig());
        Period period = new Period(periodMillis);
        jobConfigView.setPeriodHours(period.getHours());
        jobConfigView.setPeriodMins(period.getMinutes());
    } else if (JobConfigKeys.FREQ_SCHEDULED.equals(jobFrequency)) {
        String crontab = jobConfig.getFrequencyConfig();
        String[] cronElements = crontab.split(" ");
        // there will be six.
        String minutesString = cronElements[1];
        jobConfigView.setScheduledMinutes(Integer.parseInt(minutesString));
        String hoursString = cronElements[2];
        jobConfigView.setScheduledHours(Integer.parseInt(hoursString));
        // skip the others right now
        String days = cronElements[5];
        // days are always set as comma list in Newsj.
        String[] dayList = days.split(",");
        for (String dayString : dayList) {
            if ("1".equals(dayString)) {
                jobConfigView.setSunday(true);
            }/*from w ww .  j a v  a 2 s . c  o m*/
            if ("2".equals(dayString)) {
                jobConfigView.setMonday(true);
            }
            if ("3".equals(dayString)) {
                jobConfigView.setTuesday(true);
            }
            if ("4".equals(dayString)) {
                jobConfigView.setWednesday(true);
            }
            if ("5".equals(dayString)) {
                jobConfigView.setThursday(true);
            }
            if ("6".equals(dayString)) {
                jobConfigView.setFriday(true);
            }
            if ("7".equals(dayString)) {
                jobConfigView.setSaturday(true);
            }
        }
    }

    return jobConfigView;
}

From source file:net.named_data.nfd.FaceStatusFragment.java

License:Open Source License

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (m_faceStatusAdapter == null) {
        m_listItems = new ArrayList<>();

        Resources res = getResources();
        m_scopes = res.getStringArray(R.array.face_scopes);
        m_linkTypes = res.getStringArray(R.array.face_link_types);
        m_persistencies = res.getStringArray(R.array.face_persistency);

        // Get face status information
        FaceStatus faceStatus = new FaceStatus();
        try {//from  w w  w. j  a v a 2s  .  c  om
            byte[] args = getArguments().getByteArray(EXTRA_FACE_INFORMATION);
            faceStatus.wireDecode(new Blob(args).buf());
        } catch (EncodingException e) {
            G.Log("EXTRA_FACE_INFORMATION: EncodingException: " + e);
        }

        // Creating list of items to be displayed
        m_listItems.add(new ListItem(R.string.face_id, String.valueOf(faceStatus.getFaceId())));
        m_listItems.add(new ListItem(R.string.local_face_uri, faceStatus.getLocalUri()));
        m_listItems.add(new ListItem(R.string.remote_face_uri, faceStatus.getRemoteUri()));
        m_listItems.add(new ListItem(R.string.expires_in,
                faceStatus.getExpirationPeriod() < 0 ? getString(R.string.expire_never)
                        : PeriodFormat.getDefault().print(new Period(faceStatus.getExpirationPeriod()))));
        m_listItems.add(new ListItem(R.string.face_scope, getScope(faceStatus.getFaceScope())));
        m_listItems
                .add(new ListItem(R.string.face_persistency, getPersistency(faceStatus.getFacePersistency())));
        m_listItems.add(new ListItem(R.string.link_type, getLinkType(faceStatus.getLinkType())));
        m_listItems.add(new ListItem(R.string.in_interests, String.valueOf(faceStatus.getNInInterests())));
        m_listItems.add(new ListItem(R.string.in_data, String.valueOf(faceStatus.getNInDatas())));
        m_listItems.add(new ListItem(R.string.out_interests, String.valueOf(faceStatus.getNOutInterests())));
        m_listItems.add(new ListItem(R.string.out_data, String.valueOf(faceStatus.getNOutDatas())));
        m_listItems.add(new ListItem(R.string.in_bytes, String.valueOf(faceStatus.getNInBytes())));
        m_listItems.add(new ListItem(R.string.out_bytes, String.valueOf(faceStatus.getNOutBytes())));

        m_faceStatusAdapter = new FaceStatusAdapter(getActivity(), m_listItems);
    }
    // setListAdapter must be called after addHeaderView.  Otherwise, there is an exception on some platforms.
    // http://stackoverflow.com/a/8141537/2150331
    setListAdapter(m_faceStatusAdapter);
}

From source file:net.sf.jacclog.service.analyzer.commands.internal.AnalyzeLogEntriesShellCommand.java

License:Apache License

private void analyzeEntries() {
    if (service != null) {
        final DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMdd");
        final DateTime from = format.parseDateTime(this.from);
        final DateTime to = (this.to != null) ? format.parseDateTime(this.to) : from.plusDays(1);
        final Interval interval = new Interval(from, to);
        final Period period = interval.toPeriod();

        final StringBuffer buffer = new StringBuffer();
        buffer.append("Analyse the log entries from '");
        buffer.append(from.toString()).append('\'');
        buffer.append(" to '").append(to);

        // print the period
        final String space = " ";
        buffer.append("'. The period includes ");
        final PeriodFormatter dateFormat = new PeriodFormatterBuilder().appendYears()
                .appendSuffix(" year", " years").appendSeparator(space).appendMonths()
                .appendSuffix(" month", " months").appendSeparator(space).appendWeeks()
                .appendSuffix(" week", " weeks").appendSeparator(space).appendDays()
                .appendSuffix(" day", " days").appendSeparator(space).appendHours()
                .appendSuffix(" hour", " hours").appendSeparator(space).appendMinutes()
                .appendSuffix(" minute", " minutes").appendSeparator(space).toFormatter();
        dateFormat.printTo(buffer, period);
        buffer.append('.');

        System.out.println(buffer.toString());

        final long maxResults = service.count(interval);
        if (maxResults > 0) {
            int maxCount = 0;
            if (proceed(maxResults)) {
                final long startTime = System.currentTimeMillis();

                final LogEntryAnalysisResult result = analyzerService.analyze(interval).toResult();
                final Map<UserAgentInfo, AtomicInteger> stats = result.getUserAgentInfos();
                System.out.println("User agent information count: " + stats.size());

                String name;/*from w  w  w  .  ja va  2 s.com*/
                String osName;
                int count;
                for (final Entry<UserAgentInfo, AtomicInteger> entry : stats.entrySet()) {
                    name = entry.getKey().getName();
                    osName = entry.getKey().getOsName();
                    count = entry.getValue().get();
                    maxCount += count;
                    System.out.println(name + " (" + osName + ") \t" + count);
                }
                System.out.println("Sum: " + maxCount);

                final long elapsedTime = System.currentTimeMillis() - startTime;
                final Period p = new Period(elapsedTime);
                System.out.println("Total processing time: " + p.toString(FORMATTER));
            }
        } else {
            System.out.println("There is nothing to analyze.");
        }
    }
}

From source file:net.sf.janos.ui.TransportControl.java

License:Apache License

public static String convertLongToDuration(long duration) {
    Period period = new Period(duration);
    return periodFormatter.print(period);
}

From source file:net.sf.janos.util.TimeUtilities.java

License:Apache License

/**
 * TODO BUG durations longer than one day will not work
 * //from   w  w w  .  j  a  v a2  s.co  m
 * @param duration
 * @return A String of the following format: h:MM:ss[.m+]
 */
public static String convertLongToDuration(long duration) {
    Period period = new Period(duration);
    return periodFormatter.print(period);
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.student.enrollment.bolonha.BolonhaStudentEnrollmentDispatchAction.java

License:Open Source License

@Override
protected ActionForward prepareShowDegreeModulesToEnrol(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response, StudentCurricularPlan studentCurricularPlan,
        ExecutionSemester executionSemester) {

    final EnrolmentPreConditionResult result = StudentCurricularPlanEnrolmentPreConditions
            .checkPreConditionsToEnrol(studentCurricularPlan, executionSemester);

    if (!result.isValid()) {
        if (result.getEnrolmentPeriod() != null) {
            DateTime now = DateTime.now().withMillisOfSecond(0);
            DateTime start = result.getEnrolmentPeriod().getStartDateDateTime();
            Period period = new Period(start.getMillis() - now.getMillis());
            if (start.toLocalDate().equals(now.toLocalDate())) {
                request.setAttribute("now", now);
                request.setAttribute("start", start);
                request.setAttribute("remaining", FORMATTER.print(period));
            }/*ww w .  ja v a2s .  c  om*/
        }
        addActionMessage(request, result.message(), result.args());
        return mapping.findForward("enrollmentCannotProceed");
    }

    return super.prepareShowDegreeModulesToEnrol(mapping, form, request, response, studentCurricularPlan,
            executionSemester);
}

From source file:net.tourbook.common.time.TimeTools.java

License:Open Source License

/**
 * @return Returns the time zone offset for the default time zone.
 *//*w w w.ja  va 2s . com*/
public static String getDefaultTimeZoneOffset() {

    final ZonedDateTime zdt = ZonedDateTime.now();
    final int tzOffset = zdt.getOffset().getTotalSeconds();

    final Period period = new Period(tzOffset * 1000);

    return period.toString(DURATION_FORMATTER);
}

From source file:net.tourbook.common.time.TimeTools.java

License:Open Source License

/**
 * @param duration//from   w  ww . j  a  va 2  s . c  om
 *            in milliseconds.
 * @return
 */
public static String printDSTDuration(final long duration) {

    final Period period = new Period(duration);

    return period.toString(DURATION_FORMATTER);
}

From source file:nl.mpcjanssen.simpletask.util.Util.java

License:Open Source License

public static DateTime addInterval(DateTime date, String interval) {
    Pattern p = Pattern.compile("(\\d+)([dwmy])");
    Matcher m = p.matcher(interval.toLowerCase());
    int amount;/*from  w  ww.  j a v a  2s . c o  m*/
    String type;
    if (date == null) {
        date = new DateTime();
    }
    m.find();
    if (m.groupCount() == 2) {
        amount = Integer.parseInt(m.group(1));
        type = m.group(2).toLowerCase();
    } else {
        return null;
    }
    Period period = new Period(0);
    if (type.equals("d")) {
        period = period.plusDays(amount);
    } else if (type.equals("w")) {
        period = period.plusWeeks(amount);
    } else if (type.equals("m")) {
        period = period.plusMonths(amount);
    } else if (type.equals("y")) {
        period = period.plusYears(amount);
    }
    return date.plus(period);
}