import net.pterodactylus.util.thread.NamedThreadFactory;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashMultimap;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
+import kotlin.jvm.functions.Function1;
/**
* The Sone core.
return database.getSones();
}
+ @Nonnull
@Override
- public Function<String, Optional<Sone>> soneLoader() {
- return database.soneLoader();
+ public Function1<String, Sone> getSoneLoader() {
+ return database.getSoneLoader();
}
/**
* Sone
*/
@Override
- public Optional<Sone> getSone(String id) {
+ @Nullable
+ public Sone getSone(@Nonnull String id) {
return database.getSone(id);
}
* @return The Sone with the given ID, or {@code null}
*/
public Sone getLocalSone(String id) {
- Optional<Sone> sone = database.getSone(id);
- if (sone.isPresent() && sone.get().isLocal()) {
- return sone.get();
+ Sone sone = database.getSone(id);
+ if ((sone != null) && sone.isLocal()) {
+ return sone;
}
return null;
}
* @return The Sone with the given ID
*/
public Sone getRemoteSone(String id) {
- return database.getSone(id).orNull();
+ return database.getSone(id);
}
/**
}
String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
long latestEdition = fromNullable(tryParse(property)).or(0L);
- Optional<Sone> existingSone = getSone(identity.getId());
- if (existingSone.isPresent() && existingSone.get().isLocal()) {
- return existingSone.get();
+ Sone existingSone = getSone(identity.getId());
+ if ((existingSone != null )&& existingSone.isLocal()) {
+ return existingSone;
}
- boolean newSone = !existingSone.isPresent();
- Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
+ boolean newSone = existingSone == null;
+ Sone sone = !newSone ? existingSone : database.newSoneBuilder().from(identity).build();
sone.setLatestEdition(latestEdition);
if (newSone) {
synchronized (knownSones) {
if (!soneFollowingTimes.containsKey(soneId)) {
long now = System.currentTimeMillis();
soneFollowingTimes.put(soneId, now);
- Optional<Sone> followedSone = getSone(soneId);
- if (!followedSone.isPresent()) {
+ Sone followedSone = getSone(soneId);
+ if (followedSone == null) {
return;
}
- for (Post post : followedSone.get().getPosts()) {
+ for (Post post : followedSone.getPosts()) {
if (post.getTime() < now) {
markPostKnown(post);
}
}
- for (PostReply reply : followedSone.get().getReplies()) {
+ for (PostReply reply : followedSone.getReplies()) {
if (reply.getTime() < now) {
markReplyKnown(reply);
}
* of the age of the given Sone
*/
public void updateSone(final Sone sone, boolean soneRescueMode) {
- Optional<Sone> storedSone = getSone(sone.getId());
- if (storedSone.isPresent()) {
- if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
+ Sone storedSone = getSone(sone.getId());
+ if (storedSone != null) {
+ if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
return;
}
List<Object> events =
- collectEventsForChangesInSone(storedSone.get(), sone);
+ collectEventsForChangesInSone(storedSone, sone);
database.storeSone(sone);
for (Object event : events) {
eventBus.post(event);
}
- sone.setOptions(storedSone.get().getOptions());
- sone.setKnown(storedSone.get().isKnown());
+ sone.setOptions(storedSone.getOptions());
+ sone.setKnown(storedSone.isKnown());
sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
if (sone.isLocal()) {
touchConfiguration();
return;
}
}
- Optional<Sone> sone = getSone(identity.getId());
- if (!sone.isPresent()) {
+ Sone sone = getSone(identity.getId());
+ if (sone == null) {
/* TODO - we don’t have the Sone anymore. should this happen? */
return;
}
- for (PostReply postReply : sone.get().getReplies()) {
+ for (PostReply postReply : sone.getReplies()) {
eventBus.post(new PostReplyRemovedEvent(postReply));
}
- for (Post post : sone.get().getPosts()) {
+ for (Post post : sone.getPosts()) {
eventBus.post(new PostRemovedEvent(post));
}
- eventBus.post(new SoneRemovedEvent(sone.get()));
- database.removeSone(sone.get());
+ eventBus.post(new SoneRemovedEvent(sone));
+ database.removeSone(sone);
}
/**
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
-import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Ordering;
import com.google.common.eventbus.EventBus;
this(core, eventBus, freenetInterface, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
@Override
public boolean isLocked() {
- final Optional<Sone> sone = core.getSone(soneId);
- if (!sone.isPresent()) {
+ Sone sone = core.getSone(soneId);
+ if (sone == null) {
return false;
}
- return core.isLocked(sone.get());
+ return core.isLocked(sone);
}
@Override
public String getFingerprint() {
- final Optional<Sone> sone = core.getSone(soneId);
- if (!sone.isPresent()) {
+ Sone sone = core.getSone(soneId);
+ if (sone == null) {
return null;
}
- return sone.get().getFingerprint();
+ return sone.getFingerprint();
}
}, insertionDelay), 1000);
}
sleep(delay);
if (soneModificationDetector.isEligibleForInsert()) {
- Optional<Sone> soneOptional = core.getSone(soneId);
- if (!soneOptional.isPresent()) {
+ Sone sone = core.getSone(soneId);
+ if (sone == null) {
logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
return;
}
- Sone sone = soneOptional.get();
InsertInformation insertInformation = new InsertInformation(sone);
logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
package net.pterodactylus.sone.data.impl;
+import static com.google.common.base.Optional.fromNullable;
+
import net.pterodactylus.sone.data.Post;
import net.pterodactylus.sone.data.Sone;
import net.pterodactylus.sone.database.SoneProvider;
*/
@Override
public Sone getSone() {
- return soneProvider.getSone(soneId).get();
+ return soneProvider.getSone(soneId);
}
/**
*/
@Override
public Optional<String> getRecipientId() {
- return Optional.fromNullable(recipientId);
+ return fromNullable(recipientId);
}
/**
*/
@Override
public Optional<Sone> getRecipient() {
- return soneProvider.getSone(recipientId);
+ return fromNullable(soneProvider.getSone(recipientId));
}
/**
*/
@Override
public Sone getSone() {
- return soneProvider.getSone(soneId).get();
+ return soneProvider.getSone(soneId);
}
/**
+++ /dev/null
-/*
- * Sone - SoneProvider.java - Copyright © 2011–2016 David Roden
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-package net.pterodactylus.sone.database;
-
-import java.util.Collection;
-
-import javax.annotation.Nonnull;
-
-import net.pterodactylus.sone.core.Core;
-import net.pterodactylus.sone.data.Sone;
-
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.inject.ImplementedBy;
-
-/**
- * Interface for objects that can provide {@link Sone}s by their ID.
- *
- * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
- */
-@ImplementedBy(Core.class)
-public interface SoneProvider {
-
- Function<String, Optional<Sone>> soneLoader();
-
- /**
- * Returns the Sone with the given ID, or {@link Optional#absent()} if it
- * does not exist.
- *
- * @param soneId
- * The ID of the Sone to return
- * @return The Sone with the given ID, or {@link Optional#absent()}
- */
- public Optional<Sone> getSone(String soneId);
-
- /**
- * Returns all Sones.
- *
- * @return All Sones
- */
- @Nonnull
- public Collection<Sone> getSones();
-
- /**
- * Returns all local Sones.
- *
- * @return All local Sones
- */
- public Collection<Sone> getLocalSones();
-
- /**
- * Returns all remote Sones.
- *
- * @return All remote Sones
- */
- public Collection<Sone> getRemoteSones();
-
-}
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
+import javax.annotation.Nonnull;
+
import net.pterodactylus.sone.data.Album;
import net.pterodactylus.sone.data.Image;
import net.pterodactylus.sone.data.Post;
import net.pterodactylus.util.config.Configuration;
import net.pterodactylus.util.config.ConfigurationException;
-import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.HashMultimap;
import com.google.common.util.concurrent.AbstractService;
import com.google.inject.Inject;
import com.google.inject.Singleton;
+import kotlin.jvm.functions.Function1;
/**
* Memory-based {@link PostDatabase} implementation.
}
}
+ @Nonnull
@Override
- public Function<String, Optional<Sone>> soneLoader() {
- return new Function<String, Optional<Sone>>() {
+ public Function1<String, Sone> getSoneLoader() {
+ return new Function1<String, Sone>() {
@Override
- public Optional<Sone> apply(String soneId) {
+ public Sone invoke(String soneId) {
return getSone(soneId);
}
};
}
@Override
- public Optional<Sone> getSone(String soneId) {
+ public Sone getSone(String soneId) {
lock.readLock().lock();
try {
- return fromNullable(allSones.get(soneId));
+ return allSones.get(soneId);
} finally {
lock.readLock().unlock();
}
package net.pterodactylus.sone.database.memory;
+import static com.google.common.base.Optional.fromNullable;
+
import java.util.UUID;
import net.pterodactylus.sone.data.Post;
*/
@Override
public Sone getSone() {
- return soneProvider.getSone(soneId).get();
+ return soneProvider.getSone(soneId);
}
/**
*/
@Override
public Optional<String> getRecipientId() {
- return Optional.fromNullable(recipientId);
+ return fromNullable(recipientId);
}
/**
*/
@Override
public Optional<Sone> getRecipient() {
- return soneProvider.getSone(recipientId);
+ return fromNullable(soneProvider.getSone(recipientId));
}
/**
*/
@Override
public Sone getSone() {
- return soneProvider.getSone(soneId).get();
+ return soneProvider.getSone(soneId);
}
/**
if (mandatory && (soneId == null)) {
throw new FcpException("Could not load Sone ID from “" + parameterName + "”.");
}
- Optional<Sone> sone = core.getSone(soneId);
- if ((mandatory && !sone.isPresent()) || (sone.isPresent() && localOnly && !sone.get().isLocal())) {
+ Sone sone = core.getSone(soneId);
+ if ((mandatory && (sone == null)) || ((sone != null) && localOnly && !sone.isLocal())) {
throw new FcpException("Could not load Sone from “" + soneId + "”.");
}
- return sone;
+ return Optional.fromNullable(sone);
}
/**
import net.pterodactylus.sone.data.Sone;
import net.pterodactylus.sone.freenet.fcp.FcpException;
-import com.google.common.base.Optional;
import com.google.common.collect.Collections2;
import freenet.support.SimpleFieldSet;
Collection<Post> allPosts = new HashSet<Post>();
allPosts.addAll(sone.getPosts());
for (String friendSoneId : sone.getFriends()) {
- Optional<Sone> friendSone = getCore().getSone(friendSoneId);
- if (!friendSone.isPresent()) {
+ Sone friendSone = getCore().getSone(friendSoneId);
+ if (friendSone == null) {
continue;
}
- allPosts.addAll(friendSone.get().getPosts());
+ allPosts.addAll(friendSone.getPosts());
}
allPosts.addAll(getCore().getDirectedPosts(sone.getId()));
allPosts = Collections2.filter(allPosts, Post.FUTURE_POSTS_FILTER);
--- /dev/null
+/*
+ * Sone - SoneProvider.java - Copyright © 2011–2016 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database
+
+import net.pterodactylus.sone.core.Core
+import net.pterodactylus.sone.data.Sone
+
+import com.google.common.base.Function
+import com.google.common.base.Optional
+import com.google.inject.ImplementedBy
+
+/**
+ * Interface for objects that can provide [Sone]s by their ID.
+ */
+@ImplementedBy(Core::class)
+interface SoneProvider {
+
+ val sones: Collection<Sone>
+ val localSones: Collection<Sone>
+ val remoteSones: Collection<Sone>
+ val soneLoader: (String) -> Sone?
+
+ fun getSone(soneId: String): Sone?
+
+}
val text = data?.toString() ?: return listOf<Part>()
val soneParameter = parameters?.get("sone")
val sone = when (soneParameter) {
- is String -> core.getSone(soneParameter).orNull()
+ is String -> core.getSone(soneParameter)
is Sone -> soneParameter
else -> null
}
private fun render(writer: Writer, freemailPart: FreemailPart) {
val sone = core.getSone(freemailPart.identityId)
- val soneName = sone.transform(SoneAccessor::getNiceName).or(freemailPart.identityId)
+ val soneName = sone?.let(SoneAccessor::getNiceName) ?: freemailPart.identityId
renderLink(writer,
"/Freemail/NewMessage?to=${freemailPart.identityId}",
"${freemailPart.emailLocalPart}@$soneName.freemail",
} catch (e: MalformedURLException) {
PlainTextPart(link)
}
- SONE -> link.substring(7).let { SonePart(soneProvider?.getSone(it)?.orNull() ?: IdOnlySone(it)) }
+ SONE -> link.substring(7).let { SonePart(soneProvider?.getSone(it) ?: IdOnlySone(it)) }
POST -> postProvider?.getPost(link.substring(7))?.let { PostPart(it) } ?: PlainTextPart(link)
FREEMAIL -> link.indexOf('@').let { atSign ->
link.substring(atSign + 1, link.length - 9).let { freemailId ->
import net.pterodactylus.sone.data.Sone
import net.pterodactylus.sone.text.TextFilter
+import net.pterodactylus.sone.utils.asOptional
import net.pterodactylus.sone.utils.emptyToNull
import net.pterodactylus.sone.utils.headers
import net.pterodactylus.sone.utils.let
request.parameters["text"].emptyToNull
?.let { TextFilter.filter(request.headers["Host"], it) }
?.let { text ->
- val sender = request.parameters["sender"].emptyToNull?.let(core::getSone)?.orNull() ?: currentSone
- val recipient = request.parameters["recipient"].let(core::getSone)
- core.createPost(sender, recipient, text).let { post ->
+ val sender = request.parameters["sender"].emptyToNull?.let(core::getSone) ?: currentSone
+ val recipient = request.parameters["recipient"]?.let(core::getSone)
+ core.createPost(sender, recipient.asOptional(), text).let { post ->
createSuccessJsonObject().apply {
put("postId", post.id)
put("sone", sender.id)
- put("recipient", recipient.let(Sone::getId))
+ put("recipient", recipient?.id)
}
}
} ?: createErrorJsonObject("text-required")
override fun createJsonObject(currentSone: Sone, request: FreenetRequest) =
request.parameters["sone"]
- .let(core::getSone)
+ ?.let(core::getSone)
?.let { sone ->
createSuccessJsonObject()
.put("trustValue", core.preferences.negativeTrust)
override fun createJsonObject(currentSone: Sone, request: FreenetRequest) =
request.parameters["sone"]
- .let(core::getSone)
+ ?.let(core::getSone)
?.also { core.followSone(currentSone, it.id) }
?.also(core::markSoneKnown)
?.let { createSuccessJsonObject() }
this["loggedIn"] = currentSone != null
this["options"] = currentSone?.options?.toJsonOptions() ?: jsonObject {}
this["notificationHash"] = webInterface.getNotifications(currentSone).sortedBy { it.createdTime }.hashCode()
- this["sones"] = request.httpRequest.getParam("soneIds").split(',').mapPresent(core::getSone).plus(currentSone).filterNotNull().toJsonSones()
+ this["sones"] = request.httpRequest.getParam("soneIds").split(',').mapNotNull(core::getSone).plus(currentSone).filterNotNull().toJsonSones()
this["newPosts"] = webInterface.getNewPosts(currentSone).toJsonPosts()
this["newReplies"] = webInterface.getNewReplies(currentSone).toJsonReplies()
this["linkedElements"] = request.httpRequest.getParam("elements", "[]").asJson().map(JsonNode::asText).map(elementLoader::loadElement).toJsonElements()
package net.pterodactylus.sone.web.ajax
import com.google.common.base.Optional
+import net.pterodactylus.sone.utils.asOptional
import net.pterodactylus.sone.utils.mapPresent
import net.pterodactylus.sone.utils.parameters
import net.pterodactylus.sone.web.WebInterface
override val requiresLogin = false
override fun createJsonObject(request: FreenetRequest) = when (request.parameters["type"]) {
- "sone" -> processIds(request, core::getSone, core::markSoneKnown)
+ "sone" -> processIds(request, { core.getSone(it).asOptional() }, core::markSoneKnown)
"post" -> processIds(request, core::getPost, core::markPostKnown)
"reply" -> processIds(request, core::getPostReply, core::markReplyKnown)
else -> createErrorJsonObject("invalid-type")
override fun createJsonObject(currentSone: Sone, request: FreenetRequest) =
request.parameters["sone"]
- .let(core::getSone)
+ ?.let(core::getSone)
?.let { core.trustSone(currentSone, it) }
?.let { createSuccessJsonObject().put("trustValue", core.preferences.positiveTrust) }
?: createErrorJsonObject("invalid-sone-id")
override fun createJsonObject(currentSone: Sone, request: FreenetRequest) =
request.parameters["sone"]
- ?.takeIf { core.getSone(it).isPresent }
- ?.also { core.unfollowSone(currentSone, it) }
+ ?.let(core::getSone)
+ ?.also { core.unfollowSone(currentSone, it.id) }
?.let { createSuccessJsonObject() }
?: createErrorJsonObject("invalid-sone-id")
package net.pterodactylus.sone.web.pages
import net.pterodactylus.sone.text.TextFilter
+import net.pterodactylus.sone.utils.asOptional
import net.pterodactylus.sone.utils.isPOST
import net.pterodactylus.sone.web.WebInterface
import net.pterodactylus.sone.web.page.FreenetRequest
}
val sender = webInterface.core.getLocalSone(freenetRequest.httpRequest.getPartAsStringFailsafe("sender", 43)) ?: getCurrentSone(freenetRequest.toadletContext)
val recipient = webInterface.core.getSone(freenetRequest.httpRequest.getPartAsStringFailsafe("recipient", 43))
- webInterface.core.createPost(sender, recipient, TextFilter.filter(freenetRequest.httpRequest.getHeader("Host"), text))
+ webInterface.core.createPost(sender, recipient.asOptional(), TextFilter.filter(freenetRequest.httpRequest.getHeader("Host"), text))
throw RedirectException(returnPage)
}
}
override fun handleRequest(freenetRequest: FreenetRequest, templateContext: TemplateContext) {
if (freenetRequest.isPOST) {
- val sone = webInterface.core.getSone(freenetRequest.httpRequest.getPartAsStringFailsafe("sone", 44)).orNull()
- sone?.run { webInterface.core.distrustSone(getCurrentSone(freenetRequest.toadletContext), this) }
+ webInterface.core.getSone(freenetRequest.httpRequest.getPartAsStringFailsafe("sone", 44))
+ ?.run { webInterface.core.distrustSone(getCurrentSone(freenetRequest.toadletContext), this) }
throw RedirectException(freenetRequest.httpRequest.getPartAsStringFailsafe("returnPage", 256))
}
}
if (freenetRequest.isPOST) {
freenetRequest.httpRequest.getPartAsStringFailsafe("sone", 1200).split(Regex("[ ,]+"))
.map { it to webInterface.core.getSone(it) }
- .filter { it.second.isPresent }
- .map { it.first to it.second.get() }
+ .filterNot { it.second == null }
.forEach { sone ->
webInterface.core.followSone(freenetRequest.currentSone, sone.first)
webInterface.core.markSoneKnown(sone.second)
}
} else {
templateContext["soneRequested"] = true
- templateContext["sone"] = webInterface.core.getSone(freenetRequest.httpRequest.getParam("sone")).orNull() ?: getCurrentSone(freenetRequest.toadletContext)
+ templateContext["sone"] = webInterface.core.getSone(freenetRequest.httpRequest.getParam("sone")) ?: getCurrentSone(freenetRequest.toadletContext)
}
}
getCurrentSone(freenetRequest.toadletContext)!!.let { currentSone ->
(currentSone.posts +
currentSone.friends
- .map { webInterface.core.getSone(it) }
- .filter { it.isPresent }
- .map { it.get() }
+ .mapNotNull(webInterface.core::getSone)
.flatMap { it.posts } +
webInterface.core.getDirectedPosts(currentSone.id)
).distinct()
override fun handleRequest(freenetRequest: FreenetRequest, templateContext: TemplateContext) {
val ids = freenetRequest.parameters["id", 65536]!!.split(" ")
when (freenetRequest.parameters["type", 5]) {
- "sone" -> ids.mapPresent(webInterface.core::getSone).forEach(webInterface.core::markSoneKnown)
+ "sone" -> ids.mapNotNull(webInterface.core::getSone).forEach(webInterface.core::markSoneKnown)
"post" -> ids.mapPresent(webInterface.core::getPost).forEach(webInterface.core::markPostKnown)
"reply" -> ids.mapPresent(webInterface.core::getPostReply).forEach(webInterface.core::markReplyKnown)
else -> throw RedirectException("invalid.html")
0 -> redirect("index.html")
1 -> phrases.first().phrase.also { word ->
when {
- word.removePrefix("sone://").let(webInterface.core::getSone).isPresent -> redirect("viewSone.html?sone=${word.removePrefix("sone://")}")
+ word.removePrefix("sone://").let(webInterface.core::getSone) != null -> redirect("viewSone.html?sone=${word.removePrefix("sone://")}")
word.removePrefix("post://").let(webInterface.core::getPost).isPresent -> redirect("viewPost.html?post=${word.removePrefix("post://")}")
word.removePrefix("reply://").let(webInterface.core::getPostReply).isPresent -> redirect("viewPost.html?post=${word.removePrefix("reply://").let(webInterface.core::getPostReply).get().postId}")
word.removePrefix("album://").let(webInterface.core::getAlbum) != null -> redirect("imageBrowser.html?album=${word.removePrefix("album://")}")
package net.pterodactylus.sone.web.pages
import net.pterodactylus.sone.utils.isPOST
-import net.pterodactylus.sone.utils.let
import net.pterodactylus.sone.utils.parameters
import net.pterodactylus.sone.web.WebInterface
import net.pterodactylus.sone.web.page.FreenetRequest
override fun handleRequest(freenetRequest: FreenetRequest, templateContext: TemplateContext) {
if (freenetRequest.isPOST) {
getCurrentSone(freenetRequest.toadletContext)?.also { currentSone ->
- webInterface.core.getSone(freenetRequest.parameters["sone"]).let { sone ->
+ webInterface.core.getSone(freenetRequest.parameters["sone"]!!)?.let { sone ->
webInterface.core.trustSone(currentSone, sone)
}
}
package net.pterodactylus.sone.web.pages
-import net.pterodactylus.sone.utils.also
import net.pterodactylus.sone.utils.isPOST
import net.pterodactylus.sone.utils.parameters
import net.pterodactylus.sone.web.WebInterface
override fun handleRequest(freenetRequest: FreenetRequest, templateContext: TemplateContext) {
if (freenetRequest.isPOST) {
getCurrentSone(freenetRequest.toadletContext)!!.also { currentSone ->
- freenetRequest.parameters["sone", 44]
+ freenetRequest.parameters["sone", 44]!!
.let(webInterface.core::getSone)
- .also { webInterface.core.untrustSone(currentSone, it) }
+ ?.also { webInterface.core.untrustSone(currentSone, it) }
}
throw RedirectException(freenetRequest.parameters["returnPage", 256])
}
import net.pterodactylus.sone.data.Post
import net.pterodactylus.sone.data.PostReply
import net.pterodactylus.sone.template.SoneAccessor
-import net.pterodactylus.sone.utils.let
import net.pterodactylus.sone.utils.mapPresent
import net.pterodactylus.sone.utils.paginate
import net.pterodactylus.sone.utils.parameters
override fun handleRequest(freenetRequest: FreenetRequest, templateContext: TemplateContext) {
templateContext["soneId"] = freenetRequest.parameters["sone"]
- freenetRequest.parameters["sone"].let(webInterface.core::getSone).let { sone ->
+ freenetRequest.parameters["sone"]!!.let(webInterface.core::getSone)?.let { sone ->
templateContext["sone"] = sone
val sonePosts = sone.posts
val directedPosts = webInterface.core.getDirectedPosts(sone.id)
override fun isLinkExcepted(link: URI?) = true
public override fun getPageTitle(freenetRequest: FreenetRequest): String =
- freenetRequest.parameters["sone"].let(webInterface.core::getSone).let { sone ->
+ freenetRequest.parameters["sone"]!!.let(webInterface.core::getSone)?.let { sone ->
"${SoneAccessor.getNiceName(sone)} - ${webInterface.l10n.getString("Page.ViewSone.Title")}"
} ?: webInterface.l10n.getString("Page.ViewSone.Page.TitleWithoutSone")
import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
import net.pterodactylus.util.config.Configuration;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.eventbus.EventBus;
Identity identity = mock(Identity.class);
when(identity.getId()).thenReturn("sone-id");
Sone sone = mock(Sone.class);
- when(database.getSone("sone-id")).thenReturn(Optional.of(sone));
+ when(database.getSone("sone-id")).thenReturn(sone);
PostReply postReply1 = mock(PostReply.class);
PostReply postReply2 = mock(PostReply.class);
when(sone.getReplies()).thenReturn(ImmutableSet.of(postReply1, postReply2));
package net.pterodactylus.sone.core;
-import static com.google.common.base.Optional.of;
import static com.google.common.io.ByteStreams.toByteArray;
import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor;
import static java.lang.System.currentTimeMillis;
public void setupCore() {
UpdateChecker updateChecker = mock(UpdateChecker.class);
when(core.getUpdateChecker()).thenReturn(updateChecker);
- when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
+ when(core.getSone(anyString())).thenReturn(null);
}
@Test
when(sone.getInsertUri()).thenReturn(insertUri);
when(sone.getFingerprint()).thenReturn(fingerprint);
when(sone.getRootAlbum()).thenReturn(mock(Album.class));
- when(core.getSone(anyString())).thenReturn(of(sone));
+ when(core.getSone(anyString())).thenReturn(sone);
return sone;
}
new SoneInserter(core, eventBus, freenetInterface, "SoneId",
soneModificationDetector, 1);
when(soneModificationDetector.isEligibleForInsert()).thenReturn(true);
- when(core.getSone("SoneId")).thenReturn(Optional.<Sone>absent());
+ when(core.getSone("SoneId")).thenReturn(null);
soneInserter.serviceRun();
}
import java.io.IOException;
import java.util.Collection;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
import net.pterodactylus.sone.data.Post;
import net.pterodactylus.sone.data.Sone;
import net.pterodactylus.sone.data.impl.IdOnlySone;
import net.pterodactylus.sone.database.PostProvider;
import net.pterodactylus.sone.database.SoneProvider;
-import com.google.common.base.Function;
import com.google.common.base.Optional;
+import kotlin.jvm.functions.Function1;
import org.junit.Test;
/**
*/
private static class TestSoneProvider implements SoneProvider {
+ @Nonnull
@Override
- public Function<String, Optional<Sone>> soneLoader() {
- return new Function<String, Optional<Sone>>() {
+ public Function1<String, Sone> getSoneLoader() {
+ return new Function1<String, Sone>() {
@Override
- public Optional<Sone> apply(String soneId) {
+ public Sone invoke(String soneId) {
return getSone(soneId);
}
};
}
- /**
- * {@inheritDoc}
- */
+ @Nullable
@Override
- public Optional<Sone> getSone(final String soneId) {
- return Optional.<Sone>of(new IdOnlySone(soneId));
+ public Sone getSone(final String soneId) {
+ return new IdOnlySone(soneId);
}
/**
private static class AbsentSoneProvider extends TestSoneProvider {
@Override
- public Optional<Sone> getSone(String soneId) {
- return Optional.absent();
+ public Sone getSone(String soneId) {
+ return null;
}
}
package net.pterodactylus.sone.fcp
-import com.google.common.base.Optional
import com.google.common.base.Optional.absent
import com.google.common.base.Optional.of
import net.pterodactylus.sone.core.Core
@Test
fun `request without text results in fcp exception`() {
parameters += "Sone" to "LocalSoneId"
- whenever(core.getSone("LocalSoneId")).thenReturn(Optional.of(localSone))
+ whenever(core.getSone("LocalSoneId")).thenReturn(localSone)
executeCommandAndExpectFcpException()
}
fun `request with text creates post`() {
parameters += "Sone" to "LocalSoneId"
parameters += "Text" to "Test"
- whenever(core.getSone("LocalSoneId")).thenReturn(of(localSone))
+ whenever(core.getSone("LocalSoneId")).thenReturn(localSone)
val post = mock<Post>().apply { whenever(id).thenReturn("PostId") }
whenever(core.createPost(localSone, absent(), "Test")).thenReturn(post)
val response = command.execute(parameters)
parameters += "Sone" to "LocalSoneId"
parameters += "Text" to "Test"
parameters += "Recipient" to "InvalidSoneId"
- whenever(core.getSone("LocalSoneId")).thenReturn(of(localSone))
+ whenever(core.getSone("LocalSoneId")).thenReturn(localSone)
executeCommandAndExpectFcpException()
}
parameters += "Sone" to "LocalSoneId"
parameters += "Text" to "Test"
parameters += "Recipient" to "LocalSoneId"
- whenever(core.getSone("LocalSoneId")).thenReturn(of(localSone))
+ whenever(core.getSone("LocalSoneId")).thenReturn(localSone)
val response = command.execute(parameters)
assertThat(response.replyParameters["Message"], equalTo("Error"))
assertThat(response.replyParameters["ErrorMessage"], notNullValue())
parameters += "Sone" to "LocalSoneId"
parameters += "Text" to "Test"
parameters += "Recipient" to "RemoteSoneId"
- whenever(core.getSone("LocalSoneId")).thenReturn(of(localSone))
- whenever(core.getSone("RemoteSoneId")).thenReturn(of(remoteSone))
+ whenever(core.getSone("LocalSoneId")).thenReturn(localSone)
+ whenever(core.getSone("RemoteSoneId")).thenReturn(remoteSone)
val post = mock<Post>().apply { whenever(id).thenReturn("PostId") }
whenever(core.createPost(localSone, of(remoteSone), "Test")).thenReturn(post)
val response = command.execute(parameters)
private fun addValidLocalSoneParameter() {
parameters += "Sone" to "LocalSoneId"
- whenever(core.getSone("LocalSoneId")).thenReturn(of(localSone))
+ whenever(core.getSone("LocalSoneId")).thenReturn(localSone)
}
@Test
import freenet.support.SimpleFieldSet
import net.pterodactylus.sone.core.Core
import net.pterodactylus.sone.test.whenever
-import net.pterodactylus.sone.utils.asOptional
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.containsInAnyOrder
import org.hamcrest.Matchers.equalTo
private fun setupAllPostsAndReplies() {
parameters += "Sone" to "ValidSoneId"
whenever(localSone.id).thenReturn("ValidSoneId")
- whenever(core.getSone("ValidSoneId")).thenReturn(localSone.asOptional())
- whenever(core.getSone("Friend1")).thenReturn(friend1.asOptional())
+ whenever(core.getSone("ValidSoneId")).thenReturn(localSone)
+ whenever(core.getSone("Friend1")).thenReturn(friend1)
whenever(core.getLikes(post1)).thenReturn(setOf(sone3, sone4))
whenever(core.getLikes(post1Reply1)).thenReturn(setOf(sone2, sone3))
whenever(core.getLikes(post1Reply2)).thenReturn(setOf(sone3))
import freenet.support.SimpleFieldSet
import net.pterodactylus.sone.core.Core
import net.pterodactylus.sone.test.whenever
-import net.pterodactylus.sone.utils.asOptional
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.containsInAnyOrder
import org.hamcrest.Matchers.equalTo
whenever(core.getReplies("Post2")).thenReturn(listOf(post2Reply1, post2Reply2))
whenever(localSone.id).thenReturn("LocalSone")
whenever(remoteSone.id).thenReturn("RemoteSone")
- whenever(core.getSone("LocalSone")).thenReturn(localSone.asOptional())
- whenever(core.getSone("ValidSoneId")).thenReturn(remoteSone.asOptional())
+ whenever(core.getSone("LocalSone")).thenReturn(localSone)
+ whenever(core.getSone("ValidSoneId")).thenReturn(remoteSone)
whenever(remoteSone.posts).thenReturn(listOf(post2, post1))
parameters += "Sone" to "ValidSoneId"
}
import net.pterodactylus.sone.core.Core
import net.pterodactylus.sone.freenet.fcp.FcpException
import net.pterodactylus.sone.test.whenever
-import net.pterodactylus.sone.utils.asOptional
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.nullValue
@Test
fun `request with valid Sone parameter results in response with Sone information`() {
- whenever(core.getSone("SoneId")).thenReturn(sone.asOptional())
- whenever(core.getSone(null)).thenReturn(null.asOptional())
+ whenever(core.getSone("SoneId")).thenReturn(sone)
parameters += "Sone" to "SoneId"
val replyParameters = command.execute(parameters).replyParameters
assertThat(replyParameters["Message"], equalTo("Sone"))
@Test
fun `request with local sone parameter results in followed being true for friend sone`() {
- whenever(core.getSone("SoneId")).thenReturn(sone.asOptional())
- whenever(core.getSone("LocalSone")).thenReturn(localSone.asOptional())
+ whenever(core.getSone("SoneId")).thenReturn(sone)
+ whenever(core.getSone("LocalSone")).thenReturn(localSone)
whenever(localSone.id).thenReturn("LocalSone")
whenever(localSone.hasFriend("SoneId")).thenReturn(true)
parameters += "Sone" to "SoneId"
@Test
fun `request with local sone parameter results in followed being false for non-friend sone`() {
- whenever(core.getSone("SoneId")).thenReturn(sone.asOptional())
- whenever(core.getSone("LocalSone")).thenReturn(localSone.asOptional())
+ whenever(core.getSone("SoneId")).thenReturn(sone)
+ whenever(core.getSone("LocalSone")).thenReturn(localSone)
whenever(localSone.id).thenReturn("LocalSone")
parameters += "Sone" to "SoneId"
parameters += "LocalSone" to "LocalSone"
@Test
fun `request with remote sone as local sone parameter results in fcp exception`() {
- whenever(core.getSone("SoneId")).thenReturn(sone.asOptional())
- whenever(core.getSone("RemoteSone")).thenReturn(remoteSone.asOptional())
+ whenever(core.getSone("SoneId")).thenReturn(sone)
+ whenever(core.getSone("RemoteSone")).thenReturn(remoteSone)
whenever(localSone.id).thenReturn("RemoteSone")
parameters += "Sone" to "SoneId"
parameters += "LocalSone" to "RemoteSone"
@Before
fun setupPostAndSones() {
whenever(core.getPost("PostId")).thenReturn(post.asOptional())
- whenever(core.getSone("RemoteSoneId")).thenReturn(remoteSone.asOptional())
- whenever(core.getSone("LocalSoneId")).thenReturn(localSone.asOptional())
+ whenever(core.getSone("RemoteSoneId")).thenReturn(remoteSone)
+ whenever(core.getSone("LocalSoneId")).thenReturn(localSone)
}
@Test
@Before
fun setupRepliesAndSones() {
whenever(core.getPostReply("ReplyId")).thenReturn(reply.asOptional())
- whenever(core.getSone("RemoteSoneId")).thenReturn(remoteSone.asOptional())
- whenever(core.getSone("LocalSoneId")).thenReturn(localSone.asOptional())
+ whenever(core.getSone("RemoteSoneId")).thenReturn(remoteSone)
+ whenever(core.getSone("LocalSoneId")).thenReturn(localSone)
}
@Test
import net.pterodactylus.sone.core.Core
import net.pterodactylus.sone.test.whenever
-import net.pterodactylus.sone.utils.asOptional
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.Before
@Before
fun setupSones() {
- whenever(core.getSone("RemoteSoneId")).thenReturn(remoteSone.asOptional())
- whenever(core.getSone("LocalSoneId")).thenReturn(localSone.asOptional())
+ whenever(core.getSone("RemoteSoneId")).thenReturn(remoteSone)
+ whenever(core.getSone("LocalSoneId")).thenReturn(localSone)
whenever(localSone.id).thenReturn("LocalSoneId")
}
package net.pterodactylus.sone.fcp
-import com.google.common.base.Optional
import com.google.common.base.Optional.absent
import freenet.support.SimpleFieldSet
import net.pterodactylus.sone.core.Core
@Before
fun setupCore() {
- whenever(core.getSone(anyString())).thenReturn(absent())
+ whenever(core.getSone(anyString())).thenReturn(null)
whenever(core.getPost(anyString())).thenReturn(absent())
whenever(core.getPostReply(anyString())).thenReturn(absent())
}
fun requestWithValidRemoteSoneParameterResultsInFcpException() {
parameters += "Sone" to "RemoteSoneId"
- whenever(core.getSone("RemoteSoneId")).thenReturn(Optional.of(remoteSone))
+ whenever(core.getSone("RemoteSoneId")).thenReturn(remoteSone)
executeCommandAndExpectFcpException()
}
import net.pterodactylus.sone.core.Core
import net.pterodactylus.sone.test.whenever
-import net.pterodactylus.sone.utils.asOptional
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.Before
@Before
fun setupSones() {
- whenever(core.getSone("RemoteSoneId")).thenReturn(remoteSone.asOptional())
- whenever(core.getSone("LocalSoneId")).thenReturn(localSone.asOptional())
+ whenever(core.getSone("RemoteSoneId")).thenReturn(remoteSone)
+ whenever(core.getSone("LocalSoneId")).thenReturn(localSone)
whenever(localSone.id).thenReturn("LocalSoneId")
}
package net.pterodactylus.sone.template
-import com.google.common.base.Optional.of
import com.google.inject.Guice
import net.pterodactylus.sone.core.Core
import net.pterodactylus.sone.data.Sone
private fun setupSone(identity: String): Sone {
val sone = mock<Sone>()
`when`(sone.id).thenReturn(identity)
- `when`(core.getSone(identity)).thenReturn(of(sone))
+ `when`(core.getSone(identity)).thenReturn(sone)
return sone
}
package net.pterodactylus.sone.template
-import com.google.common.base.Optional
import net.pterodactylus.sone.core.Core
import net.pterodactylus.sone.data.Post
import net.pterodactylus.sone.data.Profile
`when`(sone.profile).thenReturn(Profile(sone))
`when`(sone.name).thenReturn(name)
sone.profile.firstName = firstName
- `when`(core.getSone(identity)).thenReturn(Optional.of<Sone>(sone))
+ `when`(core.getSone(identity)).thenReturn(sone)
return sone
}
whenever(core.preferences).thenReturn(preferences)
whenever(core.updateChecker).thenReturn(updateChecker)
- whenever(core.getSone(ArgumentMatchers.anyString())).thenAnswer { (localSones + remoteSones)[it.getArgument(0)].asOptional() }
+ whenever(core.getSone(ArgumentMatchers.anyString())).thenAnswer { (localSones + remoteSones)[it.getArgument(0)] }
whenever(core.getLocalSone(ArgumentMatchers.anyString())).thenAnswer { localSones[it[0]] }
whenever(core.getPost(ArgumentMatchers.anyString())).thenAnswer { (posts + newPosts)[it[0]].asOptional() }
whenever(core.getLikes(ArgumentMatchers.any<Post>())).then { postLikes[it[0]] ?: emptySet<Sone>() }
package net.pterodactylus.sone.web.ajax
+import net.pterodactylus.sone.data.Sone
import net.pterodactylus.sone.test.mock
+import net.pterodactylus.sone.test.whenever
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.Test
@Test
fun `request with valid sone unfollows sone`() {
- addSone(mock(), "sone-id")
+ addSone(mock<Sone>().apply { whenever(id).thenReturn("sone-id") })
addRequestParameter("sone", "sone-id")
assertThatJsonIsSuccessful()
verify(core).unfollowSone(currentSone, "sone-id")
whenever(core.preferences).thenReturn(preferences)
whenever(core.identityManager.allOwnIdentities).then { ownIdentities }
whenever(core.sones).then { allSones.values }
- whenever(core.getSone(anyString())).then { allSones[it[0]].asOptional() }
+ whenever(core.getSone(anyString())).then { allSones[it[0]] }
whenever(core.localSones).then { localSones.values }
whenever(core.getLocalSone(anyString())).then { localSones[it[0]] }
whenever(core.getPost(anyString())).then { allPosts[it[0]].asOptional() }