@Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object top = stack.pop(); if (!(top instanceof Long)) { throw new WarpScriptException(getName() + " expects a number of time units (LONG) on top of the stack."); } long duration = ((Number) top).longValue(); StringBuffer buf = new StringBuffer(); ReadablePeriod period = new MutablePeriod(duration / Constants.TIME_UNITS_PER_MS); ISOPeriodFormat.standard().getPrinter().printTo(buf, period, Locale.US); stack.push(buf.toString()); return stack; }
/** * Takes an xs:duration string as defined by the W3 Consortiums * Recommendation "XML Schema Part 2: Datatypes Second Edition", * http://www.w3.org/TR/xmlschema-2/#duration, and converts it into a * System.TimeSpan structure This method uses the following approximations: * 1 year = 365 days 1 month = 30 days Additionally, it only allows for four * decimal points of seconds precision. * * @param xsDuration xs:duration string to convert * @return System.TimeSpan structure */ public static TimeSpan getXSDurationToTimeSpan(String xsDuration) { // TODO: Need to check whether this should be the equivalent or not Matcher m = PATTERN_TIME_SPAN.matcher(xsDuration); boolean negative = false; if (m.find()) { negative = true; } // Removing leading '-' if (negative) { xsDuration = xsDuration.replace("-P", "P"); } Period period = Period.parse(xsDuration, ISOPeriodFormat.standard()); long retval = period.toStandardDuration().getMillis(); if (negative) { retval = -retval; } return new TimeSpan(retval); }
private static <T> DurationLiteral coherceDuration(T value) { DurationLiteral duration=null; if(value instanceof Duration) { duration=of((Duration)value); } else if(value instanceof javax.xml.datatype.Duration) { duration=of((javax.xml.datatype.Duration)value); } else if(value instanceof String) { try { Period period = ISOPeriodFormat.standard().parsePeriod((String)value); duration=of(period.toStandardDuration()); } catch (Exception e) { throw new DatatypeCohercionException(value,Datatypes.DURATION,e); } } else { throw new DatatypeCohercionException(value,Datatypes.DURATION); } return duration; }
@Override public void init(CommonSchedule schedule, XElement config) { super.init(schedule, config); if (config == null) return; String period = config.getAttribute("Value"); if (!StringUtil.isEmpty(period)) try { this.period = ISOPeriodFormat.standard().parsePeriod(period); } catch (Exception x) { // TODO log } }
public static String formatDuration(String duration) { Duration d = ISOPeriodFormat.standard().parsePeriod(duration).toStandardDuration(); long hours = d.getStandardHours(); Duration minusHours = d.minus(Duration.standardHours(hours)); long minutes = minusHours.getStandardMinutes(); long seconds = minusHours.minus(Duration.standardMinutes(minutes)).getStandardSeconds(); String format = hours > 0 ? "%3$d:%2$02d:%1$02d" : "%2$d:%1$02d"; return String.format(format, seconds, minutes, hours); }
@Override public void writeInterval(boolean isNull) throws IOException { IntervalWriter intervalWriter = writer.interval(); if(!isNull){ final Period p = ISOPeriodFormat.standard().parsePeriod(parser.getValueAsString()); int months = DateUtility.monthsFromPeriod(p); int days = p.getDays(); int millis = DateUtility.millisFromPeriod(p); intervalWriter.writeInterval(months, days, millis); } }
@Override public void writeInterval(boolean isNull) throws IOException { IntervalWriter intervalWriter = writer.interval(fieldName); if(!isNull){ final Period p = ISOPeriodFormat.standard().parsePeriod(parser.getValueAsString()); int months = DateUtility.monthsFromPeriod(p); int days = p.getDays(); int millis = DateUtility.millisFromPeriod(p); intervalWriter.writeInterval(months, days, millis); } }
private int convertTime(String time) { PeriodFormatter formatter = ISOPeriodFormat.standard(); Period p = formatter.parsePeriod(time); Seconds s = p.toStandardSeconds(); return s.getSeconds(); }
@Test public void retrievePeriodValueFromConfiguration() { Configuration configuration = ConfigurationProvider.getConfiguration(); MutablePeriod referenceValue = new MutablePeriod(); ISOPeriodFormat.standard().getParser().parseInto(referenceValue, "P1Y1M1W1DT1H1M1S", 0, Locale.ENGLISH); String periodAsString = configuration.get("periodValueA"); Period period = configuration.get("periodValueA", Period.class); assertThat(periodAsString, equalTo("P1Y1M1W1DT1H1M1S")); assertThat(period, equalTo(referenceValue.toPeriod())); }
@Override public void serialize( final Duration duration, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { if (duration == null) { jgen.writeNull(); return; } final PeriodFormatter formatter = ISOPeriodFormat.standard(); jgen.writeString(duration.toPeriod().toString(formatter)); }
@Override public Duration deserialize(final JsonParser parser, final DeserializationContext ctxt) throws JsonParseException, IOException { final JsonToken jsonToken = parser.getCurrentToken(); if (jsonToken == JsonToken.VALUE_NUMBER_INT) { return new Duration(parser.getLongValue()); } else if (jsonToken == JsonToken.VALUE_STRING) { final String str = parser.getText().trim(); if (str.length() == 0) { return null; } final PeriodFormatter formatter = ISOPeriodFormat.standard(); return formatter.parsePeriod(str).toStandardDuration(); } throw ctxt.mappingException(Duration.class); }
/** * Extracts duration values from an object of this converter's type, and * sets them into the given ReadWritableDuration. * * @param period period to get modified * @param object the String to convert, must not be null * @param chrono the chronology to use * @return the millisecond duration * @throws ClassCastException if the object is invalid */ public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) { String str = (String) object; PeriodFormatter parser = ISOPeriodFormat.standard(); period.clear(); int pos = parser.parseInto(period, str, 0); if (pos < str.length()) { if (pos < 0) { // Parse again to get a better exception thrown. parser.withParseType(period.getPeriodType()).parseMutablePeriod(str); } throw new IllegalArgumentException("Invalid format: \"" + str + '"'); } }
@Before public void setUp() { formatter = ISOPeriodFormat.standard(); processor1 = new ParsePeriod(); processor2 = new ParsePeriod(formatter); processorChain1 = new ParsePeriod(new IdentityTransform()); processorChain2 = new ParsePeriod(formatter, new IdentityTransform()); processors = Arrays.asList(processor1, processor2, processorChain1, processorChain2); }
@Before public void setUp() { formatter = ISOPeriodFormat.standard(); processor1 = new FmtPeriod(); processor2 = new FmtPeriod(formatter); processorChain1 = new FmtPeriod(new IdentityTransform()); processorChain2 = new FmtPeriod(formatter, new IdentityTransform()); processors = Arrays.asList(processor1, processor2, processorChain1, processorChain2); }
@Override public Duration fromString(String rawValue) { try { Period period = ISOPeriodFormat.standard().parsePeriod(rawValue); return period.toStandardDuration(); } catch (Exception e) { throw new ObjectParseException(e,Duration.class,rawValue); } }
@Override public Duration fromString(String rawValue) { try { Period period = ISOPeriodFormat.standard().parsePeriod(rawValue); return TimeUtils.newInstance().from(period.toStandardDuration()).toDuration(); } catch (Exception e) { throw new ObjectParseException(e,Duration.class,rawValue); } }
@Override public ObjectNode toJSONNode(TCAPIVersion version) { ObjectMapper mapper = Mapper.getInstance(); ObjectNode node = mapper.createObjectNode(); if (this.score != null) { node.put("score", this.getScore().toJSONNode(version)); } if (this.success != null) { node.put("success", this.getSuccess()); } if (this.completion != null) { node.put("completion", this.getCompletion()); } if (this.duration != null) { // // ISOPeriodFormat includes milliseconds but the spec only allows // hundredths of a second here, so get the normal string, then truncate // the last digit to provide the proper precision // String shortenedDuration = ISOPeriodFormat.standard().print(this.getDuration()).replaceAll("(\\.\\d\\d)\\dS", "$1S"); node.put("duration", shortenedDuration); } if (this.response != null) { node.put("response", this.getResponse()); } if (this.extensions != null) { node.put("extensions", this.getExtensions().toJSONNode(version)); } return node; }
public Date resolveDuedate(String duedate) { try { if (duedate.startsWith("P")){ return DateTimeUtil.now().plus(ISOPeriodFormat.standard().parsePeriod(duedate)).toDate(); } return DateTimeUtil.parseDateTime(duedate).toDate(); } catch (Exception e) { throw LOG.exceptionWhileResolvingDuedate(duedate, e); } }
@Override public void writeInterval(Period value) throws IOException { gen.writeString(value.toString(ISOPeriodFormat.standard())); }
public int[] GetVideoLength(String id) { if (Quorrabot.enableDebugging) { com.gmt2001.Console.out.println(">>>[DEBUG] 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")); //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"))); */ if (Quorrabot.enableDebugging) { com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetVideoLength Success"); } return new int[]{ h, m, s }; } else { if (Quorrabot.enableDebugging) { com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetVideoLength Fail"); } return new int[]{ 0, 0, 0 }; } } else { if (Quorrabot.enableDebugging) { com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetVideoLength Fail2"); } return new int[]{ 0, 0, 0 }; } } if (Quorrabot.enableDebugging) { com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetVideoLength Fail3"); } return new int[]{ 0, 0, 0 }; }
@Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object o = stack.pop(); if (!(o instanceof String)) { throw new WarpScriptException(getName() + " expects an ISO8601 duration (a string) on top of the stack. See http://en.wikipedia.org/wiki/ISO_8601#Durations"); } ReadWritablePeriod period = new MutablePeriod(); ISOPeriodFormat.standard().getParser().parseInto(period, o.toString(), 0, Locale.US); Period p = period.toPeriod(); if (p.getMonths() != 0 || p.getYears() != 0) { throw new WarpScriptException(getName() + " doesn't support ambiguous durations containing years or months, please convert those to days."); } Duration duration = p.toDurationFrom(new Instant()); stack.push(duration.getMillis() * Constants.TIME_UNITS_PER_MS); return stack; }
public static LocalTime parseTime(String value) { Period period = ISOPeriodFormat.standard().parsePeriod(value); return new LocalTime(period.toStandardDuration().getMillis(), DateTimeZone.UTC); }
public static String formatTimeForXml(LocalTime localTime) { return ISOPeriodFormat.standard().print(new Period(localTime.getMillisOfDay())); }
/** * Sets the value of the mutable interval from the string. * * @param writableInterval the interval to set * @param object the String to convert, must not be null * @param chrono the chronology to use, may be null */ public void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono) { String str = (String) object; int separator = str.indexOf('/'); if (separator < 0) { throw new IllegalArgumentException("Format requires a '/' separator: " + str); } String leftStr = str.substring(0, separator); if (leftStr.length() <= 0) { throw new IllegalArgumentException("Format invalid: " + str); } String rightStr = str.substring(separator + 1); if (rightStr.length() <= 0) { throw new IllegalArgumentException("Format invalid: " + str); } DateTimeFormatter dateTimeParser = ISODateTimeFormat.dateTimeParser(); dateTimeParser = dateTimeParser.withChronology(chrono); PeriodFormatter periodParser = ISOPeriodFormat.standard(); long startInstant = 0, endInstant = 0; Period period = null; Chronology parsedChrono = null; // before slash char c = leftStr.charAt(0); if (c == 'P' || c == 'p') { period = periodParser.withParseType(getPeriodType(leftStr)).parsePeriod(leftStr); } else { DateTime start = dateTimeParser.parseDateTime(leftStr); startInstant = start.getMillis(); parsedChrono = start.getChronology(); } // after slash c = rightStr.charAt(0); if (c == 'P' || c == 'p') { if (period != null) { throw new IllegalArgumentException("Interval composed of two durations: " + str); } period = periodParser.withParseType(getPeriodType(rightStr)).parsePeriod(rightStr); chrono = (chrono != null ? chrono : parsedChrono); endInstant = chrono.add(period, startInstant, 1); } else { DateTime end = dateTimeParser.parseDateTime(rightStr); endInstant = end.getMillis(); parsedChrono = (parsedChrono != null ? parsedChrono : end.getChronology()); chrono = (chrono != null ? chrono : parsedChrono); if (period != null) { startInstant = chrono.add(period, endInstant, -1); } } writableInterval.setInterval(startInstant, endInstant); writableInterval.setChronology(chrono); }
/** * * @param response * gets the detailed informations JSON produced eariler, * containing all informations about a sinlge video * @param youtubeTemp * is a reference to the youtube object we try to fill in the for * loop * * the method iterates over the details JSON and fills all fields * @throws java.text.ParseException */ private YoutubeMetaData processingDetailedResults(JSONObject response, YoutubeMetaData youtubeTemp) { JSONArray responseItems = (JSONArray) response.get("items"); JSONObject responseItemsEntry = (JSONObject) responseItems.get(0); JSONObject responseSnippet = (JSONObject) responseItemsEntry .get("snippet"); JSONObject responseStatus = (JSONObject) responseItemsEntry .get("status"); System.out.println("channelId " + responseSnippet.get("channelId").toString()); youtubeTemp.setChannelID(responseSnippet.get("channelId").toString()); youtubeTemp.setTitle(responseSnippet.get("title").toString()); System.out.println("title: " + responseSnippet.get("title").toString()); String tempDate = responseSnippet.get("publishedAt").toString(); DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss"); Date date = null; try { date = formatter.parse(tempDate); } catch (java.text.ParseException e) { e.printStackTrace(); return null; } youtubeTemp.setPublishedAt(date); System.out.println("publishedAt: " + youtubeTemp.getPublishedAt()); JSONObject responseContentDetails = (JSONObject) responseItemsEntry .get("contentDetails"); youtubeTemp.setDuration(responseContentDetails.get("duration") .toString()); PeriodFormatter pf = ISOPeriodFormat.standard(); Period p = pf.parsePeriod(responseContentDetails.get("duration") .toString()); Seconds s = p.toStandardSeconds(); System.out.println("durationInSecond: " + s.getSeconds()); youtubeTemp.setDurationInSeconds(s.getSeconds()); System.out.println("duration " + responseContentDetails.get("duration").toString()); JSONObject responseStatistics = (JSONObject) responseItemsEntry .get("statistics"); youtubeTemp .setViewCount(responseStatistics.get("viewCount").toString()); System.out.println("viewCount" + responseStatistics.get("viewCount").toString()); youtubeTemp .setLikeCount(responseStatistics.get("likeCount").toString()); System.out.println("likeCount" + responseStatistics.get("likeCount").toString()); youtubeTemp.setDislikeCount(responseStatistics.get("dislikeCount") .toString()); System.out.println("dislikeCount" + responseStatistics.get("dislikeCount").toString()); youtubeTemp.setCommentCount(responseStatistics.get("commentCount") .toString()); System.out.println("commentCount" + responseStatistics.get("commentCount").toString()); boolean isCreativeCommon = false; if (responseStatus.get("license").toString() == "creativeCommon") isCreativeCommon = true; youtubeTemp.setCreativeCommon(isCreativeCommon); System.out.println("creativeCommon: " + youtubeTemp.isCreativeCommon()); System.out.println("------------------------------"); return youtubeTemp; }
public FetchResult fetchSongData(String youtubeId) { try { JSONObject obj = getJsonForYoutubeId(youtubeId); JSONArray items = obj.getJSONArray("items"); if(items.length() == 0) { return new FetchResult("I couldn't find info about that video on youtube"); } JSONObject item = items.getJSONObject(0); JSONObject snippet = item.getJSONObject("snippet"); JSONObject status = item.getJSONObject("status"); JSONObject contentDetails = item.getJSONObject("contentDetails"); String title = snippet.getString("title"); String durationStr = contentDetails.getString("duration"); //format is like "PT5M30S" for 5 minutes 30 seconds Period p = ISOPeriodFormat.standard().parsePeriod(durationStr); int durationSeconds = p.toStandardSeconds().getSeconds(); if (! countryIsAllowed(contentDetails)) { return new FetchResult("that video can't be played in the streamer's country"); } if(!("public".equals(status.getString("privacyStatus")))) { return new FetchResult("that video is private"); } if(!status.getBoolean("embeddable")) { return new FetchResult("that video is not allowed to be embedded"); } if(durationSeconds == 0) { return new FetchResult("that video has length 0 (probably it's a live stream)"); } SongEntry newSong = new SongEntry(title, youtubeId, -1, null, new Date().getTime(), durationSeconds, false, 0, SiteIds.YOUTUBE); return new FetchResult(newSong); } catch (Exception e) { logger.error("Problem with youtube request \"" + youtubeId + "\"", e); return new FetchResult("I had an error while trying to add that song"); } }
public FetchResult youtubeSearch(String sender, String q, DjService dj) { try { String searchUrl = "https://www.googleapis.com/youtube/v3/search?videoEmbeddable=true&part=id&q=" + URLEncoder.encode(q, "UTF-8") + "&type=video®ionCode=" + conf.getUserCountryCode() + "&maxResults=5&key=" + conf.getYoutubeAccessToken(); GetMethod get; HttpClient client = new HttpClient(); get = new GetMethod(searchUrl); int errcode = client.executeMethod(get); if (errcode != 200) { logger.info("Song search error: got code " + errcode + " from " + searchUrl); return new FetchResult("I couldn't run that search properly on youtube"); } String resp = IOUtils.toString(get.getResponseBodyAsStream(), "utf-8"); if (resp == null) { logger.info("Couldn't get detail at " + searchUrl); return new FetchResult("I couldn't run that search properly on youtube"); } JSONObject searchObj = new JSONObject(resp); JSONArray searchItems = searchObj.getJSONArray("items"); if (searchItems.length() == 0) { logger.info("Empty 'items' array in youtube response for url " + searchUrl); return new FetchResult("that search gave no results"); } for (int i = 0; i < searchItems.length(); ++i) { JSONObject resultItem = searchItems.getJSONObject(i); JSONObject id = resultItem.getJSONObject("id"); String videoId = id.getString("videoId"); JSONObject obj = getJsonForYoutubeId(videoId); JSONArray items = obj.getJSONArray("items"); if (items.length() == 0) { continue; } JSONObject item = items.getJSONObject(0); JSONObject snippet = item.getJSONObject("snippet"); JSONObject status = item.getJSONObject("status"); JSONObject contentDetails = item.getJSONObject("contentDetails"); String title = snippet.getString("title"); String durationStr = contentDetails.getString("duration"); //format is like "PT5M30S" for 5 minutes 30 seconds Period p = ISOPeriodFormat.standard().parsePeriod(durationStr); int durationSeconds = p.toStandardSeconds().getSeconds(); if (!countryIsAllowed(contentDetails)) { continue; } if (!("public".equals(status.getString("privacyStatus")))) { continue; } if (!status.getBoolean("embeddable")) { continue; } if (durationSeconds == 0) { continue; } SongEntry newSong = new SongEntry(title, videoId, -1, sender, new Date().getTime(), durationSeconds, false, 0, SiteIds.YOUTUBE); if (dj.getPossiblePolicyFailureReason(newSong, sender) != null) { continue; } return new FetchResult(newSong); } //if we get here, it means none of the songs in the results were okay return new FetchResult("I didn't find an appropriate video early enough in the search results"); } catch (Exception e) { logger.error("Problem with youtube search \"" + q + "\"", e); return new FetchResult("I had an error while trying to add that song"); } }
public static DurationLiteral of(javax.xml.datatype.Duration duration) { checkNotNull(duration,DURATION_CANNOT_BE_NULL); Period period = ISOPeriodFormat.standard().parsePeriod(duration.toString()); return new ImmutableDurationLiteral(period.toStandardDuration(),Datatypes.DURATION); }