Example usage for org.joda.time Seconds getSeconds

List of usage examples for org.joda.time Seconds getSeconds

Introduction

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

Prototype

public int getSeconds() 

Source Link

Document

Gets the number of seconds that this period represents.

Usage

From source file:com.qcadoo.mes.cmmsMachineParts.states.MaintenanceEventStateValidationService.java

License:Open Source License

private Optional<Integer> getProgressTime(Entity event) {
    StringBuilder hqlForStart = new StringBuilder();
    hqlForStart/*from   ww w . j  a v  a2  s  .  c  o m*/
            .append("select max(dateAndTime) as date from #cmmsMachineParts_maintenanceEventStateChange sc ");
    hqlForStart.append("where sc.maintenanceEvent = :eventId and sc.status = '03successful' ");
    hqlForStart.append("and sc.targetState = '02inProgress'");
    SearchQueryBuilder query = dataDefinitionService
            .get(CmmsMachinePartsConstants.PLUGIN_IDENTIFIER,
                    CmmsMachinePartsConstants.MODEL_MAINTENANCE_EVENT_STATE_CHANGE)
            .find(hqlForStart.toString());
    query.setLong("eventId", event.getId());
    Date start = query.setMaxResults(1).uniqueResult().getDateField("date");

    StringBuilder hqlForEnd = new StringBuilder();
    hqlForEnd.append("select max(dateAndTime) as date from #cmmsMachineParts_maintenanceEventStateChange sc ");
    hqlForEnd.append("where sc.maintenanceEvent = :eventId and sc.status = '03successful' ");
    hqlForEnd.append("and sc.targetState = '03edited'");
    query = dataDefinitionService.get(CmmsMachinePartsConstants.PLUGIN_IDENTIFIER,
            CmmsMachinePartsConstants.MODEL_MAINTENANCE_EVENT_STATE_CHANGE).find(hqlForEnd.toString());
    query.setLong("eventId", event.getId());

    Date end = query.setMaxResults(1).uniqueResult().getDateField("date");

    if (start != null && end != null && start.before(end)) {
        Seconds seconds = Seconds.secondsBetween(new DateTime(start), new DateTime(end));
        return Optional.of(Integer.valueOf(seconds.getSeconds()));
    }
    return Optional.empty();
}

From source file:com.rapidminer.operator.GenerateDateSeries.java

License:Open Source License

private long calculateNumberOfExample(DateTime startTime, DateTime endTime) {
    // TODO Auto-generated method stub
    long valuetoReturn = 0;
    try {/*from  w w w .j  a  va2  s  .  com*/

        //getParameterAsString(key)

        switch (getParameterAsString(PARAMETER_INTERVALTYPE)) {

        case "YEAR":
            Years year = Years.yearsBetween(startTime, endTime);
            valuetoReturn = year.getYears() / getParameterAsInt(INTERVAL);
            break;
        case "MONTH":
            Months month = Months.monthsBetween(startTime, endTime);
            valuetoReturn = month.getMonths() / getParameterAsInt(INTERVAL);
            break;

        case "DAY":
            Days days = Days.daysBetween(startTime, endTime);
            valuetoReturn = days.getDays() / getParameterAsInt(INTERVAL);

            break;

        case "HOUR":
            Hours hours = Hours.hoursBetween(startTime, endTime);
            valuetoReturn = hours.getHours() / getParameterAsInt(INTERVAL);
            break;

        case "MINUTE":
            Minutes minute = Minutes.minutesBetween(startTime, endTime);
            valuetoReturn = minute.getMinutes() / getParameterAsInt(INTERVAL);
            break;
        case "SECOND":
            Seconds second = Seconds.secondsBetween(startTime, endTime);
            valuetoReturn = second.getSeconds() / getParameterAsInt(INTERVAL);
            break;
        case "MILLISECOND":
            // Milliseconds millisecond = milli
            long milli = endTime.getMillis() - startTime.getMillis();
            valuetoReturn = milli / getParameterAsInt(INTERVAL);

            break;
        default:
            valuetoReturn = 0;
        }

    } catch (Exception e) {
        valuetoReturn = 0;
    }

    return valuetoReturn;
}

From source file:com.rubenlaguna.en4j.sync.SyncAction.java

License:Open Source License

public void actionPerformed(ActionEvent e) {
    // TODO implement action body
    final SynchronizationService sservice = Lookup.getDefault().lookup(SynchronizationService.class);

    Runnable task = new Runnable() {

        public void run() {
            DateTime startTime = new DateTime();
            StatusDisplayer.getDefault().setStatusText("Sync started at " + startTime.toString("HH:mm"));

            if (toolbarPresenter.startAnimator()) { //dont run if it was already running
                sservice.sync();/*ww w. j  a v a 2  s.  c  om*/
                toolbarPresenter.stopAnimator();
                if (sservice.isSyncFailed()) {
                    StatusDisplayer.getDefault().setStatusText("Sync failed.");
                } else {
                    DateTime finishTime = new DateTime();
                    Duration dur = new Duration(startTime, finishTime);
                    Minutes minutes = dur.toPeriod().toStandardMinutes();
                    Seconds seconds = dur.toPeriod().minus(minutes).toStandardSeconds();
                    final String message = "sync finished at " + finishTime.toString("HH:mm") + ". Sync took "
                            + minutes.getMinutes() + " minutes and " + seconds.getSeconds() + " seconds.";
                    final StatusDisplayer.Message sbMess = StatusDisplayer.getDefault().setStatusText(message,
                            1);
                    RP.post(new Runnable() {
                        public void run() {
                            sbMess.clear(10000);
                        }
                    });
                }
            }
        }
    };
    RP.post(task);
}

