Use try with for sessions (#222)

This commit is contained in:
Kavin 2022-03-16 03:21:24 +00:00 committed by GitHub
parent 860bd57b3d
commit 43d6dc93c0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 347 additions and 394 deletions

View File

@ -31,8 +31,7 @@ public class Main {
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
CriteriaBuilder cb = s.getCriteriaBuilder();
CriteriaQuery<PubSub> criteria = cb.createQuery(PubSub.class);
@ -51,16 +50,13 @@ public class Main {
for (PubSub pubsub : pubSubList)
if (pubsub != null)
Multithreading.runAsyncLimitedPubSub(() -> {
Session sess = DatabaseSessionFactory.createSession();
try {
try (Session sess = DatabaseSessionFactory.createSession()) {
ResponseHelper.subscribePubSub(pubsub.getId(), sess);
} catch (Exception e) {
e.printStackTrace();
}
sess.close();
});
s.close();
} catch (Exception e) {
e.printStackTrace();
}
@ -70,8 +66,7 @@ public class Main {
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
Transaction tr = s.getTransaction();
@ -84,7 +79,6 @@ public class Main {
tr.commit();
s.close();
} catch (Exception e) {
e.printStackTrace();
}

View File

@ -55,12 +55,12 @@ public class ServerLauncher extends MultithreadedHttpServerLauncher {
new InputSource(new ByteArrayInputStream(request.loadBody().getResult().asArray())));
Multithreading.runAsync(() -> {
Session s = DatabaseSessionFactory.createSession();
feed.getEntries().forEach(entry -> {
try (Session s = DatabaseSessionFactory.createSession()) {
for (var entry : feed.getEntries()) {
ResponseHelper.handleNewVideo(entry.getLinks().get(0).getHref(),
entry.getPublishedDate().getTime(), null, s);
});
s.close();
}
}
});
return HttpResponse.ofCode(204);

View File

@ -1,14 +1,13 @@
package me.kavin.piped.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import me.kavin.piped.consts.Constants;
import me.kavin.piped.utils.obj.db.Channel;
import me.kavin.piped.utils.obj.db.PubSub;
import me.kavin.piped.utils.obj.db.User;
import me.kavin.piped.utils.obj.db.Video;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DatabaseSessionFactory {

View File

@ -1,7 +1,9 @@
package me.kavin.piped.utils;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
public class Multithreading {
@ -26,4 +28,8 @@ public class Multithreading {
public static ExecutorService getCachedExecutor() {
return es;
}
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return CompletableFuture.supplyAsync(supplier, es);
}
}

View File

@ -50,7 +50,6 @@ import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static java.nio.charset.StandardCharsets.UTF_8;
@ -66,25 +65,25 @@ public class ResponseHelper {
public static byte[] streamsResponse(String videoId) throws Exception {
CompletableFuture<StreamInfo> futureStream = CompletableFuture.supplyAsync(() -> {
final var futureStream = Multithreading.supplyAsync(() -> {
try {
return StreamInfo.getInfo("https://www.youtube.com/watch?v=" + videoId);
} catch (Exception e) {
ExceptionUtils.rethrow(e);
}
return null;
}, Multithreading.getCachedExecutor());
});
CompletableFuture<String> futureLbryId = CompletableFuture.supplyAsync(() -> {
final var futureLbryId = Multithreading.supplyAsync(() -> {
try {
return LbryHelper.getLBRYId(videoId);
} catch (Exception e) {
ExceptionHandler.handle(e);
}
return null;
}, Multithreading.getCachedExecutor());
});
CompletableFuture<String> futureLBRY = CompletableFuture.supplyAsync(() -> {
final var futureLBRY = Multithreading.supplyAsync(() -> {
try {
String lbryId = futureLbryId.completeOnTimeout(null, 2, TimeUnit.SECONDS).get();
@ -93,7 +92,7 @@ public class ResponseHelper {
ExceptionHandler.handle(e);
}
return null;
}, Multithreading.getCachedExecutor());
});
final List<Subtitle> subtitles = new ObjectArrayList<>();
final List<ChapterSegment> chapters = new ObjectArrayList<>();
@ -187,7 +186,7 @@ public class ResponseHelper {
info.getRelatedItems().forEach(o -> relatedStreams.add(collectRelatedStream(o)));
Multithreading.runAsync(() -> {
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
me.kavin.piped.utils.obj.db.Channel channel = DatabaseHelper.getChannelFromId(s, info.getId());
@ -214,8 +213,7 @@ public class ResponseHelper {
}
}
}
s.close();
}
});
String nextpage = null;
@ -527,15 +525,14 @@ public class ResponseHelper {
user = user.toLowerCase();
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
CriteriaBuilder cb = s.getCriteriaBuilder();
CriteriaQuery<User> cr = cb.createQuery(User.class);
Root<User> root = cr.from(User.class);
cr.select(root).where(root.get("username").in(user));
cr.select(root).where(cb.equal(root.get("username"), user));
boolean registered = s.createQuery(cr).uniqueResult() != null;
if (registered) {
s.close();
return Constants.mapper.writeValueAsBytes(new AlreadyRegisteredResponse());
}
@ -557,10 +554,9 @@ public class ResponseHelper {
s.getTransaction().begin();
s.getTransaction().commit();
s.close();
return Constants.mapper.writeValueAsBytes(new LoginResponse(newuser.getSessionId()));
}
}
private static final BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
@ -573,7 +569,7 @@ public class ResponseHelper {
user = user.toLowerCase();
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
CriteriaBuilder cb = s.getCriteriaBuilder();
CriteriaQuery<User> cr = cb.createQuery(User.class);
Root<User> root = cr.from(User.class);
@ -585,25 +581,21 @@ public class ResponseHelper {
String hash = dbuser.getPassword();
if (hash.startsWith("$argon2")) {
if (argon2PasswordEncoder.matches(pass, hash)) {
s.close();
return Constants.mapper.writeValueAsBytes(new LoginResponse(dbuser.getSessionId()));
}
} else if (bcryptPasswordEncoder.matches(pass, hash)) {
s.close();
return Constants.mapper.writeValueAsBytes(new LoginResponse(dbuser.getSessionId()));
}
}
s.close();
return Constants.mapper.writeValueAsBytes(new IncorrectCredentialsResponse());
}
}
public static byte[] subscribeResponse(String session, String channelId)
throws IOException {
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
User user = DatabaseHelper.getUserFromSessionWithSubscribed(s, session);
@ -614,10 +606,9 @@ public class ResponseHelper {
s.createNativeQuery("insert into users_subscribed (subscriber, channel) values (?,?)")
.setParameter(1, user.getId()).setParameter(2, channelId).executeUpdate();
s.getTransaction().commit();
s.close();
Multithreading.runAsync(() -> {
Session sess = DatabaseSessionFactory.createSession();
try (Session sess = DatabaseSessionFactory.createSession()) {
var channel = DatabaseHelper.getChannelFromId(sess, channelId);
if (channel == null) {
@ -635,10 +626,8 @@ public class ResponseHelper {
sess.beginTransaction().commit();
Multithreading.runAsync(() -> {
try {
Session sessSub = DatabaseSessionFactory.createSession();
try (Session sessSub = DatabaseSessionFactory.createSession()) {
subscribePubSub(channelId, sessSub);
sessSub.close();
} catch (Exception e) {
ExceptionHandler.handle(e);
}
@ -652,25 +641,23 @@ public class ResponseHelper {
handleNewVideo(item.getUrl(), time, channel, sess);
}
}
sess.close();
}
});
}
return Constants.mapper.writeValueAsBytes(new AcceptedResponse());
}
s.close();
return Constants.mapper.writeValueAsBytes(new AuthenticationFailureResponse());
}
}
public static byte[] unsubscribeResponse(String session, String channelId)
throws IOException {
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
User user = DatabaseHelper.getUserFromSession(s, session);
if (user != null) {
@ -678,21 +665,16 @@ public class ResponseHelper {
s.createNativeQuery("delete from users_subscribed where subscriber = :id and channel = :channel")
.setParameter("id", user.getId()).setParameter("channel", channelId).executeUpdate();
s.getTransaction().commit();
s.close();
return Constants.mapper.writeValueAsBytes(new AcceptedResponse());
}
s.close();
}
return Constants.mapper.writeValueAsBytes(new AuthenticationFailureResponse());
}
public static byte[] isSubscribedResponse(String session, String channelId)
throws IOException {
Session s = DatabaseSessionFactory.createSession();
public static byte[] isSubscribedResponse(String session, String channelId) throws IOException {
try (Session s = DatabaseSessionFactory.createSession()) {
var cb = s.getCriteriaBuilder();
var query = cb.createQuery(Long.class);
var root = query.from(User.class);
@ -703,15 +685,12 @@ public class ResponseHelper {
));
var subscribed = s.createQuery(query).getSingleResult() > 0;
s.close();
return Constants.mapper.writeValueAsBytes(new SubscribeStatusResponse(subscribed));
}
}
public static byte[] feedResponse(String session)
throws IOException {
Session s = DatabaseSessionFactory.createSession();
public static byte[] feedResponse(String session) throws IOException {
try (Session s = DatabaseSessionFactory.createSession()) {
User user = DatabaseHelper.getUserFromSession(s, session);
@ -746,21 +725,17 @@ public class ResponseHelper {
feedItems.sort(Comparator.<StreamItem>comparingLong(o -> o.uploaded).reversed());
s.close();
return Constants.mapper.writeValueAsBytes(feedItems);
}
s.close();
return Constants.mapper.writeValueAsBytes(new AuthenticationFailureResponse());
}
}
public static byte[] feedResponseRSS(String session)
throws IOException, FeedException {
public static byte[] feedResponseRSS(String session) throws IOException, FeedException {
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
User user = DatabaseHelper.getUserFromSession(s, session);
@ -812,22 +787,16 @@ public class ResponseHelper {
feed.setEntries(entries);
s.close();
return new SyndFeedOutput().outputString(feed).getBytes(UTF_8);
}
s.close();
return Constants.mapper.writeValueAsBytes(new AuthenticationFailureResponse());
}
}
public static byte[] importResponse(String session, String[] channelIds, boolean override)
throws IOException {
public static byte[] importResponse(String session, String[] channelIds, boolean override) throws IOException {
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
User user = DatabaseHelper.getUserFromSessionWithSubscribed(s, session);
@ -845,16 +814,12 @@ public class ResponseHelper {
s.update(user);
s.beginTransaction().commit();
}
s.close();
});
for (String channelId : channelIds) {
Multithreading.runAsyncLimited(() -> {
try {
Session sess = DatabaseSessionFactory.createSession();
try (Session sess = DatabaseSessionFactory.createSession()) {
var channel = DatabaseHelper.getChannelFromId(sess, channelId);
@ -872,10 +837,8 @@ public class ResponseHelper {
sess.save(channel);
Multithreading.runAsync(() -> {
try {
Session sessSub = DatabaseSessionFactory.createSession();
try (Session sessSub = DatabaseSessionFactory.createSession()) {
subscribePubSub(channelId, sessSub);
sessSub.close();
} catch (Exception e) {
ExceptionHandler.handle(e);
}
@ -894,8 +857,6 @@ public class ResponseHelper {
sess.getTransaction().commit();
}
sess.close();
} catch (Exception e) {
ExceptionHandler.handle(e);
}
@ -907,16 +868,14 @@ public class ResponseHelper {
return Constants.mapper.writeValueAsBytes(new AcceptedResponse());
}
s.close();
return Constants.mapper.writeValueAsBytes(new AuthenticationFailureResponse());
}
}
public static byte[] subscriptionsResponse(String session)
throws IOException {
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
User user = DatabaseHelper.getUserFromSession(s, session);
@ -941,27 +900,22 @@ public class ResponseHelper {
subscriptionItems.sort(Comparator.comparing(o -> o.name));
s.close();
return Constants.mapper.writeValueAsBytes(subscriptionItems);
}
s.close();
return Constants.mapper.writeValueAsBytes(new AuthenticationFailureResponse());
}
}
public static String registeredBadgeRedirect() {
Session s = DatabaseSessionFactory.createSession();
try (Session s = DatabaseSessionFactory.createSession()) {
long registered = (Long) s.createQuery("select count(*) from User").uniqueResult();
s.close();
return String.format("https://img.shields.io/badge/Registered%%20Users-%s-blue", registered);
}
}
public static void handleNewVideo(String url, long time, me.kavin.piped.utils.obj.db.Channel channel, Session s) {
try {