import freenet.keys.FreenetURI;
import freenet.support.api.Bucket;
-import com.google.common.base.Optional;
-
/**
* The Sone downloader is responsible for download Sones as they are updated.
*
* @return The downloaded Sone, or {@code null} if the Sone could not be
* downloaded
*/
- public Optional<Sone> fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
+ public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
sone.setStatus(SoneStatus.downloading);
return null;
}
logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
- Optional<Sone> parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
- if (parsedSone.isPresent()) {
+ Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
+ if (parsedSone != null) {
if (!fetchOnly) {
- parsedSone.get().setStatus((parsedSone.get().getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
- core.updateSone(parsedSone.get());
- addSone(parsedSone.get());
+ parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
+ core.updateSone(parsedSone);
+ addSone(parsedSone);
}
}
return parsedSone;
* The requested URI
* @return The parsed Sone, or {@code null} if the Sone could not be parsed
*/
- public Optional<Sone> parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
+ public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
Bucket soneBucket = fetchResult.asBucket();
InputStream soneInputStream = null;
try {
soneInputStream = soneBucket.getInputStream();
- Optional<Sone> parsedSone = parseSone(originalSone, soneInputStream);
- if (parsedSone.isPresent()) {
- parsedSone.get().modify().setLatestEdition(requestUri.getEdition()).update();
+ Sone parsedSone = parseSone(originalSone, soneInputStream);
+ if (parsedSone != null) {
+ parsedSone.modify().setLatestEdition(requestUri.getEdition()).update();
}
return parsedSone;
} catch (Exception e1) {
* The input stream to parse the Sone from
* @return The parsed Sone
*/
- public Optional<Sone> parseSone(Sone originalSone, InputStream soneInputStream) {
+ public Sone parseSone(Sone originalSone, InputStream soneInputStream) {
return new SoneParser().parseSone(core.getDatabase(), originalSone, soneInputStream);
}
* The input stream to parse the Sone from
* @return The parsed Sone
*/
- public Optional<Sone> parseSone(Database database, Sone originalSone, InputStream soneInputStream) {
+ public Sone parseSone(Database database, Sone originalSone, InputStream soneInputStream) {
/* TODO - impose a size limit? */
Document document;
if (document == null) {
/* TODO - mark Sone as bad. */
logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone.getId()));
- return absent();
+ return null;
}
Optional<SimpleXML> soneXml = parseXml(originalSone, document);
if (!soneXml.isPresent()) {
logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", originalSone.getId()));
- return absent();
+ return null;
}
Optional<Client> parsedClient = parseClient(originalSone, soneXml.get());
if (protocolVersion.isPresent()) {
if (protocolVersion.get() < 0) {
logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion.get()));
- return absent();
+ return null;
}
if (protocolVersion.get() > MAX_PROTOCOL_VERSION) {
logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion.get()));
- return absent();
+ return null;
}
}
if (soneTime == null) {
/* TODO - mark Sone as bad. */
logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
- return absent();
+ return null;
}
try {
sone.setTime(Long.parseLong(soneTime));
} catch (NumberFormatException nfe1) {
/* TODO - mark Sone as bad. */
logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
- return absent();
+ return null;
}
SimpleXML profileXml = soneXml.get().getNode("profile");
if (profileXml == null) {
/* TODO - mark Sone as bad. */
logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
- return absent();
+ return null;
}
/* parse profile. */
String fieldValue = fieldXml.getValue("field-value", "");
if (fieldName == null) {
logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
- return absent();
+ return null;
}
try {
profile.setField(profile.addField(fieldName), fieldValue);
} catch (IllegalArgumentException iae1) {
logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
- return absent();
+ return null;
}
}
}
if ((postId == null) || (postTime == null) || (postText == null)) {
/* TODO - mark Sone as bad. */
logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
- return absent();
+ return null;
}
try {
PostBuilder postBuilder = sone.newPostBuilder();
} catch (NumberFormatException nfe1) {
/* TODO - mark Sone as bad. */
logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
- return absent();
+ return null;
}
}
}
if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
/* TODO - mark Sone as bad. */
logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", sone, replyId, replyPostId, replyTime, replyText));
- return absent();
+ return null;
}
try {
/* TODO - parse time correctly. */
} catch (NumberFormatException nfe1) {
/* TODO - mark Sone as bad. */
logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
- return absent();
+ return null;
}
}
}
String albumImageId = albumXml.getValue("album-image", null);
if ((id == null) || (title == null) || (description == null)) {
logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
- return absent();
+ return null;
}
Album parent = sone.getRootAlbum();
if (parentId != null) {
parent = albums.get(parentId);
if (parent == null) {
logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
- return absent();
+ return null;
}
}
Album album = parent.newAlbumBuilder().withId(id).build().modify().setTitle(title).setDescription(description).update();
String imageHeightString = imageXml.getValue("height", null);
if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
- return absent();
+ return null;
}
long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
if ((imageWidth < 1) || (imageHeight < 1)) {
logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
- return absent();
+ return null;
}
Image image = album.newImageBuilder().withId(imageId).at(imageKey).created(creationTime).sized(imageWidth, imageHeight).build(Optional.<ImageCreated>absent());
image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
sone.setLikePostIds(likedPostIds);
sone.setLikeReplyIds(likedReplyIds);
- return of(sone);
+ return sone;
}
private Optional<Integer> parseProtocolVersion(SimpleXML soneXml) {
import net.pterodactylus.sone.data.Sone;
import net.pterodactylus.util.service.AbstractService;
-
import freenet.keys.FreenetURI;
-import com.google.common.base.Optional;
-
/**
* The Sone rescuer downloads older editions of a Sone and updates the currently
* stored Sone with it.
core.lockSone(sone);
FreenetURI soneUri = TO_FREENET_URI.apply(sone).setKeyType("SSK").setDocName("Sone-" + currentEdition).setMetaString(new String[] { "sone.xml" });
System.out.println("URI: " + soneUri);
- Optional<Sone> fetchedSone = soneDownloader.fetchSone(sone, soneUri, true);
+ Sone fetchedSone = soneDownloader.fetchSone(sone, soneUri, true);
System.out.println("Sone: " + fetchedSone);
- lastFetchSuccessful = fetchedSone.isPresent();
+ lastFetchSuccessful = (fetchedSone != null);
if (lastFetchSuccessful) {
- core.updateSone(fetchedSone.get(), true);
+ core.updateSone(fetchedSone, true);
}
fetching = false;
}
import static java.util.logging.Level.OFF;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
}
@Test
- public void verifyThatAnInvalidXmlDocumentIsNotParsed() throws UnsupportedEncodingException {
- Optional<Sone> sone = soneParser.parseSone(database, originalSone, getXml("invalid-xml"));
- assertThat(sone, notNullValue());
- assertThat(sone.isPresent(), is(false));
+ public void verifyThatAnInvalidXmlDocumentIsNotParsed() {
+ soneParser.parseSone(database, originalSone, getXml("invalid-xml"));
}
@Test
public void verifyThatANegativeProtocolVersionCausesAnError() {
- Optional<Sone> sone = soneParser.parseSone(database, originalSone, getXml("negative-protocol-version"));
- assertThat(sone, notNullValue());
- assertThat(sone.isPresent(), is(false));
+ soneParser.parseSone(database, originalSone, getXml("negative-protocol-version"));
}
@Test
public void verifyThatATooLargeProtocolVersionCausesAnError() {
- Optional<Sone> sone = soneParser.parseSone(database, originalSone, getXml("too-large-protocol-version"));
- assertThat(sone, notNullValue());
- assertThat(sone.isPresent(), is(false));
+ soneParser.parseSone(database, originalSone, getXml("too-large-protocol-version"));
}
@Test
public void verifyThatAMissingTimeCausesAnError() {
- Optional<Sone> sone = soneParser.parseSone(database, originalSone, getXml("missing-time"));
- assertThat(sone, notNullValue());
- assertThat(sone.isPresent(), is(false));
+ soneParser.parseSone(database, originalSone, getXml("missing-time"));
}
@Test
public void verifyThatAMissingClientCausesTheOriginalClientToBeUsed() {
- Optional<Sone> sone = soneParser.parseSone(database, originalSone, getXml("missing-client"));
+ Sone sone = soneParser.parseSone(database, originalSone, getXml("missing-client"));
assertThat(sone, notNullValue());
- assertThat(sone.isPresent(), is(true));
- assertThat(sone.get().getClient(), notNullValue());
- assertThat(sone.get().getClient(), is(originalSone.getClient()));
+ assertThat(sone.getClient(), notNullValue());
+ assertThat(sone.getClient(), is(originalSone.getClient()));
}
@Test
public void verifyThatAnInvalidClientCausesTheOriginalClientToBeUsed() {
- Optional<Sone> sone = soneParser.parseSone(database, originalSone, getXml("invalid-client"));
+ Sone sone = soneParser.parseSone(database, originalSone, getXml("invalid-client"));
assertThat(sone, notNullValue());
- assertThat(sone.isPresent(), is(true));
- assertThat(sone.get().getClient(), notNullValue());
- assertThat(sone.get().getClient(), is(originalSone.getClient()));
+ assertThat(sone.getClient(), notNullValue());
+ assertThat(sone.getClient(), is(originalSone.getClient()));
}
@Test
public void verifyThatTheCreatedSoneMeetsAllExpectations() {
- Optional<Sone> sone = soneParser.parseSone(database, originalSone, getXml("complete"));
+ Sone sone = soneParser.parseSone(database, originalSone, getXml("complete"));
assertThat(sone, notNullValue());
- assertThat(sone.isPresent(), is(true));
- assertThat(sone.get().getTime(), is(1382419919000L));
- assertThat(sone.get().getClient(), notNullValue());
- assertThat(sone.get().getClient().getName(), is("Sone"));
- assertThat(sone.get().getClient().getVersion(), is("0.8.7"));
- assertThat(sone.get().getProfile(), notNullValue());
- assertThat(sone.get().getProfile().getFirstName(), is("First"));
- assertThat(sone.get().getProfile().getMiddleName(), is("M."));
- assertThat(sone.get().getProfile().getLastName(), is("Last"));
- assertThat(sone.get().getProfile().getBirthYear(), is(2013));
- assertThat(sone.get().getProfile().getBirthMonth(), is(10));
- assertThat(sone.get().getProfile().getBirthDay(), is(22));
- assertThat(sone.get().getProfile().getAvatar(), is("96431abe-3add-11e3-8a46-67047503bf6d"));
- assertThat(sone.get().getProfile().getFields(), contains(
+ assertThat(sone.getTime(), is(1382419919000L));
+ assertThat(sone.getClient(), notNullValue());
+ assertThat(sone.getClient().getName(), is("Sone"));
+ assertThat(sone.getClient().getVersion(), is("0.8.7"));
+ assertThat(sone.getProfile(), notNullValue());
+ assertThat(sone.getProfile().getFirstName(), is("First"));
+ assertThat(sone.getProfile().getMiddleName(), is("M."));
+ assertThat(sone.getProfile().getLastName(), is("Last"));
+ assertThat(sone.getProfile().getBirthYear(), is(2013));
+ assertThat(sone.getProfile().getBirthMonth(), is(10));
+ assertThat(sone.getProfile().getBirthDay(), is(22));
+ assertThat(sone.getProfile().getAvatar(), is("96431abe-3add-11e3-8a46-67047503bf6d"));
+ assertThat(sone.getProfile().getFields(), contains(
fieldMatcher("Field1", "Value1"),
fieldMatcher("Field2", "Value2")
));
- assertThat(sone.get().getPosts(), contains(
+ assertThat(sone.getPosts(), contains(
postMatcher("d8c9586e-3adb-11e3-bb31-171fc040e645", "0rpD4gL8mszav2trndhIdKIxvKUCNAe2kjA3dLV8CVU", 1382420181000L, "Hello, User!"),
postMatcher("bbb7ebf0-3adb-11e3-8a0b-630cd8f21cf3", null, 1382420140000L, "Hello, World!")
));
- assertThat(sone.get().getReplies(), containsInAnyOrder(
+ assertThat(sone.getReplies(), containsInAnyOrder(
postReplyMatcher("f09fa448-3adb-11e3-a783-ab54a11aacc4", "bbb7ebf0-3adb-11e3-8a0b-630cd8f21cf3", 1382420224000L, "Talking to myself."),
postReplyMatcher("0a376440-3adc-11e3-8f45-c7cc157436a5", "11ebe86e-3adc-11e3-b7b9-7f2c88018a33", 1382420271000L, "Talking to somebody I can't see.")
));
- assertThat(sone.get().getLikedPostIds(), containsInAnyOrder(
+ assertThat(sone.getLikedPostIds(), containsInAnyOrder(
"bbb7ebf0-3adb-11e3-8a0b-630cd8f21cf3",
"305d85e6-3adc-11e3-be45-8b53dd91f0af"
));
- assertThat(sone.get().getLikedReplyIds(), containsInAnyOrder(
+ assertThat(sone.getLikedReplyIds(), containsInAnyOrder(
"f09fa448-3adb-11e3-a783-ab54a11aacc4",
"3ba28960-3adc-11e3-93c7-6713d170f44c"
));
-
}
private Matcher<PostReply> postReplyMatcher(final String id, final String postId, final long time, final String text) {