From source file:com.sloca.entity.Group.java

/**
 * Compare the overlap time/* ww w.  j  ava2 s  . c  o m*/
 * @param other the group to compare
 * @return -1 if not overlap, otherwise return fullCount
 */
public int compareOverlap(Group other) {
    int fullCount = 0;
    ArrayList<Interval> intervalList = new ArrayList<Interval>();
    for (String s : getLocOverlapMap().keySet()) {
        ArrayList<Interval> firstList = getLocOverlapMap().get(s);
        ArrayList<Interval> secondList = other.getLocOverlapMap().get(s);
        for (Interval first : firstList) {
            for (Interval second : secondList) {
                Interval overlap = first.overlap(second);
                if (overlap != null) {
                    Seconds seconds = Seconds.secondsIn(overlap);
                    int secs = seconds.getSeconds();
                    fullCount = fullCount + secs;
                    intervalList.add(overlap);
                }
            }
        }
    }
    if (fullCount >= 720) {
        return fullCount;
    } else {
        return -1;
    }
}

From source file:com.sonicle.webtop.core.xmpp.XMPPClient.java

License:Open Source License

private boolean joinMuc(final MultiUserChat muc, final DateTime lastSeenActivity) {
    try {//from ww  w. j av  a  2 s . com
        logger.debug("Joining group chat [{}, {}]", muc.getRoom().toString(), lastSeenActivity);
        DiscussionHistory mucHistory = new DiscussionHistory();
        if (lastSeenActivity != null) {
            DateTime now = new DateTime(DateTimeZone.UTC);
            Seconds seconds = Seconds.secondsBetween(lastSeenActivity.withZone(DateTimeZone.UTC), now);
            mucHistory.setSeconds(Math.abs(seconds.getSeconds()));
        }
        muc.join(userNickname, null, mucHistory, SmackConfiguration.getDefaultReplyTimeout());
        return true;

    } catch (SmackException | XMPPException | InterruptedException ex) {
        logger.error("Error joining group chat", ex);
        return false;
    }
}

From source file:com.tdclighthouse.prototype.scheduler.Scheduler.java

License:Apache License

protected long getInitialDelayInMilliseconds(Configuration configuration) {
    DateTime dateTime = new DateTime(configuration.getTime(START_TIME_PROPERTY, getMidnight()));
    Seconds secondsBetween = Seconds.secondsBetween(new DateTime(), dateTime);
    return TimeUnit.SECONDS.toMillis((long) secondsBetween.getSeconds() + 30);
}

From source file:com.thinkbiganalytics.scheduler.util.TimerToCronExpression.java

License:Apache License

private static String getSecondsCron(Period p) {
    Integer sec = p.getSeconds();
    Seconds s = p.toStandardSeconds();
    Integer seconds = s.getSeconds();
    String str = "0" + (sec > 0 ? "/" + sec : "");
    if (seconds > 60) {
        str = sec + "";
    }//from  ww w .  jav  a  2 s.  c o  m
    return str;
}

From source file:com.thoughtworks.go.util.TimeConverter.java

License:Apache License

public ConvertedTime getConvertedTime(long duration) {
    Set<Seconds> keys = RULES.keySet();
    for (Seconds seconds : keys) {
        if (duration <= seconds.getSeconds()) {
            return RULES.get(seconds).getConvertedTime(duration);
        }//from w  w w .  jav  a  2s .c o  m
    }
    return new TimeConverter.OverTwoYears().getConvertedTime(duration);
}

From source file:com.xrdev.musicast.connection.YouTubeManager.java

