List of usage examples for org.joda.time Period toStandardSeconds
public Seconds toStandardSeconds()
From source file:com.arpnetworking.tsdcore.sinks.KMonDSink.java
License:Apache License
/** * {@inheritDoc}/*from www.j a va 2 s . c om*/ */ @Override protected Collection<byte[]> serialize(final PeriodicData periodicData) { final Period period = periodicData.getPeriod(); final Multimap<String, AggregatedData> indexedData = prepareData(periodicData); final Multimap<String, Condition> indexedConditions = prepareConditions(periodicData.getConditions()); // Serialize final List<byte[]> serializedData = Lists.newArrayListWithCapacity(indexedData.size()); final StringBuilder stringBuilder = new StringBuilder(); for (final String key : indexedData.keySet()) { final Collection<AggregatedData> namedData = indexedData.get(key); if (!namedData.isEmpty()) { stringBuilder.setLength(0); final AggregatedData first = Iterables.getFirst(namedData, null); final String name = new StringBuilder().append(first.getFQDSN().getService()).append("_") .append(period.toString(ISOPeriodFormat.standard())).append("_") .append(first.getFQDSN().getMetric()).toString(); int maxStatus = 0; boolean hasAlert = false; final StringBuilder dataBuilder = new StringBuilder(); for (final AggregatedData datum : namedData) { if (!datum.isSpecified()) { continue; } dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("%3D") .append(datum.getValue().getValue()).append("%3B"); final String conditionKey = datum.getFQDSN().getService() + "_" + datum.getFQDSN().getMetric() + "_" + datum.getFQDSN().getCluster() + "_" + datum.getFQDSN().getStatistic(); for (final Condition condition : indexedConditions.get(conditionKey)) { hasAlert = true; maxStatus = serializeCondition(maxStatus, dataBuilder, datum, condition); } } // Don't send an empty payload if (dataBuilder.length() == 0) { continue; } stringBuilder.append("run_every=").append(period.toStandardSeconds().getSeconds()) .append("&has_alert=").append(hasAlert).append("&path=") .append(first.getFQDSN().getCluster()).append("%2f") .append(periodicData.getDimensions().get("host")).append("&monitor=").append(name) .append("&status=").append(maxStatus).append("×tamp=") .append((int) Unit.SECOND.convert(periodicData.getStart().getMillis(), Unit.MILLISECOND)) .append("&output=").append(name).append("%7C").append(dataBuilder.toString()); stringBuilder.setLength(stringBuilder.length() - 3); serializedData.add(stringBuilder.toString().getBytes(Charset.forName("UTF-8"))); } } return serializedData; }
From source file:com.arpnetworking.tsdcore.sinks.MonitordSink.java
License:Apache License
/** * {@inheritDoc}/*from w w w .ja v a2 s .com*/ */ @Override protected Collection<byte[]> serialize(final PeriodicData periodicData) { final Period period = periodicData.getPeriod(); final Multimap<String, AggregatedData> indexedData = prepareData(periodicData); final Multimap<String, Condition> indexedConditions = prepareConditions(periodicData.getConditions()); // Serialize final List<byte[]> serializedData = Lists.newArrayListWithCapacity(indexedData.size()); final StringBuilder stringBuilder = new StringBuilder(); for (final String key : indexedData.keySet()) { final Collection<AggregatedData> namedData = indexedData.get(key); if (!namedData.isEmpty()) { stringBuilder.setLength(0); final AggregatedData first = Iterables.getFirst(namedData, null); final String name = new StringBuilder().append(first.getFQDSN().getService()).append("_") .append(period.toString(ISOPeriodFormat.standard())).append("_") .append(first.getFQDSN().getMetric()).toString(); int maxStatus = 0; final StringBuilder dataBuilder = new StringBuilder(); for (final AggregatedData datum : namedData) { if (!datum.isSpecified()) { continue; } dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("%3D") .append(datum.getValue().getValue()).append("%3B"); final String conditionKey = datum.getFQDSN().getService() + "_" + datum.getFQDSN().getMetric() + "_" + datum.getFQDSN().getCluster() + "_" + datum.getFQDSN().getStatistic(); for (final Condition condition : indexedConditions.get(conditionKey)) { dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("_") .append(condition.getName()).append("%3D") .append(condition.getThreshold().getValue()).append("%3B"); if (condition.isTriggered().isPresent() && condition.isTriggered().get()) { // Collect the status of this metric final Object severity = condition.getExtensions().get("severity"); int status = _unknownSeverityStatus; if (severity != null && _severityToStatus.containsKey(severity)) { status = _severityToStatus.get(severity); } maxStatus = Math.max(status, maxStatus); } } } // Don't send an empty payload if (dataBuilder.length() == 0) { continue; } stringBuilder.append("run_every=").append(period.toStandardSeconds().getSeconds()).append("&path=") .append(first.getFQDSN().getCluster()).append("%2f") .append(periodicData.getDimensions().get("host")).append("&monitor=").append(name) .append("&status=").append(maxStatus).append("×tamp=") .append((int) Unit.SECOND.convert(periodicData.getStart().getMillis(), Unit.MILLISECOND)) .append("&output=").append(name).append("%7C").append(dataBuilder.toString()); stringBuilder.setLength(stringBuilder.length() - 3); serializedData.add(stringBuilder.toString().getBytes(Charset.forName("UTF-8"))); } } return serializedData; }
From source file:com.gmt2001.YouTubeAPIv3.java
License:Open Source License
public int[] GetVideoLength(String id) { com.gmt2001.Console.debug.println("YouTubeAPIv3.GetVideoLength Start id=" + id); JSONObject j = GetData(request_type.GET, "https://www.googleapis.com/youtube/v3/videos?id=" + id + "&key=" + apikey + "&part=contentDetails"); if (j.getBoolean("_success")) { if (j.getInt("_http") == 200) { JSONArray a = j.getJSONArray("items"); if (a.length() > 0) { JSONObject i = a.getJSONObject(0); JSONObject cd = i.getJSONObject("contentDetails"); PeriodFormatter formatter = ISOPeriodFormat.standard(); Period d = formatter.parsePeriod(cd.getString("duration")); if (cd.getString("duration").equalsIgnoreCase("PT0S")) { com.gmt2001.Console.debug.println("YouTubeAPIv3.GetVideoLength Fail (Live Stream)"); return new int[] { 123, 456, 7899 }; }/*from w ww. j a v a2s . co m*/ //String d = cd.getString("duration").substring(2); int h, m, s; String hours = d.toStandardHours().toString().substring(2); h = Integer.parseInt(hours.substring(0, hours.indexOf("H"))); String minutes = d.toStandardMinutes().toString().substring(2); m = Integer.parseInt(minutes.substring(0, minutes.indexOf("M"))); String seconds = d.toStandardSeconds().toString().substring(2); s = Integer.parseInt(seconds.substring(0, seconds.indexOf("S"))); /* * if (d.contains("H")) { h = * Integer.parseInt(d.substring(0, d.indexOf("H"))); * * d = d.substring(0, d.indexOf("H")); } * * if (d.contains("M")) { m = * Integer.parseInt(d.substring(0, d.indexOf("M"))); * * d = d.substring(0, d.indexOf("M")); } * * s = Integer.parseInt(d.substring(0, d.indexOf("S"))); */ com.gmt2001.Console.debug.println("YouTubeAPIv3.GetVideoLength Success"); return new int[] { h, m, s }; } else { com.gmt2001.Console.debug.println("YouTubeAPIv3.GetVideoLength Fail"); return new int[] { 0, 0, 0 }; } } else { com.gmt2001.Console.debug.println("YouTubeAPIv3.GetVideoLength Fail2"); return new int[] { 0, 0, 0 }; } } com.gmt2001.Console.debug.println("YouTubeAPIv3.GetVideoLength Fail3"); return new int[] { 0, 0, 0 }; }
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 .j a v a 2 s . c om*/ return str; }
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 ww w .j a v a 2 s.c o m 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:datafu.pig.date.TimeCount.java
License:Apache License
public TimeCount(String timeSpec) { Period p = new Period("PT" + timeSpec.toUpperCase()); this.millis = p.toStandardSeconds().getSeconds() * 1000; }
From source file:datafu.pig.sessions.SessionCount.java
License:Apache License
public SessionCount(String timeSpec) { Period p = new Period("PT" + timeSpec.toUpperCase()); this.millis = p.toStandardSeconds().getSeconds() * 1000; cleanup();//from w ww .ja va 2s . c o m }
From source file:datafu.pig.sessions.Sessionize.java
License:Apache License
public Sessionize(String timeSpec) { Period p = new Period("PT" + timeSpec.toUpperCase()); this.millis = p.toStandardSeconds().getSeconds() * 1000; cleanup();//from w w w . java 2s. c o m }
From source file:dumbo.pig.util.SessionizeCounter.java
License:Apache License
public SessionizeCounter(String timeSpec) { Period p = new Period("PT" + timeSpec.toUpperCase()); this.millis = p.toStandardSeconds().getSeconds() * 1000; cleanup();/*from ww w . ja va2 s. c om*/ }
From source file:eagle.security.userprofile.UserProfileUtils.java
License:Apache License
/** * @param seconds/* w w w. j av a 2s . c om*/ * @param period * @return */ public static long formatSecondsByPeriod(long seconds, Period period) { return seconds - (seconds % Int.int2long(period.toStandardSeconds().getSeconds())); }