use of org.joda.time.LocalTime in project SeriesGuide by UweTrottmann.
the class TvdbTools method parseEpisodes.
/**
* Loads the given zipped XML and parses containing episodes to create an array of {@link
* ContentValues} for new episodes.<br> Adds update ops for updated episodes and delete ops for
* local orphaned episodes to the given {@link ContentProviderOperation} batch.
*/
private ArrayList<ContentValues> parseEpisodes(final ArrayList<ContentProviderOperation> batch, final Show show, String url) throws TvdbException {
final long dateLastMonthEpoch = (System.currentTimeMillis() - (DateUtils.DAY_IN_MILLIS * 30)) / 1000;
final DateTimeZone showTimeZone = TimeTools.getDateTimeZone(show.release_timezone);
final LocalTime showReleaseTime = TimeTools.getShowReleaseTime(show.release_time);
final String deviceTimeZone = TimeZone.getDefault().getID();
RootElement root = new RootElement("Data");
Element episode = root.getChild("Episode");
final ArrayList<ContentValues> newEpisodesValues = new ArrayList<>();
final HashMap<Integer, Long> localEpisodeIds = DBUtils.getEpisodeMapForShow(app, show.tvdb_id);
final HashMap<Integer, Long> removableEpisodeIds = new HashMap<>(// just copy episodes list, then remove valid ones
localEpisodeIds);
final HashSet<Integer> localSeasonIds = DBUtils.getSeasonIdsOfShow(app, show.tvdb_id);
// store updated seasons to avoid duplicate ops
final HashSet<Integer> seasonIdsToUpdate = new HashSet<>();
final ContentValues values = new ContentValues();
// set handlers for elements we want to react to
episode.setEndElementListener(new EndElementListener() {
public void end() {
Integer episodeId = values.getAsInteger(Episodes._ID);
if (episodeId == null || episodeId <= 0) {
// invalid id, skip
return;
}
// don't clean up this episode
removableEpisodeIds.remove(episodeId);
// decide whether to insert or update
if (localEpisodeIds.containsKey(episodeId)) {
/*
* Update uses provider ops which take a long time. Only
* update if episode was edited on TVDb or is not older than
* a month (ensures show air time changes get stored).
*/
Long lastEditEpoch = localEpisodeIds.get(episodeId);
Long lastEditEpochNew = values.getAsLong(Episodes.LAST_EDITED);
if (lastEditEpoch != null && lastEditEpochNew != null && (lastEditEpoch < lastEditEpochNew || dateLastMonthEpoch < lastEditEpoch)) {
// complete update op for episode
batch.add(DBUtils.buildEpisodeUpdateOp(values));
}
} else {
// episode does not exist, yet
newEpisodesValues.add(new ContentValues(values));
}
Integer seasonId = values.getAsInteger(Seasons.REF_SEASON_ID);
if (seasonId != null && !seasonIdsToUpdate.contains(seasonId)) {
// add insert/update op for season
batch.add(DBUtils.buildSeasonOp(values, !localSeasonIds.contains(seasonId)));
seasonIdsToUpdate.add(values.getAsInteger(Seasons.REF_SEASON_ID));
}
values.clear();
}
});
episode.getChild("id").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes._ID, body.trim());
}
});
episode.getChild("EpisodeNumber").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.NUMBER, body.trim());
}
});
episode.getChild("absolute_number").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.ABSOLUTE_NUMBER, body.trim());
}
});
episode.getChild("SeasonNumber").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.SEASON, body.trim());
}
});
episode.getChild("DVD_episodenumber").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.DVDNUMBER, body.trim());
}
});
episode.getChild("FirstAired").setEndTextElementListener(new EndTextElementListener() {
public void end(String releaseDate) {
long releaseDateTime = TimeTools.parseEpisodeReleaseDate(app, showTimeZone, releaseDate, showReleaseTime, show.country, show.network, deviceTimeZone);
values.put(Episodes.FIRSTAIREDMS, releaseDateTime);
}
});
episode.getChild("EpisodeName").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.TITLE, body.trim());
}
});
episode.getChild("Overview").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.OVERVIEW, body.trim());
}
});
episode.getChild("seasonid").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Seasons.REF_SEASON_ID, body.trim());
}
});
episode.getChild("seriesid").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Shows.REF_SHOW_ID, body.trim());
}
});
episode.getChild("Director").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.DIRECTORS, body.trim());
}
});
episode.getChild("GuestStars").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.GUESTSTARS, body.trim());
}
});
episode.getChild("Writer").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.WRITERS, body.trim());
}
});
episode.getChild("filename").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.IMAGE, body.trim());
}
});
episode.getChild("IMDB_ID").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.IMDBID, body.trim());
}
});
episode.getChild("lastupdated").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
// system populated field, trimming not necessary
try {
values.put(Episodes.LAST_EDITED, Long.valueOf(body));
} catch (NumberFormatException e) {
values.put(Episodes.LAST_EDITED, 0);
}
}
});
downloadAndParse(root.getContentHandler(), url, true, "parseEpisodes: ");
// add delete ops for leftover episodeIds in our db
for (Integer episodeId : removableEpisodeIds.keySet()) {
batch.add(ContentProviderOperation.newDelete(Episodes.buildEpisodeUri(episodeId)).build());
}
return newEpisodesValues;
}
use of org.joda.time.LocalTime in project joda-time by JodaOrg.
the class TestUnsupportedDateTimeField method setUp.
protected void setUp() throws Exception {
weeks = DurationFieldType.weeks();
months = DurationFieldType.months();
dateTimeFieldTypeOne = DateTimeFieldType.centuryOfEra();
localTime = new LocalTime();
}
use of org.joda.time.LocalTime in project presto by prestodb.
the class TestDateTimeFunctions method testCurrentTime.
@Test
public void testCurrentTime() throws Exception {
long millis = new LocalTime(session.getStartTime(), DATE_TIME_ZONE).getMillisOfDay();
functionAssertions.assertFunction("CURRENT_TIME", TIME_WITH_TIME_ZONE, new SqlTimeWithTimeZone(millis, session.getTimeZoneKey()));
}
use of org.joda.time.LocalTime in project presto by prestodb.
the class TestDateTimeFunctions method testLocalTime.
@Test
public void testLocalTime() throws Exception {
long millis = new LocalTime(session.getStartTime(), DATE_TIME_ZONE).getMillisOfDay();
functionAssertions.assertFunction("LOCALTIME", TimeType.TIME, toTime(millis));
}
use of org.joda.time.LocalTime in project nifi by apache.
the class StandardContentViewerController method doGet.
/**
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final ViewableContent content = (ViewableContent) request.getAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE);
// handle json/xml specifically, treat others as plain text
String contentType = content.getContentType();
if (supportedMimeTypes.contains(contentType)) {
final String formatted;
// leave the content alone if specified
if (DisplayMode.Original.equals(content.getDisplayMode())) {
formatted = content.getContent();
} else {
if ("application/json".equals(contentType)) {
// format json
final ObjectMapper mapper = new ObjectMapper();
final Object objectJson = mapper.readValue(content.getContentStream(), Object.class);
formatted = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectJson);
} else if ("application/xml".equals(contentType) || "text/xml".equals(contentType)) {
// format xml
final StringWriter writer = new StringWriter();
try {
final StreamSource source = new StreamSource(content.getContentStream());
final StreamResult result = new StreamResult(writer);
final TransformerFactory transformFactory = TransformerFactory.newInstance();
final Transformer transformer = transformFactory.newTransformer();
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
} catch (final TransformerFactoryConfigurationError | TransformerException te) {
throw new IOException("Unable to transform content as XML: " + te, te);
}
// get the transformed xml
formatted = writer.toString();
} else if ("application/avro-binary".equals(contentType) || "avro/binary".equals(contentType) || "application/avro+binary".equals(contentType)) {
final StringBuilder sb = new StringBuilder();
sb.append("[");
// Use Avro conversions to display logical type values in human readable way.
final GenericData genericData = new GenericData() {
@Override
protected void toString(Object datum, StringBuilder buffer) {
// Since these types are not quoted and produce a malformed JSON string, quote it here.
if (datum instanceof LocalDate || datum instanceof LocalTime || datum instanceof DateTime) {
buffer.append("\"").append(datum).append("\"");
return;
}
super.toString(datum, buffer);
}
};
genericData.addLogicalTypeConversion(new Conversions.DecimalConversion());
genericData.addLogicalTypeConversion(new TimeConversions.DateConversion());
genericData.addLogicalTypeConversion(new TimeConversions.TimeConversion());
genericData.addLogicalTypeConversion(new TimeConversions.TimestampConversion());
final DatumReader<GenericData.Record> datumReader = new GenericDatumReader<>(null, null, genericData);
try (final DataFileStream<GenericData.Record> dataFileReader = new DataFileStream<>(content.getContentStream(), datumReader)) {
while (dataFileReader.hasNext()) {
final GenericData.Record record = dataFileReader.next();
final String formattedRecord = genericData.toString(record);
sb.append(formattedRecord);
sb.append(",");
// Do not format more than 10 MB of content.
if (sb.length() > 1024 * 1024 * 2) {
break;
}
}
}
if (sb.length() > 1) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("]");
final String json = sb.toString();
final ObjectMapper mapper = new ObjectMapper();
final Object objectJson = mapper.readValue(json, Object.class);
formatted = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectJson);
contentType = "application/json";
} else {
// leave plain text alone when formatting
formatted = content.getContent();
}
}
// defer to the jsp
request.setAttribute("mode", contentType);
request.setAttribute("content", formatted);
request.getRequestDispatcher("/WEB-INF/jsp/codemirror.jsp").include(request, response);
} else {
final PrintWriter out = response.getWriter();
out.println("Unexpected content type: " + contentType);
}
}
Aggregations