public static VideoItem searchVideo(String searchTerm) {
    //ArrayList<VideoItem> videoItemList = new ArrayList<VideoItem>();
    VideoItem resultVideo = null;/*from w  w w  . j av a  2s  .  c om*/

    try {
        // Construir o objeto que ser a referncia para todas as solicitaes  API.
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("musicast").build();

        System.out.println("[YoutubeHandler]: Conexo construda.");
        YouTube.Search.List search = youtube.search().list("id,snippet");

        String apiKey = "AIzaSyBTXTaiH-BYye70pKDGc_Bpf1dkqiPDLcw";

        search.setKey(apiKey);

        search.setQ(searchTerm);
        /*
         * We are only searching for videos (not playlists or channels). If we were searching for
         * more, we would add them as a string like this: "video,playlist,channel".
         */
        search.setType("video");

        /*
         * setFields: reduz as informaes retornadas para apenas os campos necessrios.
         */
        // search.setFields("items(id/kind,id/videoId,snippet/title,snippet/description)"); --> Sem viewcount.

        search.setFields("items(id/kind,id/videoId)"); // Pega apenas o ID. Pegar o restante do objeto Video que ser encontrado.

        // Campos possveis: https://developers.google.com/youtube/v3/docs/search
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);

        System.out.println("[YouTubeHandler]: Iniciando busca.");

        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

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

        /**
         * Pegar apenas os IDs dos vdeos encontrados.
         */
        if (searchResultList != null) {
            Iterator resultsIterator = searchResultList.iterator();

            while (resultsIterator.hasNext()) {
                SearchResult searchResult = (SearchResult) resultsIterator.next();
                ResourceId rId = searchResult.getId(); // Pegar o ID do resultado.

                // Verifica se o resultado  um video. Adiciona a lista de IDs.
                if (rId.getKind().equals("youtube#video")) {

                    videoIds.add(rId.getVideoId());

                    System.out.println("[YouTubeHandler]: Video ID encontrado adicionado: " + rId.getVideoId());
                    /**
                    String videoId = rId.getVideoId();
                    String title = searchResult.getSnippet().getTitle();
                    String description = searchResult.getSnippet().getDescription();
                    VideoListResponse videoListResponse = youtube.videos().list("statistics").setId(videoId).execute();
                            
                    resultList.add(new VideoItem(videoId, title, description));
                    */

                } // end if

            } // end while

            /**
             * Busca realizada, a lista videoId foi preenchida pelos IDs encontrados pela busca.
             */

            /**
             * Fazer uma busca usando Videos.list da API. Esta lista retorna objetos "Video", uma representaao em Java
             * do objeto JSON enviado pelo servidor.
             * Por este objeto,  possvel obter ttulo, descrio, estatsticas (como viewcount) e contentDetails (como durao).
             */

            /**
             * Montar a Lista:
             * youtube.videos() - chamada da API
             * .list("id,snippet,statistics,contentDetails") - Informar quais atributos do JSON retornar -
             * https://developers.google.com/youtube/v3/docs/videos#resource
             * .setId - A nica forma de pesquisar os vdeos desta forma  por ID. Juntar tudo usando vrgula como delimitador.
             * .execute() - Autoexplicativo.
             */
            System.out.println("[YouTubeHandler]: Montando lista de Objetos Video com IDs encontrados");
            // VideoListResponse vlr = youtube.videos().list("id,snippet,statistics,contentDetails") // Adicionado ,contentDetails - testar.
            VideoListResponse vlr = youtube.videos().list("id,contentDetails")
                    .setId(TextUtils.join(",", videoIds)).setKey(apiKey).execute();

            for (Video video : vlr.getItems()) {
                /**
                 * Para cada video, buscar as informaes relevantes e instanciar um VideoItem.
                 */
                String videoId = video.getId();
                //String title = video.getSnippet().getTitle();
                //String description = video.getSnippet().getDescription();
                //BigInteger viewCount = video.getStatistics().getViewCount();
                String durationString = video.getContentDetails().getDuration();
                boolean isLicensed = video.getContentDetails().getLicensedContent();

                // Converter a durao do formato String enviado pela API para segundos.
                PeriodFormatter formatter = ISOPeriodFormat.standard();
                Period p = formatter.parsePeriod(durationString);
                Seconds s = p.toStandardSeconds();

                int durationInt = s.getSeconds();

                // Adicionar o VideoItem ao Array.
                // videoItemList.add(new VideoItem(videoId, title, description, viewCount, durationInt));

                resultVideo = new VideoItem(videoId, durationInt, isLicensed);

                System.out.println("[YouTubeHandler] Video adicionado  lista para o View: " + videoId);

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return resultVideo;
}

From source file:de.fhdo.collaboration.helper.LoginHelper.java

License:Apache License

public boolean activate(String hash) {
    Session hb_session = HibernateUtil.getSessionFactory().openSession();
    hb_session.getTransaction().begin();

    org.hibernate.Query q = hb_session.createQuery("from Collaborationuser WHERE activation_md5=:p_hash");
    q.setString("p_hash", hash);

    java.util.List<Collaborationuser> userList = (java.util.List<Collaborationuser>) q.list();

    if (userList.size() == 1) {
        Collaborationuser user = userList.get(0);
        DateTime now = DateTime.now();/*  w w  w.j a  va2 s.c  o  m*/
        DateTime origin = new DateTime(user.getActivationTime());
        Seconds seconds = Seconds.secondsBetween(origin, now);
        int sec = seconds.getSeconds();
        if (seconds.getSeconds() < activationTimespan) {

            user.setEnabled(true);
            user.setActivated(true);
            user.setActivationMd5("");

            hb_session.merge(user);

            hb_session.getTransaction().commit();
            hb_session.close();

            return true;
        } else {
            return false;
        }
    }

    hb_session.close();

    return false;
}