prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
package com.example.controllsdemo; import javafx.event.ActionEvent; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.stage.Stage; import model.Reservation; import model.ReservationDAO; import model.SharedDataModel; public class Paymenu { @javafx.fxml.FXML private TextField tfCustomer; @javafx.fxml.FXML private TextField tfPrice; @javafx.fxml.FXML private Button btnPay; @javafx.fxml.FXML private Button btnCancel; @javafx.fxml.FXML private TextField tfCntSessions; @javafx.fxml.FXML public void initialize() { Reservation reservation = SharedDataModel.getReservation(); int sessions = reservation.sessions * reservation.court_count; double price; if (sessions ==1) { price = 19.9; } else { price =19.9 +(sessions-1) * 9.95; } tfCustomer.setText(reservation.customer.firstname + " " + reservation.customer.lastname); tfPrice.setText(String.format("%.2f", price) + "€"); tfCntSessions.setText(String.valueOf(sessions)); } @javafx.fxml.FXML public void handlePay(ActionEvent actionEvent) { SharedDataModel.getReservation().state = "paid"; ReservationDAO
.update(SharedDataModel.getReservation());
Stage currentStage = (Stage) btnCancel.getScene().getWindow(); currentStage.close(); } @javafx.fxml.FXML public void handlebtnCancel(ActionEvent actionEvent) { Stage currentStage = (Stage) btnCancel.getScene().getWindow(); currentStage.close(); } }
src/main/java/com/example/controllsdemo/Paymenu.java
k0hlii-reservationsystem-cf95137
[ { "filename": "src/main/java/com/example/controllsdemo/HelloController.java", "retrieved_chunk": " void handleReservationButton(ActionEvent actionEvent)\n {\n Button btn = (Button) actionEvent.getSource();\n for (int i = 0; i < reservations.size(); i++) {\n if (reservations.get(i).court == Integer.parseInt(btn.getText())) {\n SharedDataModel data = new SharedDataModel();\n data.setReservation(reservations.get(i));\n try {\n Stage stage = new Stage();\n FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource(\"paymenu.fxml\"));", "score": 0.9090756177902222 }, { "filename": "src/main/java/com/example/controllsdemo/Reservationmenu_Controller.java", "retrieved_chunk": "// alert.showAndWait();\n// return;\n// }\n SharedDataModel data = new SharedDataModel();\n float price = 10.5F;\n Date date = data.getDate();\n System.out.println(date);\n Customer customer = (Customer) cbCustomer.getSelectionModel().getSelectedItem();\n String state =\"reserved\";\n Reservation r = new Reservation(spCourts.getValue(),spSessions.getValue(),price,date,new Time(654),data.getCourt(),customer.id,state);", "score": 0.88309645652771 }, { "filename": "src/main/java/com/example/controllsdemo/Reservationmenu_Controller.java", "retrieved_chunk": " ReservationDAO.add(r);\n Stage currentStage = (Stage) btnCancel.getScene().getWindow();\n currentStage.close();\n }\n @javafx.fxml.FXML\n public void handlebtnCancel(ActionEvent actionEvent) {\n Stage currentStage = (Stage) btnCancel.getScene().getWindow();\n currentStage.close();\n }\n @FXML", "score": 0.8657795190811157 }, { "filename": "src/main/java/com/example/controllsdemo/HelloController.java", "retrieved_chunk": " }\n }\n @FXML\n public void handleDatePicker(ActionEvent actionEvent)\n {\n datepicker.setValue(datepicker.getValue());\n updateWeekdays();\n updateReservations();\n }\n public Pane createPane(Reservation reservation)", "score": 0.8631466627120972 }, { "filename": "src/main/java/com/example/controllsdemo/Reservationmenu_Controller.java", "retrieved_chunk": "import javafx.stage.Stage;\nimport model.*;\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Date;\nimport java.sql.Time;\nimport java.util.ResourceBundle;\npublic class Reservationmenu_Controller implements Initializable {\n @javafx.fxml.FXML\n private ComboBox cbCustomer;", "score": 0.8569998741149902 } ]
java
.update(SharedDataModel.getReservation());
package com.rosan.dhizuku.api; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import androidx.annotation.NonNull; import com.rosan.dhizuku.aidl.IDhizuku; import com.rosan.dhizuku.aidl.IDhizukuUserServiceConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; class DhizukuServiceConnections { static final IDhizukuUserServiceConnection iDhizukuUserServiceConnection = new IDhizukuUserServiceConnection.Stub() { @Override public void connected(Bundle bundle, IBinder service) { onServiceConnected(bundle, service); try { service.linkToDeath(() -> { died(bundle); }, 0); } catch (RemoteException ignored) { } } void onServiceConnected(Bundle bundle, IBinder service) { DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(bundle); ComponentName name = args.getComponentName(); String token = name.flattenToString(); services.put(token, service); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) return; serviceConnection.onServiceConnected(name, service); } @Override public void died(Bundle bundle) { DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(bundle); ComponentName name = args.getComponentName(); String token = name.flattenToString(); services.remove(token); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) return; serviceConnection.onServiceDisconnected(name); } }; private static final Map<String, DhizukuServiceConnection> map = new HashMap<>(); private static final Map<String, IBinder> services = new HashMap<>(); static void start(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args) throws RemoteException { ComponentName name = args.getComponentName(); String token = name.flattenToString(); IBinder service = services.get(token); if (service == null) dhizuku.bindUserService(iDhizukuUserServiceConnection, args.build()); } static void stop(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args) throws RemoteException { dhizuku.unbindUserService(
args.build());
} static void bind(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args, @NonNull ServiceConnection connection) throws RemoteException { ComponentName name = args.getComponentName(); String token = name.flattenToString(); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) { serviceConnection = new DhizukuServiceConnection(); map.put(token, serviceConnection); } serviceConnection.add(connection); IBinder service = services.get(token); if (service == null) dhizuku.bindUserService(iDhizukuUserServiceConnection, args.build()); else connection.onServiceConnected(name, service); } static void unbind(@NonNull IDhizuku dhizuku, @NonNull ServiceConnection connection) throws RemoteException { List<String> tokens = new ArrayList<>(); for (Map.Entry<String, DhizukuServiceConnection> entry : map.entrySet()) { String token = entry.getKey(); DhizukuServiceConnection serviceConnection = entry.getValue(); if (serviceConnection == null) { tokens.add(token); continue; } serviceConnection.remove(connection); if (serviceConnection.isEmpty()) tokens.add(token); } for (String token : tokens) { map.remove(token); ComponentName name = ComponentName.unflattenFromString(token); DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(name); stop(dhizuku, args); } } }
dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnections.java
iamr0s-Dhizuku-API-009d517
[ { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/Dhizuku.java", "retrieved_chunk": " throw new RuntimeException(e);\n }\n }\n /**\n * start a UserService.\n */\n public static void startUserService(@NonNull DhizukuUserServiceArgs args) {\n try {\n DhizukuServiceConnections.start(requireServer(), args);\n } catch (RemoteException e) {", "score": 0.9031741619110107 }, { "filename": "demo-user_service/src/main/java/com/rosan/dhizuku/demo/MainActivity.java", "retrieved_chunk": " findViewById(R.id.remove_user).setOnClickListener(this);\n }\n void bindUserService() {\n DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(new ComponentName(this, UserService.class));\n boolean bind = Dhizuku.bindUserService(args, new ServiceConnection() {\n @Override\n public void onServiceConnected(ComponentName name, IBinder iBinder) {\n toast(\"connected UserService\");\n service = IUserService.Stub.asInterface(iBinder);\n }", "score": 0.8972558975219727 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/Dhizuku.java", "retrieved_chunk": " e.printStackTrace();\n }\n }\n /**\n * bind a UserService.\n */\n public static boolean bindUserService(@NonNull DhizukuUserServiceArgs args, @NonNull ServiceConnection connection) {\n try {\n DhizukuServiceConnections.bind(requireServer(), args, connection);\n return true;", "score": 0.8932254314422607 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/Dhizuku.java", "retrieved_chunk": " e.printStackTrace();\n }\n }\n /**\n * stop a UserService.\n */\n public static void stopUserService(@NonNull DhizukuUserServiceArgs args) {\n try {\n DhizukuServiceConnections.stop(requireServer(), args);\n } catch (RemoteException e) {", "score": 0.8910143375396729 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnection.java", "retrieved_chunk": "package com.rosan.dhizuku.api;\nimport android.content.ComponentName;\nimport android.content.ServiceConnection;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Looper;\nimport java.util.ArrayList;\nimport java.util.List;\nclass DhizukuServiceConnection {\n private final Handler handler = new Handler(Looper.getMainLooper());", "score": 0.8704882860183716 } ]
java
args.build());
package com.example.controllsdemo; import javafx.event.ActionEvent; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.stage.Stage; import model.Reservation; import model.ReservationDAO; import model.SharedDataModel; public class Paymenu { @javafx.fxml.FXML private TextField tfCustomer; @javafx.fxml.FXML private TextField tfPrice; @javafx.fxml.FXML private Button btnPay; @javafx.fxml.FXML private Button btnCancel; @javafx.fxml.FXML private TextField tfCntSessions; @javafx.fxml.FXML public void initialize() { Reservation reservation = SharedDataModel.getReservation(); int sessions = reservation.sessions * reservation.court_count; double price; if (sessions ==1) { price = 19.9; } else { price =19.9 +(sessions-1) * 9.95; } tfCustomer.setText(reservation.customer.firstname + " " + reservation.customer.lastname); tfPrice.setText(String.format("%.2f", price) + "€"); tfCntSessions.setText(String.valueOf(sessions)); } @javafx.fxml.FXML public void handlePay(ActionEvent actionEvent) {
SharedDataModel.getReservation().state = "paid";
ReservationDAO.update(SharedDataModel.getReservation()); Stage currentStage = (Stage) btnCancel.getScene().getWindow(); currentStage.close(); } @javafx.fxml.FXML public void handlebtnCancel(ActionEvent actionEvent) { Stage currentStage = (Stage) btnCancel.getScene().getWindow(); currentStage.close(); } }
src/main/java/com/example/controllsdemo/Paymenu.java
k0hlii-reservationsystem-cf95137
[ { "filename": "src/main/java/com/example/controllsdemo/HelloController.java", "retrieved_chunk": " void handleReservationButton(ActionEvent actionEvent)\n {\n Button btn = (Button) actionEvent.getSource();\n for (int i = 0; i < reservations.size(); i++) {\n if (reservations.get(i).court == Integer.parseInt(btn.getText())) {\n SharedDataModel data = new SharedDataModel();\n data.setReservation(reservations.get(i));\n try {\n Stage stage = new Stage();\n FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource(\"paymenu.fxml\"));", "score": 0.8996704816818237 }, { "filename": "src/main/java/com/example/controllsdemo/Reservationmenu_Controller.java", "retrieved_chunk": "// alert.showAndWait();\n// return;\n// }\n SharedDataModel data = new SharedDataModel();\n float price = 10.5F;\n Date date = data.getDate();\n System.out.println(date);\n Customer customer = (Customer) cbCustomer.getSelectionModel().getSelectedItem();\n String state =\"reserved\";\n Reservation r = new Reservation(spCourts.getValue(),spSessions.getValue(),price,date,new Time(654),data.getCourt(),customer.id,state);", "score": 0.8750643730163574 }, { "filename": "src/main/java/com/example/controllsdemo/HelloController.java", "retrieved_chunk": " }\n }\n @FXML\n public void handleDatePicker(ActionEvent actionEvent)\n {\n datepicker.setValue(datepicker.getValue());\n updateWeekdays();\n updateReservations();\n }\n public Pane createPane(Reservation reservation)", "score": 0.8554457426071167 }, { "filename": "src/main/java/com/example/controllsdemo/Reservationmenu_Controller.java", "retrieved_chunk": " ReservationDAO.add(r);\n Stage currentStage = (Stage) btnCancel.getScene().getWindow();\n currentStage.close();\n }\n @javafx.fxml.FXML\n public void handlebtnCancel(ActionEvent actionEvent) {\n Stage currentStage = (Stage) btnCancel.getScene().getWindow();\n currentStage.close();\n }\n @FXML", "score": 0.8532420992851257 }, { "filename": "src/main/java/com/example/controllsdemo/Reservationmenu_Controller.java", "retrieved_chunk": "import javafx.stage.Stage;\nimport model.*;\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Date;\nimport java.sql.Time;\nimport java.util.ResourceBundle;\npublic class Reservationmenu_Controller implements Initializable {\n @javafx.fxml.FXML\n private ComboBox cbCustomer;", "score": 0.8436123132705688 } ]
java
SharedDataModel.getReservation().state = "paid";
package model; import java.sql.Time; import java.util.Date; public class Reservation { public int court; public int court_count; public int sessions; public Customer customer; public java.util.Date date; int id; float price; int cusomerID; public String state; public Reservation(int court, int court_count, int sessions, Customer customer, Date date) { this.court = court; this.court_count = court_count; this.sessions = sessions; this.customer = customer; this.date = date; } public Reservation(int id, int anzahlPlätze, int anzahlEinheiten, float preis, Date datum, Time uhrzeit, int platz, int kundenID, String zustand) { this.id = id; this.court_count = anzahlPlätze; this.sessions = anzahlEinheiten; this.price = preis; this.date = datum; this.cusomerID = kundenID; this.state = zustand; this.
customer = CustomerDAO.getCustomerbyID(kundenID);
this.court = platz; } public Reservation(int anzahlPlätze, int anzahlEinheiten, float preis, Date datum, Time uhrzeit, int platz, int kundenID, String zustand) { this.court_count = anzahlPlätze; this.sessions = anzahlEinheiten; this.price = preis; this.date = datum; this.cusomerID = kundenID; this.state = zustand; this.customer = CustomerDAO.getCustomerbyID(kundenID); this.court = platz; } @Override public String toString() { return "Reservation{" + "court=" + court + ", court_count=" + court_count + ", sessions=" + sessions + ", customer=" + customer + ", date=" + date + '}'; } }
src/main/java/model/Reservation.java
k0hlii-reservationsystem-cf95137
[ { "filename": "src/main/java/model/ReservationDAO.java", "retrieved_chunk": " java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());\n String sql = \"INSERT INTO Reservierungen (AnzahlPlätze, AnzahlEinheiten, Preis, Datum, Uhrzeit, Platz, KundenID, Zustand) \" +\n \"VALUES (?, ?, ?, ?, ?, ?, ?, ?)\";\n PreparedStatement preparedStatement = con.prepareStatement(sql);\n preparedStatement.setInt(1, r.court_count);\n preparedStatement.setInt(2, r.sessions);\n preparedStatement.setDouble(3, r.price);\n preparedStatement.setDate(4, sqlDate);\n preparedStatement.setString(5, \"09:00:00\");\n preparedStatement.setInt(6, r.court);", "score": 0.8829926252365112 }, { "filename": "src/main/java/model/ReservationDAO.java", "retrieved_chunk": " rs.getInt(\"AnzahlPlätze\"),\n rs.getInt(\"AnzahlEinheiten\"),\n rs.getFloat(\"Preis\"),\n rs.getDate(\"Datum\"),\n rs.getTime(\"Uhrzeit\"),\n rs.getInt(\"Platz\"),\n rs.getInt(\"KundenID\"),\n rs.getString(\"Zustand\")\n )\n );", "score": 0.8697344064712524 }, { "filename": "src/main/java/model/ReservationDAO.java", "retrieved_chunk": " rs.getInt(\"ReservierungsID\"),\n rs.getInt(\"AnzahlPlätze\"),\n rs.getInt(\"AnzahlEinheiten\"),\n rs.getFloat(\"Preis\"),\n rs.getDate(\"Datum\"),\n rs.getTime(\"Uhrzeit\"),\n rs.getInt(\"Platz\"),\n rs.getInt(\"KundenID\"),\n rs.getString(\"Zustand\")\n )", "score": 0.8618009686470032 }, { "filename": "src/main/java/model/ReservationDAO.java", "retrieved_chunk": " ObservableList<Reservation> reservations = FXCollections.observableArrayList();\n Connection con;\n try {\n con = DBConnector.connect();\n String sql = \"SELECT * FROM Reservierungen WHERE Datum = ?\";\n PreparedStatement preparedStatement = con.prepareStatement(sql);\n preparedStatement.setDate(1, sqlDate);\n ResultSet rs = preparedStatement.executeQuery();\n while (rs.next()) {\n reservations.add(new Reservation(", "score": 0.8371018171310425 }, { "filename": "src/main/java/model/Customer.java", "retrieved_chunk": " this.lastname = lastname;\n }\n public Customer(int id, String firstname, String lastname, String phone, String email, int addressID) {\n this.id = id;\n this.firstname = firstname;\n this.lastname = lastname;\n this.phone = phone;\n this.email = email;\n this.addressID = addressID;\n }", "score": 0.8366655111312866 } ]
java
customer = CustomerDAO.getCustomerbyID(kundenID);
package com.rosan.dhizuku.api; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import androidx.annotation.NonNull; import com.rosan.dhizuku.aidl.IDhizuku; import com.rosan.dhizuku.aidl.IDhizukuUserServiceConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; class DhizukuServiceConnections { static final IDhizukuUserServiceConnection iDhizukuUserServiceConnection = new IDhizukuUserServiceConnection.Stub() { @Override public void connected(Bundle bundle, IBinder service) { onServiceConnected(bundle, service); try { service.linkToDeath(() -> { died(bundle); }, 0); } catch (RemoteException ignored) { } } void onServiceConnected(Bundle bundle, IBinder service) { DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(bundle); ComponentName name = args.getComponentName(); String token = name.flattenToString(); services.put(token, service); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) return; serviceConnection.onServiceConnected(name, service); } @Override public void died(Bundle bundle) { DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(bundle); ComponentName name = args.getComponentName(); String token = name.flattenToString(); services.remove(token); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) return; serviceConnection.onServiceDisconnected(name); } }; private static final Map<String, DhizukuServiceConnection> map = new HashMap<>(); private static final Map<String, IBinder> services = new HashMap<>(); static void start(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args) throws RemoteException { ComponentName name = args.getComponentName(); String token = name.flattenToString(); IBinder service = services.get(token); if (service
== null) dhizuku.bindUserService(iDhizukuUserServiceConnection, args.build());
} static void stop(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args) throws RemoteException { dhizuku.unbindUserService(args.build()); } static void bind(@NonNull IDhizuku dhizuku, @NonNull DhizukuUserServiceArgs args, @NonNull ServiceConnection connection) throws RemoteException { ComponentName name = args.getComponentName(); String token = name.flattenToString(); DhizukuServiceConnection serviceConnection = map.get(token); if (serviceConnection == null) { serviceConnection = new DhizukuServiceConnection(); map.put(token, serviceConnection); } serviceConnection.add(connection); IBinder service = services.get(token); if (service == null) dhizuku.bindUserService(iDhizukuUserServiceConnection, args.build()); else connection.onServiceConnected(name, service); } static void unbind(@NonNull IDhizuku dhizuku, @NonNull ServiceConnection connection) throws RemoteException { List<String> tokens = new ArrayList<>(); for (Map.Entry<String, DhizukuServiceConnection> entry : map.entrySet()) { String token = entry.getKey(); DhizukuServiceConnection serviceConnection = entry.getValue(); if (serviceConnection == null) { tokens.add(token); continue; } serviceConnection.remove(connection); if (serviceConnection.isEmpty()) tokens.add(token); } for (String token : tokens) { map.remove(token); ComponentName name = ComponentName.unflattenFromString(token); DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(name); stop(dhizuku, args); } } }
dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnections.java
iamr0s-Dhizuku-API-009d517
[ { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/Dhizuku.java", "retrieved_chunk": " throw new RuntimeException(e);\n }\n }\n /**\n * start a UserService.\n */\n public static void startUserService(@NonNull DhizukuUserServiceArgs args) {\n try {\n DhizukuServiceConnections.start(requireServer(), args);\n } catch (RemoteException e) {", "score": 0.9108482599258423 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/Dhizuku.java", "retrieved_chunk": " e.printStackTrace();\n }\n }\n /**\n * bind a UserService.\n */\n public static boolean bindUserService(@NonNull DhizukuUserServiceArgs args, @NonNull ServiceConnection connection) {\n try {\n DhizukuServiceConnections.bind(requireServer(), args, connection);\n return true;", "score": 0.9011847376823425 }, { "filename": "demo-user_service/src/main/java/com/rosan/dhizuku/demo/MainActivity.java", "retrieved_chunk": " findViewById(R.id.remove_user).setOnClickListener(this);\n }\n void bindUserService() {\n DhizukuUserServiceArgs args = new DhizukuUserServiceArgs(new ComponentName(this, UserService.class));\n boolean bind = Dhizuku.bindUserService(args, new ServiceConnection() {\n @Override\n public void onServiceConnected(ComponentName name, IBinder iBinder) {\n toast(\"connected UserService\");\n service = IUserService.Stub.asInterface(iBinder);\n }", "score": 0.893388569355011 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/Dhizuku.java", "retrieved_chunk": " e.printStackTrace();\n }\n }\n /**\n * stop a UserService.\n */\n public static void stopUserService(@NonNull DhizukuUserServiceArgs args) {\n try {\n DhizukuServiceConnections.stop(requireServer(), args);\n } catch (RemoteException e) {", "score": 0.8793944120407104 }, { "filename": "dhizuku-api-impl/src/main/java/com/rosan/dhizuku/api/DhizukuServiceConnection.java", "retrieved_chunk": "package com.rosan.dhizuku.api;\nimport android.content.ComponentName;\nimport android.content.ServiceConnection;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Looper;\nimport java.util.ArrayList;\nimport java.util.List;\nclass DhizukuServiceConnection {\n private final Handler handler = new Handler(Looper.getMainLooper());", "score": 0.8729738593101501 } ]
java
== null) dhizuku.bindUserService(iDhizukuUserServiceConnection, args.build());
package org.chelonix.dagger.client.engineconn; import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient; import io.smallrye.graphql.client.vertx.dynamic.VertxDynamicGraphQLClientBuilder; import io.vertx.core.Vertx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Optional; public final class Connection { static final Logger LOG = LoggerFactory.getLogger(Connection.class); private final DynamicGraphQLClient graphQLClient; private final Vertx vertx; private final Optional<CLIRunner> daggerRunner; Connection(DynamicGraphQLClient graphQLClient, Vertx vertx, Optional<CLIRunner> daggerRunner) { this.graphQLClient = graphQLClient; this.vertx = vertx; this.daggerRunner = daggerRunner; } public DynamicGraphQLClient getGraphQLClient() { return this.graphQLClient; } public void close() throws Exception { this.graphQLClient.close(); this.vertx.close(); this.daggerRunner.ifPresent(CLIRunner::shutdown); } static Optional<Connection> fromEnv() { LOG.info("Trying initializing connection with engine from environment variables..."); String portStr = System.getenv("DAGGER_SESSION_PORT"); String sessionToken = System.getenv("DAGGER_SESSION_TOKEN"); if (portStr != null && sessionToken != null) { try { int port = Integer.parseInt(portStr); return Optional.of(getConnection(port, sessionToken, Optional.empty())); } catch (NumberFormatException nfe) { LOG.error("invalid port value in DAGGER_SESSION_PORT", nfe); } } else if (portStr == null) { LOG.error("DAGGER_SESSION_TOKEN is required when using DAGGER_SESSION_PORT"); } else if (sessionToken == null) { LOG.error("DAGGER_SESSION_PORT is required when using DAGGER_SESSION_TOKEN"); } return Optional.empty(); } static Connection fromCLI(CLIRunner cliRunner) throws IOException { LOG.info("Trying initializing connection with engine from automatic provisioning..."); try { cliRunner.start(); ConnectParams connectParams = cliRunner.getConnectionParams(); return getConnection(connectParams.getPort
(), connectParams.getSessionToken(), Optional.of(cliRunner));
} catch (IOException ioe) { cliRunner.shutdown(); throw ioe; } } public static Connection get(String workingDir) throws IOException { return fromEnv().orElse(fromCLI(new CLIRunner(workingDir))); } private static Connection getConnection(int port, String token, Optional<CLIRunner> runner) { Vertx vertx = Vertx.vertx(); String encodedToken = Base64.getEncoder().encodeToString((token + ":").getBytes(StandardCharsets.UTF_8)); DynamicGraphQLClient dynamicGraphQLClient = new VertxDynamicGraphQLClientBuilder() .vertx(vertx) .url(String.format("http://127.0.0.1:%d/query", port)) .header("authorization", "Basic " + encodedToken) .build(); return new Connection(dynamicGraphQLClient, vertx, runner); } }
dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/Connection.java
jcsirot-dagger-java-sdk-366c947
[ { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " CLIRunner runner = mock(CLIRunner.class);\n when(runner.getConnectionParams()).thenReturn(new ConnectParams(57535, \"6fb6d80b-5e7a-42f7-913c-31a6e50c140d\"));\n Connection conn = Connection.fromCLI(runner);\n verify(runner, times(1)).getConnectionParams();\n conn.close();\n verify(runner, times(1)).shutdown();\n }\n @Test\n public void should_fail_when_clirunner_fails() throws Exception {\n CLIRunner runner = mock(CLIRunner.class);", "score": 0.8402214050292969 }, { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " when(runner.getConnectionParams()).thenThrow(new IOException(\"FAILED\"));\n assertThatThrownBy(() -> Connection.fromCLI(runner)).isInstanceOf(IOException.class).hasMessage(\"FAILED\");\n }\n}", "score": 0.8270032405853271 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": "import java.util.concurrent.Executors;\nclass CLIRunner implements Runnable {\n static final Logger LOG = LoggerFactory.getLogger(CLIRunner.class);\n private final FluentProcess process;\n private ConnectParams params;\n private boolean failed = false;\n private final ExecutorService executorService;\n private static String getCLIPath() throws IOException {\n String cliBinPath = System.getenv(\"_EXPERIMENTAL_DAGGER_CLI_BIN\");\n if (cliBinPath == null) {", "score": 0.8145424723625183 }, { "filename": "dagger-java-sdk/src/test/java/org/chelonix/dagger/client/engineconn/ConnectionTest.java", "retrieved_chunk": " assertThat(conn).isPresent();\n }\n @Test\n public void should_return_empty_connection_when_env_not_set() throws Exception {\n Optional<Connection> conn;\n environmentVariables.set(\"DAGGER_SESSION_PORT\", null);\n environmentVariables.set(\"DAGGER_SESSION_TOKEN\", null);\n conn = Connection.fromEnv();\n assertThat(conn).isEmpty();\n environmentVariables.set(\"DAGGER_SESSION_PORT\", \"52037\");", "score": 0.8109861016273499 }, { "filename": "dagger-java-sdk/src/main/java/org/chelonix/dagger/client/engineconn/CLIRunner.java", "retrieved_chunk": " cliBinPath = new CLIDownloader().downloadCLI();\n }\n return cliBinPath;\n }\n public CLIRunner(String workingDir) throws IOException {\n String bin = getCLIPath();\n this.process = FluentProcess.start(bin, \"session\",\n \"--workdir\", workingDir,\n \"--label\", \"dagger.io/sdk.name:java\",\n \"--label\", \"dagger.io/sdk.version:\" + CLIDownloader.CLI_VERSION)", "score": 0.8084390759468079 } ]
java
(), connectParams.getSessionToken(), Optional.of(cliRunner));
package org.chelonix.dagger.codegen; import com.ongres.process.FluentProcess; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.chelonix.dagger.codegen.introspection.CodegenVisitor; import org.chelonix.dagger.codegen.introspection.Schema; import org.chelonix.dagger.codegen.introspection.SchemaVisitor; import org.chelonix.dagger.codegen.introspection.Type; import java.io.*; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Path; import java.time.Duration; import java.time.temporal.ChronoUnit; @Mojo(name = "codegen", defaultPhase = LifecyclePhase.GENERATE_SOURCES, requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true) public class DaggerCodegenMojo extends AbstractMojo { /** * specify output file encoding; defaults to source encoding */ @Parameter(property = "project.build.sourceEncoding") protected String outputEncoding; /** * The current Maven project. */ @Parameter(property = "project", required = true, readonly = true) protected MavenProject project; @Parameter(property = "dagger.bin", defaultValue = "dagger") protected String bin; @Parameter(property = "dagger.version", required = true) protected String version; @Parameter(property = "dagger.introspectionQuertyURL") protected String introspectionQuertyURL; @Parameter(property = "dagger.introspectionQuertyPath") protected String introspectionQuertyPath; @Parameter(property = "dagger.regenerateSchema", defaultValue = "false") protected boolean online; /** * Specify output directory where the Java files are generated. */ @Parameter(defaultValue = "${project.build.directory}/generated-sources/dagger") private File outputDirectory; @Override public void execute() throws MojoExecutionException, MojoFailureException { outputEncoding = validateEncoding(outputEncoding); // Ensure that the output directory path is all in tact so that // ANTLR can just write into it. // File outputDir = getOutputDirectory(); if (!outputDir.exists()) { outputDir.mkdirs(); } Path dest = outputDir.toPath(); try (InputStream in = daggerSchema()) { Schema schema =
Schema.initialize(in);
SchemaVisitor codegen = new CodegenVisitor(schema, dest, Charset.forName(outputEncoding)); schema.visit(new SchemaVisitor() { @Override public void visitScalar(Type type) { getLog().info(String.format("Generating scala %s", type.getName())); codegen.visitScalar(type); } @Override public void visitObject(Type type) { getLog().info(String.format("Generating object %s", type.getName())); codegen.visitObject(type); } @Override public void visitInput(Type type) { getLog().info(String.format("Generating input %s", type.getName())); codegen.visitInput(type); } @Override public void visitEnum(Type type) { getLog().info(String.format("Generating enum %s", type.getName())); codegen.visitEnum(type); } }); } catch (IOException ioe) { throw new MojoFailureException(ioe); } catch (InterruptedException ie) { throw new MojoFailureException(ie); } if (project != null) { // Tell Maven that there are some new source files underneath the output directory. project.addCompileSourceRoot(getOutputDirectory().getPath()); } } private InputStream daggerSchema() throws IOException, InterruptedException, MojoFailureException { if (!online) { InputStream in = getClass().getClassLoader().getResourceAsStream(String.format("schemas/schema-v%s.json", version)); if (in == null) { throw new MojoFailureException(String.format("GraphQL schema not available for version %s", version)); } return in; } if (introspectionQuertyPath != null) { return new FileInputStream(introspectionQuertyPath); } InputStream in; if (introspectionQuertyPath != null) { return new FileInputStream(introspectionQuertyPath); } else if (introspectionQuertyURL == null) { in = new URL(String.format("https://raw.githubusercontent.com/dagger/dagger/v%s/codegen/introspection/introspection.graphql", version)).openStream(); } else if (introspectionQuertyURL != null) { in = new URL(introspectionQuertyURL).openStream(); } else { throw new MojoFailureException("Could not locate, download or generate GraphQL schema"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); FluentProcess.start(bin, "query") .withTimeout(Duration.of(60, ChronoUnit.SECONDS)) .inputStream(in) .writeToOutputStream(out); return new ByteArrayInputStream(out.toByteArray()); } public File getOutputDirectory() { return outputDirectory; } /** * Validates the given encoding. * * @return the validated encoding. If {@code null} was provided, returns the platform default encoding. */ private String validateEncoding(String encoding) { return (encoding == null) ? Charset.defaultCharset().name() : Charset.forName(encoding.trim()).name(); } }
dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java
jcsirot-dagger-java-sdk-366c947
[ { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/introspection/AbstractVisitor.java", "retrieved_chunk": "package org.chelonix.dagger.codegen.introspection;\nimport com.squareup.javapoet.JavaFile;\nimport com.squareup.javapoet.TypeSpec;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.nio.file.Path;\nabstract class AbstractVisitor {\n private Schema schema;\n private Charset encoding;\n private Path targetDirectory;", "score": 0.8169589638710022 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/introspection/AbstractVisitor.java", "retrieved_chunk": " .build();\n javaFile.writeTo(targetDirectory, encoding);\n }\n public Schema getSchema() {\n return schema;\n }\n abstract TypeSpec generateType(Type type);\n}", "score": 0.8142401576042175 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/introspection/AbstractVisitor.java", "retrieved_chunk": " public AbstractVisitor(Schema schema, Path targetDirectory, Charset encoding) {\n this.schema = schema;\n this.targetDirectory = targetDirectory;\n this.encoding = encoding;\n }\n void visit(Type type) throws IOException {\n TypeSpec typeSpec = generateType(type);\n JavaFile javaFile = JavaFile.builder(\"org.chelonix.dagger.client\", typeSpec)\n .addFileComment(\"This class has been generated by dagger-java-sdk. DO NOT EDIT.\")\n .indent(\" \")", "score": 0.8129285573959351 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/introspection/InputVisitor.java", "retrieved_chunk": "package org.chelonix.dagger.codegen.introspection;\nimport com.squareup.javapoet.*;\nimport javax.lang.model.element.Modifier;\nimport java.nio.charset.Charset;\nimport java.nio.file.Path;\nimport java.util.HashMap;\nimport java.util.Map;\nclass InputVisitor extends AbstractVisitor {\n public InputVisitor(Schema schema, Path targetDirectory, Charset encoding) {\n super(schema, targetDirectory, encoding);", "score": 0.8106790781021118 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/introspection/CodegenVisitor.java", "retrieved_chunk": "package org.chelonix.dagger.codegen.introspection;\nimport java.io.*;\nimport java.nio.charset.Charset;\nimport java.nio.file.Path;\npublic class CodegenVisitor implements SchemaVisitor {\n private final ScalarVisitor scalarVisitor;\n private final InputVisitor inputVisitor;\n private final EnumVisitor enumVisitor;\n private final ObjectVisitor objectVisitor;\n public CodegenVisitor(Schema schema, Path targetDirectory, Charset encoding) {", "score": 0.808623731136322 } ]
java
Schema.initialize(in);
package org.chelonix.dagger.codegen; import com.ongres.process.FluentProcess; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.chelonix.dagger.codegen.introspection.CodegenVisitor; import org.chelonix.dagger.codegen.introspection.Schema; import org.chelonix.dagger.codegen.introspection.SchemaVisitor; import org.chelonix.dagger.codegen.introspection.Type; import java.io.*; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Path; import java.time.Duration; import java.time.temporal.ChronoUnit; @Mojo(name = "codegen", defaultPhase = LifecyclePhase.GENERATE_SOURCES, requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true) public class DaggerCodegenMojo extends AbstractMojo { /** * specify output file encoding; defaults to source encoding */ @Parameter(property = "project.build.sourceEncoding") protected String outputEncoding; /** * The current Maven project. */ @Parameter(property = "project", required = true, readonly = true) protected MavenProject project; @Parameter(property = "dagger.bin", defaultValue = "dagger") protected String bin; @Parameter(property = "dagger.version", required = true) protected String version; @Parameter(property = "dagger.introspectionQuertyURL") protected String introspectionQuertyURL; @Parameter(property = "dagger.introspectionQuertyPath") protected String introspectionQuertyPath; @Parameter(property = "dagger.regenerateSchema", defaultValue = "false") protected boolean online; /** * Specify output directory where the Java files are generated. */ @Parameter(defaultValue = "${project.build.directory}/generated-sources/dagger") private File outputDirectory; @Override public void execute() throws MojoExecutionException, MojoFailureException { outputEncoding = validateEncoding(outputEncoding); // Ensure that the output directory path is all in tact so that // ANTLR can just write into it. // File outputDir = getOutputDirectory(); if (!outputDir.exists()) { outputDir.mkdirs(); } Path dest = outputDir.toPath(); try (InputStream in = daggerSchema()) { Schema schema = Schema.initialize(in); SchemaVisitor codegen = new CodegenVisitor(schema, dest, Charset.forName(outputEncoding)); schema.visit(new SchemaVisitor() { @Override public void visitScalar(Type type) { getLog
().info(String.format("Generating scala %s", type.getName()));
codegen.visitScalar(type); } @Override public void visitObject(Type type) { getLog().info(String.format("Generating object %s", type.getName())); codegen.visitObject(type); } @Override public void visitInput(Type type) { getLog().info(String.format("Generating input %s", type.getName())); codegen.visitInput(type); } @Override public void visitEnum(Type type) { getLog().info(String.format("Generating enum %s", type.getName())); codegen.visitEnum(type); } }); } catch (IOException ioe) { throw new MojoFailureException(ioe); } catch (InterruptedException ie) { throw new MojoFailureException(ie); } if (project != null) { // Tell Maven that there are some new source files underneath the output directory. project.addCompileSourceRoot(getOutputDirectory().getPath()); } } private InputStream daggerSchema() throws IOException, InterruptedException, MojoFailureException { if (!online) { InputStream in = getClass().getClassLoader().getResourceAsStream(String.format("schemas/schema-v%s.json", version)); if (in == null) { throw new MojoFailureException(String.format("GraphQL schema not available for version %s", version)); } return in; } if (introspectionQuertyPath != null) { return new FileInputStream(introspectionQuertyPath); } InputStream in; if (introspectionQuertyPath != null) { return new FileInputStream(introspectionQuertyPath); } else if (introspectionQuertyURL == null) { in = new URL(String.format("https://raw.githubusercontent.com/dagger/dagger/v%s/codegen/introspection/introspection.graphql", version)).openStream(); } else if (introspectionQuertyURL != null) { in = new URL(introspectionQuertyURL).openStream(); } else { throw new MojoFailureException("Could not locate, download or generate GraphQL schema"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); FluentProcess.start(bin, "query") .withTimeout(Duration.of(60, ChronoUnit.SECONDS)) .inputStream(in) .writeToOutputStream(out); return new ByteArrayInputStream(out.toByteArray()); } public File getOutputDirectory() { return outputDirectory; } /** * Validates the given encoding. * * @return the validated encoding. If {@code null} was provided, returns the platform default encoding. */ private String validateEncoding(String encoding) { return (encoding == null) ? Charset.defaultCharset().name() : Charset.forName(encoding.trim()).name(); } }
dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/DaggerCodegenMojo.java
jcsirot-dagger-java-sdk-366c947
[ { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/introspection/CodegenVisitor.java", "retrieved_chunk": " this.scalarVisitor = new ScalarVisitor(schema, targetDirectory, encoding);\n this.inputVisitor = new InputVisitor(schema, targetDirectory, encoding);\n this.enumVisitor = new EnumVisitor(schema, targetDirectory, encoding);\n this.objectVisitor = new ObjectVisitor(schema, targetDirectory, encoding);\n }\n @Override\n public void visitScalar(Type type) {\n try {\n scalarVisitor.visit(type);\n } catch (IOException e) {", "score": 0.8674420714378357 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/introspection/AbstractVisitor.java", "retrieved_chunk": " public AbstractVisitor(Schema schema, Path targetDirectory, Charset encoding) {\n this.schema = schema;\n this.targetDirectory = targetDirectory;\n this.encoding = encoding;\n }\n void visit(Type type) throws IOException {\n TypeSpec typeSpec = generateType(type);\n JavaFile javaFile = JavaFile.builder(\"org.chelonix.dagger.client\", typeSpec)\n .addFileComment(\"This class has been generated by dagger-java-sdk. DO NOT EDIT.\")\n .indent(\" \")", "score": 0.8617546558380127 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/introspection/ScalarVisitor.java", "retrieved_chunk": "package org.chelonix.dagger.codegen.introspection;\nimport com.squareup.javapoet.*;\nimport javax.lang.model.element.Modifier;\nimport java.nio.charset.Charset;\nimport java.nio.file.Path;\nclass ScalarVisitor extends AbstractVisitor {\n public ScalarVisitor(Schema schema, Path targetDirectory, Charset encoding) {\n super(schema, targetDirectory, encoding);\n }\n @Override", "score": 0.8598952293395996 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/introspection/AbstractVisitor.java", "retrieved_chunk": " .build();\n javaFile.writeTo(targetDirectory, encoding);\n }\n public Schema getSchema() {\n return schema;\n }\n abstract TypeSpec generateType(Type type);\n}", "score": 0.8583974838256836 }, { "filename": "dagger-codegen-maven-plugin/src/main/java/org/chelonix/dagger/codegen/introspection/CodegenVisitor.java", "retrieved_chunk": "package org.chelonix.dagger.codegen.introspection;\nimport java.io.*;\nimport java.nio.charset.Charset;\nimport java.nio.file.Path;\npublic class CodegenVisitor implements SchemaVisitor {\n private final ScalarVisitor scalarVisitor;\n private final InputVisitor inputVisitor;\n private final EnumVisitor enumVisitor;\n private final ObjectVisitor objectVisitor;\n public CodegenVisitor(Schema schema, Path targetDirectory, Charset encoding) {", "score": 0.8578646183013916 } ]
java
().info(String.format("Generating scala %s", type.getName()));
package org.kasun.discordleaderboards.Leaderboard; import me.clip.placeholderapi.PlaceholderAPI; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.*; public class DescriptionGenerator { private final Leaderboard leaderboard; private final List<String> embedDescriptionlist; private final TopList topList; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; private int numberOfFloatingPoints; private boolean isHigherBetter; public DescriptionGenerator(Leaderboard leaderboard) { this.leaderboard = leaderboard; embedDescriptionlist = leaderboard.getConfig().getEmbedDescription(); topList = leaderboard.getTopList(); numberOfFloatingPoints = leaderboard.getConfig().getFloatingpoints(); isHigherBetter = leaderboard.getConfig().isHigherisbetter(); } public DescriptionGenerator(String leaderboardname) { this.leaderboard = new Leaderboard(leaderboardname); embedDescriptionlist = leaderboard.getConfig().getEmbedDescription(); topList = leaderboard.getTopList(); } public String getDescription(boolean isForWebhook) { String description = String.join(isForWebhook ? "\\u000A" : "\n", embedDescriptionlist); //{toplist} placeholder String replacement1
= "```" + (isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + "```";
if (replacement1.equals("``````") || replacement1 == null) { description = description.replace("{toplist}", "```Leaderboard is empty!```"); } else { description = description.replace("{toplist}", replacement1); } //{top-1-name} {top-1-score} placeholders Map<String, Double> playerScores = topList.getTopListAsMap(); Pattern pattern = Pattern.compile("\\{top-(\\d+)-(name|score)\\}"); Matcher matcher = pattern.matcher(description); while (matcher.find()) { int position = Integer.parseInt(matcher.group(1)); String placeholderType = matcher.group(2); Comparator<Map.Entry<String, Double>> scoreComparator; if (isHigherBetter) { scoreComparator = Map.Entry.comparingByValue(Comparator.reverseOrder()); } else { scoreComparator = Map.Entry.comparingByValue(); } Map.Entry<String, Double> entry = playerScores.entrySet().stream() .sorted(scoreComparator) .skip(position - 1) .findFirst() .orElse(null); if (entry != null) { String placeholder = "{top-" + position + "-" + placeholderType + "}"; int intValue = entry.getValue().intValue(); String replacement = ""; if (leaderboard.getConfig().getFloatingpoints() > 0){ replacement = placeholderType.equals("name") ? entry.getKey() : String.valueOf(entry.getValue()); }else{ replacement = placeholderType.equals("name") ? entry.getKey() : String.valueOf(intValue); } description = description.replace(placeholder, replacement); } } //{timestamp-now} placeholder description = description.replace("{timestamp-now}", "<t:" + TimeUtils.getCurrentUnixTimestamp() + ":R>"); //{timestamp-next} placeholder String delay = leaderboard.getConfig().getDelay(); switch (delay.toLowerCase()) { case "hourly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORHOUR) + ":R>"); break; case "daily": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORDAY) + ":R>"); break; case "weekly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORWEEK) + ":R>"); break; case "monthly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSSFORMONTH) + ":R>"); break; default: break; } //{%papi%} placeholders String patternString = "\\{%(.*?)%\\}"; Pattern pattern1 = Pattern.compile(patternString); Matcher matcher1 = pattern1.matcher(description); StringBuilder result = new StringBuilder(); while (matcher1.find()) { String placeholder = matcher1.group(0); String innerValue = matcher1.group(1); String replacement = PlaceholderAPI.setPlaceholders(null, "%" + innerValue + "%"); description = description.replace(placeholder, replacement); result.append(innerValue).append(", "); } return description; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8804636001586914 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": "package org.kasun.discordleaderboards.DiscordSRV;\nimport org.kasun.discordleaderboards.Configs.MainConfig;\nimport org.kasun.discordleaderboards.Leaderboard.DescriptionGenerator;\nimport org.kasun.discordleaderboards.Leaderboard.Leaderboard;\nimport org.kasun.discordleaderboards.Leaderboard.TopList;\npublic class LeaderboardDiscordSrvEmbed {\n private Leaderboard leaderboard;\n private DiscordsrvEmbed discordsrvEmbed;\n private TopList topList;\n public LeaderboardDiscordSrvEmbed(Leaderboard leaderboard) {", "score": 0.8743884563446045 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " }\n //constructer for create leaderboard\n public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){\n this.name = name;\n MainConfig mainConfig = new MainConfig();\n List<String> leaderboards = mainConfig.getLeaderboardsList();\n leaderboards.add(name);\n mainConfig.setLeaderboardsList(leaderboards);\n mainConfig.saveConfig();\n leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig", "score": 0.8684816956520081 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance();\n public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None}\n private final LeaderboardConfig leaderboardConfig;\n private final String name;\n private final TopList topList;\n //constructer for load leaderboard\n public Leaderboard(String name) {\n this.name = name;\n leaderboardConfig = new LeaderboardConfig(name);\n topList = new TopList(leaderboardConfig);", "score": 0.8679677248001099 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this);\n String description = descriptionGenerator.getDescription(true);\n if (description == null || description.equals(\"\") || dembedDescription.equals(\"-\")) {\n description = dembedDescription;\n }\n embed.setDescription(description);\n webhook.addEmbed(embed);\n try{\n webhook.execute();\n }catch (IOException e){", "score": 0.8666486740112305 } ]
java
= "```" + (isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + "```";
package org.kasun.discordleaderboards.Leaderboard; import org.kasun.discordleaderboards.Utils.SqlUtils; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.Map; public class TopList { private final int top; private final LeaderboardConfig leaderboardConfig; private final String placeholder; private final String leaderboardname; String placeholderColumnName; private int numberOfFloatingPoints; public TopList(LeaderboardConfig leaderboardConfig) { this.leaderboardConfig = leaderboardConfig; top = leaderboardConfig.getTop(); placeholder = leaderboardConfig.getPlaceholder(); leaderboardname = leaderboardConfig.getName(); placeholderColumnName = leaderboardConfig.getPlaceholder().substring(1, leaderboardConfig.getPlaceholder().length() - 1); numberOfFloatingPoints = leaderboardConfig.getFloatingpoints(); } public Map<String, Double> getTopListAsMap() { int top = leaderboardConfig.getTop(); return SqlUtils.getTopPlayerMap(placeholderColumnName, top, leaderboardConfig.isHigherisbetter()); } public String getTopListAsString(boolean isWebhookFormat) { Map<String, Double> toplistmap = getTopListAsMap(); int maxNameLength = getmaxnamelenght(toplistmap); StringBuilder sb = new StringBuilder(); int i = 1; for (Map.Entry<String, Double> entry : toplistmap.entrySet()) { String name = entry.getKey(); double score = entry.getValue(); int intValue = (int) score; String formattedEntry = ""; if (numberOfFloatingPoints <= 0) { if (isWebhookFormat) { formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %d%s\\u000A", i++, name, intValue, leaderboardConfig.getMetric()); } else { formattedEntry = String.format("%d. %-" + (
maxNameLength + 3) + "s %d%s\n", i++, name, intValue, leaderboardConfig.getMetric());
} } else { double roundedScore = roundScore(score); if (isWebhookFormat) { formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %." + numberOfFloatingPoints + "f%s\\u000A", i++, name, roundedScore, leaderboardConfig.getMetric()); } else { formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %." + numberOfFloatingPoints + "f%s\n", i++, name, roundedScore, leaderboardConfig.getMetric()); } } sb.append(formattedEntry); } String leaderboardString = sb.toString(); return leaderboardString; } public String getTopListAsStringForWebhook() { Map<String, Double> toplistmap = getTopListAsMap(); int maxNameLength = getmaxnamelenght(toplistmap); StringBuilder sb = new StringBuilder(); int i = 1; for (Map.Entry<String, Double> entry : toplistmap.entrySet()) { String name = entry.getKey(); double score = entry.getValue(); int intValue = (int) score; String formattedEntry = ""; if (numberOfFloatingPoints <= 0) { formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %d%s\\u000A", i++, name, intValue, leaderboardConfig.getMetric()); } else { double roundedScore = roundScore(score); formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %." + numberOfFloatingPoints + "f%s\\u000A", i++, name, roundedScore, leaderboardConfig.getMetric()); } sb.append(formattedEntry); } String leaderboardString = sb.toString(); return leaderboardString; } public String getTopListAsString() { Map<String, Double> toplistmap = getTopListAsMap(); int maxNameLength = getmaxnamelenght(toplistmap); StringBuilder sb = new StringBuilder(); int i = 1; for (Map.Entry<String, Double> entry : toplistmap.entrySet()) { System.out.println("debug : 1"); String name = entry.getKey(); double score = entry.getValue(); int intValue = (int) score; System.out.println("debug : 2"); String formattedEntry = ""; if (numberOfFloatingPoints <= 0){ formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %d%s\n", i++, name, intValue, leaderboardConfig.getMetric()); }else{ double roundedScore = roundScore(score); formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %." + numberOfFloatingPoints + "f%s\n", i++, name, roundedScore, leaderboardConfig.getMetric()); } System.out.println("debug : 3"); sb.append(formattedEntry); System.out.println("Debug : " + numberOfFloatingPoints); } String leaderboardString = sb.toString(); return leaderboardString; } private int getmaxnamelenght(Map<String, Double> toplistmap) { // find the maximum length of the names int maxNameLength = 0; for (String name : toplistmap.keySet()) { if (name.length() > maxNameLength) { maxNameLength = name.length(); } } return maxNameLength; } private double roundScore(double score) { BigDecimal bd = new BigDecimal(score); bd = bd.setScale(numberOfFloatingPoints, RoundingMode.HALF_UP); return bd.doubleValue(); } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " String placeholder = \"{top-\" + position + \"-\" + placeholderType + \"}\";\n int intValue = entry.getValue().intValue();\n String replacement = \"\";\n if (leaderboard.getConfig().getFloatingpoints() > 0){\n replacement = placeholderType.equals(\"name\") ? entry.getKey() : String.valueOf(entry.getValue());\n }else{\n replacement = placeholderType.equals(\"name\") ? entry.getKey() : String.valueOf(intValue);\n }\n description = description.replace(placeholder, replacement);\n }", "score": 0.8792747259140015 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " topList = leaderboard.getTopList();\n }\n public String getDescription(boolean isForWebhook) {\n String description = String.join(isForWebhook ? \"\\\\u000A\" : \"\\n\", embedDescriptionlist);\n //{toplist} placeholder\n String replacement1 = \"```\" + (isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + \"```\";\n if (replacement1.equals(\"``````\") || replacement1 == null) {\n description = description.replace(\"{toplist}\", \"```Leaderboard is empty!```\");\n } else {\n description = description.replace(\"{toplist}\", replacement1);", "score": 0.825060248374939 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java", "retrieved_chunk": " //getters and setters\n public String getLeaderboardversion() {\n return leaderboardversion;\n }\n public void setLeaderboardversion(String leaderboardversion) {\n this.leaderboardversion = leaderboardversion;\n }\n public String getMetric() {\n String output = \"\";\n if (!metric.equals(null) && !metric.equals(\"-\")){", "score": 0.8222406506538391 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " }\n //{timestamp-now} placeholder\n description = description.replace(\"{timestamp-now}\", \"<t:\" + TimeUtils.getCurrentUnixTimestamp() + \":R>\");\n //{timestamp-next} placeholder\n String delay = leaderboard.getConfig().getDelay();\n switch (delay.toLowerCase()) {\n case \"hourly\":\n description = description.replace(\"{timestamp-next}\", \"<t:\" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORHOUR) + \":R>\");\n break;\n case \"daily\":", "score": 0.815686047077179 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " //getting leaderboard's values from leaderboard config\n String placeholder = leaderboardConfig.getPlaceholder();\n int top = leaderboardConfig.getTop();\n String delay = leaderboardConfig.getDelay();\n String webhookurl = leaderboardConfig.getWebhookurl();\n String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl();\n String webhookUserName = leaderboardConfig.getWebhookUserName();\n String embedTitle = leaderboardConfig.getEmbedTitle();\n String embedUrl = leaderboardConfig.getEmbedUrl();\n String embedColour = leaderboardConfig.getEmbedColour();", "score": 0.8153791427612305 } ]
java
maxNameLength + 3) + "s %d%s\n", i++, name, intValue, leaderboardConfig.getMetric());
package org.kasun.discordleaderboards.Leaderboard; import me.clip.placeholderapi.PlaceholderAPI; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.*; public class DescriptionGenerator { private final Leaderboard leaderboard; private final List<String> embedDescriptionlist; private final TopList topList; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; private int numberOfFloatingPoints; private boolean isHigherBetter; public DescriptionGenerator(Leaderboard leaderboard) { this.leaderboard = leaderboard; embedDescriptionlist = leaderboard.getConfig().getEmbedDescription(); topList = leaderboard.getTopList(); numberOfFloatingPoints = leaderboard.getConfig().getFloatingpoints(); isHigherBetter = leaderboard.getConfig().isHigherisbetter(); } public DescriptionGenerator(String leaderboardname) { this.leaderboard = new Leaderboard(leaderboardname); embedDescriptionlist = leaderboard.getConfig().getEmbedDescription(); topList = leaderboard.getTopList(); } public String getDescription(boolean isForWebhook) { String description = String.join(isForWebhook ? "\\u000A" : "\n", embedDescriptionlist); //{toplist} placeholder String replacement1 = "```" +
(isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + "```";
if (replacement1.equals("``````") || replacement1 == null) { description = description.replace("{toplist}", "```Leaderboard is empty!```"); } else { description = description.replace("{toplist}", replacement1); } //{top-1-name} {top-1-score} placeholders Map<String, Double> playerScores = topList.getTopListAsMap(); Pattern pattern = Pattern.compile("\\{top-(\\d+)-(name|score)\\}"); Matcher matcher = pattern.matcher(description); while (matcher.find()) { int position = Integer.parseInt(matcher.group(1)); String placeholderType = matcher.group(2); Comparator<Map.Entry<String, Double>> scoreComparator; if (isHigherBetter) { scoreComparator = Map.Entry.comparingByValue(Comparator.reverseOrder()); } else { scoreComparator = Map.Entry.comparingByValue(); } Map.Entry<String, Double> entry = playerScores.entrySet().stream() .sorted(scoreComparator) .skip(position - 1) .findFirst() .orElse(null); if (entry != null) { String placeholder = "{top-" + position + "-" + placeholderType + "}"; int intValue = entry.getValue().intValue(); String replacement = ""; if (leaderboard.getConfig().getFloatingpoints() > 0){ replacement = placeholderType.equals("name") ? entry.getKey() : String.valueOf(entry.getValue()); }else{ replacement = placeholderType.equals("name") ? entry.getKey() : String.valueOf(intValue); } description = description.replace(placeholder, replacement); } } //{timestamp-now} placeholder description = description.replace("{timestamp-now}", "<t:" + TimeUtils.getCurrentUnixTimestamp() + ":R>"); //{timestamp-next} placeholder String delay = leaderboard.getConfig().getDelay(); switch (delay.toLowerCase()) { case "hourly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORHOUR) + ":R>"); break; case "daily": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORDAY) + ":R>"); break; case "weekly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORWEEK) + ":R>"); break; case "monthly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSSFORMONTH) + ":R>"); break; default: break; } //{%papi%} placeholders String patternString = "\\{%(.*?)%\\}"; Pattern pattern1 = Pattern.compile(patternString); Matcher matcher1 = pattern1.matcher(description); StringBuilder result = new StringBuilder(); while (matcher1.find()) { String placeholder = matcher1.group(0); String innerValue = matcher1.group(1); String replacement = PlaceholderAPI.setPlaceholders(null, "%" + innerValue + "%"); description = description.replace(placeholder, replacement); result.append(innerValue).append(", "); } return description; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8792070150375366 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": "package org.kasun.discordleaderboards.DiscordSRV;\nimport org.kasun.discordleaderboards.Configs.MainConfig;\nimport org.kasun.discordleaderboards.Leaderboard.DescriptionGenerator;\nimport org.kasun.discordleaderboards.Leaderboard.Leaderboard;\nimport org.kasun.discordleaderboards.Leaderboard.TopList;\npublic class LeaderboardDiscordSrvEmbed {\n private Leaderboard leaderboard;\n private DiscordsrvEmbed discordsrvEmbed;\n private TopList topList;\n public LeaderboardDiscordSrvEmbed(Leaderboard leaderboard) {", "score": 0.8735129833221436 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " }\n //constructer for create leaderboard\n public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){\n this.name = name;\n MainConfig mainConfig = new MainConfig();\n List<String> leaderboards = mainConfig.getLeaderboardsList();\n leaderboards.add(name);\n mainConfig.setLeaderboardsList(leaderboards);\n mainConfig.saveConfig();\n leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig", "score": 0.867889404296875 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this);\n String description = descriptionGenerator.getDescription(true);\n if (description == null || description.equals(\"\") || dembedDescription.equals(\"-\")) {\n description = dembedDescription;\n }\n embed.setDescription(description);\n webhook.addEmbed(embed);\n try{\n webhook.execute();\n }catch (IOException e){", "score": 0.867121160030365 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance();\n public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None}\n private final LeaderboardConfig leaderboardConfig;\n private final String name;\n private final TopList topList;\n //constructer for load leaderboard\n public Leaderboard(String name) {\n this.name = name;\n leaderboardConfig = new LeaderboardConfig(name);\n topList = new TopList(leaderboardConfig);", "score": 0.8658957481384277 } ]
java
(isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + "```";
package org.kasun.discordleaderboards.Leaderboard; import org.kasun.discordleaderboards.Utils.SqlUtils; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.Map; public class TopList { private final int top; private final LeaderboardConfig leaderboardConfig; private final String placeholder; private final String leaderboardname; String placeholderColumnName; private int numberOfFloatingPoints; public TopList(LeaderboardConfig leaderboardConfig) { this.leaderboardConfig = leaderboardConfig; top = leaderboardConfig.getTop(); placeholder = leaderboardConfig.getPlaceholder(); leaderboardname = leaderboardConfig.getName(); placeholderColumnName = leaderboardConfig.getPlaceholder().substring(1, leaderboardConfig.getPlaceholder().length() - 1); numberOfFloatingPoints = leaderboardConfig.getFloatingpoints(); } public Map<String, Double> getTopListAsMap() { int top = leaderboardConfig.getTop(); return SqlUtils.getTopPlayerMap(placeholderColumnName, top, leaderboardConfig.isHigherisbetter()); } public String getTopListAsString(boolean isWebhookFormat) { Map<String, Double> toplistmap = getTopListAsMap(); int maxNameLength = getmaxnamelenght(toplistmap); StringBuilder sb = new StringBuilder(); int i = 1; for (Map.Entry<String, Double> entry : toplistmap.entrySet()) { String name = entry.getKey(); double score = entry.getValue(); int intValue = (int) score; String formattedEntry = ""; if (numberOfFloatingPoints <= 0) { if (isWebhookFormat) { formattedEntry = String.format("%d. %-" + (maxNameLength + 3
) + "s %d%s\\u000A", i++, name, intValue, leaderboardConfig.getMetric());
} else { formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %d%s\n", i++, name, intValue, leaderboardConfig.getMetric()); } } else { double roundedScore = roundScore(score); if (isWebhookFormat) { formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %." + numberOfFloatingPoints + "f%s\\u000A", i++, name, roundedScore, leaderboardConfig.getMetric()); } else { formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %." + numberOfFloatingPoints + "f%s\n", i++, name, roundedScore, leaderboardConfig.getMetric()); } } sb.append(formattedEntry); } String leaderboardString = sb.toString(); return leaderboardString; } public String getTopListAsStringForWebhook() { Map<String, Double> toplistmap = getTopListAsMap(); int maxNameLength = getmaxnamelenght(toplistmap); StringBuilder sb = new StringBuilder(); int i = 1; for (Map.Entry<String, Double> entry : toplistmap.entrySet()) { String name = entry.getKey(); double score = entry.getValue(); int intValue = (int) score; String formattedEntry = ""; if (numberOfFloatingPoints <= 0) { formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %d%s\\u000A", i++, name, intValue, leaderboardConfig.getMetric()); } else { double roundedScore = roundScore(score); formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %." + numberOfFloatingPoints + "f%s\\u000A", i++, name, roundedScore, leaderboardConfig.getMetric()); } sb.append(formattedEntry); } String leaderboardString = sb.toString(); return leaderboardString; } public String getTopListAsString() { Map<String, Double> toplistmap = getTopListAsMap(); int maxNameLength = getmaxnamelenght(toplistmap); StringBuilder sb = new StringBuilder(); int i = 1; for (Map.Entry<String, Double> entry : toplistmap.entrySet()) { System.out.println("debug : 1"); String name = entry.getKey(); double score = entry.getValue(); int intValue = (int) score; System.out.println("debug : 2"); String formattedEntry = ""; if (numberOfFloatingPoints <= 0){ formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %d%s\n", i++, name, intValue, leaderboardConfig.getMetric()); }else{ double roundedScore = roundScore(score); formattedEntry = String.format("%d. %-" + (maxNameLength + 3) + "s %." + numberOfFloatingPoints + "f%s\n", i++, name, roundedScore, leaderboardConfig.getMetric()); } System.out.println("debug : 3"); sb.append(formattedEntry); System.out.println("Debug : " + numberOfFloatingPoints); } String leaderboardString = sb.toString(); return leaderboardString; } private int getmaxnamelenght(Map<String, Double> toplistmap) { // find the maximum length of the names int maxNameLength = 0; for (String name : toplistmap.keySet()) { if (name.length() > maxNameLength) { maxNameLength = name.length(); } } return maxNameLength; } private double roundScore(double score) { BigDecimal bd = new BigDecimal(score); bd = bd.setScale(numberOfFloatingPoints, RoundingMode.HALF_UP); return bd.doubleValue(); } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " String placeholder = \"{top-\" + position + \"-\" + placeholderType + \"}\";\n int intValue = entry.getValue().intValue();\n String replacement = \"\";\n if (leaderboard.getConfig().getFloatingpoints() > 0){\n replacement = placeholderType.equals(\"name\") ? entry.getKey() : String.valueOf(entry.getValue());\n }else{\n replacement = placeholderType.equals(\"name\") ? entry.getKey() : String.valueOf(intValue);\n }\n description = description.replace(placeholder, replacement);\n }", "score": 0.8665004372596741 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " topList = leaderboard.getTopList();\n }\n public String getDescription(boolean isForWebhook) {\n String description = String.join(isForWebhook ? \"\\\\u000A\" : \"\\n\", embedDescriptionlist);\n //{toplist} placeholder\n String replacement1 = \"```\" + (isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + \"```\";\n if (replacement1.equals(\"``````\") || replacement1 == null) {\n description = description.replace(\"{toplist}\", \"```Leaderboard is empty!```\");\n } else {\n description = description.replace(\"{toplist}\", replacement1);", "score": 0.848496675491333 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " }\n //{top-1-name} {top-1-score} placeholders\n Map<String, Double> playerScores = topList.getTopListAsMap();\n Pattern pattern = Pattern.compile(\"\\\\{top-(\\\\d+)-(name|score)\\\\}\");\n Matcher matcher = pattern.matcher(description);\n while (matcher.find()) {\n int position = Integer.parseInt(matcher.group(1));\n String placeholderType = matcher.group(2);\n Comparator<Map.Entry<String, Double>> scoreComparator;\n if (isHigherBetter) {", "score": 0.8386929035186768 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": "public class DescriptionGenerator {\n private final Leaderboard leaderboard;\n private final List<String> embedDescriptionlist;\n private final TopList topList;\n private final long SECSFORHOUR = 3600;\n private final long SECSFORDAY = 86400;\n private final long SECSFORWEEK = 604800;\n private final long SECSSFORMONTH = 2629746;\n private int numberOfFloatingPoints;\n private boolean isHigherBetter;", "score": 0.8287424445152283 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java", "retrieved_chunk": " //getters and setters\n public String getLeaderboardversion() {\n return leaderboardversion;\n }\n public void setLeaderboardversion(String leaderboardversion) {\n this.leaderboardversion = leaderboardversion;\n }\n public String getMetric() {\n String output = \"\";\n if (!metric.equals(null) && !metric.equals(\"-\")){", "score": 0.8198257684707642 } ]
java
) + "s %d%s\\u000A", i++, name, intValue, leaderboardConfig.getMetric());
package org.kasun.discordleaderboards.Leaderboard; import me.clip.placeholderapi.PlaceholderAPI; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.*; public class DescriptionGenerator { private final Leaderboard leaderboard; private final List<String> embedDescriptionlist; private final TopList topList; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; private int numberOfFloatingPoints; private boolean isHigherBetter; public DescriptionGenerator(Leaderboard leaderboard) { this.leaderboard = leaderboard; embedDescriptionlist = leaderboard.getConfig().getEmbedDescription(); topList = leaderboard.getTopList(); numberOfFloatingPoints = leaderboard.getConfig().getFloatingpoints(); isHigherBetter = leaderboard.getConfig().isHigherisbetter(); } public DescriptionGenerator(String leaderboardname) { this.leaderboard = new Leaderboard(leaderboardname); embedDescriptionlist = leaderboard.getConfig().getEmbedDescription(); topList = leaderboard.getTopList(); } public String getDescription(boolean isForWebhook) { String description = String.join(isForWebhook ? "\\u000A" : "\n", embedDescriptionlist); //{toplist} placeholder String replacement1 = "```" + (isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + "```"; if (replacement1.equals("``````") || replacement1 == null) { description = description.replace("{toplist}", "```Leaderboard is empty!```"); } else { description = description.replace("{toplist}", replacement1); } //{top-1-name} {top-1-score} placeholders Map<String, Double> playerScores = topList.getTopListAsMap(); Pattern pattern = Pattern.compile("\\{top-(\\d+)-(name|score)\\}"); Matcher matcher = pattern.matcher(description); while (matcher.find()) { int position = Integer.parseInt(matcher.group(1)); String placeholderType = matcher.group(2); Comparator<Map.Entry<String, Double>> scoreComparator; if (isHigherBetter) { scoreComparator = Map.Entry.comparingByValue(Comparator.reverseOrder()); } else { scoreComparator = Map.Entry.comparingByValue(); } Map.Entry<String, Double> entry = playerScores.entrySet().stream() .sorted(scoreComparator) .skip(position - 1) .findFirst() .orElse(null); if (entry != null) { String placeholder = "{top-" + position + "-" + placeholderType + "}"; int intValue = entry.getValue().intValue(); String replacement = "";
if (leaderboard.getConfig().getFloatingpoints() > 0){
replacement = placeholderType.equals("name") ? entry.getKey() : String.valueOf(entry.getValue()); }else{ replacement = placeholderType.equals("name") ? entry.getKey() : String.valueOf(intValue); } description = description.replace(placeholder, replacement); } } //{timestamp-now} placeholder description = description.replace("{timestamp-now}", "<t:" + TimeUtils.getCurrentUnixTimestamp() + ":R>"); //{timestamp-next} placeholder String delay = leaderboard.getConfig().getDelay(); switch (delay.toLowerCase()) { case "hourly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORHOUR) + ":R>"); break; case "daily": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORDAY) + ":R>"); break; case "weekly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORWEEK) + ":R>"); break; case "monthly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSSFORMONTH) + ":R>"); break; default: break; } //{%papi%} placeholders String patternString = "\\{%(.*?)%\\}"; Pattern pattern1 = Pattern.compile(patternString); Matcher matcher1 = pattern1.matcher(description); StringBuilder result = new StringBuilder(); while (matcher1.find()) { String placeholder = matcher1.group(0); String innerValue = matcher1.group(1); String replacement = PlaceholderAPI.setPlaceholders(null, "%" + innerValue + "%"); description = description.replace(placeholder, replacement); result.append(innerValue).append(", "); } return description; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " String name = entry.getKey();\n double score = entry.getValue();\n int intValue = (int) score;\n String formattedEntry = \"\";\n if (numberOfFloatingPoints <= 0) {\n formattedEntry = String.format(\"%d. %-\" + (maxNameLength + 3) + \"s %d%s\\\\u000A\", i++, name, intValue, leaderboardConfig.getMetric());\n } else {\n double roundedScore = roundScore(score);\n formattedEntry = String.format(\"%d. %-\" + (maxNameLength + 3) + \"s %.\" + numberOfFloatingPoints + \"f%s\\\\u000A\", i++, name, roundedScore, leaderboardConfig.getMetric());\n }", "score": 0.8634741306304932 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " for (Map.Entry<String, Double> entry : toplistmap.entrySet()) {\n System.out.println(\"debug : 1\");\n String name = entry.getKey();\n double score = entry.getValue();\n int intValue = (int) score;\n System.out.println(\"debug : 2\");\n String formattedEntry = \"\";\n if (numberOfFloatingPoints <= 0){\n formattedEntry = String.format(\"%d. %-\" + (maxNameLength + 3) + \"s %d%s\\n\", i++, name, intValue, leaderboardConfig.getMetric());\n }else{", "score": 0.8558800220489502 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " for (Map.Entry<String, Double> entry : toplistmap.entrySet()) {\n String name = entry.getKey();\n double score = entry.getValue();\n int intValue = (int) score;\n String formattedEntry = \"\";\n if (numberOfFloatingPoints <= 0) {\n if (isWebhookFormat) {\n formattedEntry = String.format(\"%d. %-\" + (maxNameLength + 3) + \"s %d%s\\\\u000A\", i++, name, intValue, leaderboardConfig.getMetric());\n } else {\n formattedEntry = String.format(\"%d. %-\" + (maxNameLength + 3) + \"s %d%s\\n\", i++, name, intValue, leaderboardConfig.getMetric());", "score": 0.8556878566741943 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " }\n } else {\n double roundedScore = roundScore(score);\n if (isWebhookFormat) {\n formattedEntry = String.format(\"%d. %-\" + (maxNameLength + 3) + \"s %.\" + numberOfFloatingPoints + \"f%s\\\\u000A\", i++, name, roundedScore, leaderboardConfig.getMetric());\n } else {\n formattedEntry = String.format(\"%d. %-\" + (maxNameLength + 3) + \"s %.\" + numberOfFloatingPoints + \"f%s\\n\", i++, name, roundedScore, leaderboardConfig.getMetric());\n }\n }\n sb.append(formattedEntry);", "score": 0.8499287366867065 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " private final String leaderboardname;\n String placeholderColumnName;\n private int numberOfFloatingPoints;\n public TopList(LeaderboardConfig leaderboardConfig) {\n this.leaderboardConfig = leaderboardConfig;\n top = leaderboardConfig.getTop();\n placeholder = leaderboardConfig.getPlaceholder();\n leaderboardname = leaderboardConfig.getName();\n placeholderColumnName = leaderboardConfig.getPlaceholder().substring(1, leaderboardConfig.getPlaceholder().length() - 1);\n numberOfFloatingPoints = leaderboardConfig.getFloatingpoints();", "score": 0.8450154066085815 } ]
java
if (leaderboard.getConfig().getFloatingpoints() > 0){
package org.kasun.discordleaderboards.Leaderboard; import me.clip.placeholderapi.PlaceholderAPI; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.*; public class DescriptionGenerator { private final Leaderboard leaderboard; private final List<String> embedDescriptionlist; private final TopList topList; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; private int numberOfFloatingPoints; private boolean isHigherBetter; public DescriptionGenerator(Leaderboard leaderboard) { this.leaderboard = leaderboard; embedDescriptionlist = leaderboard.getConfig().getEmbedDescription(); topList = leaderboard.getTopList(); numberOfFloatingPoints = leaderboard.getConfig().getFloatingpoints(); isHigherBetter = leaderboard.getConfig().isHigherisbetter(); } public DescriptionGenerator(String leaderboardname) { this.leaderboard = new Leaderboard(leaderboardname); embedDescriptionlist = leaderboard.getConfig().getEmbedDescription(); topList = leaderboard.getTopList(); } public String getDescription(boolean isForWebhook) { String description = String.join(isForWebhook ? "\\u000A" : "\n", embedDescriptionlist); //{toplist} placeholder String replacement1 = "```" + (isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + "```"; if (replacement1.equals("``````") || replacement1 == null) { description = description.replace("{toplist}", "```Leaderboard is empty!```"); } else { description = description.replace("{toplist}", replacement1); } //{top-1-name} {top-1-score} placeholders Map<String
, Double> playerScores = topList.getTopListAsMap();
Pattern pattern = Pattern.compile("\\{top-(\\d+)-(name|score)\\}"); Matcher matcher = pattern.matcher(description); while (matcher.find()) { int position = Integer.parseInt(matcher.group(1)); String placeholderType = matcher.group(2); Comparator<Map.Entry<String, Double>> scoreComparator; if (isHigherBetter) { scoreComparator = Map.Entry.comparingByValue(Comparator.reverseOrder()); } else { scoreComparator = Map.Entry.comparingByValue(); } Map.Entry<String, Double> entry = playerScores.entrySet().stream() .sorted(scoreComparator) .skip(position - 1) .findFirst() .orElse(null); if (entry != null) { String placeholder = "{top-" + position + "-" + placeholderType + "}"; int intValue = entry.getValue().intValue(); String replacement = ""; if (leaderboard.getConfig().getFloatingpoints() > 0){ replacement = placeholderType.equals("name") ? entry.getKey() : String.valueOf(entry.getValue()); }else{ replacement = placeholderType.equals("name") ? entry.getKey() : String.valueOf(intValue); } description = description.replace(placeholder, replacement); } } //{timestamp-now} placeholder description = description.replace("{timestamp-now}", "<t:" + TimeUtils.getCurrentUnixTimestamp() + ":R>"); //{timestamp-next} placeholder String delay = leaderboard.getConfig().getDelay(); switch (delay.toLowerCase()) { case "hourly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORHOUR) + ":R>"); break; case "daily": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORDAY) + ":R>"); break; case "weekly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSFORWEEK) + ":R>"); break; case "monthly": description = description.replace("{timestamp-next}", "<t:" + (TimeUtils.getCurrentUnixTimestamp() + SECSSFORMONTH) + ":R>"); break; default: break; } //{%papi%} placeholders String patternString = "\\{%(.*?)%\\}"; Pattern pattern1 = Pattern.compile(patternString); Matcher matcher1 = pattern1.matcher(description); StringBuilder result = new StringBuilder(); while (matcher1.find()) { String placeholder = matcher1.group(0); String innerValue = matcher1.group(1); String replacement = PlaceholderAPI.setPlaceholders(null, "%" + innerValue + "%"); description = description.replace(placeholder, replacement); result.append(innerValue).append(", "); } return description; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " }\n String leaderboardString = sb.toString();\n return leaderboardString;\n }\n public String getTopListAsStringForWebhook() {\n Map<String, Double> toplistmap = getTopListAsMap();\n int maxNameLength = getmaxnamelenght(toplistmap);\n StringBuilder sb = new StringBuilder();\n int i = 1;\n for (Map.Entry<String, Double> entry : toplistmap.entrySet()) {", "score": 0.8495596051216125 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " for (Map.Entry<String, Double> entry : toplistmap.entrySet()) {\n String name = entry.getKey();\n double score = entry.getValue();\n int intValue = (int) score;\n String formattedEntry = \"\";\n if (numberOfFloatingPoints <= 0) {\n if (isWebhookFormat) {\n formattedEntry = String.format(\"%d. %-\" + (maxNameLength + 3) + \"s %d%s\\\\u000A\", i++, name, intValue, leaderboardConfig.getMetric());\n } else {\n formattedEntry = String.format(\"%d. %-\" + (maxNameLength + 3) + \"s %d%s\\n\", i++, name, intValue, leaderboardConfig.getMetric());", "score": 0.8483647704124451 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " }\n public Map<String, Double> getTopListAsMap() {\n int top = leaderboardConfig.getTop();\n return SqlUtils.getTopPlayerMap(placeholderColumnName, top, leaderboardConfig.isHigherisbetter());\n }\n public String getTopListAsString(boolean isWebhookFormat) {\n Map<String, Double> toplistmap = getTopListAsMap();\n int maxNameLength = getmaxnamelenght(toplistmap);\n StringBuilder sb = new StringBuilder();\n int i = 1;", "score": 0.8433870077133179 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Leaderboard;\nimport org.kasun.discordleaderboards.Utils.SqlUtils;\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.util.Map;\npublic class TopList {\n private final int top;\n private final LeaderboardConfig leaderboardConfig;\n private final String placeholder;", "score": 0.8430994749069214 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " sb.append(formattedEntry);\n }\n String leaderboardString = sb.toString();\n return leaderboardString;\n }\n public String getTopListAsString() {\n Map<String, Double> toplistmap = getTopListAsMap();\n int maxNameLength = getmaxnamelenght(toplistmap);\n StringBuilder sb = new StringBuilder();\n int i = 1;", "score": 0.8425565958023071 } ]
java
, Double> playerScores = topList.getTopListAsMap();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.configuration.file.FileConfiguration; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Configs.CustomConfig; import java.util.ArrayList; import java.util.List; public class LeaderboardConfig { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); private String name; private FileConfiguration config; private String placeholder; private int top; private String delay; private boolean refreshOnSent; private String metric; private boolean higherisbetter; private int floatingpoints; private String webhookurl; private String webhookAvatarUrl; private String webhookUserName; private String embedTitle; private List<String> embedDescription; private String embedUrl; private String embedColour; private String embedFooter; private String embedImage; private String embedThumbnail; private String leaderboardversion; private final CustomConfig customConfig; //Constructer for load exciting leaderboardConfig public LeaderboardConfig(String name) { this.name = name; customConfig = new CustomConfig(name); config = customConfig.get(); load(); } //Constructer for create new LeaderboardConfig public LeaderboardConfig(String name, String placeholder, int top, String delay) { MainConfig mainConfig = new MainConfig(); this.name = name; this.placeholder = placeholder; this.top = top; this.delay = delay; this.refreshOnSent = false; this.metric = "-"; this.higherisbetter = true; this.floatingpoints = 0; this.webhookurl = "-"; this.webhookAvatarUrl = "-"; this.webhookUserName = "-"; this.embedTitle = "-"; List<String> description = new ArrayList<>(); description.add("{toplist}"); this.embedDescription = description; this.embedUrl = "-"; this.embedColour = "-"; this.embedFooter = "-"; this.embedImage = "-"; this.embedThumbnail = "-";
this.leaderboardversion = mainConfig.getPluginVersion();
customConfig = new CustomConfig(name); customConfig.setup(); config = customConfig.get(); save(); } //save methode public void save() { config.set("placeholder", placeholder); config.set("top", top); config.set("delay", delay); config.set("refresh-database-onsent", refreshOnSent); config.set("metric", metric); config.set("higherisbetter", higherisbetter); config.set("floatingpoints", floatingpoints); config.set("webhook-url", webhookurl); config.set("webhook-avatar-url", webhookAvatarUrl); config.set("webhook-user-name", webhookUserName); config.set("embed-title", embedTitle); config.set("embed-description", embedDescription); config.set("embed-url", embedUrl); config.set("embed-colour", embedColour); config.set("embed-footer", embedFooter); config.set("embed-image", embedImage); config.set("embed-thumbnail", embedThumbnail); config.set("leaderboard-version", leaderboardversion); customConfig.save(); customConfig.reload(); } //load methode public void load(){ this.placeholder = config.getString("placeholder"); this.top = config.getInt("top"); this.delay = config.getString("delay"); this.refreshOnSent = config.getBoolean("refresh-database-onsent"); this.metric = config.getString("metric"); this.higherisbetter = config.getBoolean("higherisbetter"); this.floatingpoints = config.getInt("floatingpoints"); this.webhookurl = config.getString("webhook-url"); this.webhookAvatarUrl = config.getString("webhook-avatar-url"); this.webhookUserName = config.getString("webhook-user-name"); this.embedTitle = config.getString("embed-title"); this.embedDescription = config.getStringList("embed-description"); this.embedUrl = config.getString("embed-url"); this.embedColour = config.getString("embed-colour"); this.embedFooter = config.getString("embed-footer"); this.embedImage = config.getString("embed-image"); this.embedThumbnail = config.getString("embed-thumbnail"); this.leaderboardversion = config.getString("leaderboard-version"); } //getters and setters public String getLeaderboardversion() { return leaderboardversion; } public void setLeaderboardversion(String leaderboardversion) { this.leaderboardversion = leaderboardversion; } public String getMetric() { String output = ""; if (!metric.equals(null) && !metric.equals("-")){ output = metric; } return output; } public void setMetric(String metric) { this.metric = metric; } public boolean isHigherisbetter() { return higherisbetter; } public void setHigherisbetter(boolean higherisbetter) { this.higherisbetter = higherisbetter; } public int getFloatingpoints() { return floatingpoints; } public void setFloatingpoints(int floatingpoints) { this.floatingpoints = floatingpoints; } public boolean isRefreshOnSent() { return refreshOnSent; } public void setRefreshOnSent(boolean refreshOnSent) { this.refreshOnSent = refreshOnSent; } public List<String> getEmbedDescription() { return embedDescription; } public void setEmbedDescription(List<String> embedDescription) { this.embedDescription = embedDescription; } public String getName() { return name; } public void setName(String name) { this.name = name; } public FileConfiguration getConfig() { return config; } public void setConfig(FileConfiguration config) { this.config = config; } public String getPlaceholder() { return placeholder; } public void setPlaceholder(String placeholder) { this.placeholder = placeholder; } public int getTop() { return top; } public void setTop(int top) { this.top = top; } public String getDelay() { return delay; } public void setDelay(String delay) { this.delay = delay; } public String getWebhookurl() { return webhookurl; } public void setWebhookurl(String webhookurl) { this.webhookurl = webhookurl; } public String getWebhookAvatarUrl() { return webhookAvatarUrl; } public void setWebhookAvatarUrl(String webhookAvatarUrl) { this.webhookAvatarUrl = webhookAvatarUrl; } public String getWebhookUserName() { return webhookUserName; } public void setWebhookUserName(String webhookUserName) { this.webhookUserName = webhookUserName; } public String getEmbedTitle() { return embedTitle; } public void setEmbedTitle(String embedTitle) { this.embedTitle = embedTitle; } public String getEmbedUrl() { return embedUrl; } public void setEmbedUrl(String embedUrl) { this.embedUrl = embedUrl; } public String getEmbedColour() { return embedColour; } public void setEmbedColour(String embedColour) { this.embedColour = embedColour; } public String getEmbedFooter() { return embedFooter; } public void setEmbedFooter(String embedFooter) { this.embedFooter = embedFooter; } public String getEmbedImage() { return embedImage; } public void setEmbedImage(String embedImage) { this.embedImage = embedImage; } public String getEmbedThumbnail() { return embedThumbnail; } public void setEmbedThumbnail(String embedThumbnail) { this.embedThumbnail = embedThumbnail; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8982148170471191 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " this.leaderboard = leaderboard;\n }\n private String getDefaultIfNullOrEmpty(String value, String defaultValue) {\n return (value == null || value.isEmpty() || value.equals(\"-\")) ? defaultValue : value;\n }\n public DiscordsrvEmbed getDiscordsrvEmbed() {\n MainConfig mainConfig = new MainConfig();\n String title = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedTitle(), mainConfig.getDembedTitle());\n String colour = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedColour(), mainConfig.getDembedColour());\n String footer = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedFooter(), mainConfig.getDembedFooter());", "score": 0.8800141215324402 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " String dembedTitle = mainConfig.getDembedTitle();\n String dwebhookurl = mainConfig.getDwebhookurl();\n String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl();\n String dwebhookUserName = mainConfig.getDwebhookUserName();\n String dembedUrl = mainConfig.getDembedUrl();\n String dembedColour = mainConfig.getDembedColour();\n String dembedFooter = mainConfig.getDembedFooter();\n String dembedImage = mainConfig.getDembedImage();\n String dembedThumbnail = mainConfig.getDembedThumbnail();\n String dembedDescription = \"Description is Empty !\";", "score": 0.876825213432312 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " public DescriptionGenerator(Leaderboard leaderboard) {\n this.leaderboard = leaderboard;\n embedDescriptionlist = leaderboard.getConfig().getEmbedDescription();\n topList = leaderboard.getTopList();\n numberOfFloatingPoints = leaderboard.getConfig().getFloatingpoints();\n isHigherBetter = leaderboard.getConfig().isHigherisbetter();\n }\n public DescriptionGenerator(String leaderboardname) {\n this.leaderboard = new Leaderboard(leaderboardname);\n embedDescriptionlist = leaderboard.getConfig().getEmbedDescription();", "score": 0.8729463815689087 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " String embedFooter = leaderboardConfig.getEmbedFooter();\n String embedImage = leaderboardConfig.getEmbedImage();\n String embedThumbnail = leaderboardConfig.getEmbedThumbnail();\n //checking if leaderboard config values are null, if it is getting default values from main config\n webhookurl = getOrDefault(webhookurl, dwebhookurl);\n webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl);\n webhookUserName = getOrDefault(webhookUserName, dwebhookUserName);\n embedTitle = getOrDefault(embedTitle, dembedTitle);\n embedUrl = getOrDefault(embedUrl, dembedUrl);\n embedColour = getOrDefault(embedColour, dembedColour);", "score": 0.8687528967857361 } ]
java
this.leaderboardversion = mainConfig.getPluginVersion();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.configuration.file.FileConfiguration; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Configs.CustomConfig; import java.util.ArrayList; import java.util.List; public class LeaderboardConfig { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); private String name; private FileConfiguration config; private String placeholder; private int top; private String delay; private boolean refreshOnSent; private String metric; private boolean higherisbetter; private int floatingpoints; private String webhookurl; private String webhookAvatarUrl; private String webhookUserName; private String embedTitle; private List<String> embedDescription; private String embedUrl; private String embedColour; private String embedFooter; private String embedImage; private String embedThumbnail; private String leaderboardversion; private final CustomConfig customConfig; //Constructer for load exciting leaderboardConfig public LeaderboardConfig(String name) { this.name = name; customConfig = new CustomConfig(name); config
= customConfig.get();
load(); } //Constructer for create new LeaderboardConfig public LeaderboardConfig(String name, String placeholder, int top, String delay) { MainConfig mainConfig = new MainConfig(); this.name = name; this.placeholder = placeholder; this.top = top; this.delay = delay; this.refreshOnSent = false; this.metric = "-"; this.higherisbetter = true; this.floatingpoints = 0; this.webhookurl = "-"; this.webhookAvatarUrl = "-"; this.webhookUserName = "-"; this.embedTitle = "-"; List<String> description = new ArrayList<>(); description.add("{toplist}"); this.embedDescription = description; this.embedUrl = "-"; this.embedColour = "-"; this.embedFooter = "-"; this.embedImage = "-"; this.embedThumbnail = "-"; this.leaderboardversion = mainConfig.getPluginVersion(); customConfig = new CustomConfig(name); customConfig.setup(); config = customConfig.get(); save(); } //save methode public void save() { config.set("placeholder", placeholder); config.set("top", top); config.set("delay", delay); config.set("refresh-database-onsent", refreshOnSent); config.set("metric", metric); config.set("higherisbetter", higherisbetter); config.set("floatingpoints", floatingpoints); config.set("webhook-url", webhookurl); config.set("webhook-avatar-url", webhookAvatarUrl); config.set("webhook-user-name", webhookUserName); config.set("embed-title", embedTitle); config.set("embed-description", embedDescription); config.set("embed-url", embedUrl); config.set("embed-colour", embedColour); config.set("embed-footer", embedFooter); config.set("embed-image", embedImage); config.set("embed-thumbnail", embedThumbnail); config.set("leaderboard-version", leaderboardversion); customConfig.save(); customConfig.reload(); } //load methode public void load(){ this.placeholder = config.getString("placeholder"); this.top = config.getInt("top"); this.delay = config.getString("delay"); this.refreshOnSent = config.getBoolean("refresh-database-onsent"); this.metric = config.getString("metric"); this.higherisbetter = config.getBoolean("higherisbetter"); this.floatingpoints = config.getInt("floatingpoints"); this.webhookurl = config.getString("webhook-url"); this.webhookAvatarUrl = config.getString("webhook-avatar-url"); this.webhookUserName = config.getString("webhook-user-name"); this.embedTitle = config.getString("embed-title"); this.embedDescription = config.getStringList("embed-description"); this.embedUrl = config.getString("embed-url"); this.embedColour = config.getString("embed-colour"); this.embedFooter = config.getString("embed-footer"); this.embedImage = config.getString("embed-image"); this.embedThumbnail = config.getString("embed-thumbnail"); this.leaderboardversion = config.getString("leaderboard-version"); } //getters and setters public String getLeaderboardversion() { return leaderboardversion; } public void setLeaderboardversion(String leaderboardversion) { this.leaderboardversion = leaderboardversion; } public String getMetric() { String output = ""; if (!metric.equals(null) && !metric.equals("-")){ output = metric; } return output; } public void setMetric(String metric) { this.metric = metric; } public boolean isHigherisbetter() { return higherisbetter; } public void setHigherisbetter(boolean higherisbetter) { this.higherisbetter = higherisbetter; } public int getFloatingpoints() { return floatingpoints; } public void setFloatingpoints(int floatingpoints) { this.floatingpoints = floatingpoints; } public boolean isRefreshOnSent() { return refreshOnSent; } public void setRefreshOnSent(boolean refreshOnSent) { this.refreshOnSent = refreshOnSent; } public List<String> getEmbedDescription() { return embedDescription; } public void setEmbedDescription(List<String> embedDescription) { this.embedDescription = embedDescription; } public String getName() { return name; } public void setName(String name) { this.name = name; } public FileConfiguration getConfig() { return config; } public void setConfig(FileConfiguration config) { this.config = config; } public String getPlaceholder() { return placeholder; } public void setPlaceholder(String placeholder) { this.placeholder = placeholder; } public int getTop() { return top; } public void setTop(int top) { this.top = top; } public String getDelay() { return delay; } public void setDelay(String delay) { this.delay = delay; } public String getWebhookurl() { return webhookurl; } public void setWebhookurl(String webhookurl) { this.webhookurl = webhookurl; } public String getWebhookAvatarUrl() { return webhookAvatarUrl; } public void setWebhookAvatarUrl(String webhookAvatarUrl) { this.webhookAvatarUrl = webhookAvatarUrl; } public String getWebhookUserName() { return webhookUserName; } public void setWebhookUserName(String webhookUserName) { this.webhookUserName = webhookUserName; } public String getEmbedTitle() { return embedTitle; } public void setEmbedTitle(String embedTitle) { this.embedTitle = embedTitle; } public String getEmbedUrl() { return embedUrl; } public void setEmbedUrl(String embedUrl) { this.embedUrl = embedUrl; } public String getEmbedColour() { return embedColour; } public void setEmbedColour(String embedColour) { this.embedColour = embedColour; } public String getEmbedFooter() { return embedFooter; } public void setEmbedFooter(String embedFooter) { this.embedFooter = embedFooter; } public String getEmbedImage() { return embedImage; } public void setEmbedImage(String embedImage) { this.embedImage = embedImage; } public String getEmbedThumbnail() { return embedThumbnail; } public void setEmbedThumbnail(String embedThumbnail) { this.embedThumbnail = embedThumbnail; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " }\n //constructer for create leaderboard\n public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){\n this.name = name;\n MainConfig mainConfig = new MainConfig();\n List<String> leaderboards = mainConfig.getLeaderboardsList();\n leaderboards.add(name);\n mainConfig.setLeaderboardsList(leaderboards);\n mainConfig.saveConfig();\n leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig", "score": 0.8827280402183533 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " //getting leaderboard's values from leaderboard config\n String placeholder = leaderboardConfig.getPlaceholder();\n int top = leaderboardConfig.getTop();\n String delay = leaderboardConfig.getDelay();\n String webhookurl = leaderboardConfig.getWebhookurl();\n String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl();\n String webhookUserName = leaderboardConfig.getWebhookUserName();\n String embedTitle = leaderboardConfig.getEmbedTitle();\n String embedUrl = leaderboardConfig.getEmbedUrl();\n String embedColour = leaderboardConfig.getEmbedColour();", "score": 0.878699779510498 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8779623508453369 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance();\n public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None}\n private final LeaderboardConfig leaderboardConfig;\n private final String name;\n private final TopList topList;\n //constructer for load leaderboard\n public Leaderboard(String name) {\n this.name = name;\n leaderboardConfig = new LeaderboardConfig(name);\n topList = new TopList(leaderboardConfig);", "score": 0.876457929611206 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " String embedFooter = leaderboardConfig.getEmbedFooter();\n String embedImage = leaderboardConfig.getEmbedImage();\n String embedThumbnail = leaderboardConfig.getEmbedThumbnail();\n //checking if leaderboard config values are null, if it is getting default values from main config\n webhookurl = getOrDefault(webhookurl, dwebhookurl);\n webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl);\n webhookUserName = getOrDefault(webhookUserName, dwebhookUserName);\n embedTitle = getOrDefault(embedTitle, dembedTitle);\n embedUrl = getOrDefault(embedUrl, dembedUrl);\n embedColour = getOrDefault(embedColour, dembedColour);", "score": 0.875036358833313 } ]
java
= customConfig.get();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.configuration.file.FileConfiguration; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Configs.CustomConfig; import java.util.ArrayList; import java.util.List; public class LeaderboardConfig { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); private String name; private FileConfiguration config; private String placeholder; private int top; private String delay; private boolean refreshOnSent; private String metric; private boolean higherisbetter; private int floatingpoints; private String webhookurl; private String webhookAvatarUrl; private String webhookUserName; private String embedTitle; private List<String> embedDescription; private String embedUrl; private String embedColour; private String embedFooter; private String embedImage; private String embedThumbnail; private String leaderboardversion; private final CustomConfig customConfig; //Constructer for load exciting leaderboardConfig public LeaderboardConfig(String name) { this.name = name; customConfig = new CustomConfig(name); config = customConfig.get(); load(); } //Constructer for create new LeaderboardConfig public LeaderboardConfig(String name, String placeholder, int top, String delay) { MainConfig mainConfig = new MainConfig(); this.name = name; this.placeholder = placeholder; this.top = top; this.delay = delay; this.refreshOnSent = false; this.metric = "-"; this.higherisbetter = true; this.floatingpoints = 0; this.webhookurl = "-"; this.webhookAvatarUrl = "-"; this.webhookUserName = "-"; this.embedTitle = "-"; List<String> description = new ArrayList<>(); description.add("{toplist}"); this.embedDescription = description; this.embedUrl = "-"; this.embedColour = "-"; this.embedFooter = "-"; this.embedImage = "-"; this.embedThumbnail = "-"; this.leaderboardversion = mainConfig.getPluginVersion(); customConfig = new CustomConfig(name);
customConfig.setup();
config = customConfig.get(); save(); } //save methode public void save() { config.set("placeholder", placeholder); config.set("top", top); config.set("delay", delay); config.set("refresh-database-onsent", refreshOnSent); config.set("metric", metric); config.set("higherisbetter", higherisbetter); config.set("floatingpoints", floatingpoints); config.set("webhook-url", webhookurl); config.set("webhook-avatar-url", webhookAvatarUrl); config.set("webhook-user-name", webhookUserName); config.set("embed-title", embedTitle); config.set("embed-description", embedDescription); config.set("embed-url", embedUrl); config.set("embed-colour", embedColour); config.set("embed-footer", embedFooter); config.set("embed-image", embedImage); config.set("embed-thumbnail", embedThumbnail); config.set("leaderboard-version", leaderboardversion); customConfig.save(); customConfig.reload(); } //load methode public void load(){ this.placeholder = config.getString("placeholder"); this.top = config.getInt("top"); this.delay = config.getString("delay"); this.refreshOnSent = config.getBoolean("refresh-database-onsent"); this.metric = config.getString("metric"); this.higherisbetter = config.getBoolean("higherisbetter"); this.floatingpoints = config.getInt("floatingpoints"); this.webhookurl = config.getString("webhook-url"); this.webhookAvatarUrl = config.getString("webhook-avatar-url"); this.webhookUserName = config.getString("webhook-user-name"); this.embedTitle = config.getString("embed-title"); this.embedDescription = config.getStringList("embed-description"); this.embedUrl = config.getString("embed-url"); this.embedColour = config.getString("embed-colour"); this.embedFooter = config.getString("embed-footer"); this.embedImage = config.getString("embed-image"); this.embedThumbnail = config.getString("embed-thumbnail"); this.leaderboardversion = config.getString("leaderboard-version"); } //getters and setters public String getLeaderboardversion() { return leaderboardversion; } public void setLeaderboardversion(String leaderboardversion) { this.leaderboardversion = leaderboardversion; } public String getMetric() { String output = ""; if (!metric.equals(null) && !metric.equals("-")){ output = metric; } return output; } public void setMetric(String metric) { this.metric = metric; } public boolean isHigherisbetter() { return higherisbetter; } public void setHigherisbetter(boolean higherisbetter) { this.higherisbetter = higherisbetter; } public int getFloatingpoints() { return floatingpoints; } public void setFloatingpoints(int floatingpoints) { this.floatingpoints = floatingpoints; } public boolean isRefreshOnSent() { return refreshOnSent; } public void setRefreshOnSent(boolean refreshOnSent) { this.refreshOnSent = refreshOnSent; } public List<String> getEmbedDescription() { return embedDescription; } public void setEmbedDescription(List<String> embedDescription) { this.embedDescription = embedDescription; } public String getName() { return name; } public void setName(String name) { this.name = name; } public FileConfiguration getConfig() { return config; } public void setConfig(FileConfiguration config) { this.config = config; } public String getPlaceholder() { return placeholder; } public void setPlaceholder(String placeholder) { this.placeholder = placeholder; } public int getTop() { return top; } public void setTop(int top) { this.top = top; } public String getDelay() { return delay; } public void setDelay(String delay) { this.delay = delay; } public String getWebhookurl() { return webhookurl; } public void setWebhookurl(String webhookurl) { this.webhookurl = webhookurl; } public String getWebhookAvatarUrl() { return webhookAvatarUrl; } public void setWebhookAvatarUrl(String webhookAvatarUrl) { this.webhookAvatarUrl = webhookAvatarUrl; } public String getWebhookUserName() { return webhookUserName; } public void setWebhookUserName(String webhookUserName) { this.webhookUserName = webhookUserName; } public String getEmbedTitle() { return embedTitle; } public void setEmbedTitle(String embedTitle) { this.embedTitle = embedTitle; } public String getEmbedUrl() { return embedUrl; } public void setEmbedUrl(String embedUrl) { this.embedUrl = embedUrl; } public String getEmbedColour() { return embedColour; } public void setEmbedColour(String embedColour) { this.embedColour = embedColour; } public String getEmbedFooter() { return embedFooter; } public void setEmbedFooter(String embedFooter) { this.embedFooter = embedFooter; } public String getEmbedImage() { return embedImage; } public void setEmbedImage(String embedImage) { this.embedImage = embedImage; } public String getEmbedThumbnail() { return embedThumbnail; } public void setEmbedThumbnail(String embedThumbnail) { this.embedThumbnail = embedThumbnail; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.894758939743042 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " public DescriptionGenerator(Leaderboard leaderboard) {\n this.leaderboard = leaderboard;\n embedDescriptionlist = leaderboard.getConfig().getEmbedDescription();\n topList = leaderboard.getTopList();\n numberOfFloatingPoints = leaderboard.getConfig().getFloatingpoints();\n isHigherBetter = leaderboard.getConfig().isHigherisbetter();\n }\n public DescriptionGenerator(String leaderboardname) {\n this.leaderboard = new Leaderboard(leaderboardname);\n embedDescriptionlist = leaderboard.getConfig().getEmbedDescription();", "score": 0.8769599199295044 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " config.set(\"leaderboards\", leaderboardsList);\n config.set(\"webhook-url\", dwebhookurl);\n config.set(\"webhook-avatar-url\", dwebhookAvatarUrl);\n config.set(\"webhook-user-name\", dwebhookUserName);\n config.set(\"embed-title\", dembedTitle);\n config.set(\"embed-url\", dembedUrl);\n config.set(\"embed-colour\", dembedColour);\n config.set(\"embed-footer\", dembedFooter);\n config.set(\"embed-image\", dembedImage);\n config.set(\"embed-thumbnail\", dembedThumbnail);", "score": 0.8668445348739624 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " this.leaderboard = leaderboard;\n }\n private String getDefaultIfNullOrEmpty(String value, String defaultValue) {\n return (value == null || value.isEmpty() || value.equals(\"-\")) ? defaultValue : value;\n }\n public DiscordsrvEmbed getDiscordsrvEmbed() {\n MainConfig mainConfig = new MainConfig();\n String title = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedTitle(), mainConfig.getDembedTitle());\n String colour = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedColour(), mainConfig.getDembedColour());\n String footer = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedFooter(), mainConfig.getDembedFooter());", "score": 0.8579127192497253 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/ConfigManager.java", "retrieved_chunk": " plugin.saveDefaultConfig();\n MainConfig mainConfig = new MainConfig();\n List<String> itemList = mainConfig.getLeaderboardsList();\n int scheduleDelay = mainConfig.getScheduleDelayMins();\n for (String lb : itemList) {\n CustomConfig c1 = new CustomConfig(lb);\n c1.setup();\n c1.get().options().copyDefaults(true);\n c1.save();\n }", "score": 0.8565906286239624 } ]
java
customConfig.setup();
package org.kasun.discordleaderboards.Schedules; import org.kasun.discordleaderboards.Database.Cache; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Utils.SqlUtils; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.sql.Timestamp; public class Schedule { private final String delay; private final Leaderboard leaderboard; private boolean isalredysent; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; public Schedule(Leaderboard leaderboard) { this.leaderboard = leaderboard; delay = leaderboard.getConfig().getDelay(); } public void run() { if (isAlredySent()){ Timestamp currentTime = TimeUtils.getCurrentTimeStamp(); Timestamp lastsent = getLastSent(); switch (delay.toLowerCase()){ case "live": Cache cache = new Cache(leaderboard);
if (cache.isDiffernt()){
leaderboard.send(); cache.setCache(); } break; case "hourly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORHOUR){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "daily": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORDAY){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "weekly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORWEEK){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "monthly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSSFORMONTH){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; default: break; } }else { leaderboard.send(); setLastSent(); } } public void setLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp currenttimestamp = TimeUtils.getCurrentTimeStamp(); SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp); } public Timestamp getLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp lastsent = SqlUtils.getScheduleLastSent(leaderboardname); return lastsent; } public boolean isAlredySent(){ String leaderboardname = leaderboard.getName(); isalredysent = SqlUtils.isScheduleAlredySent(leaderboardname); return isalredysent; } public void deleteDataIfNeeded(){ boolean isrefreshonsent = leaderboard.getConfig().isRefreshOnSent(); String ColumnName = leaderboard.getConfig().getPlaceholder().substring(1, leaderboard.getConfig().getPlaceholder().length() - 1); String tablename = "UserData"; if (isrefreshonsent){ SqlUtils.deleteAllValues(tablename, ColumnName); } } }
src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Cache.java", "retrieved_chunk": " public void setCache(){\n String leaderboardname = leaderboard.getName();\n SqlUtils.setCache(leaderboardname, cache);\n }\n public String getCache(){\n String leaderboardname = leaderboard.getName();\n return SqlUtils.getCache(leaderboardname);\n }\n public boolean isDiffernt(){\n String cache = getCache();", "score": 0.8730597496032715 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " public static boolean isScheduleAlredySent(String leaderboard){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n int count = rs.getInt(\"count\");", "score": 0.8580363392829895 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT \" + \"LastSent\" + \" FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n lastsent = rs.getTimestamp(\"LastSent\");\n }", "score": 0.8489136099815369 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " }\n public static String getCache(String leaderboard) {\n String cache = null;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n PreparedStatement preparedStatement;\n ResultSet resultSet;\n try {\n Connection conn = database.getConnection();\n preparedStatement = conn.prepareStatement(\"SELECT Cache FROM LiveCache WHERE Leaderboard = ?\");", "score": 0.8411946892738342 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/ScheduleManager.java", "retrieved_chunk": " int scheduleDelay = mainConfig.getScheduleDelayMins();\n DiscordLeaderboards plugin = DiscordLeaderboards.getInstance();\n new BukkitRunnable() {\n @Override\n public void run() {\n // This code will run every x minutes\n List<String> itemList = mainConfig.getLeaderboardsList();\n for (String leaderboardname : itemList) {\n Leaderboard leaderboard = new Leaderboard(leaderboardname);\n Schedule schedule = new Schedule(leaderboard);", "score": 0.8386193513870239 } ]
java
if (cache.isDiffernt()){
package org.kasun.discordleaderboards.DiscordSRV; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Leaderboard.DescriptionGenerator; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Leaderboard.TopList; public class LeaderboardDiscordSrvEmbed { private Leaderboard leaderboard; private DiscordsrvEmbed discordsrvEmbed; private TopList topList; public LeaderboardDiscordSrvEmbed(Leaderboard leaderboard) { this.leaderboard = leaderboard; } private String getDefaultIfNullOrEmpty(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } public DiscordsrvEmbed getDiscordsrvEmbed() { MainConfig mainConfig = new MainConfig(); String title = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedTitle(), mainConfig.getDembedTitle()); String colour = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedColour(), mainConfig.getDembedColour()); String footer = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedFooter(), mainConfig.getDembedFooter()); String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage()); String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail()); discordsrvEmbed = new DiscordsrvEmbed(); discordsrvEmbed.setEmbedTitle(title); discordsrvEmbed.setEmbedColour(colour); discordsrvEmbed.setEmbedFooter(footer); discordsrvEmbed.setEmbedImage(image); discordsrvEmbed.setEmbedThumbnail(thumb); DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard); discordsrvEmbed.setEmbedDescription
(descriptionGenerator.getDescription(false));
return discordsrvEmbed; } }
src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/DiscordsrvEmbed.java", "retrieved_chunk": "package org.kasun.discordleaderboards.DiscordSRV;\nimport github.scarsz.discordsrv.dependencies.jda.api.EmbedBuilder;\nimport github.scarsz.discordsrv.dependencies.jda.api.entities.MessageEmbed;\nimport java.awt.*;\npublic class DiscordsrvEmbed {\n private String embedTitle;\n private String embedColour;\n private String embedFooter;\n private String embedImage;\n private String embedThumbnail;", "score": 0.9020099639892578 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " String embedFooter = leaderboardConfig.getEmbedFooter();\n String embedImage = leaderboardConfig.getEmbedImage();\n String embedThumbnail = leaderboardConfig.getEmbedThumbnail();\n //checking if leaderboard config values are null, if it is getting default values from main config\n webhookurl = getOrDefault(webhookurl, dwebhookurl);\n webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl);\n webhookUserName = getOrDefault(webhookUserName, dwebhookUserName);\n embedTitle = getOrDefault(embedTitle, dembedTitle);\n embedUrl = getOrDefault(embedUrl, dembedUrl);\n embedColour = getOrDefault(embedColour, dembedColour);", "score": 0.8950989246368408 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " public DescriptionGenerator(Leaderboard leaderboard) {\n this.leaderboard = leaderboard;\n embedDescriptionlist = leaderboard.getConfig().getEmbedDescription();\n topList = leaderboard.getTopList();\n numberOfFloatingPoints = leaderboard.getConfig().getFloatingpoints();\n isHigherBetter = leaderboard.getConfig().isHigherisbetter();\n }\n public DescriptionGenerator(String leaderboardname) {\n this.leaderboard = new Leaderboard(leaderboardname);\n embedDescriptionlist = leaderboard.getConfig().getEmbedDescription();", "score": 0.8937249183654785 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " String dembedTitle = mainConfig.getDembedTitle();\n String dwebhookurl = mainConfig.getDwebhookurl();\n String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl();\n String dwebhookUserName = mainConfig.getDwebhookUserName();\n String dembedUrl = mainConfig.getDembedUrl();\n String dembedColour = mainConfig.getDembedColour();\n String dembedFooter = mainConfig.getDembedFooter();\n String dembedImage = mainConfig.getDembedImage();\n String dembedThumbnail = mainConfig.getDembedThumbnail();\n String dembedDescription = \"Description is Empty !\";", "score": 0.8729792833328247 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " }\n DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject();\n if (embedTitle != null && !embedTitle.equals(\"\") && !embedTitle.equals(\"-\")){\n embed.setTitle(embedTitle);\n }\n if (embedUrl != null && !embedUrl.equals(\"\") && !embedUrl.equals(\"-\")){\n embed.setUrl(embedUrl);\n }\n if (embedColour != null && !embedColour.equals(\"\") && !embedColour.equals(\"-\")){\n embed.setColor(Color.decode(embedColour));", "score": 0.872736930847168 } ]
java
(descriptionGenerator.getDescription(false));
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.configuration.file.FileConfiguration; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Configs.CustomConfig; import java.util.ArrayList; import java.util.List; public class LeaderboardConfig { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); private String name; private FileConfiguration config; private String placeholder; private int top; private String delay; private boolean refreshOnSent; private String metric; private boolean higherisbetter; private int floatingpoints; private String webhookurl; private String webhookAvatarUrl; private String webhookUserName; private String embedTitle; private List<String> embedDescription; private String embedUrl; private String embedColour; private String embedFooter; private String embedImage; private String embedThumbnail; private String leaderboardversion; private final CustomConfig customConfig; //Constructer for load exciting leaderboardConfig public LeaderboardConfig(String name) { this.name = name; customConfig = new CustomConfig(name); config = customConfig.get(); load(); } //Constructer for create new LeaderboardConfig public LeaderboardConfig(String name, String placeholder, int top, String delay) { MainConfig mainConfig = new MainConfig(); this.name = name; this.placeholder = placeholder; this.top = top; this.delay = delay; this.refreshOnSent = false; this.metric = "-"; this.higherisbetter = true; this.floatingpoints = 0; this.webhookurl = "-"; this.webhookAvatarUrl = "-"; this.webhookUserName = "-"; this.embedTitle = "-"; List<String> description = new ArrayList<>(); description.add("{toplist}"); this.embedDescription = description; this.embedUrl = "-"; this.embedColour = "-"; this.embedFooter = "-"; this.embedImage = "-"; this.embedThumbnail = "-"; this.leaderboardversion = mainConfig.getPluginVersion(); customConfig = new CustomConfig(name); customConfig.setup(); config = customConfig.get(); save(); } //save methode public void save() { config.set("placeholder", placeholder); config.set("top", top); config.set("delay", delay); config.set("refresh-database-onsent", refreshOnSent); config.set("metric", metric); config.set("higherisbetter", higherisbetter); config.set("floatingpoints", floatingpoints); config.set("webhook-url", webhookurl); config.set("webhook-avatar-url", webhookAvatarUrl); config.set("webhook-user-name", webhookUserName); config.set("embed-title", embedTitle); config.set("embed-description", embedDescription); config.set("embed-url", embedUrl); config.set("embed-colour", embedColour); config.set("embed-footer", embedFooter); config.set("embed-image", embedImage); config.set("embed-thumbnail", embedThumbnail); config.set("leaderboard-version", leaderboardversion); customConfig.save();
customConfig.reload();
} //load methode public void load(){ this.placeholder = config.getString("placeholder"); this.top = config.getInt("top"); this.delay = config.getString("delay"); this.refreshOnSent = config.getBoolean("refresh-database-onsent"); this.metric = config.getString("metric"); this.higherisbetter = config.getBoolean("higherisbetter"); this.floatingpoints = config.getInt("floatingpoints"); this.webhookurl = config.getString("webhook-url"); this.webhookAvatarUrl = config.getString("webhook-avatar-url"); this.webhookUserName = config.getString("webhook-user-name"); this.embedTitle = config.getString("embed-title"); this.embedDescription = config.getStringList("embed-description"); this.embedUrl = config.getString("embed-url"); this.embedColour = config.getString("embed-colour"); this.embedFooter = config.getString("embed-footer"); this.embedImage = config.getString("embed-image"); this.embedThumbnail = config.getString("embed-thumbnail"); this.leaderboardversion = config.getString("leaderboard-version"); } //getters and setters public String getLeaderboardversion() { return leaderboardversion; } public void setLeaderboardversion(String leaderboardversion) { this.leaderboardversion = leaderboardversion; } public String getMetric() { String output = ""; if (!metric.equals(null) && !metric.equals("-")){ output = metric; } return output; } public void setMetric(String metric) { this.metric = metric; } public boolean isHigherisbetter() { return higherisbetter; } public void setHigherisbetter(boolean higherisbetter) { this.higherisbetter = higherisbetter; } public int getFloatingpoints() { return floatingpoints; } public void setFloatingpoints(int floatingpoints) { this.floatingpoints = floatingpoints; } public boolean isRefreshOnSent() { return refreshOnSent; } public void setRefreshOnSent(boolean refreshOnSent) { this.refreshOnSent = refreshOnSent; } public List<String> getEmbedDescription() { return embedDescription; } public void setEmbedDescription(List<String> embedDescription) { this.embedDescription = embedDescription; } public String getName() { return name; } public void setName(String name) { this.name = name; } public FileConfiguration getConfig() { return config; } public void setConfig(FileConfiguration config) { this.config = config; } public String getPlaceholder() { return placeholder; } public void setPlaceholder(String placeholder) { this.placeholder = placeholder; } public int getTop() { return top; } public void setTop(int top) { this.top = top; } public String getDelay() { return delay; } public void setDelay(String delay) { this.delay = delay; } public String getWebhookurl() { return webhookurl; } public void setWebhookurl(String webhookurl) { this.webhookurl = webhookurl; } public String getWebhookAvatarUrl() { return webhookAvatarUrl; } public void setWebhookAvatarUrl(String webhookAvatarUrl) { this.webhookAvatarUrl = webhookAvatarUrl; } public String getWebhookUserName() { return webhookUserName; } public void setWebhookUserName(String webhookUserName) { this.webhookUserName = webhookUserName; } public String getEmbedTitle() { return embedTitle; } public void setEmbedTitle(String embedTitle) { this.embedTitle = embedTitle; } public String getEmbedUrl() { return embedUrl; } public void setEmbedUrl(String embedUrl) { this.embedUrl = embedUrl; } public String getEmbedColour() { return embedColour; } public void setEmbedColour(String embedColour) { this.embedColour = embedColour; } public String getEmbedFooter() { return embedFooter; } public void setEmbedFooter(String embedFooter) { this.embedFooter = embedFooter; } public String getEmbedImage() { return embedImage; } public void setEmbedImage(String embedImage) { this.embedImage = embedImage; } public String getEmbedThumbnail() { return embedThumbnail; } public void setEmbedThumbnail(String embedThumbnail) { this.embedThumbnail = embedThumbnail; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " config.set(\"leaderboards\", leaderboardsList);\n config.set(\"webhook-url\", dwebhookurl);\n config.set(\"webhook-avatar-url\", dwebhookAvatarUrl);\n config.set(\"webhook-user-name\", dwebhookUserName);\n config.set(\"embed-title\", dembedTitle);\n config.set(\"embed-url\", dembedUrl);\n config.set(\"embed-colour\", dembedColour);\n config.set(\"embed-footer\", dembedFooter);\n config.set(\"embed-image\", dembedImage);\n config.set(\"embed-thumbnail\", dembedThumbnail);", "score": 0.923808217048645 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " String embedFooter = leaderboardConfig.getEmbedFooter();\n String embedImage = leaderboardConfig.getEmbedImage();\n String embedThumbnail = leaderboardConfig.getEmbedThumbnail();\n //checking if leaderboard config values are null, if it is getting default values from main config\n webhookurl = getOrDefault(webhookurl, dwebhookurl);\n webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl);\n webhookUserName = getOrDefault(webhookUserName, dwebhookUserName);\n embedTitle = getOrDefault(embedTitle, dembedTitle);\n embedUrl = getOrDefault(embedUrl, dembedUrl);\n embedColour = getOrDefault(embedColour, dembedColour);", "score": 0.8752495050430298 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8741157650947571 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " dwebhookAvatarUrl = config.getString(\"webhook-avatar-url\");\n dwebhookUserName = config.getString(\"webhook-user-name\");\n dembedTitle = config.getString(\"embed-title\");\n dembedUrl = config.getString(\"embed-url\");\n dembedColour = config.getString(\"embed-colour\");\n dembedFooter = config.getString(\"embed-footer\");\n dembedImage = config.getString(\"embed-image\");\n dembedThumbnail = config.getString(\"embed-thumbnail\");\n storageType = config.getString(\"storage-method\");\n mysqlAddress = config.getString(\"address\");", "score": 0.8740174770355225 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/ConfigManager.java", "retrieved_chunk": " plugin.saveDefaultConfig();\n MainConfig mainConfig = new MainConfig();\n List<String> itemList = mainConfig.getLeaderboardsList();\n int scheduleDelay = mainConfig.getScheduleDelayMins();\n for (String lb : itemList) {\n CustomConfig c1 = new CustomConfig(lb);\n c1.setup();\n c1.get().options().copyDefaults(true);\n c1.save();\n }", "score": 0.8726084232330322 } ]
java
customConfig.reload();
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String
content = jsonData.getDataAttributes().get("content");
String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/ChatGptResponse.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.List;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true )\npublic class ChatGptResponse {\n private List<Choice> choices;\n @Data\n @JsonIgnoreProperties(ignoreUnknown = true )", "score": 0.8311453461647034 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptRequest.java", "retrieved_chunk": "package work.noice.core.beans;\nimport lombok.Data;\nimport java.util.List;\nimport java.util.ArrayList;\n@Data\npublic class ChatGptRequest {\n private final int max_tokens;\n private final String model;\n private List<Message> messages;\n public ChatGptRequest(String prompt, String model, String role) {", "score": 0.8187640309333801 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptRequest.java", "retrieved_chunk": " this.max_tokens = 1500;\n this.model = model;\n this.messages = new ArrayList<>();\n Message message = new Message();\n message.setRole(role);\n message.setContent(prompt);\n this.messages.add(message);\n }\n}", "score": 0.8032448291778564 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.7747286558151245 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptResponse.java", "retrieved_chunk": " public static class Choice {\n private Message message; \n }\n}", "score": 0.767450749874115 } ]
java
content = jsonData.getDataAttributes().get("content");
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String
companyProductName = jsonData.getDataAttributes().get("companyProductName");
String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": " }\n public void setDataAttributes(Map<String, String> dataAttributes) {\n this.dataAttributes = dataAttributes;\n }\n public void setTemplateId(String templateId) {\n this.templateId = templateId;\n }\n}", "score": 0.8040519952774048 }, { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.Map;\npublic class Data {\n private String templateId;\n private Map<String, String> dataAttributes;\n public String getTemplateId() {\n return templateId;\n }\n public Map<String, String> getDataAttributes() {\n return dataAttributes;", "score": 0.8008885383605957 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " List<DomNode> coreComponents = page.getByXPath(\"//div[contains(@class, 'cmp-image')]\");\n for (DomNode child: coreComponents) {\n String src = null;\n String width = null;\n if (child.getAttributes().getNamedItem(\"data-cmp-src\") != null) {\n src = child.getAttributes().getNamedItem(\"data-cmp-src\").getNodeValue();\n }\n if (child.getAttributes().getNamedItem(\"data-cmp-widths\") != null) {\n width = child.getAttributes().getNamedItem(\"data-cmp-widths\").getNodeValue();\n }", "score": 0.7705885171890259 }, { "filename": "core/src/main/java/work/noice/core/services/impl/OpaxServiceImpl.java", "retrieved_chunk": " toolbarEnabled = configuration.getToolbarEnabled();\n components = configuration.getComponents();\n openAIAPIKey = configuration.getOpenAIAPIKey();\n }\n @Override\n public String getOpenAIAPIKey() {\n return openAIAPIKey;\n }\n @Override\n public boolean getToolbarEnabled() {", "score": 0.7667078375816345 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.7565189599990845 } ]
java
companyProductName = jsonData.getDataAttributes().get("companyProductName");
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String
info = jsonData.getDataAttributes().get("info");
String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.Map;\npublic class Data {\n private String templateId;\n private Map<String, String> dataAttributes;\n public String getTemplateId() {\n return templateId;\n }\n public Map<String, String> getDataAttributes() {\n return dataAttributes;", "score": 0.8033249378204346 }, { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": " }\n public void setDataAttributes(Map<String, String> dataAttributes) {\n this.dataAttributes = dataAttributes;\n }\n public void setTemplateId(String templateId) {\n this.templateId = templateId;\n }\n}", "score": 0.7987247705459595 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.7705377340316772 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " List<DomNode> coreComponents = page.getByXPath(\"//div[contains(@class, 'cmp-image')]\");\n for (DomNode child: coreComponents) {\n String src = null;\n String width = null;\n if (child.getAttributes().getNamedItem(\"data-cmp-src\") != null) {\n src = child.getAttributes().getNamedItem(\"data-cmp-src\").getNodeValue();\n }\n if (child.getAttributes().getNamedItem(\"data-cmp-widths\") != null) {\n width = child.getAttributes().getNamedItem(\"data-cmp-widths\").getNodeValue();\n }", "score": 0.7670457363128662 }, { "filename": "core/src/main/java/work/noice/core/services/impl/OpaxServiceImpl.java", "retrieved_chunk": " toolbarEnabled = configuration.getToolbarEnabled();\n components = configuration.getComponents();\n openAIAPIKey = configuration.getOpenAIAPIKey();\n }\n @Override\n public String getOpenAIAPIKey() {\n return openAIAPIKey;\n }\n @Override\n public boolean getToolbarEnabled() {", "score": 0.7623559832572937 } ]
java
info = jsonData.getDataAttributes().get("info");
package org.kasun.discordleaderboards.DiscordSRV; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Leaderboard.DescriptionGenerator; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Leaderboard.TopList; public class LeaderboardDiscordSrvEmbed { private Leaderboard leaderboard; private DiscordsrvEmbed discordsrvEmbed; private TopList topList; public LeaderboardDiscordSrvEmbed(Leaderboard leaderboard) { this.leaderboard = leaderboard; } private String getDefaultIfNullOrEmpty(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } public DiscordsrvEmbed getDiscordsrvEmbed() { MainConfig mainConfig = new MainConfig(); String title = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedTitle(), mainConfig.getDembedTitle()); String colour = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedColour(), mainConfig.getDembedColour()); String footer = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedFooter(), mainConfig.getDembedFooter()); String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage()); String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail()); discordsrvEmbed = new DiscordsrvEmbed(); discordsrvEmbed.setEmbedTitle(title); discordsrvEmbed.setEmbedColour(colour); discordsrvEmbed.setEmbedFooter(footer);
discordsrvEmbed.setEmbedImage(image);
discordsrvEmbed.setEmbedThumbnail(thumb); DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard); discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false)); return discordsrvEmbed; } }
src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " String embedFooter = leaderboardConfig.getEmbedFooter();\n String embedImage = leaderboardConfig.getEmbedImage();\n String embedThumbnail = leaderboardConfig.getEmbedThumbnail();\n //checking if leaderboard config values are null, if it is getting default values from main config\n webhookurl = getOrDefault(webhookurl, dwebhookurl);\n webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl);\n webhookUserName = getOrDefault(webhookUserName, dwebhookUserName);\n embedTitle = getOrDefault(embedTitle, dembedTitle);\n embedUrl = getOrDefault(embedUrl, dembedUrl);\n embedColour = getOrDefault(embedColour, dembedColour);", "score": 0.9117027521133423 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/DiscordsrvEmbed.java", "retrieved_chunk": "package org.kasun.discordleaderboards.DiscordSRV;\nimport github.scarsz.discordsrv.dependencies.jda.api.EmbedBuilder;\nimport github.scarsz.discordsrv.dependencies.jda.api.entities.MessageEmbed;\nimport java.awt.*;\npublic class DiscordsrvEmbed {\n private String embedTitle;\n private String embedColour;\n private String embedFooter;\n private String embedImage;\n private String embedThumbnail;", "score": 0.9112643599510193 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " String dembedTitle = mainConfig.getDembedTitle();\n String dwebhookurl = mainConfig.getDwebhookurl();\n String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl();\n String dwebhookUserName = mainConfig.getDwebhookUserName();\n String dembedUrl = mainConfig.getDembedUrl();\n String dembedColour = mainConfig.getDembedColour();\n String dembedFooter = mainConfig.getDembedFooter();\n String dembedImage = mainConfig.getDembedImage();\n String dembedThumbnail = mainConfig.getDembedThumbnail();\n String dembedDescription = \"Description is Empty !\";", "score": 0.8930014371871948 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " config.set(\"leaderboards\", leaderboardsList);\n config.set(\"webhook-url\", dwebhookurl);\n config.set(\"webhook-avatar-url\", dwebhookAvatarUrl);\n config.set(\"webhook-user-name\", dwebhookUserName);\n config.set(\"embed-title\", dembedTitle);\n config.set(\"embed-url\", dembedUrl);\n config.set(\"embed-colour\", dembedColour);\n config.set(\"embed-footer\", dembedFooter);\n config.set(\"embed-image\", dembedImage);\n config.set(\"embed-thumbnail\", dembedThumbnail);", "score": 0.8847284317016602 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " }\n DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject();\n if (embedTitle != null && !embedTitle.equals(\"\") && !embedTitle.equals(\"-\")){\n embed.setTitle(embedTitle);\n }\n if (embedUrl != null && !embedUrl.equals(\"\") && !embedUrl.equals(\"-\")){\n embed.setUrl(embedUrl);\n }\n if (embedColour != null && !embedColour.equals(\"\") && !embedColour.equals(\"-\")){\n embed.setColor(Color.decode(embedColour));", "score": 0.8827961683273315 } ]
java
discordsrvEmbed.setEmbedImage(image);
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String
sentence = jsonData.getDataAttributes().get("sentence");
String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.Map;\npublic class Data {\n private String templateId;\n private Map<String, String> dataAttributes;\n public String getTemplateId() {\n return templateId;\n }\n public Map<String, String> getDataAttributes() {\n return dataAttributes;", "score": 0.8031471967697144 }, { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": " }\n public void setDataAttributes(Map<String, String> dataAttributes) {\n this.dataAttributes = dataAttributes;\n }\n public void setTemplateId(String templateId) {\n this.templateId = templateId;\n }\n}", "score": 0.8026443719863892 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.7783037424087524 }, { "filename": "core/src/main/java/work/noice/core/services/impl/OpaxServiceImpl.java", "retrieved_chunk": " toolbarEnabled = configuration.getToolbarEnabled();\n components = configuration.getComponents();\n openAIAPIKey = configuration.getOpenAIAPIKey();\n }\n @Override\n public String getOpenAIAPIKey() {\n return openAIAPIKey;\n }\n @Override\n public boolean getToolbarEnabled() {", "score": 0.7698432207107544 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " List<DomNode> coreComponents = page.getByXPath(\"//div[contains(@class, 'cmp-image')]\");\n for (DomNode child: coreComponents) {\n String src = null;\n String width = null;\n if (child.getAttributes().getNamedItem(\"data-cmp-src\") != null) {\n src = child.getAttributes().getNamedItem(\"data-cmp-src\").getNodeValue();\n }\n if (child.getAttributes().getNamedItem(\"data-cmp-widths\") != null) {\n width = child.getAttributes().getNamedItem(\"data-cmp-widths\").getNodeValue();\n }", "score": 0.7694873809814453 } ]
java
sentence = jsonData.getDataAttributes().get("sentence");
/* * Copyright 2020 Adobe Systems Incorporated * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package work.noice.it.tests; import com.adobe.cq.testing.client.CQClient; import com.adobe.cq.testing.junit.assertion.CQAssert; import com.adobe.cq.testing.junit.rules.CQAuthorClassRule; import com.adobe.cq.testing.junit.rules.CQAuthorPublishClassRule; import com.adobe.cq.testing.junit.rules.CQRule; import com.adobe.cq.testing.junit.rules.Page; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.sling.testing.clients.ClientException; import org.apache.sling.testing.clients.SlingHttpResponse; import org.eclipse.jetty.client.HttpResponse; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.Ignore; import org.slf4j.LoggerFactory; import static java.util.concurrent.TimeUnit.MINUTES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; /** * Validates pages on publish and makes sure that the page renders completely and also * validates all linked resources (images, clientlibs etc). * */ public class PublishPageValidationIT { // the page to test private static final String HOMEPAGE = "/"; // list files which do return a zerobyte response body private static final List<String> ZEROBYTEFILES = Arrays.asList(); private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(PublishPageValidationIT.class); @ClassRule public static final CQAuthorPublishClassRule cqBaseClassRule = new CQAuthorPublishClassRule(true); @Rule public CQRule cqBaseRule = new CQRule(cqBaseClassRule.publishRule); private static HtmlUnitClient adminPublish; @BeforeClass public static void beforeClass() throws ClientException { adminPublish = cqBaseClassRule.publishRule.getAdminClient(CQClient.class).adaptTo(HtmlUnitClient.class); } @AfterClass public static void afterClass() { // As of 2022/10/13, AEM declares 'org.apache.commons.io.IOUtils.closeQuietly' as deprecated, // even though the function has been un-deprecated again in version 2.9.0 of 'commons-io' // (https://issues.apache.org/jira/browse/IO-504); thus a try-catch is used instead. try {
adminPublish.close();
} catch (IOException ignored) {} } @Test @Ignore public void validateHomepage() throws ClientException, IOException, URISyntaxException { String path = HOMEPAGE; verifyPage(adminPublish, path); verifyLinkedResources(adminPublish,path); } private static void verifyPage (HtmlUnitClient client, String path) throws ClientProtocolException, IOException { URI baseURI = client.getUrl(); LOG.info("Using {} as baseURL", baseURI.toString()); HttpGet get = new HttpGet(baseURI.toString() + path); org.apache.http.HttpResponse validationResponse = client.execute(get); assertEquals("Request to [" + get.getURI().toString() + "] does not return expected returncode 200", 200, validationResponse.getStatusLine().getStatusCode()); } private static void verifyLinkedResources(HtmlUnitClient client, String path) throws ClientException, IOException, URISyntaxException { List<URI> references = client.getResourceRefs(path); assertTrue(path + " does not contain any references!", references.size() > 0); for (URI ref : references ) { if (isSameOrigin(client.getUrl(), ref)) { LOG.info("verifying linked resource {}", ref.toString()); SlingHttpResponse response = client.doGet(ref.getPath()); int statusCode = response.getStatusLine().getStatusCode(); int responseSize = response.getContent().length(); assertEquals("Unexpected status returned from [" + ref + "]", 200, statusCode); if (! ZEROBYTEFILES.stream().anyMatch(s -> ref.getPath().startsWith(s))) { if (responseSize == 0) { LOG.warn("Empty response body from [" + ref.getPath() + "], please validate if this is correct"); } } } else { LOG.info("skipping linked resource from another domain {}", ref.toString()); } } } /** Checks if two URIs have the same origin. * * @param uri1 first URI * @param uri2 second URI * @return true if two URI come from the same host, port and use the same scheme */ private static boolean isSameOrigin(URI uri1, URI uri2) { if (!uri1.getScheme().equals(uri2.getScheme())) { return false; } else return uri1.getAuthority().equals(uri2.getAuthority()); } }
it.tests/src/main/java/work/noice/it/tests/PublishPageValidationIT.java
jaketracey-opax-44a71f1
[ { "filename": "it.tests/src/main/java/work/noice/it/tests/GetPageIT.java", "retrieved_chunk": " public CQRule cqBaseRule = new CQRule(cqBaseClassRule.authorRule, cqBaseClassRule.publishRule);\n static CQClient adminAuthor;\n static CQClient adminPublish;\n // Thanks to the CQAuthorClassRule, we can create two CQClient instances\n // bound to the admin user on both the author and publish service.\n @BeforeClass\n public static void beforeClass() throws ClientException {\n adminAuthor = cqBaseClassRule.authorRule.getAdminClient(CQClient.class);\n adminPublish = cqBaseClassRule.publishRule.getAdminClient(CQClient.class);\n }", "score": 0.9152339696884155 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/CreatePageIT.java", "retrieved_chunk": " @Rule\n public Page root = new Page(cqBaseClassRule.authorRule);\n static CQClient adminAuthor;\n // Thanks to the CQAuthorClassRule, we can create a CQClient bound to the\n // admin user on the author instance.\n @BeforeClass\n public static void beforeClass() {\n adminAuthor = cqBaseClassRule.authorRule.getAdminClient(CQClient.class);\n }\n @Test", "score": 0.8738577365875244 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/GetPageIT.java", "retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage work.noice.it.tests;\nimport com.adobe.cq.testing.client.CQClient;\nimport com.adobe.cq.testing.junit.rules.CQAuthorPublishClassRule;\nimport com.adobe.cq.testing.junit.rules.CQRule;\nimport com.adobe.cq.testing.junit.rules.Page;", "score": 0.830419659614563 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/GetPageIT.java", "retrieved_chunk": "public class GetPageIT {\n // The CQAuthorClassRule represents an author service. The rule will read\n // the hostname and port of the author service from the system properties\n // passed to the tests.@ClassRule\n @ClassRule\n public static final CQAuthorPublishClassRule cqBaseClassRule = new CQAuthorPublishClassRule();\n // CQRule decorates your test and adds additional functionality on top of\n // it, like session stickyness, test filtering and identification of the\n // test on the remote service.\n @Rule", "score": 0.8262695670127869 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/CreatePageIT.java", "retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage work.noice.it.tests;\nimport com.adobe.cq.testing.client.CQClient;\nimport com.adobe.cq.testing.junit.assertion.CQAssert;\nimport com.adobe.cq.testing.junit.rules.CQAuthorClassRule;\nimport com.adobe.cq.testing.junit.rules.CQRule;", "score": 0.8200555443763733 } ]
java
adminPublish.close();
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (
jsonData.getTemplateId()) {
case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.Map;\npublic class Data {\n private String templateId;\n private Map<String, String> dataAttributes;\n public String getTemplateId() {\n return templateId;\n }\n public Map<String, String> getDataAttributes() {\n return dataAttributes;", "score": 0.7947010397911072 }, { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": " }\n public void setDataAttributes(Map<String, String> dataAttributes) {\n this.dataAttributes = dataAttributes;\n }\n public void setTemplateId(String templateId) {\n this.templateId = templateId;\n }\n}", "score": 0.7936549186706543 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptRequest.java", "retrieved_chunk": "package work.noice.core.beans;\nimport lombok.Data;\nimport java.util.List;\nimport java.util.ArrayList;\n@Data\npublic class ChatGptRequest {\n private final int max_tokens;\n private final String model;\n private List<Message> messages;\n public ChatGptRequest(String prompt, String model, String role) {", "score": 0.7693434953689575 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptRequest.java", "retrieved_chunk": " this.max_tokens = 1500;\n this.model = model;\n this.messages = new ArrayList<>();\n Message message = new Message();\n message.setRole(role);\n message.setContent(prompt);\n this.messages.add(message);\n }\n}", "score": 0.7662503719329834 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " List<DomNode> coreComponents = page.getByXPath(\"//div[contains(@class, 'cmp-image')]\");\n for (DomNode child: coreComponents) {\n String src = null;\n String width = null;\n if (child.getAttributes().getNamedItem(\"data-cmp-src\") != null) {\n src = child.getAttributes().getNamedItem(\"data-cmp-src\").getNodeValue();\n }\n if (child.getAttributes().getNamedItem(\"data-cmp-widths\") != null) {\n width = child.getAttributes().getNamedItem(\"data-cmp-widths\").getNodeValue();\n }", "score": 0.7648555040359497 } ]
java
jsonData.getTemplateId()) {
package org.kasun.discordleaderboards.Schedules; import org.kasun.discordleaderboards.Database.Cache; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Utils.SqlUtils; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.sql.Timestamp; public class Schedule { private final String delay; private final Leaderboard leaderboard; private boolean isalredysent; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; public Schedule(Leaderboard leaderboard) { this.leaderboard = leaderboard; delay = leaderboard.getConfig().getDelay(); } public void run() { if (isAlredySent()){ Timestamp currentTime = TimeUtils.getCurrentTimeStamp(); Timestamp lastsent = getLastSent(); switch (delay.toLowerCase()){ case "live": Cache cache = new Cache(leaderboard); if (cache.isDiffernt()){ leaderboard.send();
cache.setCache();
} break; case "hourly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORHOUR){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "daily": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORDAY){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "weekly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORWEEK){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "monthly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSSFORMONTH){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; default: break; } }else { leaderboard.send(); setLastSent(); } } public void setLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp currenttimestamp = TimeUtils.getCurrentTimeStamp(); SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp); } public Timestamp getLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp lastsent = SqlUtils.getScheduleLastSent(leaderboardname); return lastsent; } public boolean isAlredySent(){ String leaderboardname = leaderboard.getName(); isalredysent = SqlUtils.isScheduleAlredySent(leaderboardname); return isalredysent; } public void deleteDataIfNeeded(){ boolean isrefreshonsent = leaderboard.getConfig().isRefreshOnSent(); String ColumnName = leaderboard.getConfig().getPlaceholder().substring(1, leaderboard.getConfig().getPlaceholder().length() - 1); String tablename = "UserData"; if (isrefreshonsent){ SqlUtils.deleteAllValues(tablename, ColumnName); } } }
src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": " topList = new TopList(leaderboardConfig);\n }\n public String toString(){\n String placeholder = leaderboardConfig.getPlaceholder();\n int top = leaderboardConfig.getTop();\n return topList.getTopListAsString(false);\n }\n public void send() {\n //getting default values from main config\n MainConfig mainConfig = new MainConfig();", "score": 0.841099739074707 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Cache.java", "retrieved_chunk": " public void setCache(){\n String leaderboardname = leaderboard.getName();\n SqlUtils.setCache(leaderboardname, cache);\n }\n public String getCache(){\n String leaderboardname = leaderboard.getName();\n return SqlUtils.getCache(leaderboardname);\n }\n public boolean isDiffernt(){\n String cache = getCache();", "score": 0.8381450772285461 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " public static boolean isScheduleAlredySent(String leaderboard){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n int count = rs.getInt(\"count\");", "score": 0.8374482989311218 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT \" + \"LastSent\" + \" FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n lastsent = rs.getTimestamp(\"LastSent\");\n }", "score": 0.8347609639167786 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/ScheduleManager.java", "retrieved_chunk": " int scheduleDelay = mainConfig.getScheduleDelayMins();\n DiscordLeaderboards plugin = DiscordLeaderboards.getInstance();\n new BukkitRunnable() {\n @Override\n public void run() {\n // This code will run every x minutes\n List<String> itemList = mainConfig.getLeaderboardsList();\n for (String leaderboardname : itemList) {\n Leaderboard leaderboard = new Leaderboard(leaderboardname);\n Schedule schedule = new Schedule(leaderboard);", "score": 0.8286939859390259 } ]
java
cache.setCache();
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description");
String topic = jsonData.getDataAttributes().get("topic");
String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": " }\n public void setDataAttributes(Map<String, String> dataAttributes) {\n this.dataAttributes = dataAttributes;\n }\n public void setTemplateId(String templateId) {\n this.templateId = templateId;\n }\n}", "score": 0.8010139465332031 }, { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.Map;\npublic class Data {\n private String templateId;\n private Map<String, String> dataAttributes;\n public String getTemplateId() {\n return templateId;\n }\n public Map<String, String> getDataAttributes() {\n return dataAttributes;", "score": 0.7999069094657898 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " List<DomNode> coreComponents = page.getByXPath(\"//div[contains(@class, 'cmp-image')]\");\n for (DomNode child: coreComponents) {\n String src = null;\n String width = null;\n if (child.getAttributes().getNamedItem(\"data-cmp-src\") != null) {\n src = child.getAttributes().getNamedItem(\"data-cmp-src\").getNodeValue();\n }\n if (child.getAttributes().getNamedItem(\"data-cmp-widths\") != null) {\n width = child.getAttributes().getNamedItem(\"data-cmp-widths\").getNodeValue();\n }", "score": 0.7682482600212097 }, { "filename": "core/src/main/java/work/noice/core/services/impl/OpaxServiceImpl.java", "retrieved_chunk": " toolbarEnabled = configuration.getToolbarEnabled();\n components = configuration.getComponents();\n openAIAPIKey = configuration.getOpenAIAPIKey();\n }\n @Override\n public String getOpenAIAPIKey() {\n return openAIAPIKey;\n }\n @Override\n public boolean getToolbarEnabled() {", "score": 0.7638854384422302 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.7603129148483276 } ]
java
String topic = jsonData.getDataAttributes().get("topic");
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String
customerAvatar = jsonData.getDataAttributes().get("customerAvatar");
String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": " }\n public void setDataAttributes(Map<String, String> dataAttributes) {\n this.dataAttributes = dataAttributes;\n }\n public void setTemplateId(String templateId) {\n this.templateId = templateId;\n }\n}", "score": 0.8039703965187073 }, { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.Map;\npublic class Data {\n private String templateId;\n private Map<String, String> dataAttributes;\n public String getTemplateId() {\n return templateId;\n }\n public Map<String, String> getDataAttributes() {\n return dataAttributes;", "score": 0.7996811866760254 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " List<DomNode> coreComponents = page.getByXPath(\"//div[contains(@class, 'cmp-image')]\");\n for (DomNode child: coreComponents) {\n String src = null;\n String width = null;\n if (child.getAttributes().getNamedItem(\"data-cmp-src\") != null) {\n src = child.getAttributes().getNamedItem(\"data-cmp-src\").getNodeValue();\n }\n if (child.getAttributes().getNamedItem(\"data-cmp-widths\") != null) {\n width = child.getAttributes().getNamedItem(\"data-cmp-widths\").getNodeValue();\n }", "score": 0.770033597946167 }, { "filename": "core/src/main/java/work/noice/core/services/impl/OpaxServiceImpl.java", "retrieved_chunk": " toolbarEnabled = configuration.getToolbarEnabled();\n components = configuration.getComponents();\n openAIAPIKey = configuration.getOpenAIAPIKey();\n }\n @Override\n public String getOpenAIAPIKey() {\n return openAIAPIKey;\n }\n @Override\n public boolean getToolbarEnabled() {", "score": 0.7639085054397583 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.7627467513084412 } ]
java
customerAvatar = jsonData.getDataAttributes().get("customerAvatar");
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request
.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey());
request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/ChatGptRequest.java", "retrieved_chunk": "package work.noice.core.beans;\nimport lombok.Data;\nimport java.util.List;\nimport java.util.ArrayList;\n@Data\npublic class ChatGptRequest {\n private final int max_tokens;\n private final String model;\n private List<Message> messages;\n public ChatGptRequest(String prompt, String model, String role) {", "score": 0.8358386754989624 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptRequest.java", "retrieved_chunk": " this.max_tokens = 1500;\n this.model = model;\n this.messages = new ArrayList<>();\n Message message = new Message();\n message.setRole(role);\n message.setContent(prompt);\n this.messages.add(message);\n }\n}", "score": 0.8178907632827759 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptResponse.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.List;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true )\npublic class ChatGptResponse {\n private List<Choice> choices;\n @Data\n @JsonIgnoreProperties(ignoreUnknown = true )", "score": 0.784369945526123 }, { "filename": "core/src/test/java/work/noice/core/models/HelloWorldModelTest.java", "retrieved_chunk": " resource = context.create().resource(page, \"hello\",\n \"sling:resourceType\", \"aemgpt/components/helloworld\");\n // create sling model\n hello = resource.adaptTo(HelloWorldModel.class);\n }\n @Test\n void testGetMessage() throws Exception {\n // some very basic junit tests\n String msg = hello.getMessage();\n assertNotNull(msg);", "score": 0.764854907989502 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.7639224529266357 } ]
java
.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey());
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String
customerProblem = jsonData.getDataAttributes().get("customerProblem");
String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": " }\n public void setDataAttributes(Map<String, String> dataAttributes) {\n this.dataAttributes = dataAttributes;\n }\n public void setTemplateId(String templateId) {\n this.templateId = templateId;\n }\n}", "score": 0.7974401712417603 }, { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.Map;\npublic class Data {\n private String templateId;\n private Map<String, String> dataAttributes;\n public String getTemplateId() {\n return templateId;\n }\n public Map<String, String> getDataAttributes() {\n return dataAttributes;", "score": 0.7937710285186768 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " List<DomNode> coreComponents = page.getByXPath(\"//div[contains(@class, 'cmp-image')]\");\n for (DomNode child: coreComponents) {\n String src = null;\n String width = null;\n if (child.getAttributes().getNamedItem(\"data-cmp-src\") != null) {\n src = child.getAttributes().getNamedItem(\"data-cmp-src\").getNodeValue();\n }\n if (child.getAttributes().getNamedItem(\"data-cmp-widths\") != null) {\n width = child.getAttributes().getNamedItem(\"data-cmp-widths\").getNodeValue();\n }", "score": 0.7684828042984009 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.764862596988678 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptResponse.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.List;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true )\npublic class ChatGptResponse {\n private List<Choice> choices;\n @Data\n @JsonIgnoreProperties(ignoreUnknown = true )", "score": 0.7639079093933105 } ]
java
customerProblem = jsonData.getDataAttributes().get("customerProblem");
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String
audience = jsonData.getDataAttributes().get("audience");
String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.Map;\npublic class Data {\n private String templateId;\n private Map<String, String> dataAttributes;\n public String getTemplateId() {\n return templateId;\n }\n public Map<String, String> getDataAttributes() {\n return dataAttributes;", "score": 0.8146333694458008 }, { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": " }\n public void setDataAttributes(Map<String, String> dataAttributes) {\n this.dataAttributes = dataAttributes;\n }\n public void setTemplateId(String templateId) {\n this.templateId = templateId;\n }\n}", "score": 0.8103816509246826 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.7836186289787292 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptResponse.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.List;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true )\npublic class ChatGptResponse {\n private List<Choice> choices;\n @Data\n @JsonIgnoreProperties(ignoreUnknown = true )", "score": 0.7720097303390503 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " List<DomNode> coreComponents = page.getByXPath(\"//div[contains(@class, 'cmp-image')]\");\n for (DomNode child: coreComponents) {\n String src = null;\n String width = null;\n if (child.getAttributes().getNamedItem(\"data-cmp-src\") != null) {\n src = child.getAttributes().getNamedItem(\"data-cmp-src\").getNodeValue();\n }\n if (child.getAttributes().getNamedItem(\"data-cmp-widths\") != null) {\n width = child.getAttributes().getNamedItem(\"data-cmp-widths\").getNodeValue();\n }", "score": 0.7705690860748291 } ]
java
audience = jsonData.getDataAttributes().get("audience");
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content");
String tone = jsonData.getDataAttributes().get("tone");
String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/ChatGptResponse.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.List;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true )\npublic class ChatGptResponse {\n private List<Choice> choices;\n @Data\n @JsonIgnoreProperties(ignoreUnknown = true )", "score": 0.8253229856491089 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptRequest.java", "retrieved_chunk": "package work.noice.core.beans;\nimport lombok.Data;\nimport java.util.List;\nimport java.util.ArrayList;\n@Data\npublic class ChatGptRequest {\n private final int max_tokens;\n private final String model;\n private List<Message> messages;\n public ChatGptRequest(String prompt, String model, String role) {", "score": 0.8167104721069336 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptRequest.java", "retrieved_chunk": " this.max_tokens = 1500;\n this.model = model;\n this.messages = new ArrayList<>();\n Message message = new Message();\n message.setRole(role);\n message.setContent(prompt);\n this.messages.add(message);\n }\n}", "score": 0.8027626872062683 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.772957444190979 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptResponse.java", "retrieved_chunk": " public static class Choice {\n private Message message; \n }\n}", "score": 0.7614554166793823 } ]
java
String tone = jsonData.getDataAttributes().get("tone");
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName");
String product = jsonData.getDataAttributes().get("product");
String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info"); String gradeLevel = jsonData.getDataAttributes().get("gradeLevel"); String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/ChatGptResponse.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.List;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true )\npublic class ChatGptResponse {\n private List<Choice> choices;\n @Data\n @JsonIgnoreProperties(ignoreUnknown = true )", "score": 0.8369348049163818 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptRequest.java", "retrieved_chunk": "package work.noice.core.beans;\nimport lombok.Data;\nimport java.util.List;\nimport java.util.ArrayList;\n@Data\npublic class ChatGptRequest {\n private final int max_tokens;\n private final String model;\n private List<Message> messages;\n public ChatGptRequest(String prompt, String model, String role) {", "score": 0.8292582631111145 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptRequest.java", "retrieved_chunk": " this.max_tokens = 1500;\n this.model = model;\n this.messages = new ArrayList<>();\n Message message = new Message();\n message.setRole(role);\n message.setContent(prompt);\n this.messages.add(message);\n }\n}", "score": 0.8068945407867432 }, { "filename": "core/src/main/java/work/noice/core/beans/ChatGptResponse.java", "retrieved_chunk": " public static class Choice {\n private Message message; \n }\n}", "score": 0.7776767015457153 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.7739696502685547 } ]
java
String product = jsonData.getDataAttributes().get("product");
/* * Copyright 2020 Adobe Systems Incorporated * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package work.noice.it.tests; import com.adobe.cq.testing.client.CQClient; import com.adobe.cq.testing.junit.assertion.CQAssert; import com.adobe.cq.testing.junit.rules.CQAuthorClassRule; import com.adobe.cq.testing.junit.rules.CQAuthorPublishClassRule; import com.adobe.cq.testing.junit.rules.CQRule; import com.adobe.cq.testing.junit.rules.Page; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.sling.testing.clients.ClientException; import org.apache.sling.testing.clients.SlingHttpResponse; import org.eclipse.jetty.client.HttpResponse; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.Ignore; import org.slf4j.LoggerFactory; import static java.util.concurrent.TimeUnit.MINUTES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; /** * Validates pages on publish and makes sure that the page renders completely and also * validates all linked resources (images, clientlibs etc). * */ public class PublishPageValidationIT { // the page to test private static final String HOMEPAGE = "/"; // list files which do return a zerobyte response body private static final List<String> ZEROBYTEFILES = Arrays.asList(); private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(PublishPageValidationIT.class); @ClassRule public static final CQAuthorPublishClassRule cqBaseClassRule = new CQAuthorPublishClassRule(true); @Rule public CQRule cqBaseRule = new CQRule(cqBaseClassRule.publishRule); private static HtmlUnitClient adminPublish; @BeforeClass public static void beforeClass() throws ClientException { adminPublish = cqBaseClassRule.publishRule.getAdminClient(CQClient.class).adaptTo(HtmlUnitClient.class); } @AfterClass public static void afterClass() { // As of 2022/10/13, AEM declares 'org.apache.commons.io.IOUtils.closeQuietly' as deprecated, // even though the function has been un-deprecated again in version 2.9.0 of 'commons-io' // (https://issues.apache.org/jira/browse/IO-504); thus a try-catch is used instead. try { adminPublish.close(); } catch (IOException ignored) {} } @Test @Ignore public void validateHomepage() throws ClientException, IOException, URISyntaxException { String path = HOMEPAGE; verifyPage(adminPublish, path); verifyLinkedResources(adminPublish,path); } private static void verifyPage (HtmlUnitClient client, String path) throws ClientProtocolException, IOException { URI baseURI = client.getUrl(); LOG.info("Using {} as baseURL", baseURI.toString()); HttpGet get = new HttpGet(baseURI.toString() + path); org.apache.http.HttpResponse validationResponse = client.execute(get); assertEquals("Request to [" + get.getURI().toString() + "] does not return expected returncode 200", 200, validationResponse.getStatusLine().getStatusCode()); } private static void verifyLinkedResources(HtmlUnitClient client, String path) throws ClientException, IOException, URISyntaxException { List<URI> references =
client.getResourceRefs(path);
assertTrue(path + " does not contain any references!", references.size() > 0); for (URI ref : references ) { if (isSameOrigin(client.getUrl(), ref)) { LOG.info("verifying linked resource {}", ref.toString()); SlingHttpResponse response = client.doGet(ref.getPath()); int statusCode = response.getStatusLine().getStatusCode(); int responseSize = response.getContent().length(); assertEquals("Unexpected status returned from [" + ref + "]", 200, statusCode); if (! ZEROBYTEFILES.stream().anyMatch(s -> ref.getPath().startsWith(s))) { if (responseSize == 0) { LOG.warn("Empty response body from [" + ref.getPath() + "], please validate if this is correct"); } } } else { LOG.info("skipping linked resource from another domain {}", ref.toString()); } } } /** Checks if two URIs have the same origin. * * @param uri1 first URI * @param uri2 second URI * @return true if two URI come from the same host, port and use the same scheme */ private static boolean isSameOrigin(URI uri1, URI uri2) { if (!uri1.getScheme().equals(uri2.getScheme())) { return false; } else return uri1.getAuthority().equals(uri2.getAuthority()); } }
it.tests/src/main/java/work/noice/it/tests/PublishPageValidationIT.java
jaketracey-opax-44a71f1
[ { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(HtmlUnitClient.class);\n private final WebClient webClient = new WebClient();\n /** Extracts references to external resources used by the specified page.\n * This method extracts references from script, img, meta and link tags.\n * @param path path to the page.\n * @return list of URIs resolved against the pages baseURL\n * @throws IOException when IO error occurs\n * @throws URISyntaxException if malformed URL reference is found.\n */\n public List<URI> getResourceRefs(String path) throws IOException, URISyntaxException {", "score": 0.8621346950531006 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " webClient.close();\n } finally {\n super.close();\n }\n }\n //*********************************************\n // Internals\n //*********************************************\n private static List<URI> getRefs(HtmlPage page, String tag, String refAttr) throws URISyntaxException {\n URI baseUri = new URI(page.getBaseURI());", "score": 0.8192335367202759 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": "import com.gargoylesoftware.htmlunit.html.DomNode;\nimport com.gargoylesoftware.htmlunit.html.HtmlPage;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.sling.testing.clients.ClientException;\nimport org.apache.sling.testing.clients.SlingClientConfig;\nimport org.slf4j.LoggerFactory;\nimport org.w3c.dom.Node;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;", "score": 0.8158025741577148 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": "import java.net.URL;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport static org.junit.Assert.fail;\n/**\n * AEM client that maintains a WebClient instance from HTMLUnit framework\n */\npublic class HtmlUnitClient extends CQClient {", "score": 0.810287594795227 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/GetPageIT.java", "retrieved_chunk": " @Test\n public void testSitesAuthor() throws ClientException {\n adminAuthor.doGet(\"/sites.html\", 200);\n }\n /**\n * Verifies that the assets console exists on author\n */\n @Test\n public void testAssetsAuthor() throws ClientException {\n adminAuthor.doGet(\"/assets.html\", 200);", "score": 0.8048654794692993 } ]
java
client.getResourceRefs(path);
package work.noice.core.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import work.noice.core.beans.ChatGptRequest; import work.noice.core.beans.ChatGptResponse; import work.noice.core.beans.Data; import work.noice.core.services.OpaxService; import javax.servlet.Servlet; import java.io.IOException; @Component(immediate = true, service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=ChatGPT Integration", "sling.servlet.methods=" + HttpConstants.METHOD_POST, "sling.servlet.paths=" + "/bin/chat", "sling.servlet.extensions={\"json\"}" }) public class OpaxServlet extends SlingAllMethodsServlet { private static final Logger Logger = LoggerFactory.getLogger(OpaxServlet.class); private static final String CHATGPT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions"; private static final HttpClient client = HttpClients.createDefault(); private static final ObjectMapper MAPPER = new ObjectMapper(); @Reference private transient OpaxService config; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String body = IOUtils.toString(request.getReader()); String key = config.getOpenAIAPIKey(); // return an error if key is not found if (StringUtils.isBlank(key)) { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Open AI API Key not found"); response.getWriter().write(errorObject.toString()); return; } if (StringUtils.isNotBlank(body)) { String prompt = generatePrompt(body); if (StringUtils.isNotBlank(prompt)) { String result = generateMessage(prompt); if (StringUtils.isNotBlank(result)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("data", StringEscapeUtils.escapeHtml4(result)); response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jsonObject.toString()); } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Error occurred while generating message"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Invalid prompt"); response.getWriter().write(errorObject.toString()); } } else { response.setStatus(400); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JsonObject errorObject = new JsonObject(); errorObject.addProperty("error", "Empty request body"); response.getWriter().write(errorObject.toString()); } } private String generateMessage(String prompt) throws IOException { String requestBody = MAPPER.writeValueAsString(new ChatGptRequest(prompt, "gpt-3.5-turbo", "user")); HttpPost request = new HttpPost(CHATGPT_API_ENDPOINT); request.addHeader("Authorization", "Bearer" + " " + config.getOpenAIAPIKey()); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(requestBody, "UTF-8")); HttpResponse response = client.execute(request); ChatGptResponse chatGptResponse = MAPPER.readValue(EntityUtils.toString(response.getEntity(), "UTF-8"), ChatGptResponse.class); String message = chatGptResponse.getChoices().get(0).getMessage().getContent(); return message; } private String generatePrompt(String data) { Gson gson = new Gson(); Data jsonData = gson.fromJson(data, Data.class); String content = jsonData.getDataAttributes().get("content"); String tone = jsonData.getDataAttributes().get("tone"); String companyName = jsonData.getDataAttributes().get("companyName"); String product = jsonData.getDataAttributes().get("product"); String outline = jsonData.getDataAttributes().get("outline"); String cta = jsonData.getDataAttributes().get("cta"); String title = jsonData.getDataAttributes().get("title"); String audience = jsonData.getDataAttributes().get("audience"); String name = jsonData.getDataAttributes().get("name"); String info = jsonData.getDataAttributes().get("info");
String gradeLevel = jsonData.getDataAttributes().get("gradeLevel");
String numQuestions = jsonData.getDataAttributes().get("numQuestions"); String description = jsonData.getDataAttributes().get("description"); String topic = jsonData.getDataAttributes().get("topic"); String listCount = jsonData.getDataAttributes().get("listCount"); String productDescription = jsonData.getDataAttributes().get("productDescription"); String companyProductName = jsonData.getDataAttributes().get("companyProductName"); String customerAvatar = jsonData.getDataAttributes().get("customerAvatar"); String customerProblem = jsonData.getDataAttributes().get("customerProblem"); String points = jsonData.getDataAttributes().get("points"); String sentence = jsonData.getDataAttributes().get("sentence"); String language = jsonData.getDataAttributes().get("language"); String promptGuide = "You are a copywriter AI that can write and edit existing content. You always respond in HTML format for consumption by a rich text editor. Your goal is to produce the content that is requested as instructed without ever identifying yourself or the changes you have made. It should only ever contain content that was requested: PROMPT: "; switch (jsonData.getTemplateId()) { case "free-prompt": return promptGuide + content; case "content-summarizer": return promptGuide + "Summarize the following content in a " + tone + "tone: " + content; case "aida-framework": return promptGuide + "Never mention the AIDA framework. Write content using the AIDA framework, without mentioning that you are using the AIDA framework - don't mention anything about attention, etc. with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "bab-framework": return promptGuide + "Write content using the BAB (Before-After-Bridge) framework with the following properties: Company Name: " + companyName + ", Product: " + product + ", Tone: " + tone + "."; case "blog-post-conclusion-paragraph": return promptGuide + "Write a conclusion paragraph for the following blog post using this post outline: " + outline + ". Include a call to action: " + cta + ". Use this tone of voice: " + tone + "."; case "blog-post-intro-paragraph": return promptGuide + "Write an introduction paragraph for the following blog post title: " + title + ". The audience is " + audience + ". Use this tone of voice: " + tone + "."; case "blog-post-outline": return promptGuide + "Write an outline for the following blog post title: " + title + ". Use this tone of voice: " + tone + "."; case "company-bio": return promptGuide + "Write a company bio for the following company name: " + name + ". Company info: " + info + ". Use this tone of voice: " + tone + "."; case "content-improver": return promptGuide + "Improve the following content: " + content + ". Use this tone of voice: " + tone + "."; case "simplify": return promptGuide + "Explain the following content to a child at grade level " + gradeLevel + ": " + content + "."; case "faq-generator": return promptGuide + "Write " + numQuestions + " FAQs for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "feature-to-benefit": return promptGuide + "Write the benefits of the features of this product description: " + description + ". Use this tone of voice: " + tone + "."; case "listicle": return promptGuide + "Write a listicle for the following topic: " + topic + ". The list should have " + listCount + " items. Use this tone of voice: " + tone + "."; case "one-shot-blog-post": return promptGuide + "Write a one-shot blog post for the following topic: " + topic + ". Use this tone of voice: " + tone + "."; case "perfect-headline": return promptGuide + "Write a perfect headline for the following product description: " + productDescription + ". The company product name is " + companyProductName + ". The customer avatar is " + customerAvatar + ". The customer problem is " + customerProblem + ". Use this tone of voice: " + tone + "."; case "persuasive-bullet-points": return promptGuide + "Write persuasive bullet points for the following content: Company/Product Name: " + companyProductName + ", Product Description: " + productDescription + ", Tone: " + tone + "."; case "press-release": return promptGuide + "Write a press release for the following topic: " + topic + ". The press release should have " + points + " points."; case "sentence-expander": return promptGuide + "Expand the following sentence: " + sentence + ". Use this tone of voice: " + tone + "."; case "proof-read": return promptGuide + "Proofread the following content: " + content + "."; case "make-longer": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "make-shorter": return promptGuide + "Make the following content longer by around half, maintaining the essential meaning of the original content: " + content + "."; case "summarize": return promptGuide + "Summarize the following content: " + content + "."; case "improve-seo": return promptGuide + "Improve the SEO of the following content: " + content + "."; case "improve-readability": return promptGuide + "Improve the readability of the following content: " + content + "."; case "improve-clarity": return promptGuide + "Improve the clarity of the following content: " + content + "."; case "improve-grammar": return promptGuide + "Improve the grammar of the following content: " + content + "."; case "improve-tone": return promptGuide + "Improve the tone of the following content: " + content + "."; case "improve-structure": return promptGuide + "Improve the structure of the following content: " + content + "."; case "improve-flow": return promptGuide + "Improve the flow of the following content: " + content + "."; case "translate": return promptGuide + "Translate the following content into " + language + ": " + content + "."; } return ""; } }
core/src/main/java/work/noice/core/servlets/OpaxServlet.java
jaketracey-opax-44a71f1
[ { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": "package work.noice.core.beans;\nimport java.util.Map;\npublic class Data {\n private String templateId;\n private Map<String, String> dataAttributes;\n public String getTemplateId() {\n return templateId;\n }\n public Map<String, String> getDataAttributes() {\n return dataAttributes;", "score": 0.7985846996307373 }, { "filename": "core/src/main/java/work/noice/core/beans/Data.java", "retrieved_chunk": " }\n public void setDataAttributes(Map<String, String> dataAttributes) {\n this.dataAttributes = dataAttributes;\n }\n public void setTemplateId(String templateId) {\n this.templateId = templateId;\n }\n}", "score": 0.7977632284164429 }, { "filename": "core/src/main/java/work/noice/core/beans/Message.java", "retrieved_chunk": "package work.noice.core.beans;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport lombok.Data;\n@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Message {\n private String role;\n private String content;\n}", "score": 0.7700756788253784 }, { "filename": "core/src/main/java/work/noice/core/services/impl/OpaxServiceImpl.java", "retrieved_chunk": " toolbarEnabled = configuration.getToolbarEnabled();\n components = configuration.getComponents();\n openAIAPIKey = configuration.getOpenAIAPIKey();\n }\n @Override\n public String getOpenAIAPIKey() {\n return openAIAPIKey;\n }\n @Override\n public boolean getToolbarEnabled() {", "score": 0.7633726596832275 }, { "filename": "it.tests/src/main/java/work/noice/it/tests/HtmlUnitClient.java", "retrieved_chunk": " List<DomNode> coreComponents = page.getByXPath(\"//div[contains(@class, 'cmp-image')]\");\n for (DomNode child: coreComponents) {\n String src = null;\n String width = null;\n if (child.getAttributes().getNamedItem(\"data-cmp-src\") != null) {\n src = child.getAttributes().getNamedItem(\"data-cmp-src\").getNodeValue();\n }\n if (child.getAttributes().getNamedItem(\"data-cmp-widths\") != null) {\n width = child.getAttributes().getNamedItem(\"data-cmp-widths\").getNodeValue();\n }", "score": 0.7620925903320312 } ]
java
String gradeLevel = jsonData.getDataAttributes().get("gradeLevel");
package org.kasun.discordleaderboards.Schedules; import org.kasun.discordleaderboards.Database.Cache; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Utils.SqlUtils; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.sql.Timestamp; public class Schedule { private final String delay; private final Leaderboard leaderboard; private boolean isalredysent; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; public Schedule(Leaderboard leaderboard) { this.leaderboard = leaderboard; delay = leaderboard.getConfig().getDelay(); } public void run() { if (isAlredySent()){ Timestamp currentTime = TimeUtils.getCurrentTimeStamp(); Timestamp lastsent = getLastSent(); switch (delay.toLowerCase()){ case "live": Cache cache = new Cache(leaderboard); if (cache.isDiffernt()){ leaderboard.send(); cache.setCache(); } break; case "hourly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORHOUR){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "daily": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORDAY){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "weekly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORWEEK){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "monthly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSSFORMONTH){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; default: break; } }else { leaderboard.send(); setLastSent(); } } public void setLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp currenttimestamp = TimeUtils.getCurrentTimeStamp();
SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp);
} public Timestamp getLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp lastsent = SqlUtils.getScheduleLastSent(leaderboardname); return lastsent; } public boolean isAlredySent(){ String leaderboardname = leaderboard.getName(); isalredysent = SqlUtils.isScheduleAlredySent(leaderboardname); return isalredysent; } public void deleteDataIfNeeded(){ boolean isrefreshonsent = leaderboard.getConfig().isRefreshOnSent(); String ColumnName = leaderboard.getConfig().getPlaceholder().substring(1, leaderboard.getConfig().getPlaceholder().length() - 1); String tablename = "UserData"; if (isrefreshonsent){ SqlUtils.deleteAllValues(tablename, ColumnName); } } }
src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT \" + \"LastSent\" + \" FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n lastsent = rs.getTimestamp(\"LastSent\");\n }", "score": 0.896455705165863 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " return topPlayerScores;\n }\n public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n if (mainConfig.getStorageType().equalsIgnoreCase(\"h2\")){\n try {\n preparedStatement = database.getConnection().prepareStatement(\"MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);\");\n preparedStatement.setString(1, leaderboard);", "score": 0.8963837623596191 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " public static boolean isScheduleAlredySent(String leaderboard){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n int count = rs.getInt(\"count\");", "score": 0.8790307641029358 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " return count > 0;\n }\n preparedStatement.close();\n }catch (SQLException ex){\n Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.RED + \"Issue while reading data in database [code : 14]\");\n }\n return false;\n }\n public static Timestamp getScheduleLastSent(String leaderboard){\n Timestamp lastsent = Timestamp.valueOf(\"2000-01-01 00:00:00\"); //Default Value - for check if lastsent", "score": 0.8772010803222656 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Cache.java", "retrieved_chunk": " public void setCache(){\n String leaderboardname = leaderboard.getName();\n SqlUtils.setCache(leaderboardname, cache);\n }\n public String getCache(){\n String leaderboardname = leaderboard.getName();\n return SqlUtils.getCache(leaderboardname);\n }\n public boolean isDiffernt(){\n String cache = getCache();", "score": 0.8496144413948059 } ]
java
SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp);
package org.kasun.discordleaderboards.Schedules; import org.kasun.discordleaderboards.Database.Cache; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Utils.SqlUtils; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.sql.Timestamp; public class Schedule { private final String delay; private final Leaderboard leaderboard; private boolean isalredysent; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; public Schedule(Leaderboard leaderboard) { this.leaderboard = leaderboard; delay = leaderboard.getConfig().getDelay(); } public void run() { if (isAlredySent()){ Timestamp currentTime = TimeUtils.getCurrentTimeStamp(); Timestamp lastsent = getLastSent(); switch (delay.toLowerCase()){ case "live": Cache cache = new Cache(leaderboard); if (cache.isDiffernt()){ leaderboard.send(); cache.setCache(); } break; case "hourly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORHOUR){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "daily": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORDAY){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "weekly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORWEEK){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "monthly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSSFORMONTH){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; default: break; } }else { leaderboard.send(); setLastSent(); } } public void setLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp currenttimestamp = TimeUtils.getCurrentTimeStamp(); SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp); } public Timestamp getLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp lastsent = SqlUtils.getScheduleLastSent(leaderboardname); return lastsent; } public boolean isAlredySent(){ String leaderboardname = leaderboard.getName(); isalredysent = SqlUtils.isScheduleAlredySent(leaderboardname); return isalredysent; } public void deleteDataIfNeeded(){
boolean isrefreshonsent = leaderboard.getConfig().isRefreshOnSent();
String ColumnName = leaderboard.getConfig().getPlaceholder().substring(1, leaderboard.getConfig().getPlaceholder().length() - 1); String tablename = "UserData"; if (isrefreshonsent){ SqlUtils.deleteAllValues(tablename, ColumnName); } } }
src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " public static boolean isScheduleAlredySent(String leaderboard){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n int count = rs.getInt(\"count\");", "score": 0.897616982460022 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " return count > 0;\n }\n preparedStatement.close();\n }catch (SQLException ex){\n Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.RED + \"Issue while reading data in database [code : 14]\");\n }\n return false;\n }\n public static Timestamp getScheduleLastSent(String leaderboard){\n Timestamp lastsent = Timestamp.valueOf(\"2000-01-01 00:00:00\"); //Default Value - for check if lastsent", "score": 0.8797975778579712 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT \" + \"LastSent\" + \" FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n lastsent = rs.getTimestamp(\"LastSent\");\n }", "score": 0.873315691947937 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Cache.java", "retrieved_chunk": " public void setCache(){\n String leaderboardname = leaderboard.getName();\n SqlUtils.setCache(leaderboardname, cache);\n }\n public String getCache(){\n String leaderboardname = leaderboard.getName();\n return SqlUtils.getCache(leaderboardname);\n }\n public boolean isDiffernt(){\n String cache = getCache();", "score": 0.861688494682312 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " return topPlayerScores;\n }\n public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n if (mainConfig.getStorageType().equalsIgnoreCase(\"h2\")){\n try {\n preparedStatement = database.getConnection().prepareStatement(\"MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);\");\n preparedStatement.setString(1, leaderboard);", "score": 0.8592133522033691 } ]
java
boolean isrefreshonsent = leaderboard.getConfig().isRefreshOnSent();
package org.kasun.discordleaderboards.Schedules; import org.kasun.discordleaderboards.Database.Cache; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Utils.SqlUtils; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.sql.Timestamp; public class Schedule { private final String delay; private final Leaderboard leaderboard; private boolean isalredysent; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; public Schedule(Leaderboard leaderboard) { this.leaderboard = leaderboard; delay = leaderboard.getConfig().getDelay(); } public void run() { if (isAlredySent()){ Timestamp currentTime = TimeUtils.getCurrentTimeStamp(); Timestamp lastsent = getLastSent(); switch (delay.toLowerCase()){ case "live": Cache cache = new Cache(leaderboard); if (cache.isDiffernt()){ leaderboard.send(); cache.setCache(); } break; case "hourly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORHOUR){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "daily": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORDAY){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "weekly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORWEEK){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "monthly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSSFORMONTH){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; default: break; } }else { leaderboard.send(); setLastSent(); } } public void setLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp currenttimestamp = TimeUtils.getCurrentTimeStamp(); SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp); } public Timestamp getLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp lastsent = SqlUtils.getScheduleLastSent(leaderboardname); return lastsent; } public boolean isAlredySent(){ String leaderboardname = leaderboard.getName(); isalredysent =
SqlUtils.isScheduleAlredySent(leaderboardname);
return isalredysent; } public void deleteDataIfNeeded(){ boolean isrefreshonsent = leaderboard.getConfig().isRefreshOnSent(); String ColumnName = leaderboard.getConfig().getPlaceholder().substring(1, leaderboard.getConfig().getPlaceholder().length() - 1); String tablename = "UserData"; if (isrefreshonsent){ SqlUtils.deleteAllValues(tablename, ColumnName); } } }
src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " public static boolean isScheduleAlredySent(String leaderboard){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n int count = rs.getInt(\"count\");", "score": 0.8988549113273621 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " return count > 0;\n }\n preparedStatement.close();\n }catch (SQLException ex){\n Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.RED + \"Issue while reading data in database [code : 14]\");\n }\n return false;\n }\n public static Timestamp getScheduleLastSent(String leaderboard){\n Timestamp lastsent = Timestamp.valueOf(\"2000-01-01 00:00:00\"); //Default Value - for check if lastsent", "score": 0.8940489292144775 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT \" + \"LastSent\" + \" FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n lastsent = rs.getTimestamp(\"LastSent\");\n }", "score": 0.890472948551178 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " return topPlayerScores;\n }\n public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n if (mainConfig.getStorageType().equalsIgnoreCase(\"h2\")){\n try {\n preparedStatement = database.getConnection().prepareStatement(\"MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);\");\n preparedStatement.setString(1, leaderboard);", "score": 0.878465473651886 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Cache.java", "retrieved_chunk": " public void setCache(){\n String leaderboardname = leaderboard.getName();\n SqlUtils.setCache(leaderboardname, cache);\n }\n public String getCache(){\n String leaderboardname = leaderboard.getName();\n return SqlUtils.getCache(leaderboardname);\n }\n public boolean isDiffernt(){\n String cache = getCache();", "score": 0.8583963513374329 } ]
java
SqlUtils.isScheduleAlredySent(leaderboardname);
package org.kasun.discordleaderboards.Schedules; import org.kasun.discordleaderboards.Database.Cache; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Utils.SqlUtils; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.sql.Timestamp; public class Schedule { private final String delay; private final Leaderboard leaderboard; private boolean isalredysent; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; public Schedule(Leaderboard leaderboard) { this.leaderboard = leaderboard; delay = leaderboard.getConfig().getDelay(); } public void run() { if (isAlredySent()){ Timestamp currentTime = TimeUtils.getCurrentTimeStamp(); Timestamp lastsent = getLastSent(); switch (delay.toLowerCase()){ case "live": Cache cache = new Cache(leaderboard); if (cache.isDiffernt()){ leaderboard.send(); cache.setCache(); } break; case "hourly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORHOUR){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "daily": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORDAY){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "weekly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORWEEK){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "monthly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSSFORMONTH){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; default: break; } }else { leaderboard.send(); setLastSent(); } } public void setLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp currenttimestamp = TimeUtils.getCurrentTimeStamp(); SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp); } public Timestamp getLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp lastsent = SqlUtils.getScheduleLastSent(leaderboardname); return lastsent; } public boolean isAlredySent(){ String leaderboardname = leaderboard.getName(); isalredysent = SqlUtils.isScheduleAlredySent(leaderboardname); return isalredysent; } public void deleteDataIfNeeded(){ boolean isrefreshonsent = leaderboard.getConfig().isRefreshOnSent(); String ColumnName = leaderboard.getConfig().getPlaceholder().substring(1, leaderboard.getConfig().getPlaceholder().length() - 1); String tablename = "UserData"; if (isrefreshonsent){
SqlUtils.deleteAllValues(tablename, ColumnName);
} } }
src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " public static boolean isScheduleAlredySent(String leaderboard){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n int count = rs.getInt(\"count\");", "score": 0.8966464996337891 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Cache.java", "retrieved_chunk": " public void setCache(){\n String leaderboardname = leaderboard.getName();\n SqlUtils.setCache(leaderboardname, cache);\n }\n public String getCache(){\n String leaderboardname = leaderboard.getName();\n return SqlUtils.getCache(leaderboardname);\n }\n public boolean isDiffernt(){\n String cache = getCache();", "score": 0.8810257911682129 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " return count > 0;\n }\n preparedStatement.close();\n }catch (SQLException ex){\n Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.RED + \"Issue while reading data in database [code : 14]\");\n }\n return false;\n }\n public static Timestamp getScheduleLastSent(String leaderboard){\n Timestamp lastsent = Timestamp.valueOf(\"2000-01-01 00:00:00\"); //Default Value - for check if lastsent", "score": 0.8603378534317017 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT \" + \"LastSent\" + \" FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n lastsent = rs.getTimestamp(\"LastSent\");\n }", "score": 0.8569800853729248 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " return topPlayerScores;\n }\n public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n if (mainConfig.getStorageType().equalsIgnoreCase(\"h2\")){\n try {\n preparedStatement = database.getConnection().prepareStatement(\"MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);\");\n preparedStatement.setString(1, leaderboard);", "score": 0.8464866876602173 } ]
java
SqlUtils.deleteAllValues(tablename, ColumnName);
package org.kasun.discordleaderboards.Schedules; import org.kasun.discordleaderboards.Database.Cache; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Utils.SqlUtils; import org.kasun.discordleaderboards.Utils.TimeUtils; import java.sql.Timestamp; public class Schedule { private final String delay; private final Leaderboard leaderboard; private boolean isalredysent; private final long SECSFORHOUR = 3600; private final long SECSFORDAY = 86400; private final long SECSFORWEEK = 604800; private final long SECSSFORMONTH = 2629746; public Schedule(Leaderboard leaderboard) { this.leaderboard = leaderboard; delay = leaderboard.getConfig().getDelay(); } public void run() { if (isAlredySent()){ Timestamp currentTime = TimeUtils.getCurrentTimeStamp(); Timestamp lastsent = getLastSent(); switch (delay.toLowerCase()){ case "live": Cache cache = new Cache(leaderboard); if (cache.isDiffernt()){ leaderboard.send(); cache.setCache(); } break; case "hourly": if
(TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORHOUR){
leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "daily": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORDAY){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "weekly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORWEEK){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; case "monthly": if (TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSSFORMONTH){ leaderboard.send(); setLastSent(); deleteDataIfNeeded(); } break; default: break; } }else { leaderboard.send(); setLastSent(); } } public void setLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp currenttimestamp = TimeUtils.getCurrentTimeStamp(); SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp); } public Timestamp getLastSent(){ String leaderboardname = leaderboard.getName(); Timestamp lastsent = SqlUtils.getScheduleLastSent(leaderboardname); return lastsent; } public boolean isAlredySent(){ String leaderboardname = leaderboard.getName(); isalredysent = SqlUtils.isScheduleAlredySent(leaderboardname); return isalredysent; } public void deleteDataIfNeeded(){ boolean isrefreshonsent = leaderboard.getConfig().isRefreshOnSent(); String ColumnName = leaderboard.getConfig().getPlaceholder().substring(1, leaderboard.getConfig().getPlaceholder().length() - 1); String tablename = "UserData"; if (isrefreshonsent){ SqlUtils.deleteAllValues(tablename, ColumnName); } } }
src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Cache.java", "retrieved_chunk": " public void setCache(){\n String leaderboardname = leaderboard.getName();\n SqlUtils.setCache(leaderboardname, cache);\n }\n public String getCache(){\n String leaderboardname = leaderboard.getName();\n return SqlUtils.getCache(leaderboardname);\n }\n public boolean isDiffernt(){\n String cache = getCache();", "score": 0.846809983253479 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT \" + \"LastSent\" + \" FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n lastsent = rs.getTimestamp(\"LastSent\");\n }", "score": 0.8347456455230713 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " }\n public static String getCache(String leaderboard) {\n String cache = null;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n PreparedStatement preparedStatement;\n ResultSet resultSet;\n try {\n Connection conn = database.getConnection();\n preparedStatement = conn.prepareStatement(\"SELECT Cache FROM LiveCache WHERE Leaderboard = ?\");", "score": 0.8288186192512512 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " public static boolean isScheduleAlredySent(String leaderboard){\n PreparedStatement preparedStatement;\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n try{\n preparedStatement = database.getConnection().prepareStatement(\"SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?\");\n preparedStatement.setString(1, leaderboard);\n ResultSet rs = preparedStatement.executeQuery();\n if (rs.next()) {\n int count = rs.getInt(\"count\");", "score": 0.8247402310371399 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " if (mainConfig.getStorageType().equalsIgnoreCase(\"h2\")){\n try {\n Connection conn = database.getConnection();\n preparedStatement = conn.prepareStatement(\"MERGE INTO LiveCache s USING (VALUES (?, ?)) data (Leaderboard, Cache) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.Cache = data.Cache WHEN NOT MATCHED THEN INSERT (Leaderboard, Cache) VALUES (data.Leaderboard, data.Cache);\");\n preparedStatement.setString(1, leaderboard);\n // Convert the 'cache' string to a Clob object\n Clob clob = conn.createClob();\n clob.setString(1, cache);\n preparedStatement.setClob(2, clob);\n int rowsUpdated = preparedStatement.executeUpdate();", "score": 0.8160659670829773 } ]
java
(TimeUtils.getTimestampDifference(currentTime, lastsent) >= SECSFORHOUR){
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{
webhook.execute();
}catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/DiscordsrvEmbed.java", "retrieved_chunk": " private String embedDescription;\n private MessageEmbed messageEmbed;\n public MessageEmbed getMessageEmbed() {\n EmbedBuilder embedBuilder = new EmbedBuilder();\n if (embedTitle != null && !embedTitle.equals(\"\") && !embedTitle.equals(\"-\")){\n embedBuilder.setTitle(embedTitle);\n }\n if (embedColour != null && !embedColour.equals(\"\") && !embedColour.equals(\"-\")){\n embedBuilder.setColor(Color.decode(embedColour));\n }", "score": 0.86130291223526 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/DiscordsrvEmbed.java", "retrieved_chunk": " embedBuilder.setDescription(embedDescription);\n }\n return embedBuilder.build();\n }\n //getters and setters\n public String getEmbedTitle() {\n return embedTitle;\n }\n public void setEmbedTitle(String embedTitle) {\n this.embedTitle = embedTitle;", "score": 0.8602094054222107 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8580313920974731 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Commands/DLCommand.java", "retrieved_chunk": " DiscordWebhook w = new DiscordWebhook(url);\n DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject();\n if (url == null || url.equalsIgnoreCase(\"-\")) {\n sender.sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.RED + \"Webhook Url not Configured\");\n return true;\n }\n embed.setTitle(\"Dleaderboards\");\n embed.setDescription(\"Your Webhook is Working\");\n w.addEmbed(embed);\n sender.sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.GRAY + \"Sending Webhook Message....\");", "score": 0.8502460718154907 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java", "retrieved_chunk": " this.webhookUserName = \"-\";\n this.embedTitle = \"-\";\n List<String> description = new ArrayList<>();\n description.add(\"{toplist}\");\n this.embedDescription = description;\n this.embedUrl = \"-\";\n this.embedColour = \"-\";\n this.embedFooter = \"-\";\n this.embedImage = \"-\";\n this.embedThumbnail = \"-\";", "score": 0.849010705947876 } ]
java
webhook.execute();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle
= mainConfig.getDembedTitle();
String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " topList = leaderboard.getTopList();\n }\n public String getDescription(boolean isForWebhook) {\n String description = String.join(isForWebhook ? \"\\\\u000A\" : \"\\n\", embedDescriptionlist);\n //{toplist} placeholder\n String replacement1 = \"```\" + (isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + \"```\";\n if (replacement1.equals(\"``````\") || replacement1 == null) {\n description = description.replace(\"{toplist}\", \"```Leaderboard is empty!```\");\n } else {\n description = description.replace(\"{toplist}\", replacement1);", "score": 0.881989061832428 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " sb.append(formattedEntry);\n }\n String leaderboardString = sb.toString();\n return leaderboardString;\n }\n public String getTopListAsString() {\n Map<String, Double> toplistmap = getTopListAsMap();\n int maxNameLength = getmaxnamelenght(toplistmap);\n StringBuilder sb = new StringBuilder();\n int i = 1;", "score": 0.8646279573440552 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " }\n public Map<String, Double> getTopListAsMap() {\n int top = leaderboardConfig.getTop();\n return SqlUtils.getTopPlayerMap(placeholderColumnName, top, leaderboardConfig.isHigherisbetter());\n }\n public String getTopListAsString(boolean isWebhookFormat) {\n Map<String, Double> toplistmap = getTopListAsMap();\n int maxNameLength = getmaxnamelenght(toplistmap);\n StringBuilder sb = new StringBuilder();\n int i = 1;", "score": 0.8644748330116272 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " this.leaderboard = leaderboard;\n }\n private String getDefaultIfNullOrEmpty(String value, String defaultValue) {\n return (value == null || value.isEmpty() || value.equals(\"-\")) ? defaultValue : value;\n }\n public DiscordsrvEmbed getDiscordsrvEmbed() {\n MainConfig mainConfig = new MainConfig();\n String title = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedTitle(), mainConfig.getDembedTitle());\n String colour = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedColour(), mainConfig.getDembedColour());\n String footer = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedFooter(), mainConfig.getDembedFooter());", "score": 0.8641780614852905 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " }\n String leaderboardString = sb.toString();\n return leaderboardString;\n }\n public String getTopListAsStringForWebhook() {\n Map<String, Double> toplistmap = getTopListAsMap();\n int maxNameLength = getmaxnamelenght(toplistmap);\n StringBuilder sb = new StringBuilder();\n int i = 1;\n for (Map.Entry<String, Double> entry : toplistmap.entrySet()) {", "score": 0.8620513677597046 } ]
java
= mainConfig.getDembedTitle();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){
webhook.setAvatarUrl(webhookAvatarUrl);
} if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/DiscordsrvEmbed.java", "retrieved_chunk": " if (embedFooter != null && !embedFooter.equals(\"\") && !embedFooter.equals(\"-\")){\n embedBuilder.setFooter(embedFooter);\n }\n if (embedThumbnail != null && !embedThumbnail.equals(\"\") && !embedThumbnail.equals(\"-\")){\n embedBuilder.setThumbnail(embedThumbnail);\n }\n if (embedImage != null && !embedImage.equals(\"\") && !embedImage.equals(\"-\")){\n embedBuilder.setImage(embedImage);\n }\n if (embedDescription != null && !embedDescription.equals(\"\") && !embedDescription.equals(\"-\")){", "score": 0.9000377655029297 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java", "retrieved_chunk": " public void setWebhookAvatarUrl(String webhookAvatarUrl) {\n this.webhookAvatarUrl = webhookAvatarUrl;\n }\n public String getWebhookUserName() {\n return webhookUserName;\n }\n public void setWebhookUserName(String webhookUserName) {\n this.webhookUserName = webhookUserName;\n }\n public String getEmbedTitle() {", "score": 0.8837412595748901 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " dwebhookAvatarUrl = config.getString(\"webhook-avatar-url\");\n dwebhookUserName = config.getString(\"webhook-user-name\");\n dembedTitle = config.getString(\"embed-title\");\n dembedUrl = config.getString(\"embed-url\");\n dembedColour = config.getString(\"embed-colour\");\n dembedFooter = config.getString(\"embed-footer\");\n dembedImage = config.getString(\"embed-image\");\n dembedThumbnail = config.getString(\"embed-thumbnail\");\n storageType = config.getString(\"storage-method\");\n mysqlAddress = config.getString(\"address\");", "score": 0.8786171674728394 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8777703046798706 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/DiscordsrvEmbed.java", "retrieved_chunk": " private String embedDescription;\n private MessageEmbed messageEmbed;\n public MessageEmbed getMessageEmbed() {\n EmbedBuilder embedBuilder = new EmbedBuilder();\n if (embedTitle != null && !embedTitle.equals(\"\") && !embedTitle.equals(\"-\")){\n embedBuilder.setTitle(embedTitle);\n }\n if (embedColour != null && !embedColour.equals(\"\") && !embedColour.equals(\"-\")){\n embedBuilder.setColor(Color.decode(embedColour));\n }", "score": 0.874657154083252 } ]
java
webhook.setAvatarUrl(webhookAvatarUrl);
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String
dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl();
String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " config.set(\"leaderboards\", leaderboardsList);\n config.set(\"webhook-url\", dwebhookurl);\n config.set(\"webhook-avatar-url\", dwebhookAvatarUrl);\n config.set(\"webhook-user-name\", dwebhookUserName);\n config.set(\"embed-title\", dembedTitle);\n config.set(\"embed-url\", dembedUrl);\n config.set(\"embed-colour\", dembedColour);\n config.set(\"embed-footer\", dembedFooter);\n config.set(\"embed-image\", dembedImage);\n config.set(\"embed-thumbnail\", dembedThumbnail);", "score": 0.8786254525184631 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " topList = leaderboard.getTopList();\n }\n public String getDescription(boolean isForWebhook) {\n String description = String.join(isForWebhook ? \"\\\\u000A\" : \"\\n\", embedDescriptionlist);\n //{toplist} placeholder\n String replacement1 = \"```\" + (isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + \"```\";\n if (replacement1.equals(\"``````\") || replacement1 == null) {\n description = description.replace(\"{toplist}\", \"```Leaderboard is empty!```\");\n } else {\n description = description.replace(\"{toplist}\", replacement1);", "score": 0.8769644498825073 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " public List<String> getLeaderboardsList() {\n return leaderboardsList;\n }\n public String getDwebhookurl() {\n return dwebhookurl;\n }\n public String getDwebhookAvatarUrl() {\n return dwebhookAvatarUrl;\n }\n public String getDwebhookUserName() {", "score": 0.875068724155426 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " private FileConfiguration config;\n private List<String> leaderboardsList;\n private String dwebhookurl;\n private String dwebhookAvatarUrl;\n private String dwebhookUserName;\n private String dembedTitle;\n private String dembedUrl;\n private String dembedColour;\n private String dembedFooter;\n private String dembedImage;", "score": 0.873749852180481 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " }\n String leaderboardString = sb.toString();\n return leaderboardString;\n }\n public String getTopListAsStringForWebhook() {\n Map<String, Double> toplistmap = getTopListAsMap();\n int maxNameLength = getmaxnamelenght(toplistmap);\n StringBuilder sb = new StringBuilder();\n int i = 1;\n for (Map.Entry<String, Double> entry : toplistmap.entrySet()) {", "score": 0.8677737712860107 } ]
java
dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String
dembedImage = mainConfig.getDembedImage();
String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " dwebhookAvatarUrl = config.getString(\"webhook-avatar-url\");\n dwebhookUserName = config.getString(\"webhook-user-name\");\n dembedTitle = config.getString(\"embed-title\");\n dembedUrl = config.getString(\"embed-url\");\n dembedColour = config.getString(\"embed-colour\");\n dembedFooter = config.getString(\"embed-footer\");\n dembedImage = config.getString(\"embed-image\");\n dembedThumbnail = config.getString(\"embed-thumbnail\");\n storageType = config.getString(\"storage-method\");\n mysqlAddress = config.getString(\"address\");", "score": 0.9277482628822327 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " return dwebhookUserName;\n }\n public String getDembedTitle() {\n return dembedTitle;\n }\n public String getDembedUrl() {\n return dembedUrl;\n }\n public String getDembedColour() {\n return dembedColour;", "score": 0.905998170375824 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " private FileConfiguration config;\n private List<String> leaderboardsList;\n private String dwebhookurl;\n private String dwebhookAvatarUrl;\n private String dwebhookUserName;\n private String dembedTitle;\n private String dembedUrl;\n private String dembedColour;\n private String dembedFooter;\n private String dembedImage;", "score": 0.9010702967643738 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " config.set(\"leaderboards\", leaderboardsList);\n config.set(\"webhook-url\", dwebhookurl);\n config.set(\"webhook-avatar-url\", dwebhookAvatarUrl);\n config.set(\"webhook-user-name\", dwebhookUserName);\n config.set(\"embed-title\", dembedTitle);\n config.set(\"embed-url\", dembedUrl);\n config.set(\"embed-colour\", dembedColour);\n config.set(\"embed-footer\", dembedFooter);\n config.set(\"embed-image\", dembedImage);\n config.set(\"embed-thumbnail\", dembedThumbnail);", "score": 0.8978832364082336 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " }\n public void setDembedTitle(String dembedTitle) {\n this.dembedTitle = dembedTitle;\n }\n public void setDembedUrl(String dembedUrl) {\n this.dembedUrl = dembedUrl;\n }\n public void setDembedColour(String dembedColour) {\n this.dembedColour = dembedColour;\n }", "score": 0.8885116577148438 } ]
java
dembedImage = mainConfig.getDembedImage();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this);
String description = descriptionGenerator.getDescription(true);
if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/DiscordsrvEmbed.java", "retrieved_chunk": " if (embedFooter != null && !embedFooter.equals(\"\") && !embedFooter.equals(\"-\")){\n embedBuilder.setFooter(embedFooter);\n }\n if (embedThumbnail != null && !embedThumbnail.equals(\"\") && !embedThumbnail.equals(\"-\")){\n embedBuilder.setThumbnail(embedThumbnail);\n }\n if (embedImage != null && !embedImage.equals(\"\") && !embedImage.equals(\"-\")){\n embedBuilder.setImage(embedImage);\n }\n if (embedDescription != null && !embedDescription.equals(\"\") && !embedDescription.equals(\"-\")){", "score": 0.9392962455749512 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/DiscordsrvEmbed.java", "retrieved_chunk": " private String embedDescription;\n private MessageEmbed messageEmbed;\n public MessageEmbed getMessageEmbed() {\n EmbedBuilder embedBuilder = new EmbedBuilder();\n if (embedTitle != null && !embedTitle.equals(\"\") && !embedTitle.equals(\"-\")){\n embedBuilder.setTitle(embedTitle);\n }\n if (embedColour != null && !embedColour.equals(\"\") && !embedColour.equals(\"-\")){\n embedBuilder.setColor(Color.decode(embedColour));\n }", "score": 0.9012771844863892 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8928331136703491 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java", "retrieved_chunk": " public void setEmbedFooter(String embedFooter) {\n this.embedFooter = embedFooter;\n }\n public String getEmbedImage() {\n return embedImage;\n }\n public void setEmbedImage(String embedImage) {\n this.embedImage = embedImage;\n }\n public String getEmbedThumbnail() {", "score": 0.889363706111908 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/DiscordsrvEmbed.java", "retrieved_chunk": " public void setEmbedFooter(String embedFooter) {\n this.embedFooter = embedFooter;\n }\n public String getEmbedImage() {\n return embedImage;\n }\n public void setEmbedImage(String embedImage) {\n this.embedImage = embedImage;\n }\n public String getEmbedThumbnail() {", "score": 0.889363706111908 } ]
java
String description = descriptionGenerator.getDescription(true);
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop();
String delay = leaderboardConfig.getDelay();
String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8944031000137329 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " config.set(\"leaderboards\", leaderboardsList);\n config.set(\"webhook-url\", dwebhookurl);\n config.set(\"webhook-avatar-url\", dwebhookAvatarUrl);\n config.set(\"webhook-user-name\", dwebhookUserName);\n config.set(\"embed-title\", dembedTitle);\n config.set(\"embed-url\", dembedUrl);\n config.set(\"embed-colour\", dembedColour);\n config.set(\"embed-footer\", dembedFooter);\n config.set(\"embed-image\", dembedImage);\n config.set(\"embed-thumbnail\", dembedThumbnail);", "score": 0.8943272829055786 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " dwebhookAvatarUrl = config.getString(\"webhook-avatar-url\");\n dwebhookUserName = config.getString(\"webhook-user-name\");\n dembedTitle = config.getString(\"embed-title\");\n dembedUrl = config.getString(\"embed-url\");\n dembedColour = config.getString(\"embed-colour\");\n dembedFooter = config.getString(\"embed-footer\");\n dembedImage = config.getString(\"embed-image\");\n dembedThumbnail = config.getString(\"embed-thumbnail\");\n storageType = config.getString(\"storage-method\");\n mysqlAddress = config.getString(\"address\");", "score": 0.8935513496398926 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " private FileConfiguration config;\n private List<String> leaderboardsList;\n private String dwebhookurl;\n private String dwebhookAvatarUrl;\n private String dwebhookUserName;\n private String dembedTitle;\n private String dembedUrl;\n private String dembedColour;\n private String dembedFooter;\n private String dembedImage;", "score": 0.8927344083786011 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " this.leaderboard = leaderboard;\n }\n private String getDefaultIfNullOrEmpty(String value, String defaultValue) {\n return (value == null || value.isEmpty() || value.equals(\"-\")) ? defaultValue : value;\n }\n public DiscordsrvEmbed getDiscordsrvEmbed() {\n MainConfig mainConfig = new MainConfig();\n String title = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedTitle(), mainConfig.getDembedTitle());\n String colour = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedColour(), mainConfig.getDembedColour());\n String footer = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedFooter(), mainConfig.getDembedFooter());", "score": 0.8830075860023499 } ]
java
String delay = leaderboardConfig.getDelay();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){
String placeholder = leaderboardConfig.getPlaceholder();
int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " private final String leaderboardname;\n String placeholderColumnName;\n private int numberOfFloatingPoints;\n public TopList(LeaderboardConfig leaderboardConfig) {\n this.leaderboardConfig = leaderboardConfig;\n top = leaderboardConfig.getTop();\n placeholder = leaderboardConfig.getPlaceholder();\n leaderboardname = leaderboardConfig.getName();\n placeholderColumnName = leaderboardConfig.getPlaceholder().substring(1, leaderboardConfig.getPlaceholder().length() - 1);\n numberOfFloatingPoints = leaderboardConfig.getFloatingpoints();", "score": 0.9072287082672119 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java", "retrieved_chunk": " //Constructer for load exciting leaderboardConfig\n public LeaderboardConfig(String name) {\n this.name = name;\n customConfig = new CustomConfig(name);\n config = customConfig.get();\n load();\n }\n //Constructer for create new LeaderboardConfig\n public LeaderboardConfig(String name, String placeholder, int top, String delay) {\n MainConfig mainConfig = new MainConfig();", "score": 0.9050397872924805 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java", "retrieved_chunk": " this.leaderboardversion = mainConfig.getPluginVersion();\n customConfig = new CustomConfig(name);\n customConfig.setup();\n config = customConfig.get();\n save();\n }\n //save methode\n public void save() {\n config.set(\"placeholder\", placeholder);\n config.set(\"top\", top);", "score": 0.8944987654685974 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Leaderboard;\nimport org.bukkit.configuration.file.FileConfiguration;\nimport org.kasun.discordleaderboards.Configs.MainConfig;\nimport org.kasun.discordleaderboards.DiscordLeaderboards;\nimport org.kasun.discordleaderboards.Configs.CustomConfig;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class LeaderboardConfig {\n private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance();\n private String name;", "score": 0.883253812789917 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Leaderboard;\nimport org.kasun.discordleaderboards.Utils.SqlUtils;\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.util.Map;\npublic class TopList {\n private final int top;\n private final LeaderboardConfig leaderboardConfig;\n private final String placeholder;", "score": 0.8705886006355286 } ]
java
String placeholder = leaderboardConfig.getPlaceholder();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour();
String dembedFooter = mainConfig.getDembedFooter();
String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " dwebhookAvatarUrl = config.getString(\"webhook-avatar-url\");\n dwebhookUserName = config.getString(\"webhook-user-name\");\n dembedTitle = config.getString(\"embed-title\");\n dembedUrl = config.getString(\"embed-url\");\n dembedColour = config.getString(\"embed-colour\");\n dembedFooter = config.getString(\"embed-footer\");\n dembedImage = config.getString(\"embed-image\");\n dembedThumbnail = config.getString(\"embed-thumbnail\");\n storageType = config.getString(\"storage-method\");\n mysqlAddress = config.getString(\"address\");", "score": 0.8555436730384827 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " config.set(\"leaderboards\", leaderboardsList);\n config.set(\"webhook-url\", dwebhookurl);\n config.set(\"webhook-avatar-url\", dwebhookAvatarUrl);\n config.set(\"webhook-user-name\", dwebhookUserName);\n config.set(\"embed-title\", dembedTitle);\n config.set(\"embed-url\", dembedUrl);\n config.set(\"embed-colour\", dembedColour);\n config.set(\"embed-footer\", dembedFooter);\n config.set(\"embed-image\", dembedImage);\n config.set(\"embed-thumbnail\", dembedThumbnail);", "score": 0.8501653671264648 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " private FileConfiguration config;\n private List<String> leaderboardsList;\n private String dwebhookurl;\n private String dwebhookAvatarUrl;\n private String dwebhookUserName;\n private String dembedTitle;\n private String dembedUrl;\n private String dembedColour;\n private String dembedFooter;\n private String dembedImage;", "score": 0.845779299736023 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " return dwebhookUserName;\n }\n public String getDembedTitle() {\n return dembedTitle;\n }\n public String getDembedUrl() {\n return dembedUrl;\n }\n public String getDembedColour() {\n return dembedColour;", "score": 0.8431637287139893 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " }\n public void setDembedTitle(String dembedTitle) {\n this.dembedTitle = dembedTitle;\n }\n public void setDembedUrl(String dembedUrl) {\n this.dembedUrl = dembedUrl;\n }\n public void setDembedColour(String dembedColour) {\n this.dembedColour = dembedColour;\n }", "score": 0.8424297571182251 } ]
java
String dembedFooter = mainConfig.getDembedFooter();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String
embedTitle = leaderboardConfig.getEmbedTitle();
String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8885136842727661 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " topList = leaderboard.getTopList();\n }\n public String getDescription(boolean isForWebhook) {\n String description = String.join(isForWebhook ? \"\\\\u000A\" : \"\\n\", embedDescriptionlist);\n //{toplist} placeholder\n String replacement1 = \"```\" + (isForWebhook ? topList.getTopListAsString(true) : topList.getTopListAsString(false)) + \"```\";\n if (replacement1.equals(\"``````\") || replacement1 == null) {\n description = description.replace(\"{toplist}\", \"```Leaderboard is empty!```\");\n } else {\n description = description.replace(\"{toplist}\", replacement1);", "score": 0.8855464458465576 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " private FileConfiguration config;\n private List<String> leaderboardsList;\n private String dwebhookurl;\n private String dwebhookAvatarUrl;\n private String dwebhookUserName;\n private String dembedTitle;\n private String dembedUrl;\n private String dembedColour;\n private String dembedFooter;\n private String dembedImage;", "score": 0.8850877285003662 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " this.leaderboard = leaderboard;\n }\n private String getDefaultIfNullOrEmpty(String value, String defaultValue) {\n return (value == null || value.isEmpty() || value.equals(\"-\")) ? defaultValue : value;\n }\n public DiscordsrvEmbed getDiscordsrvEmbed() {\n MainConfig mainConfig = new MainConfig();\n String title = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedTitle(), mainConfig.getDembedTitle());\n String colour = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedColour(), mainConfig.getDembedColour());\n String footer = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedFooter(), mainConfig.getDembedFooter());", "score": 0.8839176297187805 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " config.set(\"leaderboards\", leaderboardsList);\n config.set(\"webhook-url\", dwebhookurl);\n config.set(\"webhook-avatar-url\", dwebhookAvatarUrl);\n config.set(\"webhook-user-name\", dwebhookUserName);\n config.set(\"embed-title\", dembedTitle);\n config.set(\"embed-url\", dembedUrl);\n config.set(\"embed-colour\", dembedColour);\n config.set(\"embed-footer\", dembedFooter);\n config.set(\"embed-image\", dembedImage);\n config.set(\"embed-thumbnail\", dembedThumbnail);", "score": 0.879461407661438 } ]
java
embedTitle = leaderboardConfig.getEmbedTitle();
package org.kasun.discordleaderboards.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Database.Database; import org.kasun.discordleaderboards.Leaderboard.LeaderboardConfig; import java.io.IOException; import java.io.Reader; import java.sql.*; import java.util.LinkedHashMap; import java.util.Map; public class SqlUtils { public static void addUserDataToDatabase(String placeholderColumnName, String UUID, String name , double value){ MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("ALTER TABLE UserData ADD COLUMN IF NOT EXISTS " + placeholderColumnName + " DOUBLE;"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO UserData u USING (SELECT '" + UUID + "' AS PlayerUUID, '" + name + "' AS PlayerName, " + value + " AS " + placeholderColumnName + " FROM DUAL) data ON u.PlayerUUID = data.PlayerUUID WHEN MATCHED THEN UPDATE SET u." + placeholderColumnName + " = data." + placeholderColumnName + " WHEN NOT MATCHED THEN INSERT (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (data.PlayerUUID, data.PlayerName, data." + placeholderColumnName + ");"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.1]"); ex.printStackTrace(); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection connection = database.getConnection(); Statement statement = connection.createStatement(); // Check if the column exists in the table ResultSet resultSet = statement.executeQuery("SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'UserData' AND COLUMN_NAME = '" + placeholderColumnName + "'"); if (!resultSet.next()) { // Column does not exist, so add it statement.executeUpdate("ALTER TABLE UserData ADD COLUMN " + placeholderColumnName + " DOUBLE"); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.2]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement( "INSERT INTO UserData (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (?, ?, ?) " + "ON DUPLICATE KEY UPDATE " + placeholderColumnName + " = VALUES(" + placeholderColumnName + ")" ); preparedStatement.setString(1, UUID); preparedStatement.setString(2, name); preparedStatement.setDouble(3, value); preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.3]"); ex.printStackTrace(); } } } public static Map<String, Double> getTopPlayerMap(String placeholderColumnName, int top, boolean ishigherbetter) { Map<String, Double> topPlayerScores = new LinkedHashMap<>(); MainConfig mainConfig = new MainConfig(); try { Database database = new Database(); PreparedStatement preparedStatement; String databaseName = mainConfig.getStorageType(); // Get the name of the current database String query; if (ishigherbetter){ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } }else{ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } } preparedStatement = database.getConnection().prepareStatement(query); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { String playerName = rs.getString("PlayerName"); double score = rs.getDouble(placeholderColumnName); if (ishigherbetter){ if (score > 0){ topPlayerScores.put(playerName, score); } }else{ topPlayerScores.put(playerName, score); } } preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Userdata, please check your placeholders in leaderboard configs [code : 10]"); } return topPlayerScores; } public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);"); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { preparedStatement = database.getConnection().prepareStatement( "REPLACE INTO Schedule (Leaderboard, LastSent) VALUES (?, ?)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13.1]"); } } } public static boolean isScheduleAlredySent(String leaderboard){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { int count = rs.getInt("count"); return count > 0; } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 14]"); } return false; } public static Timestamp getScheduleLastSent(String leaderboard){ Timestamp lastsent = Timestamp.valueOf("2000-01-01 00:00:00"); //Default Value - for check if lastsent PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT " + "LastSent" + " FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { lastsent = rs.getTimestamp("LastSent"); } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 15]"); } return lastsent; } public static void setCache(String leaderboard, String cache) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("MERGE INTO LiveCache s USING (VALUES (?, ?)) data (Leaderboard, Cache) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.Cache = data.Cache WHEN NOT MATCHED THEN INSERT (Leaderboard, Cache) VALUES (data.Leaderboard, data.Cache);"); preparedStatement.setString(1, leaderboard); // Convert the 'cache' string to a Clob object Clob clob = conn.createClob(); clob.setString(1, cache); preparedStatement.setClob(2, clob); int rowsUpdated = preparedStatement.executeUpdate(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement( "INSERT INTO LiveCache (Leaderboard, Cache) VALUES (?, ?) " + "ON DUPLICATE KEY UPDATE Cache = VALUES(Cache)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setString(2, cache); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02.1]"); } } } public static String getCache(String leaderboard) { String cache = null; MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; ResultSet resultSet; try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("SELECT Cache FROM LiveCache WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Clob clob = resultSet.getClob("Cache"); Reader reader = clob.getCharacterStream(); StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, bytesRead); } cache = sb.toString(); } resultSet.close(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Live Cache [code : 03]"); } catch (IOException ex) { return null; } return cache; } public static void deleteAllValues(String tableName, String columnName) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try { if (mainConfig.getStorageType().equalsIgnoreCase("h2")) { preparedStatement =
database.getConnection().prepareStatement( "DELETE FROM " + tableName + " WHERE " + columnName + " IS NOT NULL" );
} else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { preparedStatement = database.getConnection().prepareStatement( "UPDATE " + tableName + " SET " + columnName + " = NULL" ); } else { throw new UnsupportedOperationException("Unsupported storage type: " + mainConfig.getStorageType()); } int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while deleting data in the database [code: 13]"); } } }
src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": " }\n public void deleteDataIfNeeded(){\n boolean isrefreshonsent = leaderboard.getConfig().isRefreshOnSent();\n String ColumnName = leaderboard.getConfig().getPlaceholder().substring(1, leaderboard.getConfig().getPlaceholder().length() - 1);\n String tablename = \"UserData\";\n if (isrefreshonsent){\n SqlUtils.deleteAllValues(tablename, ColumnName);\n }\n }\n}", "score": 0.8157868981361389 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS Schedule (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" LastSent TIMESTAMP\" +\n \");\");\n preparedStatement.execute();\n preparedStatement.close();\n preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS LiveCache (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" Cache \" + largetextsqltype +\n \");\");", "score": 0.8045594096183777 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " largetextsqltype = \"LONGTEXT\";\n }\n PreparedStatement preparedStatement;\n try {\n preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS UserData (\" +\n \" PlayerUUID varchar(255) PRIMARY KEY,\" +\n \" PlayerName varchar(255)\" +\n \");\");\n preparedStatement.execute();\n preparedStatement.close();", "score": 0.8035341501235962 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " }\n }\n return connection;\n }\n */\n public void initializeDatabase() {\n String largetextsqltype = \"CLOB\";\n if (mainConfig.getStorageType().equalsIgnoreCase(\"h2\")){\n largetextsqltype = \"CLOB\";\n } else if (mainConfig.getStorageType().equalsIgnoreCase(\"mysql\")) {", "score": 0.8017545342445374 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " preparedStatement.execute();\n preparedStatement.close();\n } catch (SQLException ex) {\n plugin.getLogger().severe(\"Database Preparation Error Detected! [code : 08]\");\n ex.printStackTrace();\n }\n }\n}", "score": 0.798829197883606 } ]
java
database.getConnection().prepareStatement( "DELETE FROM " + tableName + " WHERE " + columnName + " IS NOT NULL" );
package org.kasun.discordleaderboards.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Database.Database; import org.kasun.discordleaderboards.Leaderboard.LeaderboardConfig; import java.io.IOException; import java.io.Reader; import java.sql.*; import java.util.LinkedHashMap; import java.util.Map; public class SqlUtils { public static void addUserDataToDatabase(String placeholderColumnName, String UUID, String name , double value){ MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("ALTER TABLE UserData ADD COLUMN IF NOT EXISTS " + placeholderColumnName + " DOUBLE;"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO UserData u USING (SELECT '" + UUID + "' AS PlayerUUID, '" + name + "' AS PlayerName, " + value + " AS " + placeholderColumnName + " FROM DUAL) data ON u.PlayerUUID = data.PlayerUUID WHEN MATCHED THEN UPDATE SET u." + placeholderColumnName + " = data." + placeholderColumnName + " WHEN NOT MATCHED THEN INSERT (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (data.PlayerUUID, data.PlayerName, data." + placeholderColumnName + ");"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.1]"); ex.printStackTrace(); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection connection = database.getConnection(); Statement statement = connection.createStatement(); // Check if the column exists in the table ResultSet resultSet = statement.executeQuery("SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'UserData' AND COLUMN_NAME = '" + placeholderColumnName + "'"); if (!resultSet.next()) { // Column does not exist, so add it statement.executeUpdate("ALTER TABLE UserData ADD COLUMN " + placeholderColumnName + " DOUBLE"); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.2]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement( "INSERT INTO UserData (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (?, ?, ?) " + "ON DUPLICATE KEY UPDATE " + placeholderColumnName + " = VALUES(" + placeholderColumnName + ")" ); preparedStatement.setString(1, UUID); preparedStatement.setString(2, name); preparedStatement.setDouble(3, value); preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.3]"); ex.printStackTrace(); } } } public static Map<String, Double> getTopPlayerMap(String placeholderColumnName, int top, boolean ishigherbetter) { Map<String, Double> topPlayerScores = new LinkedHashMap<>(); MainConfig mainConfig = new MainConfig(); try { Database database = new Database(); PreparedStatement preparedStatement; String databaseName = mainConfig.getStorageType(); // Get the name of the current database String query; if (ishigherbetter){ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } }else{ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } } preparedStatement = database.getConnection().prepareStatement(query); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { String playerName = rs.getString("PlayerName"); double score = rs.getDouble(placeholderColumnName); if (ishigherbetter){ if (score > 0){ topPlayerScores.put(playerName, score); } }else{ topPlayerScores.put(playerName, score); } } preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Userdata, please check your placeholders in leaderboard configs [code : 10]"); } return topPlayerScores; } public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);"); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { preparedStatement =
database.getConnection().prepareStatement( "REPLACE INTO Schedule (Leaderboard, LastSent) VALUES (?, ?)" );
preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13.1]"); } } } public static boolean isScheduleAlredySent(String leaderboard){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { int count = rs.getInt("count"); return count > 0; } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 14]"); } return false; } public static Timestamp getScheduleLastSent(String leaderboard){ Timestamp lastsent = Timestamp.valueOf("2000-01-01 00:00:00"); //Default Value - for check if lastsent PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT " + "LastSent" + " FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { lastsent = rs.getTimestamp("LastSent"); } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 15]"); } return lastsent; } public static void setCache(String leaderboard, String cache) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("MERGE INTO LiveCache s USING (VALUES (?, ?)) data (Leaderboard, Cache) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.Cache = data.Cache WHEN NOT MATCHED THEN INSERT (Leaderboard, Cache) VALUES (data.Leaderboard, data.Cache);"); preparedStatement.setString(1, leaderboard); // Convert the 'cache' string to a Clob object Clob clob = conn.createClob(); clob.setString(1, cache); preparedStatement.setClob(2, clob); int rowsUpdated = preparedStatement.executeUpdate(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement( "INSERT INTO LiveCache (Leaderboard, Cache) VALUES (?, ?) " + "ON DUPLICATE KEY UPDATE Cache = VALUES(Cache)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setString(2, cache); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02.1]"); } } } public static String getCache(String leaderboard) { String cache = null; MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; ResultSet resultSet; try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("SELECT Cache FROM LiveCache WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Clob clob = resultSet.getClob("Cache"); Reader reader = clob.getCharacterStream(); StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, bytesRead); } cache = sb.toString(); } resultSet.close(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Live Cache [code : 03]"); } catch (IOException ex) { return null; } return cache; } public static void deleteAllValues(String tableName, String columnName) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try { if (mainConfig.getStorageType().equalsIgnoreCase("h2")) { preparedStatement = database.getConnection().prepareStatement( "DELETE FROM " + tableName + " WHERE " + columnName + " IS NOT NULL" ); } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { preparedStatement = database.getConnection().prepareStatement( "UPDATE " + tableName + " SET " + columnName + " = NULL" ); } else { throw new UnsupportedOperationException("Unsupported storage type: " + mainConfig.getStorageType()); } int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while deleting data in the database [code: 13]"); } } }
src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS Schedule (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" LastSent TIMESTAMP\" +\n \");\");\n preparedStatement.execute();\n preparedStatement.close();\n preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS LiveCache (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" Cache \" + largetextsqltype +\n \");\");", "score": 0.89219069480896 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " preparedStatement.execute();\n preparedStatement.close();\n } catch (SQLException ex) {\n plugin.getLogger().severe(\"Database Preparation Error Detected! [code : 08]\");\n ex.printStackTrace();\n }\n }\n}", "score": 0.8831693530082703 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " } catch (SQLException e) {\n plugin.getLogger().severe(\"Failed to Connect H2 Database! [code: 07]\");\n e.printStackTrace();\n }\n } else if (mainConfig.getStorageType().equalsIgnoreCase(\"mysql\")) {\n String address = mainConfig.getMysqlAddress();\n String database = mainConfig.getMysqlDatabase();\n String username = mainConfig.getMysqlUsername();\n String password = mainConfig.getMysqlPassword();\n try {", "score": 0.8559900522232056 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/UserData.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Database;\nimport me.clip.placeholderapi.PlaceholderAPI;\nimport org.bukkit.OfflinePlayer;\nimport org.bukkit.entity.Player;\nimport org.kasun.discordleaderboards.Configs.MainConfig;\nimport org.kasun.discordleaderboards.Leaderboard.Leaderboard;\nimport org.kasun.discordleaderboards.Utils.PlayerUtils;\nimport org.kasun.discordleaderboards.Utils.SqlUtils;\nimport java.util.List;\nimport java.util.concurrent.CompletableFuture;", "score": 0.851426362991333 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Database;\nimport org.kasun.discordleaderboards.DiscordLeaderboards;\nimport org.kasun.discordleaderboards.Configs.MainConfig;\nimport java.sql.*;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.util.Properties;\npublic class Database {\n MainConfig mainConfig = new MainConfig();", "score": 0.850125253200531 } ]
java
database.getConnection().prepareStatement( "REPLACE INTO Schedule (Leaderboard, LastSent) VALUES (?, ?)" );
package org.kasun.discordleaderboards.Database; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Utils.PlayerUtils; import org.kasun.discordleaderboards.Utils.SqlUtils; import java.util.List; import java.util.concurrent.CompletableFuture; public class UserData { private final MainConfig mainConfig = new MainConfig(); private final Database database = new Database(); private Player player; private OfflinePlayer offlinePlayer; private String placeholder; private String username; private String uuid; private double value; String placeholderColumnName; //constructers public UserData() {} public UserData(Player player, String placeholder) { this.player = player; this.placeholder = placeholder; placeholderColumnName = placeholder.substring(1, placeholder.length() - 1); uuid = player.getUniqueId().toString(); try{ value = Double.parseDouble(PlaceholderAPI.setPlaceholders(player, placeholder)); }catch (NumberFormatException e){ value = 0.0; } username = player.getName(); } public UserData(OfflinePlayer offlinePlayer, String placeholder) { this.offlinePlayer = offlinePlayer; this.placeholder = placeholder; placeholderColumnName = placeholder.substring(1, placeholder.length() - 1); uuid = offlinePlayer.getUniqueId().toString(); try{ value = Double.parseDouble(PlaceholderAPI.setPlaceholders(offlinePlayer, placeholder)); }catch (NumberFormatException e){ value = 0.0; } username = offlinePlayer.getName(); } //One Player One Placeholder public void addToDatabase(){ CompletableFuture.runAsync(() -> {
SqlUtils.addUserDataToDatabase(placeholderColumnName, uuid, username, value);
}); } //getters and setters public String getUserName(){ if (player != null){ username = player.getName(); } else if (offlinePlayer != null) { username = offlinePlayer.getName(); } return username; } public String getUuid(){ if (player != null){ uuid = player.getUniqueId().toString(); } else if (offlinePlayer != null) { uuid = offlinePlayer.getUniqueId().toString(); } return uuid; } public double getValue(){ if (player != null){ value = Double.parseDouble(PlaceholderAPI.setPlaceholders(player, placeholder)); } else if (offlinePlayer != null) { value = Double.parseDouble(PlaceholderAPI.setPlaceholders(offlinePlayer, placeholder)); } return value; } //One Player All Placeholders public void addUserDataToDBAllPlaceholders(Player player){ MainConfig mainConfig = new MainConfig(); List<String> leaderboardnamelist = mainConfig.getLeaderboardsList(); for (String lbname : leaderboardnamelist){ Leaderboard leaderboard = new Leaderboard(lbname); UserData userData = new UserData(player, leaderboard.getConfig().getPlaceholder()); userData.addToDatabase(); } } //One Player All Placeholders public void addUserDataToDBAllPlaceholders(OfflinePlayer offlinePlayer){ MainConfig mainConfig = new MainConfig(); List<String> leaderboardnamelist = mainConfig.getLeaderboardsList(); for (String lbname : leaderboardnamelist){ Leaderboard leaderboard = new Leaderboard(lbname); String valuestring = PlaceholderAPI.setPlaceholders(offlinePlayer, leaderboard.getConfig().getPlaceholder()); if (valuestring != null && valuestring != ""){ UserData userData = new UserData(offlinePlayer, leaderboard.getConfig().getPlaceholder()); userData.addToDatabase(); } } } //All Players All Placeholders public void addUserDataToDBAllPlayersAllPlaceholders(){ List<OfflinePlayer> players = PlayerUtils.getAllPlayers(); for (OfflinePlayer player : players) { if (player != null){ addUserDataToDBAllPlaceholders(player); } } } //All Players One Placeholder (Dont use Void Constructer for this METHODE) public void addUserDataToDBAllPlayersThisPlaceholder(){ List<OfflinePlayer> players = PlayerUtils.getAllPlayers(); for (OfflinePlayer player : players) { if (player != null){ addToDatabase(); } } } public String getPlaceholder() { return placeholder; } }
src/main/java/org/kasun/discordleaderboards/Database/UserData.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " try {\n preparedStatement = database.getConnection().prepareStatement(\n \"INSERT INTO UserData (PlayerUUID, PlayerName, \" + placeholderColumnName + \") VALUES (?, ?, ?) \" +\n \"ON DUPLICATE KEY UPDATE \" + placeholderColumnName + \" = VALUES(\" + placeholderColumnName + \")\"\n );\n preparedStatement.setString(1, UUID);\n preparedStatement.setString(2, name);\n preparedStatement.setDouble(3, value);\n preparedStatement.executeUpdate();\n preparedStatement.close();", "score": 0.8898636102676392 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": "import java.util.Map;\npublic class SqlUtils {\n public static void addUserDataToDatabase(String placeholderColumnName, String UUID, String name , double value){\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n PreparedStatement preparedStatement;\n if (mainConfig.getStorageType().equalsIgnoreCase(\"h2\")){\n try {\n preparedStatement = database.getConnection().prepareStatement(\"ALTER TABLE UserData ADD COLUMN IF NOT EXISTS \" + placeholderColumnName + \" DOUBLE;\");\n preparedStatement.execute();", "score": 0.8748185038566589 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " preparedStatement.close();\n } catch (SQLException ex) {\n Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.RED + \"Issue while adding UserData to database [code : 09]\");\n ex.printStackTrace();\n }\n try {\n preparedStatement = database.getConnection().prepareStatement(\"MERGE INTO UserData u USING (SELECT '\" + UUID + \"' AS PlayerUUID, '\" + name + \"' AS PlayerName, \" + value + \" AS \" + placeholderColumnName + \" FROM DUAL) data ON u.PlayerUUID = data.PlayerUUID WHEN MATCHED THEN UPDATE SET u.\" + placeholderColumnName + \" = data.\" + placeholderColumnName + \" WHEN NOT MATCHED THEN INSERT (PlayerUUID, PlayerName, \" + placeholderColumnName + \") VALUES (data.PlayerUUID, data.PlayerName, data.\" + placeholderColumnName + \");\");\n preparedStatement.execute();\n preparedStatement.close();\n } catch (SQLException ex) {", "score": 0.864039421081543 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Listeners/PlayerQuit.java", "retrieved_chunk": " UserData userData = new UserData();\n userData.addUserDataToDBAllPlaceholders(player);\n }\n}", "score": 0.8633131980895996 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Listeners/PlayerJoin.java", "retrieved_chunk": " UserData userData = new UserData();\n userData.addUserDataToDBAllPlaceholders(player);\n }\n}", "score": 0.8633131980895996 } ]
java
SqlUtils.addUserDataToDatabase(placeholderColumnName, uuid, username, value);
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl(); String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl(); String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl();
String embedColour = leaderboardConfig.getEmbedColour();
String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " config.set(\"leaderboards\", leaderboardsList);\n config.set(\"webhook-url\", dwebhookurl);\n config.set(\"webhook-avatar-url\", dwebhookAvatarUrl);\n config.set(\"webhook-user-name\", dwebhookUserName);\n config.set(\"embed-title\", dembedTitle);\n config.set(\"embed-url\", dembedUrl);\n config.set(\"embed-colour\", dembedColour);\n config.set(\"embed-footer\", dembedFooter);\n config.set(\"embed-image\", dembedImage);\n config.set(\"embed-thumbnail\", dembedThumbnail);", "score": 0.8965753316879272 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " private FileConfiguration config;\n private List<String> leaderboardsList;\n private String dwebhookurl;\n private String dwebhookAvatarUrl;\n private String dwebhookUserName;\n private String dembedTitle;\n private String dembedUrl;\n private String dembedColour;\n private String dembedFooter;\n private String dembedImage;", "score": 0.8921525478363037 }, { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " this.leaderboard = leaderboard;\n }\n private String getDefaultIfNullOrEmpty(String value, String defaultValue) {\n return (value == null || value.isEmpty() || value.equals(\"-\")) ? defaultValue : value;\n }\n public DiscordsrvEmbed getDiscordsrvEmbed() {\n MainConfig mainConfig = new MainConfig();\n String title = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedTitle(), mainConfig.getDembedTitle());\n String colour = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedColour(), mainConfig.getDembedColour());\n String footer = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedFooter(), mainConfig.getDembedFooter());", "score": 0.888695240020752 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/LeaderboardConfig.java", "retrieved_chunk": " this.webhookUserName = config.getString(\"webhook-user-name\");\n this.embedTitle = config.getString(\"embed-title\");\n this.embedDescription = config.getStringList(\"embed-description\");\n this.embedUrl = config.getString(\"embed-url\");\n this.embedColour = config.getString(\"embed-colour\");\n this.embedFooter = config.getString(\"embed-footer\");\n this.embedImage = config.getString(\"embed-image\");\n this.embedThumbnail = config.getString(\"embed-thumbnail\");\n this.leaderboardversion = config.getString(\"leaderboard-version\");\n }", "score": 0.8843411803245544 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " private final String leaderboardname;\n String placeholderColumnName;\n private int numberOfFloatingPoints;\n public TopList(LeaderboardConfig leaderboardConfig) {\n this.leaderboardConfig = leaderboardConfig;\n top = leaderboardConfig.getTop();\n placeholder = leaderboardConfig.getPlaceholder();\n leaderboardname = leaderboardConfig.getName();\n placeholderColumnName = leaderboardConfig.getPlaceholder().substring(1, leaderboardConfig.getPlaceholder().length() - 1);\n numberOfFloatingPoints = leaderboardConfig.getFloatingpoints();", "score": 0.8837634921073914 } ]
java
String embedColour = leaderboardConfig.getEmbedColour();
package org.kasun.discordleaderboards.Leaderboard; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Configs.MainConfig; import java.awt.*; import java.io.IOException; import java.util.List; public class Leaderboard { private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); public enum WebhookDelay {Live, Hourly, Daily, Weekly, Monthly, None} private final LeaderboardConfig leaderboardConfig; private final String name; private final TopList topList; //constructer for load leaderboard public Leaderboard(String name) { this.name = name; leaderboardConfig = new LeaderboardConfig(name); topList = new TopList(leaderboardConfig); } //constructer for create leaderboard public Leaderboard(String name, int top, String placeholder, WebhookDelay delay){ this.name = name; MainConfig mainConfig = new MainConfig(); List<String> leaderboards = mainConfig.getLeaderboardsList(); leaderboards.add(name); mainConfig.setLeaderboardsList(leaderboards); mainConfig.saveConfig(); leaderboardConfig = new LeaderboardConfig(name, placeholder, top, delay.toString()); //creating LeaderboardConfig topList = new TopList(leaderboardConfig); } public String toString(){ String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); return topList.getTopListAsString(false); } public void send() { //getting default values from main config MainConfig mainConfig = new MainConfig(); String dembedTitle = mainConfig.getDembedTitle(); String dwebhookurl = mainConfig.getDwebhookurl(); String dwebhookAvatarUrl = mainConfig.getDwebhookAvatarUrl(); String dwebhookUserName = mainConfig.getDwebhookUserName(); String dembedUrl = mainConfig.getDembedUrl(); String dembedColour = mainConfig.getDembedColour(); String dembedFooter = mainConfig.getDembedFooter(); String dembedImage = mainConfig.getDembedImage(); String dembedThumbnail = mainConfig.getDembedThumbnail(); String dembedDescription = "Description is Empty !"; //getting leaderboard's values from leaderboard config String placeholder = leaderboardConfig.getPlaceholder(); int top = leaderboardConfig.getTop(); String delay = leaderboardConfig.getDelay(); String webhookurl = leaderboardConfig.getWebhookurl();
String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl();
String webhookUserName = leaderboardConfig.getWebhookUserName(); String embedTitle = leaderboardConfig.getEmbedTitle(); String embedUrl = leaderboardConfig.getEmbedUrl(); String embedColour = leaderboardConfig.getEmbedColour(); String embedFooter = leaderboardConfig.getEmbedFooter(); String embedImage = leaderboardConfig.getEmbedImage(); String embedThumbnail = leaderboardConfig.getEmbedThumbnail(); //checking if leaderboard config values are null, if it is getting default values from main config webhookurl = getOrDefault(webhookurl, dwebhookurl); webhookAvatarUrl = getOrDefault(webhookAvatarUrl, dwebhookAvatarUrl); webhookUserName = getOrDefault(webhookUserName, dwebhookUserName); embedTitle = getOrDefault(embedTitle, dembedTitle); embedUrl = getOrDefault(embedUrl, dembedUrl); embedColour = getOrDefault(embedColour, dembedColour); embedFooter = getOrDefault(embedFooter, dembedFooter); embedImage = getOrDefault(embedImage, dembedImage); embedThumbnail = getOrDefault(embedThumbnail, dembedThumbnail); DiscordWebhook webhook = new DiscordWebhook(webhookurl); //checking if final values are not null and them to discord webhook if (webhookAvatarUrl != null && !webhookAvatarUrl.equals("") && !webhookAvatarUrl.equals("-")){ webhook.setAvatarUrl(webhookAvatarUrl); } if (webhookUserName != null && !webhookUserName.equals("") && !webhookUserName.equals("-")){ webhook.setUsername(webhookUserName); } DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (embedTitle != null && !embedTitle.equals("") && !embedTitle.equals("-")){ embed.setTitle(embedTitle); } if (embedUrl != null && !embedUrl.equals("") && !embedUrl.equals("-")){ embed.setUrl(embedUrl); } if (embedColour != null && !embedColour.equals("") && !embedColour.equals("-")){ embed.setColor(Color.decode(embedColour)); } if (embedFooter != null && !embedFooter.equals("") && !embedFooter.equals("-")){ embed.setFooter(embedFooter); } if (embedThumbnail != null && !embedThumbnail.equals("") && !embedThumbnail.equals("-")){ embed.setThumbnail(embedThumbnail); } if (embedImage != null && !embedImage.equals("") && !embedImage.equals("-")){ embed.setImage(embedImage); } DescriptionGenerator descriptionGenerator = new DescriptionGenerator(this); String description = descriptionGenerator.getDescription(true); if (description == null || description.equals("") || dembedDescription.equals("-")) { description = dembedDescription; } embed.setDescription(description); webhook.addEmbed(embed); try{ webhook.execute(); }catch (IOException e){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook issue detected, Check You Config Files [code : 24]"); e.printStackTrace(); } } //methode for select default value or leaderboard value private String getOrDefault(String value, String defaultValue) { return (value == null || value.isEmpty() || value.equals("-")) ? defaultValue : value; } //all Getters public LeaderboardConfig getConfig() { return leaderboardConfig; } public String getName() { return name; } public TopList getTopList() { return topList; } }
src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/DiscordSRV/LeaderboardDiscordSrvEmbed.java", "retrieved_chunk": " String image = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedImage(), mainConfig.getDembedImage());\n String thumb = getDefaultIfNullOrEmpty(leaderboard.getConfig().getEmbedThumbnail(), mainConfig.getDembedThumbnail());\n discordsrvEmbed = new DiscordsrvEmbed();\n discordsrvEmbed.setEmbedTitle(title);\n discordsrvEmbed.setEmbedColour(colour);\n discordsrvEmbed.setEmbedFooter(footer);\n discordsrvEmbed.setEmbedImage(image);\n discordsrvEmbed.setEmbedThumbnail(thumb);\n DescriptionGenerator descriptionGenerator = new DescriptionGenerator(leaderboard);\n discordsrvEmbed.setEmbedDescription(descriptionGenerator.getDescription(false));", "score": 0.8978911638259888 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " private FileConfiguration config;\n private List<String> leaderboardsList;\n private String dwebhookurl;\n private String dwebhookAvatarUrl;\n private String dwebhookUserName;\n private String dembedTitle;\n private String dembedUrl;\n private String dembedColour;\n private String dembedFooter;\n private String dembedImage;", "score": 0.8954482674598694 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " dwebhookAvatarUrl = config.getString(\"webhook-avatar-url\");\n dwebhookUserName = config.getString(\"webhook-user-name\");\n dembedTitle = config.getString(\"embed-title\");\n dembedUrl = config.getString(\"embed-url\");\n dembedColour = config.getString(\"embed-colour\");\n dembedFooter = config.getString(\"embed-footer\");\n dembedImage = config.getString(\"embed-image\");\n dembedThumbnail = config.getString(\"embed-thumbnail\");\n storageType = config.getString(\"storage-method\");\n mysqlAddress = config.getString(\"address\");", "score": 0.8925864696502686 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " config.set(\"leaderboards\", leaderboardsList);\n config.set(\"webhook-url\", dwebhookurl);\n config.set(\"webhook-avatar-url\", dwebhookAvatarUrl);\n config.set(\"webhook-user-name\", dwebhookUserName);\n config.set(\"embed-title\", dembedTitle);\n config.set(\"embed-url\", dembedUrl);\n config.set(\"embed-colour\", dembedColour);\n config.set(\"embed-footer\", dembedFooter);\n config.set(\"embed-image\", dembedImage);\n config.set(\"embed-thumbnail\", dembedThumbnail);", "score": 0.890570342540741 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Configs/MainConfig.java", "retrieved_chunk": " }\n public String getDembedFooter() {\n return dembedFooter;\n }\n public String getDembedImage() {\n return dembedImage;\n }\n public String getDembedThumbnail() {\n return dembedThumbnail;\n }", "score": 0.8876173496246338 } ]
java
String webhookAvatarUrl = leaderboardConfig.getWebhookAvatarUrl();
package org.kasun.discordleaderboards.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Database.Database; import org.kasun.discordleaderboards.Leaderboard.LeaderboardConfig; import java.io.IOException; import java.io.Reader; import java.sql.*; import java.util.LinkedHashMap; import java.util.Map; public class SqlUtils { public static void addUserDataToDatabase(String placeholderColumnName, String UUID, String name , double value){ MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("ALTER TABLE UserData ADD COLUMN IF NOT EXISTS " + placeholderColumnName + " DOUBLE;"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO UserData u USING (SELECT '" + UUID + "' AS PlayerUUID, '" + name + "' AS PlayerName, " + value + " AS " + placeholderColumnName + " FROM DUAL) data ON u.PlayerUUID = data.PlayerUUID WHEN MATCHED THEN UPDATE SET u." + placeholderColumnName + " = data." + placeholderColumnName + " WHEN NOT MATCHED THEN INSERT (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (data.PlayerUUID, data.PlayerName, data." + placeholderColumnName + ");"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.1]"); ex.printStackTrace(); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection connection = database.getConnection(); Statement statement = connection.createStatement(); // Check if the column exists in the table ResultSet resultSet = statement.executeQuery("SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'UserData' AND COLUMN_NAME = '" + placeholderColumnName + "'"); if (!resultSet.next()) { // Column does not exist, so add it statement.executeUpdate("ALTER TABLE UserData ADD COLUMN " + placeholderColumnName + " DOUBLE"); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.2]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement( "INSERT INTO UserData (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (?, ?, ?) " + "ON DUPLICATE KEY UPDATE " + placeholderColumnName + " = VALUES(" + placeholderColumnName + ")" ); preparedStatement.setString(1, UUID); preparedStatement.setString(2, name); preparedStatement.setDouble(3, value); preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.3]"); ex.printStackTrace(); } } } public static Map<String, Double> getTopPlayerMap(String placeholderColumnName, int top, boolean ishigherbetter) { Map<String, Double> topPlayerScores = new LinkedHashMap<>(); MainConfig mainConfig = new MainConfig(); try { Database database = new Database(); PreparedStatement preparedStatement; String databaseName = mainConfig.getStorageType(); // Get the name of the current database String query; if (ishigherbetter){ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } }else{ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } } preparedStatement = database.getConnection().prepareStatement(query); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { String playerName = rs.getString("PlayerName"); double score = rs.getDouble(placeholderColumnName); if (ishigherbetter){ if (score > 0){ topPlayerScores.put(playerName, score); } }else{ topPlayerScores.put(playerName, score); } } preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Userdata, please check your placeholders in leaderboard configs [code : 10]"); } return topPlayerScores; } public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);"); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { preparedStatement = database.getConnection().prepareStatement( "REPLACE INTO Schedule (Leaderboard, LastSent) VALUES (?, ?)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13.1]"); } } } public static boolean isScheduleAlredySent(String leaderboard){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { int count = rs.getInt("count"); return count > 0; } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 14]"); } return false; } public static Timestamp getScheduleLastSent(String leaderboard){ Timestamp lastsent = Timestamp.valueOf("2000-01-01 00:00:00"); //Default Value - for check if lastsent PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT " + "LastSent" + " FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { lastsent = rs.getTimestamp("LastSent"); } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 15]"); } return lastsent; } public static void setCache(String leaderboard, String cache) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("MERGE INTO LiveCache s USING (VALUES (?, ?)) data (Leaderboard, Cache) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.Cache = data.Cache WHEN NOT MATCHED THEN INSERT (Leaderboard, Cache) VALUES (data.Leaderboard, data.Cache);"); preparedStatement.setString(1, leaderboard); // Convert the 'cache' string to a Clob object Clob clob = conn.createClob(); clob.setString(1, cache); preparedStatement.setClob(2, clob); int rowsUpdated = preparedStatement.executeUpdate(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement( "INSERT INTO LiveCache (Leaderboard, Cache) VALUES (?, ?) " + "ON DUPLICATE KEY UPDATE Cache = VALUES(Cache)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setString(2, cache); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02.1]"); } } } public static String getCache(String leaderboard) { String cache = null; MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; ResultSet resultSet; try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("SELECT Cache FROM LiveCache WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Clob clob = resultSet.getClob("Cache"); Reader reader = clob.getCharacterStream(); StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, bytesRead); } cache = sb.toString(); } resultSet.close(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Live Cache [code : 03]"); } catch (IOException ex) { return null; } return cache; } public static void deleteAllValues(String tableName, String columnName) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try { if (mainConfig.getStorageType().equalsIgnoreCase("h2")) { preparedStatement = database.getConnection().prepareStatement( "DELETE FROM " + tableName + " WHERE " + columnName + " IS NOT NULL" ); } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { preparedStatement = database.getConnection().prepareStatement( "UPDATE " + tableName + " SET " + columnName + " = NULL" ); } else { throw new
UnsupportedOperationException("Unsupported storage type: " + mainConfig.getStorageType());
} int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while deleting data in the database [code: 13]"); } } }
src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS Schedule (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" LastSent TIMESTAMP\" +\n \");\");\n preparedStatement.execute();\n preparedStatement.close();\n preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS LiveCache (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" Cache \" + largetextsqltype +\n \");\");", "score": 0.824397623538971 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " largetextsqltype = \"LONGTEXT\";\n }\n PreparedStatement preparedStatement;\n try {\n preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS UserData (\" +\n \" PlayerUUID varchar(255) PRIMARY KEY,\" +\n \" PlayerName varchar(255)\" +\n \");\");\n preparedStatement.execute();\n preparedStatement.close();", "score": 0.8224271535873413 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " }\n }\n return connection;\n }\n */\n public void initializeDatabase() {\n String largetextsqltype = \"CLOB\";\n if (mainConfig.getStorageType().equalsIgnoreCase(\"h2\")){\n largetextsqltype = \"CLOB\";\n } else if (mainConfig.getStorageType().equalsIgnoreCase(\"mysql\")) {", "score": 0.8207387328147888 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " preparedStatement.execute();\n preparedStatement.close();\n } catch (SQLException ex) {\n plugin.getLogger().severe(\"Database Preparation Error Detected! [code : 08]\");\n ex.printStackTrace();\n }\n }\n}", "score": 0.8177953362464905 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " } catch (SQLException e) {\n plugin.getLogger().severe(\"Failed to Connect H2 Database! [code: 07]\");\n e.printStackTrace();\n }\n } else if (mainConfig.getStorageType().equalsIgnoreCase(\"mysql\")) {\n String address = mainConfig.getMysqlAddress();\n String database = mainConfig.getMysqlDatabase();\n String username = mainConfig.getMysqlUsername();\n String password = mainConfig.getMysqlPassword();\n try {", "score": 0.8166619539260864 } ]
java
UnsupportedOperationException("Unsupported storage type: " + mainConfig.getStorageType());
package org.kasun.discordleaderboards.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Database.Database; import org.kasun.discordleaderboards.Leaderboard.LeaderboardConfig; import java.io.IOException; import java.io.Reader; import java.sql.*; import java.util.LinkedHashMap; import java.util.Map; public class SqlUtils { public static void addUserDataToDatabase(String placeholderColumnName, String UUID, String name , double value){ MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("ALTER TABLE UserData ADD COLUMN IF NOT EXISTS " + placeholderColumnName + " DOUBLE;"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO UserData u USING (SELECT '" + UUID + "' AS PlayerUUID, '" + name + "' AS PlayerName, " + value + " AS " + placeholderColumnName + " FROM DUAL) data ON u.PlayerUUID = data.PlayerUUID WHEN MATCHED THEN UPDATE SET u." + placeholderColumnName + " = data." + placeholderColumnName + " WHEN NOT MATCHED THEN INSERT (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (data.PlayerUUID, data.PlayerName, data." + placeholderColumnName + ");"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.1]"); ex.printStackTrace(); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection connection = database.getConnection(); Statement statement = connection.createStatement(); // Check if the column exists in the table ResultSet resultSet = statement.executeQuery("SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'UserData' AND COLUMN_NAME = '" + placeholderColumnName + "'"); if (!resultSet.next()) { // Column does not exist, so add it statement.executeUpdate("ALTER TABLE UserData ADD COLUMN " + placeholderColumnName + " DOUBLE"); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.2]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement( "INSERT INTO UserData (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (?, ?, ?) " + "ON DUPLICATE KEY UPDATE " + placeholderColumnName + " = VALUES(" + placeholderColumnName + ")" ); preparedStatement.setString(1, UUID); preparedStatement.setString(2, name); preparedStatement.setDouble(3, value); preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.3]"); ex.printStackTrace(); } } } public static Map<String, Double> getTopPlayerMap(String placeholderColumnName, int top, boolean ishigherbetter) { Map<String, Double> topPlayerScores = new LinkedHashMap<>(); MainConfig mainConfig = new MainConfig(); try { Database database = new Database(); PreparedStatement preparedStatement; String databaseName = mainConfig.getStorageType(); // Get the name of the current database String query; if (ishigherbetter){ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } }else{ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } } preparedStatement = database.getConnection().prepareStatement(query); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { String playerName = rs.getString("PlayerName"); double score = rs.getDouble(placeholderColumnName); if (ishigherbetter){ if (score > 0){ topPlayerScores.put(playerName, score); } }else{ topPlayerScores.put(playerName, score); } } preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Userdata, please check your placeholders in leaderboard configs [code : 10]"); } return topPlayerScores; } public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);"); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { preparedStatement = database.getConnection().prepareStatement( "REPLACE INTO Schedule (Leaderboard, LastSent) VALUES (?, ?)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13.1]"); } } } public static boolean isScheduleAlredySent(String leaderboard){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{
preparedStatement = database.getConnection().prepareStatement("SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?");
preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { int count = rs.getInt("count"); return count > 0; } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 14]"); } return false; } public static Timestamp getScheduleLastSent(String leaderboard){ Timestamp lastsent = Timestamp.valueOf("2000-01-01 00:00:00"); //Default Value - for check if lastsent PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT " + "LastSent" + " FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { lastsent = rs.getTimestamp("LastSent"); } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 15]"); } return lastsent; } public static void setCache(String leaderboard, String cache) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("MERGE INTO LiveCache s USING (VALUES (?, ?)) data (Leaderboard, Cache) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.Cache = data.Cache WHEN NOT MATCHED THEN INSERT (Leaderboard, Cache) VALUES (data.Leaderboard, data.Cache);"); preparedStatement.setString(1, leaderboard); // Convert the 'cache' string to a Clob object Clob clob = conn.createClob(); clob.setString(1, cache); preparedStatement.setClob(2, clob); int rowsUpdated = preparedStatement.executeUpdate(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement( "INSERT INTO LiveCache (Leaderboard, Cache) VALUES (?, ?) " + "ON DUPLICATE KEY UPDATE Cache = VALUES(Cache)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setString(2, cache); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02.1]"); } } } public static String getCache(String leaderboard) { String cache = null; MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; ResultSet resultSet; try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("SELECT Cache FROM LiveCache WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Clob clob = resultSet.getClob("Cache"); Reader reader = clob.getCharacterStream(); StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, bytesRead); } cache = sb.toString(); } resultSet.close(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Live Cache [code : 03]"); } catch (IOException ex) { return null; } return cache; } public static void deleteAllValues(String tableName, String columnName) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try { if (mainConfig.getStorageType().equalsIgnoreCase("h2")) { preparedStatement = database.getConnection().prepareStatement( "DELETE FROM " + tableName + " WHERE " + columnName + " IS NOT NULL" ); } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { preparedStatement = database.getConnection().prepareStatement( "UPDATE " + tableName + " SET " + columnName + " = NULL" ); } else { throw new UnsupportedOperationException("Unsupported storage type: " + mainConfig.getStorageType()); } int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while deleting data in the database [code: 13]"); } } }
src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/ScheduleManager.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Schedules;\nimport org.bukkit.scheduler.BukkitRunnable;\nimport org.kasun.discordleaderboards.Configs.MainConfig;\nimport org.kasun.discordleaderboards.DiscordLeaderboards;\nimport org.kasun.discordleaderboards.Leaderboard.Leaderboard;\nimport java.util.List;\npublic class ScheduleManager {\n public ScheduleManager() {\n MainConfig mainConfig = new MainConfig();\n if (!mainConfig.isFirstTime()){", "score": 0.8717812299728394 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS Schedule (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" LastSent TIMESTAMP\" +\n \");\");\n preparedStatement.execute();\n preparedStatement.close();\n preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS LiveCache (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" Cache \" + largetextsqltype +\n \");\");", "score": 0.862853467464447 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": " }\n }else {\n leaderboard.send();\n setLastSent();\n }\n }\n public void setLastSent(){\n String leaderboardname = leaderboard.getName();\n Timestamp currenttimestamp = TimeUtils.getCurrentTimeStamp();\n SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp);", "score": 0.8619506359100342 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": " }\n public Timestamp getLastSent(){\n String leaderboardname = leaderboard.getName();\n Timestamp lastsent = SqlUtils.getScheduleLastSent(leaderboardname);\n return lastsent;\n }\n public boolean isAlredySent(){\n String leaderboardname = leaderboard.getName();\n isalredysent = SqlUtils.isScheduleAlredySent(leaderboardname);\n return isalredysent;", "score": 0.860061764717102 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Schedules;\nimport org.kasun.discordleaderboards.Database.Cache;\nimport org.kasun.discordleaderboards.Leaderboard.Leaderboard;\nimport org.kasun.discordleaderboards.Utils.SqlUtils;\nimport org.kasun.discordleaderboards.Utils.TimeUtils;\nimport java.sql.Timestamp;\npublic class Schedule {\n private final String delay;\n private final Leaderboard leaderboard;\n private boolean isalredysent;", "score": 0.8554125428199768 } ]
java
preparedStatement = database.getConnection().prepareStatement("SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?");
package org.kasun.discordleaderboards.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Database.Database; import org.kasun.discordleaderboards.Leaderboard.LeaderboardConfig; import java.io.IOException; import java.io.Reader; import java.sql.*; import java.util.LinkedHashMap; import java.util.Map; public class SqlUtils { public static void addUserDataToDatabase(String placeholderColumnName, String UUID, String name , double value){ MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("ALTER TABLE UserData ADD COLUMN IF NOT EXISTS " + placeholderColumnName + " DOUBLE;"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO UserData u USING (SELECT '" + UUID + "' AS PlayerUUID, '" + name + "' AS PlayerName, " + value + " AS " + placeholderColumnName + " FROM DUAL) data ON u.PlayerUUID = data.PlayerUUID WHEN MATCHED THEN UPDATE SET u." + placeholderColumnName + " = data." + placeholderColumnName + " WHEN NOT MATCHED THEN INSERT (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (data.PlayerUUID, data.PlayerName, data." + placeholderColumnName + ");"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.1]"); ex.printStackTrace(); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection connection = database.getConnection(); Statement statement = connection.createStatement(); // Check if the column exists in the table ResultSet resultSet = statement.executeQuery("SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'UserData' AND COLUMN_NAME = '" + placeholderColumnName + "'"); if (!resultSet.next()) { // Column does not exist, so add it statement.executeUpdate("ALTER TABLE UserData ADD COLUMN " + placeholderColumnName + " DOUBLE"); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.2]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement( "INSERT INTO UserData (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (?, ?, ?) " + "ON DUPLICATE KEY UPDATE " + placeholderColumnName + " = VALUES(" + placeholderColumnName + ")" ); preparedStatement.setString(1, UUID); preparedStatement.setString(2, name); preparedStatement.setDouble(3, value); preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.3]"); ex.printStackTrace(); } } } public static Map<String, Double> getTopPlayerMap(String placeholderColumnName, int top, boolean ishigherbetter) { Map<String, Double> topPlayerScores = new LinkedHashMap<>(); MainConfig mainConfig = new MainConfig(); try { Database database = new Database(); PreparedStatement preparedStatement; String databaseName = mainConfig.getStorageType(); // Get the name of the current database String query; if (ishigherbetter){ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } }else{ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } } preparedStatement = database.getConnection().prepareStatement(query); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { String playerName = rs.getString("PlayerName"); double score = rs.getDouble(placeholderColumnName); if (ishigherbetter){ if (score > 0){ topPlayerScores.put(playerName, score); } }else{ topPlayerScores.put(playerName, score); } } preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Userdata, please check your placeholders in leaderboard configs [code : 10]"); } return topPlayerScores; } public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);"); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { preparedStatement = database.getConnection().prepareStatement( "REPLACE INTO Schedule (Leaderboard, LastSent) VALUES (?, ?)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13.1]"); } } } public static boolean isScheduleAlredySent(String leaderboard){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { int count = rs.getInt("count"); return count > 0; } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 14]"); } return false; } public static Timestamp getScheduleLastSent(String leaderboard){ Timestamp lastsent = Timestamp.valueOf("2000-01-01 00:00:00"); //Default Value - for check if lastsent PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT " + "LastSent" + " FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { lastsent = rs.getTimestamp("LastSent"); } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 15]"); } return lastsent; } public static void setCache(String leaderboard, String cache) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("MERGE INTO LiveCache s USING (VALUES (?, ?)) data (Leaderboard, Cache) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.Cache = data.Cache WHEN NOT MATCHED THEN INSERT (Leaderboard, Cache) VALUES (data.Leaderboard, data.Cache);"); preparedStatement.setString(1, leaderboard); // Convert the 'cache' string to a Clob object Clob clob = conn.createClob(); clob.setString(1, cache); preparedStatement.setClob(2, clob); int rowsUpdated = preparedStatement.executeUpdate(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement( "INSERT INTO LiveCache (Leaderboard, Cache) VALUES (?, ?) " + "ON DUPLICATE KEY UPDATE Cache = VALUES(Cache)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setString(2, cache); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02.1]"); } } } public static String getCache(String leaderboard) { String cache = null; MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; ResultSet resultSet; try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("SELECT Cache FROM LiveCache WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Clob clob = resultSet.getClob("Cache"); Reader reader = clob.getCharacterStream(); StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, bytesRead); } cache = sb.toString(); } resultSet.close(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Live Cache [code : 03]"); } catch (IOException ex) { return null; } return cache; } public static void deleteAllValues(String tableName, String columnName) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try { if (mainConfig.getStorageType().equalsIgnoreCase("h2")) { preparedStatement = database.getConnection().prepareStatement( "DELETE FROM " + tableName + " WHERE " + columnName + " IS NOT NULL" ); } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) {
preparedStatement = database.getConnection().prepareStatement( "UPDATE " + tableName + " SET " + columnName + " = NULL" );
} else { throw new UnsupportedOperationException("Unsupported storage type: " + mainConfig.getStorageType()); } int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while deleting data in the database [code: 13]"); } } }
src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " }\n }\n return connection;\n }\n */\n public void initializeDatabase() {\n String largetextsqltype = \"CLOB\";\n if (mainConfig.getStorageType().equalsIgnoreCase(\"h2\")){\n largetextsqltype = \"CLOB\";\n } else if (mainConfig.getStorageType().equalsIgnoreCase(\"mysql\")) {", "score": 0.8541766405105591 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS Schedule (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" LastSent TIMESTAMP\" +\n \");\");\n preparedStatement.execute();\n preparedStatement.close();\n preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS LiveCache (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" Cache \" + largetextsqltype +\n \");\");", "score": 0.8475275039672852 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " } catch (SQLException e) {\n plugin.getLogger().severe(\"Failed to Connect H2 Database! [code: 07]\");\n e.printStackTrace();\n }\n } else if (mainConfig.getStorageType().equalsIgnoreCase(\"mysql\")) {\n String address = mainConfig.getMysqlAddress();\n String database = mainConfig.getMysqlDatabase();\n String username = mainConfig.getMysqlUsername();\n String password = mainConfig.getMysqlPassword();\n try {", "score": 0.8451091051101685 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " connection = DriverManager.getConnection(h2url);\n } catch (ClassNotFoundException e) {\n plugin.getLogger().severe(\"Database Driver Not Found ! [code : 06]\");\n } catch (SQLException e) {\n plugin.getLogger().severe(\"Failed to Connect H2 Database ! [code : 07]\");\n }\n } else if (mainConfig.getStorageType().equalsIgnoreCase(\"mysql\")) {\n String adderss = mainConfig.getMysqlAddress();\n String database = mainConfig.getMysqlDatabase();\n String username = mainConfig.getMysqlUsername();", "score": 0.8390569686889648 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " largetextsqltype = \"LONGTEXT\";\n }\n PreparedStatement preparedStatement;\n try {\n preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS UserData (\" +\n \" PlayerUUID varchar(255) PRIMARY KEY,\" +\n \" PlayerName varchar(255)\" +\n \");\");\n preparedStatement.execute();\n preparedStatement.close();", "score": 0.8385941982269287 } ]
java
preparedStatement = database.getConnection().prepareStatement( "UPDATE " + tableName + " SET " + columnName + " = NULL" );
package org.kasun.discordleaderboards.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Database.Database; import org.kasun.discordleaderboards.Leaderboard.LeaderboardConfig; import java.io.IOException; import java.io.Reader; import java.sql.*; import java.util.LinkedHashMap; import java.util.Map; public class SqlUtils { public static void addUserDataToDatabase(String placeholderColumnName, String UUID, String name , double value){ MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("ALTER TABLE UserData ADD COLUMN IF NOT EXISTS " + placeholderColumnName + " DOUBLE;"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO UserData u USING (SELECT '" + UUID + "' AS PlayerUUID, '" + name + "' AS PlayerName, " + value + " AS " + placeholderColumnName + " FROM DUAL) data ON u.PlayerUUID = data.PlayerUUID WHEN MATCHED THEN UPDATE SET u." + placeholderColumnName + " = data." + placeholderColumnName + " WHEN NOT MATCHED THEN INSERT (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (data.PlayerUUID, data.PlayerName, data." + placeholderColumnName + ");"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.1]"); ex.printStackTrace(); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection connection = database.getConnection(); Statement statement = connection.createStatement(); // Check if the column exists in the table ResultSet resultSet = statement.executeQuery("SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'UserData' AND COLUMN_NAME = '" + placeholderColumnName + "'"); if (!resultSet.next()) { // Column does not exist, so add it statement.executeUpdate("ALTER TABLE UserData ADD COLUMN " + placeholderColumnName + " DOUBLE"); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.2]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement( "INSERT INTO UserData (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (?, ?, ?) " + "ON DUPLICATE KEY UPDATE " + placeholderColumnName + " = VALUES(" + placeholderColumnName + ")" ); preparedStatement.setString(1, UUID); preparedStatement.setString(2, name); preparedStatement.setDouble(3, value); preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.3]"); ex.printStackTrace(); } } } public static Map<String, Double> getTopPlayerMap(String placeholderColumnName, int top, boolean ishigherbetter) { Map<String, Double> topPlayerScores = new LinkedHashMap<>(); MainConfig mainConfig = new MainConfig(); try { Database database = new Database(); PreparedStatement preparedStatement; String databaseName = mainConfig.getStorageType(); // Get the name of the current database String query; if (ishigherbetter){ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } }else{ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } } preparedStatement = database.getConnection().prepareStatement(query); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { String playerName = rs.getString("PlayerName"); double score = rs.getDouble(placeholderColumnName); if (ishigherbetter){ if (score > 0){ topPlayerScores.put(playerName, score); } }else{ topPlayerScores.put(playerName, score); } } preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Userdata, please check your placeholders in leaderboard configs [code : 10]"); } return topPlayerScores; } public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);"); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { preparedStatement = database.getConnection().prepareStatement( "REPLACE INTO Schedule (Leaderboard, LastSent) VALUES (?, ?)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13.1]"); } } } public static boolean isScheduleAlredySent(String leaderboard){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { int count = rs.getInt("count"); return count > 0; } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 14]"); } return false; } public static Timestamp getScheduleLastSent(String leaderboard){ Timestamp lastsent = Timestamp.valueOf("2000-01-01 00:00:00"); //Default Value - for check if lastsent PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement =
database.getConnection().prepareStatement("SELECT " + "LastSent" + " FROM Schedule WHERE Leaderboard = ?");
preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { lastsent = rs.getTimestamp("LastSent"); } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 15]"); } return lastsent; } public static void setCache(String leaderboard, String cache) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("MERGE INTO LiveCache s USING (VALUES (?, ?)) data (Leaderboard, Cache) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.Cache = data.Cache WHEN NOT MATCHED THEN INSERT (Leaderboard, Cache) VALUES (data.Leaderboard, data.Cache);"); preparedStatement.setString(1, leaderboard); // Convert the 'cache' string to a Clob object Clob clob = conn.createClob(); clob.setString(1, cache); preparedStatement.setClob(2, clob); int rowsUpdated = preparedStatement.executeUpdate(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement( "INSERT INTO LiveCache (Leaderboard, Cache) VALUES (?, ?) " + "ON DUPLICATE KEY UPDATE Cache = VALUES(Cache)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setString(2, cache); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02.1]"); } } } public static String getCache(String leaderboard) { String cache = null; MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; ResultSet resultSet; try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("SELECT Cache FROM LiveCache WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Clob clob = resultSet.getClob("Cache"); Reader reader = clob.getCharacterStream(); StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, bytesRead); } cache = sb.toString(); } resultSet.close(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Live Cache [code : 03]"); } catch (IOException ex) { return null; } return cache; } public static void deleteAllValues(String tableName, String columnName) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try { if (mainConfig.getStorageType().equalsIgnoreCase("h2")) { preparedStatement = database.getConnection().prepareStatement( "DELETE FROM " + tableName + " WHERE " + columnName + " IS NOT NULL" ); } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { preparedStatement = database.getConnection().prepareStatement( "UPDATE " + tableName + " SET " + columnName + " = NULL" ); } else { throw new UnsupportedOperationException("Unsupported storage type: " + mainConfig.getStorageType()); } int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while deleting data in the database [code: 13]"); } } }
src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": " }\n public Timestamp getLastSent(){\n String leaderboardname = leaderboard.getName();\n Timestamp lastsent = SqlUtils.getScheduleLastSent(leaderboardname);\n return lastsent;\n }\n public boolean isAlredySent(){\n String leaderboardname = leaderboard.getName();\n isalredysent = SqlUtils.isScheduleAlredySent(leaderboardname);\n return isalredysent;", "score": 0.9096627235412598 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": " }\n }else {\n leaderboard.send();\n setLastSent();\n }\n }\n public void setLastSent(){\n String leaderboardname = leaderboard.getName();\n Timestamp currenttimestamp = TimeUtils.getCurrentTimeStamp();\n SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp);", "score": 0.8891826272010803 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Schedules;\nimport org.kasun.discordleaderboards.Database.Cache;\nimport org.kasun.discordleaderboards.Leaderboard.Leaderboard;\nimport org.kasun.discordleaderboards.Utils.SqlUtils;\nimport org.kasun.discordleaderboards.Utils.TimeUtils;\nimport java.sql.Timestamp;\npublic class Schedule {\n private final String delay;\n private final Leaderboard leaderboard;\n private boolean isalredysent;", "score": 0.856093168258667 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS Schedule (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" LastSent TIMESTAMP\" +\n \");\");\n preparedStatement.execute();\n preparedStatement.close();\n preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS LiveCache (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" Cache \" + largetextsqltype +\n \");\");", "score": 0.8517980575561523 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": " private final long SECSFORHOUR = 3600;\n private final long SECSFORDAY = 86400;\n private final long SECSFORWEEK = 604800;\n private final long SECSSFORMONTH = 2629746;\n public Schedule(Leaderboard leaderboard) {\n this.leaderboard = leaderboard;\n delay = leaderboard.getConfig().getDelay();\n }\n public void run() {\n if (isAlredySent()){", "score": 0.8419675230979919 } ]
java
database.getConnection().prepareStatement("SELECT " + "LastSent" + " FROM Schedule WHERE Leaderboard = ?");
package org.kasun.discordleaderboards.Database; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Utils.PlayerUtils; import org.kasun.discordleaderboards.Utils.SqlUtils; import java.util.List; import java.util.concurrent.CompletableFuture; public class UserData { private final MainConfig mainConfig = new MainConfig(); private final Database database = new Database(); private Player player; private OfflinePlayer offlinePlayer; private String placeholder; private String username; private String uuid; private double value; String placeholderColumnName; //constructers public UserData() {} public UserData(Player player, String placeholder) { this.player = player; this.placeholder = placeholder; placeholderColumnName = placeholder.substring(1, placeholder.length() - 1); uuid = player.getUniqueId().toString(); try{ value = Double.parseDouble(PlaceholderAPI.setPlaceholders(player, placeholder)); }catch (NumberFormatException e){ value = 0.0; } username = player.getName(); } public UserData(OfflinePlayer offlinePlayer, String placeholder) { this.offlinePlayer = offlinePlayer; this.placeholder = placeholder; placeholderColumnName = placeholder.substring(1, placeholder.length() - 1); uuid = offlinePlayer.getUniqueId().toString(); try{ value = Double.parseDouble(PlaceholderAPI.setPlaceholders(offlinePlayer, placeholder)); }catch (NumberFormatException e){ value = 0.0; } username = offlinePlayer.getName(); } //One Player One Placeholder public void addToDatabase(){ CompletableFuture.runAsync(() -> { SqlUtils.addUserDataToDatabase(placeholderColumnName, uuid, username, value); }); } //getters and setters public String getUserName(){ if (player != null){ username = player.getName(); } else if (offlinePlayer != null) { username = offlinePlayer.getName(); } return username; } public String getUuid(){ if (player != null){ uuid = player.getUniqueId().toString(); } else if (offlinePlayer != null) { uuid = offlinePlayer.getUniqueId().toString(); } return uuid; } public double getValue(){ if (player != null){ value = Double.parseDouble(PlaceholderAPI.setPlaceholders(player, placeholder)); } else if (offlinePlayer != null) { value = Double.parseDouble(PlaceholderAPI.setPlaceholders(offlinePlayer, placeholder)); } return value; } //One Player All Placeholders public void addUserDataToDBAllPlaceholders(Player player){ MainConfig mainConfig = new MainConfig(); List<String> leaderboardnamelist = mainConfig.getLeaderboardsList(); for (String lbname : leaderboardnamelist){ Leaderboard leaderboard = new Leaderboard(lbname); UserData userData = new UserData(player
, leaderboard.getConfig().getPlaceholder());
userData.addToDatabase(); } } //One Player All Placeholders public void addUserDataToDBAllPlaceholders(OfflinePlayer offlinePlayer){ MainConfig mainConfig = new MainConfig(); List<String> leaderboardnamelist = mainConfig.getLeaderboardsList(); for (String lbname : leaderboardnamelist){ Leaderboard leaderboard = new Leaderboard(lbname); String valuestring = PlaceholderAPI.setPlaceholders(offlinePlayer, leaderboard.getConfig().getPlaceholder()); if (valuestring != null && valuestring != ""){ UserData userData = new UserData(offlinePlayer, leaderboard.getConfig().getPlaceholder()); userData.addToDatabase(); } } } //All Players All Placeholders public void addUserDataToDBAllPlayersAllPlaceholders(){ List<OfflinePlayer> players = PlayerUtils.getAllPlayers(); for (OfflinePlayer player : players) { if (player != null){ addUserDataToDBAllPlaceholders(player); } } } //All Players One Placeholder (Dont use Void Constructer for this METHODE) public void addUserDataToDBAllPlayersThisPlaceholder(){ List<OfflinePlayer> players = PlayerUtils.getAllPlayers(); for (OfflinePlayer player : players) { if (player != null){ addToDatabase(); } } } public String getPlaceholder() { return placeholder; } }
src/main/java/org/kasun/discordleaderboards/Database/UserData.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Listeners/PlayerQuit.java", "retrieved_chunk": " UserData userData = new UserData();\n userData.addUserDataToDBAllPlaceholders(player);\n }\n}", "score": 0.9144024848937988 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Listeners/PlayerJoin.java", "retrieved_chunk": " UserData userData = new UserData();\n userData.addUserDataToDBAllPlaceholders(player);\n }\n}", "score": 0.9144024848937988 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " } catch (SQLException ex) {\n Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.RED + \"Issue while adding UserData to database [code : 09.3]\");\n ex.printStackTrace();\n }\n }\n }\n public static Map<String, Double> getTopPlayerMap(String placeholderColumnName, int top, boolean ishigherbetter) {\n Map<String, Double> topPlayerScores = new LinkedHashMap<>();\n MainConfig mainConfig = new MainConfig();\n try {", "score": 0.8586410284042358 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": "import java.util.Map;\npublic class SqlUtils {\n public static void addUserDataToDatabase(String placeholderColumnName, String UUID, String name , double value){\n MainConfig mainConfig = new MainConfig();\n Database database = new Database();\n PreparedStatement preparedStatement;\n if (mainConfig.getStorageType().equalsIgnoreCase(\"h2\")){\n try {\n preparedStatement = database.getConnection().prepareStatement(\"ALTER TABLE UserData ADD COLUMN IF NOT EXISTS \" + placeholderColumnName + \" DOUBLE;\");\n preparedStatement.execute();", "score": 0.8454213738441467 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Commands/DLCommand.java", "retrieved_chunk": " userData.addUserDataToDBAllPlayersThisPlaceholder();\n Bukkit.getScheduler().runTask(plugin, () -> {\n p.sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.YELLOW + \"Synchronization Complete !\");\n p.sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.GREEN + \"Leaderboard Created!\");\n p.sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.GRAY + \"you can change the settings from plugins\\\\DiscordLeaderboards\\\\leaderboard\\\\\" + args[1] + \".yml\");\n });\n });\n //getting random offline player\n List<OfflinePlayer> players = PlayerUtils.getAllPlayers();\n players.remove(p);", "score": 0.8444838523864746 } ]
java
, leaderboard.getConfig().getPlaceholder());
/* * SharedTexture * @author : keith@robot9.me * */ package me.robot9.shared; import android.app.Service; import android.content.Intent; import android.hardware.HardwareBuffer; import android.opengl.EGL14; import android.opengl.EGLSurface; import android.opengl.GLES20; import android.os.IBinder; import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.util.Log; import androidx.annotation.Nullable; public class OffscreenService extends Service { private static final String TAG = "OffscreenService"; private EGLCore outputEglCore = null; private EGLSurface outputEGLSurface = EGL14.EGL_NO_SURFACE; private SharedTexture sharedTexture; private int renderWidth = 0; private int renderHeight = 0; private int texId = 0; private int framebufferId = 0; private boolean renderReady = false; private float color = 0.f; @Nullable @Override public IBinder onBind(Intent intent) { return new IOffscreenInterface.Stub() { @Override public void init(HardwareBuffer buff, int width, int height) throws RemoteException { Log.d(TAG, "AIDL call: init"); renderWidth = width; renderHeight = height; outputEglCore.makeCurrent(outputEGLSurface); // create gl texture and bind to SharedTexture texId = EGLCore.createTexture(GLES20.GL_TEXTURE_2D); sharedTexture = new SharedTexture(buff); sharedTexture.bindTexture(texId); // render to texture int[] framebuffers = new int[1]; GLES20.glGenFramebuffers(1, framebuffers, 0); framebufferId = framebuffers[0]; GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebufferId); GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, texId, 0); renderReady = true; } @Override public ParcelFileDescriptor drawFrame() throws RemoteException { if (!renderReady) { return null; } outputEglCore.makeCurrent(outputEGLSurface); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebufferId); GLES20.glViewport(0, 0, renderWidth, renderHeight); // change clear color every frame color += 0.01f; if (color > 1.f) { color = 0.f; } GLES20.glClearColor(color, 0, 0, 1.0f); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); // TODO draw implementation GLES20.glFlush(); return sharedTexture.createFence(); } @Override public void destroy() throws RemoteException { Log.d(TAG, "AIDL call: destroy"); if (!renderReady) { return; } sharedTexture.release(); EGLCore.deleteTexture(texId); int[] frameBuffers = new int[]{framebufferId}; GLES20.glDeleteFramebuffers(frameBuffers.length, frameBuffers, 0); } }; } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); // create egl context outputEglCore = new EGLCore(EGL14.EGL_NO_CONTEXT, EGLCore.FLAG_TRY_GLES3);
outputEGLSurface = outputEglCore.createOffsetScreenSurface(renderWidth, renderHeight);
} @Override public void onDestroy() { Log.d(TAG, "onDestroy"); renderReady = false; outputEglCore.releaseSurface(outputEGLSurface); outputEglCore.release(); outputEglCore = null; outputEGLSurface = EGL14.EGL_NO_SURFACE; super.onDestroy(); } }
app/src/main/java/me/robot9/shared/OffscreenService.java
keith2018-SharedTexture-1995d41
[ { "filename": "app/src/main/java/me/robot9/shared/OnscreenRenderView.java", "retrieved_chunk": " @Override\n public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {\n firstFrame = true;\n }\n @Override\n public void onSurfaceChanged(GL10 gl10, int width, int height) {\n renderWidth = width;\n renderHeight = height;\n }\n @Override", "score": 0.9097893238067627 }, { "filename": "app/src/main/java/me/robot9/shared/MainActivity.java", "retrieved_chunk": " surfaceView.setSurfaceViewCallback(new OnscreenRenderView.SurfaceViewCallback() {\n @Override\n public void onCreated(int width, int height) {\n renderWidth = width;\n renderHeight = height;\n }\n @Override\n public void onDrawFrame() {\n GLES20.glClearColor(0, 0, 0, 0);\n GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);", "score": 0.9018856883049011 }, { "filename": "app/src/main/java/me/robot9/shared/EGLCore.java", "retrieved_chunk": " }\n return eglSurface;\n }\n public EGLSurface createOffsetScreenSurface(int width, int height) {\n int[] surfaceAttr = {EGL14.EGL_WIDTH, width,\n EGL14.EGL_HEIGHT, height,\n EGL14.EGL_NONE};\n EGLSurface eglSurface = EGL14.eglCreatePbufferSurface(mEGLDisplay, mEGLConfig, surfaceAttr, 0);\n if (eglSurface == null) {\n throw new RuntimeException(\"offset-screen surface is null\");", "score": 0.8874834179878235 }, { "filename": "app/src/main/java/me/robot9/shared/OnscreenRenderView.java", "retrieved_chunk": " super(context);\n init();\n }\n public OnscreenRenderView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init();\n }\n private void init() {\n setEGLContextClientVersion(3);\n setRenderer(new GLSurfaceView.Renderer() {", "score": 0.8869282007217407 }, { "filename": "app/src/main/java/me/robot9/shared/OnscreenRenderView.java", "retrieved_chunk": "import android.view.SurfaceHolder;\nimport javax.microedition.khronos.egl.EGLConfig;\nimport javax.microedition.khronos.opengles.GL10;\npublic class OnscreenRenderView extends GLSurfaceView {\n private static final String TAG = \"OnscreenRenderView\";\n private int renderWidth = 0;\n private int renderHeight = 0;\n private boolean firstFrame = true;\n private SurfaceViewCallback callback;\n public OnscreenRenderView(Context context) {", "score": 0.883935272693634 } ]
java
outputEGLSurface = outputEglCore.createOffsetScreenSurface(renderWidth, renderHeight);
/* * SharedTexture * @author : keith@robot9.me * */ package me.robot9.shared; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.opengl.GLES20; import android.os.Bundle; import android.os.IBinder; import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.util.Log; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import java.util.concurrent.atomic.AtomicBoolean; import me.robot9.shared.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private ActivityMainBinding binding; private OnscreenRenderView surfaceView; private ServiceConnection aidlConnection; private IOffscreenInterface aidlInterface; private QuadRenderer quadRenderer; private SharedTexture sharedTexture; private int renderWidth = 0; private int renderHeight = 0; private int texId = 0; private final AtomicBoolean aidlReady = new AtomicBoolean(false); private final AtomicBoolean renderReady = new AtomicBoolean(false); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); initGLSurfaceView(); if (!SharedTexture.isAvailable()) { Toast.makeText(this, "shared texture not available !", Toast.LENGTH_SHORT).show(); } } @Override protected void onStart() { super.onStart(); if (SharedTexture.isAvailable()) { startOffscreenService(); } surfaceView.onResume(); } @Override protected void onStop() { super.onStop(); if (SharedTexture.isAvailable()) { stopOffscreenService(); } surfaceView.onPause(); } private void initGLSurfaceView() { surfaceView = binding.surfaceView; surfaceView.setSurfaceViewCallback(new OnscreenRenderView.SurfaceViewCallback() { @Override public void onCreated(int width, int height) { renderWidth = width; renderHeight = height; } @Override public void onDrawFrame() { GLES20.glClearColor(0, 0, 0, 0); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); if (aidlReady.get()) { // init render context if (!renderReady.get()) { createRenderResources(); offscreenRenderInit(); } // draw frame offscreenRenderDrawFrame(); // draw shared texture
quadRenderer.drawTexture(texId, renderWidth, renderHeight);
} } @Override public void onDestroy() { destroyRenderResources(); } }); } private void createRenderResources() { Log.d(TAG, "createRenderResources"); quadRenderer = new QuadRenderer(); texId = EGLCore.createTexture(GLES20.GL_TEXTURE_2D); sharedTexture = new SharedTexture(renderWidth, renderHeight); sharedTexture.bindTexture(texId); renderReady.set(true); } private void destroyRenderResources() { Log.d(TAG, "destroyRenderResources"); renderReady.set(false); if (quadRenderer != null) { quadRenderer.release(); quadRenderer = null; } EGLCore.deleteTexture(texId); if (sharedTexture != null) { sharedTexture.release(); sharedTexture = null; } } private void offscreenRenderInit() { try { aidlInterface.init(sharedTexture.getHardwareBuffer(), renderWidth, renderHeight); } catch (RemoteException e) { e.printStackTrace(); } } private void offscreenRenderDrawFrame() { try { ParcelFileDescriptor fence = aidlInterface.drawFrame(); if (fence != null) { sharedTexture.waitFence(fence); } } catch (RemoteException e) { e.printStackTrace(); } } private void offscreenRenderDestroy() { try { aidlInterface.destroy(); } catch (RemoteException e) { e.printStackTrace(); } } private void startOffscreenService() { Log.d(TAG, "startOffscreenService"); if (aidlConnection == null) { aidlConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d(TAG, "onServiceConnected"); aidlInterface = IOffscreenInterface.Stub.asInterface(service); aidlReady.set(true); } @Override public void onServiceDisconnected(ComponentName name) { Log.d(TAG, "onServiceDisconnected"); } }; } Intent it = new Intent(this, OffscreenService.class); bindService(it, aidlConnection, BIND_AUTO_CREATE | BIND_IMPORTANT); } private void stopOffscreenService() { Log.d(TAG, "stopOffscreenService"); aidlReady.set(false); if (aidlInterface != null) { offscreenRenderDestroy(); aidlInterface = null; } if (aidlConnection != null) { unbindService(aidlConnection); aidlConnection = null; } } }
app/src/main/java/me/robot9/shared/MainActivity.java
keith2018-SharedTexture-1995d41
[ { "filename": "app/src/main/java/me/robot9/shared/OffscreenService.java", "retrieved_chunk": " sharedTexture = new SharedTexture(buff);\n sharedTexture.bindTexture(texId);\n // render to texture\n int[] framebuffers = new int[1];\n GLES20.glGenFramebuffers(1, framebuffers, 0);\n framebufferId = framebuffers[0];\n GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebufferId);\n GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, texId, 0);\n renderReady = true;\n }", "score": 0.8739223480224609 }, { "filename": "app/src/main/java/me/robot9/shared/OffscreenService.java", "retrieved_chunk": " @Override\n public ParcelFileDescriptor drawFrame() throws RemoteException {\n if (!renderReady) {\n return null;\n }\n outputEglCore.makeCurrent(outputEGLSurface);\n GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebufferId);\n GLES20.glViewport(0, 0, renderWidth, renderHeight);\n // change clear color every frame\n color += 0.01f;", "score": 0.8479949235916138 }, { "filename": "app/src/main/java/me/robot9/shared/OnscreenRenderView.java", "retrieved_chunk": " public void onDrawFrame(GL10 gl10) {\n if (firstFrame) {\n firstFrame = false;\n if (callback != null) {\n callback.onCreated(renderWidth, renderHeight);\n }\n }\n if (callback != null) {\n callback.onDrawFrame();\n }", "score": 0.8453618884086609 }, { "filename": "app/src/main/java/me/robot9/shared/OffscreenService.java", "retrieved_chunk": " public void destroy() throws RemoteException {\n Log.d(TAG, \"AIDL call: destroy\");\n if (!renderReady) {\n return;\n }\n sharedTexture.release();\n EGLCore.deleteTexture(texId);\n int[] frameBuffers = new int[]{framebufferId};\n GLES20.glDeleteFramebuffers(frameBuffers.length, frameBuffers, 0);\n }", "score": 0.8437047004699707 }, { "filename": "app/src/main/java/me/robot9/shared/OffscreenService.java", "retrieved_chunk": " public IBinder onBind(Intent intent) {\n return new IOffscreenInterface.Stub() {\n @Override\n public void init(HardwareBuffer buff, int width, int height) throws RemoteException {\n Log.d(TAG, \"AIDL call: init\");\n renderWidth = width;\n renderHeight = height;\n outputEglCore.makeCurrent(outputEGLSurface);\n // create gl texture and bind to SharedTexture\n texId = EGLCore.createTexture(GLES20.GL_TEXTURE_2D);", "score": 0.8435994982719421 } ]
java
quadRenderer.drawTexture(texId, renderWidth, renderHeight);
package org.kasun.discordleaderboards.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Database.Database; import org.kasun.discordleaderboards.Leaderboard.LeaderboardConfig; import java.io.IOException; import java.io.Reader; import java.sql.*; import java.util.LinkedHashMap; import java.util.Map; public class SqlUtils { public static void addUserDataToDatabase(String placeholderColumnName, String UUID, String name , double value){ MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("ALTER TABLE UserData ADD COLUMN IF NOT EXISTS " + placeholderColumnName + " DOUBLE;"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO UserData u USING (SELECT '" + UUID + "' AS PlayerUUID, '" + name + "' AS PlayerName, " + value + " AS " + placeholderColumnName + " FROM DUAL) data ON u.PlayerUUID = data.PlayerUUID WHEN MATCHED THEN UPDATE SET u." + placeholderColumnName + " = data." + placeholderColumnName + " WHEN NOT MATCHED THEN INSERT (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (data.PlayerUUID, data.PlayerName, data." + placeholderColumnName + ");"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.1]"); ex.printStackTrace(); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection connection = database.getConnection(); Statement statement = connection.createStatement(); // Check if the column exists in the table ResultSet resultSet = statement.executeQuery("SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'UserData' AND COLUMN_NAME = '" + placeholderColumnName + "'"); if (!resultSet.next()) { // Column does not exist, so add it statement.executeUpdate("ALTER TABLE UserData ADD COLUMN " + placeholderColumnName + " DOUBLE"); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.2]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement( "INSERT INTO UserData (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (?, ?, ?) " + "ON DUPLICATE KEY UPDATE " + placeholderColumnName + " = VALUES(" + placeholderColumnName + ")" ); preparedStatement.setString(1, UUID); preparedStatement.setString(2, name); preparedStatement.setDouble(3, value); preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.3]"); ex.printStackTrace(); } } } public static Map<String, Double> getTopPlayerMap(String placeholderColumnName, int top, boolean ishigherbetter) { Map<String, Double> topPlayerScores = new LinkedHashMap<>(); MainConfig mainConfig = new MainConfig(); try { Database database = new Database(); PreparedStatement preparedStatement; String databaseName = mainConfig.getStorageType(); // Get the name of the current database String query; if (ishigherbetter){ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } }else{ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } } preparedStatement = database.getConnection().prepareStatement(query); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { String playerName = rs.getString("PlayerName"); double score = rs.getDouble(placeholderColumnName); if (ishigherbetter){ if (score > 0){ topPlayerScores.put(playerName, score); } }else{ topPlayerScores.put(playerName, score); } } preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Userdata, please check your placeholders in leaderboard configs [code : 10]"); } return topPlayerScores; } public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement =
database.getConnection().prepareStatement("MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);
"); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { preparedStatement = database.getConnection().prepareStatement( "REPLACE INTO Schedule (Leaderboard, LastSent) VALUES (?, ?)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13.1]"); } } } public static boolean isScheduleAlredySent(String leaderboard){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { int count = rs.getInt("count"); return count > 0; } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 14]"); } return false; } public static Timestamp getScheduleLastSent(String leaderboard){ Timestamp lastsent = Timestamp.valueOf("2000-01-01 00:00:00"); //Default Value - for check if lastsent PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT " + "LastSent" + " FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { lastsent = rs.getTimestamp("LastSent"); } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 15]"); } return lastsent; } public static void setCache(String leaderboard, String cache) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("MERGE INTO LiveCache s USING (VALUES (?, ?)) data (Leaderboard, Cache) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.Cache = data.Cache WHEN NOT MATCHED THEN INSERT (Leaderboard, Cache) VALUES (data.Leaderboard, data.Cache);"); preparedStatement.setString(1, leaderboard); // Convert the 'cache' string to a Clob object Clob clob = conn.createClob(); clob.setString(1, cache); preparedStatement.setClob(2, clob); int rowsUpdated = preparedStatement.executeUpdate(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement( "INSERT INTO LiveCache (Leaderboard, Cache) VALUES (?, ?) " + "ON DUPLICATE KEY UPDATE Cache = VALUES(Cache)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setString(2, cache); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02.1]"); } } } public static String getCache(String leaderboard) { String cache = null; MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; ResultSet resultSet; try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("SELECT Cache FROM LiveCache WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Clob clob = resultSet.getClob("Cache"); Reader reader = clob.getCharacterStream(); StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, bytesRead); } cache = sb.toString(); } resultSet.close(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Live Cache [code : 03]"); } catch (IOException ex) { return null; } return cache; } public static void deleteAllValues(String tableName, String columnName) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try { if (mainConfig.getStorageType().equalsIgnoreCase("h2")) { preparedStatement = database.getConnection().prepareStatement( "DELETE FROM " + tableName + " WHERE " + columnName + " IS NOT NULL" ); } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { preparedStatement = database.getConnection().prepareStatement( "UPDATE " + tableName + " SET " + columnName + " = NULL" ); } else { throw new UnsupportedOperationException("Unsupported storage type: " + mainConfig.getStorageType()); } int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while deleting data in the database [code: 13]"); } } }
src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": " }\n }else {\n leaderboard.send();\n setLastSent();\n }\n }\n public void setLastSent(){\n String leaderboardname = leaderboard.getName();\n Timestamp currenttimestamp = TimeUtils.getCurrentTimeStamp();\n SqlUtils.setScheduleLastSent(leaderboardname, currenttimestamp);", "score": 0.8800786733627319 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": " }\n public Timestamp getLastSent(){\n String leaderboardname = leaderboard.getName();\n Timestamp lastsent = SqlUtils.getScheduleLastSent(leaderboardname);\n return lastsent;\n }\n public boolean isAlredySent(){\n String leaderboardname = leaderboard.getName();\n isalredysent = SqlUtils.isScheduleAlredySent(leaderboardname);\n return isalredysent;", "score": 0.8706789612770081 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/Database.java", "retrieved_chunk": " preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS Schedule (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" LastSent TIMESTAMP\" +\n \");\");\n preparedStatement.execute();\n preparedStatement.close();\n preparedStatement = getConnection().prepareStatement(\"CREATE TABLE IF NOT EXISTS LiveCache (\" +\n \" Leaderboard varchar(255) PRIMARY KEY,\" +\n \" Cache \" + largetextsqltype +\n \");\");", "score": 0.846332311630249 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Schedules/Schedule.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Schedules;\nimport org.kasun.discordleaderboards.Database.Cache;\nimport org.kasun.discordleaderboards.Leaderboard.Leaderboard;\nimport org.kasun.discordleaderboards.Utils.SqlUtils;\nimport org.kasun.discordleaderboards.Utils.TimeUtils;\nimport java.sql.Timestamp;\npublic class Schedule {\n private final String delay;\n private final Leaderboard leaderboard;\n private boolean isalredysent;", "score": 0.8392633199691772 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " }\n public Map<String, Double> getTopListAsMap() {\n int top = leaderboardConfig.getTop();\n return SqlUtils.getTopPlayerMap(placeholderColumnName, top, leaderboardConfig.isHigherisbetter());\n }\n public String getTopListAsString(boolean isWebhookFormat) {\n Map<String, Double> toplistmap = getTopListAsMap();\n int maxNameLength = getmaxnamelenght(toplistmap);\n StringBuilder sb = new StringBuilder();\n int i = 1;", "score": 0.8221760988235474 } ]
java
database.getConnection().prepareStatement("MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);
package me.khajiitos.servercountryflags.common.config; import me.khajiitos.servercountryflags.common.ServerCountryFlags; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen; import net.minecraft.client.resources.language.LanguageManager; import java.io.*; import java.lang.reflect.Field; import java.nio.file.*; import java.util.Arrays; import java.util.Optional; import java.util.Properties; public class Config { public static class Values { @ConfigEntry(name = "Flag border", description = "Displays a border around flags", configCategory = "Border") public boolean flagBorder = true; @ConfigEntry(name = "Border color R", description = "Red channel value for the border color around flags", configCategory = "Border", constraints = @Constraints(maxValue = 255)) public int borderR = 65; @ConfigEntry(name = "Border color G", description = "Green channel value for the border color around flags", configCategory = "Border", constraints = @Constraints(maxValue = 255)) public int borderG = 65; @ConfigEntry(name = "Border color B", description = "Blue channel value for the border color around flags", configCategory = "Border", constraints = @Constraints(maxValue = 255)) public int borderB = 65; @ConfigEntry(name = "Border color A", description = "Alpha channel value for the border color around flags", configCategory = "Border", constraints = @Constraints(maxValue = 255)) public int borderA = 255; @ConfigEntry(name = "Reload on refresh", description = "Forces flags to be reloaded when the server list is refreshed") public boolean reloadOnRefresh = false; @ConfigEntry(name = "Show distance", description = "Shows the approximate distance between the server and you when you hover over a flag", configCategory = "Preferences") public boolean showDistance = true; @ConfigEntry(name = "Use kilometers", description = "Uses kilometers instead of miles", configCategory = "Locale") public boolean useKm = true; @ConfigEntry(name = "Force English", description = "Forces the API results to be in English instead of your in-game language", configCategory = "Locale") public boolean forceEnglish = false; @ConfigEntry(name = "Display unknown flag", description = "Displays the unknown flag when we don't have data about the server yet") public boolean displayUnknownFlag = true; @ConfigEntry(name = "Display cooldown flag", description = "Displays a timeout flag when we have an API cooldown") public boolean displayCooldownFlag = true; @ConfigEntry(name = "Show district", description = "Shows the district of the location too, if available") public boolean showDistrict = false; @ConfigEntry(name = "Show ISP", description = "Shows the ISP of the host, if available") public boolean showISP = false; @ConfigEntry(name = "Map button", description = "Shows a map button in the server list which opens the server map", configCategory = "Preferences") public boolean mapButton = true; @ConfigEntry(name = "Map button on the right side", description = "Decides whether the map button should be on the right side or the left side", configCategory = "Preferences") public boolean mapButtonRight = true; @ConfigEntry(name = "Show home on map", description = "Shows your location on the server map too", configCategory = "Preferences") public boolean showHomeOnMap = true; @ConfigEntry(name = "Resolve SRV redirects", description = "Uses the redirected IP (if present) instead of just the resolved IP") public boolean resolveRedirects = true; @ConfigEntry(name = "Flag position", description = "Changes the flags' positions. Available options: default, left, right, behindName", stringValues = {"default", "left", "right", "behindName"}, configCategory = "Preferences") public String flagPosition = "behindName"; } private static File configDirectory; private static File propertiesFile; private static WatchService watchService; // DO NOT TOUCH public static final Config.Values DEFAULT = new Config.Values(); // but feel free to touch this one :) public static final Config.Values cfg = new Config.Values(); public static void init() { String minecraftDir = Minecraft.getInstance().gameDirectory.getAbsolutePath(); configDirectory = new File(minecraftDir + "/config/" + ServerCountryFlags.MOD_ID); propertiesFile = new File(configDirectory.getAbsolutePath() + "/" + ServerCountryFlags.MOD_ID + ".properties"); load(); registerWatchService(); } public static void load() { Properties properties = new Properties(); boolean loadedProperties = false; try { properties.load(new FileInputStream(propertiesFile)); loadedProperties = true; } catch (FileNotFoundException e) { ServerCountryFlags.LOGGER.info("Our properties file doesn't exist, creating it"); try { boolean ignored = configDirectory.mkdirs(); if (!propertiesFile.createNewFile()) { ServerCountryFlags.LOGGER.warn("Our properties file actually exists... What?"); } save(); } catch (IOException ex) { ServerCountryFlags.LOGGER.error("Couldn't create the properties file"); ServerCountryFlags.LOGGER.error(ex.getMessage()); } } catch (IOException e) { ServerCountryFlags.LOGGER.error("Couldn't read the properties file"); ServerCountryFlags.LOGGER.error(e.getMessage()); } if (!loadedProperties) return; boolean rewriteConfig = false; for (Field field : Config.Values.class.getDeclaredFields()) { ConfigEntry annotation = field.getAnnotation(ConfigEntry.class); if (annotation != null) { String propertiesValue = properties.getProperty(field.getName()); if (propertiesValue == null) { rewriteConfig = true; } else { try { if (field.getType() == String.class) { field.set(cfg, propertiesValue); } else if (field.getType() == boolean.class) { field.setBoolean(cfg, Boolean.parseBoolean(propertiesValue)); } else if (field.getType() == int.class) { Optional<Constraints> constraints = Arrays.stream(annotation.constraints()).findFirst(); int value = Integer.parseInt(propertiesValue); if (constraints.isPresent()) { value = Math.max(Math.min(value, constraints.get().maxValue()), constraints.get().minValue()); } field.setInt(cfg, value); } else if (field.getType() == float.class) { field.setFloat(cfg, Float.parseFloat(propertiesValue)); } else { ServerCountryFlags.LOGGER.warn("Bug: unsupported config type " + field.getType().getSimpleName()); } } catch (IllegalAccessException e) { ServerCountryFlags.LOGGER.warn("Bug: can't modify a config field"); } catch (NumberFormatException e) { ServerCountryFlags.LOGGER.warn("Field " + field.getName() + " in the properties type is not of type " + field.getType().getSimpleName()); } } } } if (rewriteConfig) { ServerCountryFlags.LOGGER.info("Properties file doesn't contain all fields available, rewriting it"); save(); } afterLoad(); } private static void afterLoad() { if (cfg.forceEnglish) {
ServerCountryFlags.updateAPILanguage(null);
} else { LanguageManager languageManager = Minecraft.getInstance().getLanguageManager(); // IntelliJ claims that languageManager will never be null // but that's actually not the case if (languageManager != null) { ServerCountryFlags.updateAPILanguage(languageManager.getSelected()); } } // So that the map button appears/disappears without having to reopen the screen Screen screen = Minecraft.getInstance().screen; if (screen instanceof JoinMultiplayerScreen) { screen.resize(Minecraft.getInstance(), screen.width, screen.height); } } public static void save() { Properties properties = new Properties(); StringBuilder fieldsDescriptions = new StringBuilder(); for (Field field : Config.Values.class.getDeclaredFields()) { ConfigEntry annotation = field.getAnnotation(ConfigEntry.class); if (annotation != null) { try { String fieldName = field.getName(); if (!annotation.description().equals("")) { fieldsDescriptions.append("\n").append(fieldName).append(" - ").append(annotation.description()); } properties.setProperty(fieldName, String.valueOf(field.get(cfg))); } catch (IllegalAccessException e) { ServerCountryFlags.LOGGER.warn("Bug: can't access a config field"); } } } try { String comments = "Mod properties file"; if (!fieldsDescriptions.isEmpty()) { comments += "\nField descriptions:" + fieldsDescriptions; } properties.store(new FileOutputStream(propertiesFile), comments); } catch (FileNotFoundException e) { ServerCountryFlags.LOGGER.error("Couldn't save the properties file because it doesn't exist"); } catch (IOException e) { ServerCountryFlags.LOGGER.error("Couldn't save the properties file"); ServerCountryFlags.LOGGER.error(e.getMessage()); } } private static void registerWatchService() { try { watchService = FileSystems.getDefault().newWatchService(); Paths.get(propertiesFile.getParent()).register(watchService, StandardWatchEventKinds.ENTRY_MODIFY); Thread watcherThread = new Thread(() -> { try { while (true) { WatchKey key = watchService.take(); // Sometimes multiple events may be taken from updating the file once, sleeping prevents it Thread.sleep(250); if (!key.pollEvents().isEmpty()) { ServerCountryFlags.LOGGER.info("Properties file modified, reloading it"); load(); } key.reset(); } } catch (Exception e) { ServerCountryFlags.LOGGER.warn("WatchService closed"); } }); watcherThread.setName("File watcher"); watcherThread.start(); } catch (IOException e) { ServerCountryFlags.LOGGER.error("Couldn't initialize WatchService"); } } }
Common/src/main/java/me/khajiitos/servercountryflags/common/config/Config.java
Khajiitos-ServerCountryFlags-e056c80
[ { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/mixin/LanguageManagerMixin.java", "retrieved_chunk": "public class LanguageManagerMixin {\n @Inject(at = @At(\"TAIL\"), method = \"onResourceManagerReload\")\n public void onResourceManagerReload(ResourceManager manager, CallbackInfo info) {\n ServerCountryFlags.updateAPILanguage(Minecraft.getInstance().getLanguageManager().getSelected());\n }\n}", "score": 0.8296329975128174 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/screen/ServerMapScreen.java", "retrieved_chunk": " points.clear();\n ServerCountryFlags.servers.clear();\n ServerCountryFlags.localLocation = null;\n }\n if (ServerCountryFlags.localLocation == null || NetworkChangeDetector.check()) {\n ServerCountryFlags.updateLocalLocationInfo();\n }\n for (int i = 0; i < ServerCountryFlags.serverList.size(); i++) {\n if (ServerCountryFlags.servers.containsKey(ServerCountryFlags.serverList.get(i).ip)) {\n continue;", "score": 0.8233833312988281 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/ServerCountryFlags.java", "retrieved_chunk": "\t}\n\tpublic static void updateAPILanguage(String language) {\n\t\tfinal String oldApiLanguage = apiLanguage;\n\t\tif (Config.cfg.forceEnglish) {\n\t\t\tapiLanguage = null;\n\t\t} else if (language != null) {\n\t\t\tif (language.startsWith(\"en\")) apiLanguage = null;\n\t\t\telse if (language.startsWith(\"de\")) apiLanguage = \"de\";\n\t\t\telse if (language.startsWith(\"es\")) apiLanguage = \"es\";\n\t\t\telse if (language.startsWith(\"pt\")) apiLanguage = \"pt-BR\";", "score": 0.8219420313835144 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/ServerCountryFlags.java", "retrieved_chunk": "\t\t\telse if (language.startsWith(\"fr\")) apiLanguage = \"fr\";\n\t\t\telse if (language.startsWith(\"ja\")) apiLanguage = \"ja\";\n\t\t\telse if (language.startsWith(\"zn\")) apiLanguage = \"zn-CN\";\n\t\t\telse if (language.startsWith(\"ru\")) apiLanguage = \"ru\";\n\t\t\telse apiLanguage = null;\n\t\t}\n\t\tif (!Objects.equals(apiLanguage, oldApiLanguage)) {\n\t\t\tservers.clear();\n\t\t}\n\t}", "score": 0.8168232440948486 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/ServerCountryFlags.java", "retrieved_chunk": "import java.util.Optional;\nimport java.util.concurrent.CompletableFuture;\npublic class ServerCountryFlags {\n\tpublic static final String MOD_ID = \"servercountryflags\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\tpublic static final String API_NAME = \"http://ip-api.com/json/\";\n\tpublic static final int API_FIELDS = 541395;\n\tpublic static String apiLanguage = null;\n\tpublic static ServerList serverList; // Servers from the server list\n\tpublic static HashMap<String, APIResponse> servers = new HashMap<>(); // Servers' flags", "score": 0.8161795139312744 } ]
java
ServerCountryFlags.updateAPILanguage(null);
package me.khajiitos.servercountryflags.common; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.mojang.blaze3d.platform.NativeImage; import me.khajiitos.servercountryflags.common.config.Config; import me.khajiitos.servercountryflags.common.util.APIResponse; import me.khajiitos.servercountryflags.common.util.LocationInfo; import me.khajiitos.servercountryflags.common.util.NetworkChangeDetector; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ServerList; import net.minecraft.client.multiplayer.resolver.ResolvedServerAddress; import net.minecraft.client.multiplayer.resolver.ServerAddress; import net.minecraft.client.multiplayer.resolver.ServerAddressResolver; import net.minecraft.client.multiplayer.resolver.ServerRedirectHandler; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; public class ServerCountryFlags { public static final String MOD_ID = "servercountryflags"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); public static final String API_NAME = "http://ip-api.com/json/"; public static final int API_FIELDS = 541395; public static String apiLanguage = null; public static ServerList serverList; // Servers from the server list public static HashMap<String, APIResponse> servers = new HashMap<>(); // Servers' flags public static HashMap<String, Float> flagAspectRatios = new HashMap<>(); public static boolean flagAspectRatiosLoaded = false; public static ServerRedirectHandler redirectResolver = ServerRedirectHandler.createDnsSrvRedirectHandler(); public static LocationInfo localLocation = null; static <T> T last(T[] arr) { return arr[arr.length - 1]; } public static void init() { Config.init(); NetworkChangeDetector.check(); Minecraft.getInstance().execute(() -> { ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); Map<ResourceLocation, Resource> resourceLocations = resourceManager.listResources("textures/flags", path -> true); Thread flagThread = new Thread(() -> { for (Map.Entry<ResourceLocation, Resource> entry : resourceLocations.entrySet()) { if (!entry.getKey().getNamespace().equals(MOD_ID)) { continue; } try { if (entry.getValue() == null) { ServerCountryFlags.LOGGER.error("Failed to load resource " + entry.getKey().getPath()); continue; } try (InputStream inputStream = entry.getValue().open()) { NativeImage image = NativeImage.read(inputStream); String code = last(entry.getKey().getPath().split("/")); code = code.substring(0, code.length() - 4); flagAspectRatios.put(code, (float)image.getWidth() / (float)image.getHeight()); } } catch (IOException e) { LOGGER.error(e.getMessage()); } } flagAspectRatiosLoaded = true; }); flagThread.setName("Flag load thread"); flagThread.start(); }); updateLocalLocationInfo(); } public static void updateAPILanguage(String language) { final String oldApiLanguage = apiLanguage; if (Config.cfg.forceEnglish) { apiLanguage = null; } else if (language != null) { if (language.startsWith("en")) apiLanguage = null; else if (language.startsWith("de")) apiLanguage = "de"; else if (language.startsWith("es")) apiLanguage = "es"; else if (language.startsWith("pt")) apiLanguage = "pt-BR"; else if (language.startsWith("fr")) apiLanguage = "fr"; else if (language.startsWith("ja")) apiLanguage = "ja"; else if (language.startsWith("zn")) apiLanguage = "zn-CN"; else if (language.startsWith("ru")) apiLanguage = "ru"; else apiLanguage = null; } if (!Objects.equals(apiLanguage, oldApiLanguage)) { servers.clear(); } } public static @NotNull APIResponse getAPIResponse(String ip) { // If the IP is empty, the API will give us our location if (APITimeoutManager.isOnCooldown()) { return new APIResponse(APIResponse.Status.COOLDOWN, null); } String apiUrlStr = API_NAME + ip + "?fields=" + API_FIELDS; if (apiLanguage != null) { apiUrlStr += "&lang=" + apiLanguage; } try { APITimeoutManager.incrementRequestsSent(); URL apiUrl = new URL(apiUrlStr); URLConnection con = apiUrl.openConnection(); con.setConnectTimeout(3000); int requestsLeft = con.getHeaderFieldInt("X-Rl", -1); int secondsLeft = con.getHeaderFieldInt("X-Ttl", -1); APITimeoutManager.decrementRequestsSent(); if (requestsLeft != -1 && secondsLeft != -1) { APITimeoutManager
.setRequestsLeft(requestsLeft - APITimeoutManager.getRequestsSent());
APITimeoutManager.setSecondsLeftUntilReset(secondsLeft); } BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); JsonElement jsonElement = JsonParser.parseReader(reader); if (jsonElement == null) { ServerCountryFlags.LOGGER.error("Received something that's not JSON"); return new APIResponse(APIResponse.Status.UNKNOWN, null); } if (jsonElement.isJsonObject()) { return new APIResponse(APIResponse.Status.SUCCESS, new LocationInfo((JsonObject) jsonElement)); } else { ServerCountryFlags.LOGGER.error("Received JSON element, but it's not an object: " + jsonElement); return new APIResponse(APIResponse.Status.UNKNOWN, null); } } catch (MalformedURLException e) { ServerCountryFlags.LOGGER.error("Malformed API Url: " + apiUrlStr); } catch (UnknownHostException e) { ServerCountryFlags.LOGGER.error("Unknown host - no internet?"); } catch (IOException e) { ServerCountryFlags.LOGGER.error(e.getMessage()); } APITimeoutManager.decrementRequestsSent(); return new APIResponse(APIResponse.Status.UNKNOWN, null); } public static boolean isIpLocal(InetAddress address) { return address.isLoopbackAddress() || address.isLinkLocalAddress() || address.isSiteLocalAddress(); } public static void updateServerLocationInfo(String serverAddress) { CompletableFuture.runAsync(() -> { ServerAddress address = ServerAddress.parseString(serverAddress); if (Config.cfg.resolveRedirects) { Optional<ServerAddress> redirect = redirectResolver.lookupRedirect(address); if (redirect.isPresent()) { address = redirect.get(); } } Optional<ResolvedServerAddress> resolvedAddress = ServerAddressResolver.SYSTEM.resolve(address); if (resolvedAddress.isPresent()) { InetSocketAddress socketAddress = resolvedAddress.get().asInetSocketAddress(); String stringHostAddress = isIpLocal(socketAddress.getAddress()) ? "" : socketAddress.getAddress().getHostAddress(); APIResponse response = getAPIResponse(stringHostAddress); APIResponse oldResponse = servers.get(serverAddress); if (oldResponse == null || (oldResponse.unknown() || !response.unknown()) || (oldResponse.cooldown() && response.locationInfo() != null)) { servers.putIfAbsent(serverAddress, response); } } }); } public static void updateLocalLocationInfo() { CompletableFuture.runAsync(() -> { APIResponse response = getAPIResponse(""); if (response.locationInfo() != null) { localLocation = response.locationInfo(); for (APIResponse serverResponse : servers.values()) { if (!serverResponse.cooldown()) { serverResponse.locationInfo().updateDistanceFromLocal(); } } } }); } }
Common/src/main/java/me/khajiitos/servercountryflags/common/ServerCountryFlags.java
Khajiitos-ServerCountryFlags-e056c80
[ { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": " }\n public static void incrementRequestsSent() {\n requestsSent++;\n }\n public static void decrementRequestsSent() {\n requestsSent--;\n }\n public static void setRequestsLeft(int apiRequestsLeft) {\n requestsLeft = apiRequestsLeft;\n }", "score": 0.8393077850341797 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": "package me.khajiitos.servercountryflags.common;\npublic class APITimeoutManager {\n private static int requestsLeft = 45;\n private static long cooldownReset = -1;\n private static int requestsSent = 0;\n public static boolean isOnCooldown() {\n return requestsLeft <= 0 && System.currentTimeMillis() < cooldownReset;\n }\n public static int getRequestsSent() {\n return requestsSent;", "score": 0.8284021615982056 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": " public static void setSecondsLeftUntilReset(int apiSecondsLeft) {\n cooldownReset = System.currentTimeMillis() + apiSecondsLeft * 1000L;\n }\n}", "score": 0.7824185490608215 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/util/LocationInfo.java", "retrieved_chunk": " ServerCountryFlags.LOGGER.error(apiObject.toString());\n return;\n }\n } else {\n ServerCountryFlags.LOGGER.error(\"API Object doesn't include the field 'status'\");\n ServerCountryFlags.LOGGER.error(apiObject.toString());\n return;\n }\n if (apiObject.keySet().containsAll(List.of(\"country\", \"countryCode\", \"city\", \"lon\", \"lat\", \"district\", \"isp\"))) {\n this.countryName = apiObject.get(\"country\").getAsString();", "score": 0.7454416751861572 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/util/LocationInfo.java", "retrieved_chunk": " this.countryCode = apiObject.get(\"countryCode\").getAsString().toLowerCase();\n this.cityName = apiObject.get(\"city\").getAsString();\n this.districtName = apiObject.get(\"district\").getAsString();\n this.ispName = apiObject.get(\"isp\").getAsString();\n this.longitude = apiObject.get(\"lon\").getAsDouble();\n this.latitude = apiObject.get(\"lat\").getAsDouble();\n this.distanceFromLocal = calculateDistanceFromLocal();\n } else {\n ServerCountryFlags.LOGGER.error(\"API Object is incomplete\");\n ServerCountryFlags.LOGGER.error(apiObject.toString());", "score": 0.7442893981933594 } ]
java
.setRequestsLeft(requestsLeft - APITimeoutManager.getRequestsSent());
package org.kasun.discordleaderboards.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Database.Database; import org.kasun.discordleaderboards.Leaderboard.LeaderboardConfig; import java.io.IOException; import java.io.Reader; import java.sql.*; import java.util.LinkedHashMap; import java.util.Map; public class SqlUtils { public static void addUserDataToDatabase(String placeholderColumnName, String UUID, String name , double value){ MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("ALTER TABLE UserData ADD COLUMN IF NOT EXISTS " + placeholderColumnName + " DOUBLE;"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO UserData u USING (SELECT '" + UUID + "' AS PlayerUUID, '" + name + "' AS PlayerName, " + value + " AS " + placeholderColumnName + " FROM DUAL) data ON u.PlayerUUID = data.PlayerUUID WHEN MATCHED THEN UPDATE SET u." + placeholderColumnName + " = data." + placeholderColumnName + " WHEN NOT MATCHED THEN INSERT (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (data.PlayerUUID, data.PlayerName, data." + placeholderColumnName + ");"); preparedStatement.execute(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.1]"); ex.printStackTrace(); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection connection = database.getConnection(); Statement statement = connection.createStatement(); // Check if the column exists in the table ResultSet resultSet = statement.executeQuery("SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'UserData' AND COLUMN_NAME = '" + placeholderColumnName + "'"); if (!resultSet.next()) { // Column does not exist, so add it statement.executeUpdate("ALTER TABLE UserData ADD COLUMN " + placeholderColumnName + " DOUBLE"); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.2]"); ex.printStackTrace(); } try { preparedStatement = database.getConnection().prepareStatement( "INSERT INTO UserData (PlayerUUID, PlayerName, " + placeholderColumnName + ") VALUES (?, ?, ?) " + "ON DUPLICATE KEY UPDATE " + placeholderColumnName + " = VALUES(" + placeholderColumnName + ")" ); preparedStatement.setString(1, UUID); preparedStatement.setString(2, name); preparedStatement.setDouble(3, value); preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while adding UserData to database [code : 09.3]"); ex.printStackTrace(); } } } public static Map<String, Double> getTopPlayerMap(String placeholderColumnName, int top, boolean ishigherbetter) { Map<String, Double> topPlayerScores = new LinkedHashMap<>(); MainConfig mainConfig = new MainConfig(); try { Database database = new Database(); PreparedStatement preparedStatement;
String databaseName = mainConfig.getStorageType();
// Get the name of the current database String query; if (ishigherbetter){ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " DESC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } }else{ if (databaseName.equalsIgnoreCase("h2")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else if (databaseName.equalsIgnoreCase("mysql")) { query = "SELECT PlayerName, " + placeholderColumnName + " FROM UserData ORDER BY " + placeholderColumnName + " ASC LIMIT " + top; } else { // Unsupported database type throw new UnsupportedOperationException("Unsupported database type: " + databaseName); } } preparedStatement = database.getConnection().prepareStatement(query); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { String playerName = rs.getString("PlayerName"); double score = rs.getDouble(placeholderColumnName); if (ishigherbetter){ if (score > 0){ topPlayerScores.put(playerName, score); } }else{ topPlayerScores.put(playerName, score); } } preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Userdata, please check your placeholders in leaderboard configs [code : 10]"); } return topPlayerScores; } public static void setScheduleLastSent(String leaderboard, Timestamp timestamp){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { preparedStatement = database.getConnection().prepareStatement("MERGE INTO Schedule s USING (VALUES (?, ?)) data (Leaderboard, LastSent) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.LastSent = data.LastSent WHEN NOT MATCHED THEN INSERT (Leaderboard, LastSent) VALUES (data.Leaderboard, data.LastSent);"); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { preparedStatement = database.getConnection().prepareStatement( "REPLACE INTO Schedule (Leaderboard, LastSent) VALUES (?, ?)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setTimestamp(2, timestamp); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 13.1]"); } } } public static boolean isScheduleAlredySent(String leaderboard){ PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT COUNT(*) AS count FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { int count = rs.getInt("count"); return count > 0; } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 14]"); } return false; } public static Timestamp getScheduleLastSent(String leaderboard){ Timestamp lastsent = Timestamp.valueOf("2000-01-01 00:00:00"); //Default Value - for check if lastsent PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try{ preparedStatement = database.getConnection().prepareStatement("SELECT " + "LastSent" + " FROM Schedule WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { lastsent = rs.getTimestamp("LastSent"); } preparedStatement.close(); }catch (SQLException ex){ Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading data in database [code : 15]"); } return lastsent; } public static void setCache(String leaderboard, String cache) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); if (mainConfig.getStorageType().equalsIgnoreCase("h2")){ try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("MERGE INTO LiveCache s USING (VALUES (?, ?)) data (Leaderboard, Cache) ON s.Leaderboard = data.Leaderboard WHEN MATCHED THEN UPDATE SET s.Cache = data.Cache WHEN NOT MATCHED THEN INSERT (Leaderboard, Cache) VALUES (data.Leaderboard, data.Cache);"); preparedStatement.setString(1, leaderboard); // Convert the 'cache' string to a Clob object Clob clob = conn.createClob(); clob.setString(1, cache); preparedStatement.setClob(2, clob); int rowsUpdated = preparedStatement.executeUpdate(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02]"); } } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement( "INSERT INTO LiveCache (Leaderboard, Cache) VALUES (?, ?) " + "ON DUPLICATE KEY UPDATE Cache = VALUES(Cache)" ); preparedStatement.setString(1, leaderboard); preparedStatement.setString(2, cache); int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while saving Live Cache [code : 02.1]"); } } } public static String getCache(String leaderboard) { String cache = null; MainConfig mainConfig = new MainConfig(); Database database = new Database(); PreparedStatement preparedStatement; ResultSet resultSet; try { Connection conn = database.getConnection(); preparedStatement = conn.prepareStatement("SELECT Cache FROM LiveCache WHERE Leaderboard = ?"); preparedStatement.setString(1, leaderboard); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Clob clob = resultSet.getClob("Cache"); Reader reader = clob.getCharacterStream(); StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, bytesRead); } cache = sb.toString(); } resultSet.close(); preparedStatement.close(); conn.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while reading Live Cache [code : 03]"); } catch (IOException ex) { return null; } return cache; } public static void deleteAllValues(String tableName, String columnName) { PreparedStatement preparedStatement; MainConfig mainConfig = new MainConfig(); Database database = new Database(); try { if (mainConfig.getStorageType().equalsIgnoreCase("h2")) { preparedStatement = database.getConnection().prepareStatement( "DELETE FROM " + tableName + " WHERE " + columnName + " IS NOT NULL" ); } else if (mainConfig.getStorageType().equalsIgnoreCase("mysql")) { preparedStatement = database.getConnection().prepareStatement( "UPDATE " + tableName + " SET " + columnName + " = NULL" ); } else { throw new UnsupportedOperationException("Unsupported storage type: " + mainConfig.getStorageType()); } int rowsUpdated = preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException ex) { Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Issue while deleting data in the database [code: 13]"); } } }
src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " }\n public Map<String, Double> getTopListAsMap() {\n int top = leaderboardConfig.getTop();\n return SqlUtils.getTopPlayerMap(placeholderColumnName, top, leaderboardConfig.isHigherisbetter());\n }\n public String getTopListAsString(boolean isWebhookFormat) {\n Map<String, Double> toplistmap = getTopListAsMap();\n int maxNameLength = getmaxnamelenght(toplistmap);\n StringBuilder sb = new StringBuilder();\n int i = 1;", "score": 0.9039921164512634 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Leaderboard;\nimport org.kasun.discordleaderboards.Utils.SqlUtils;\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.util.Map;\npublic class TopList {\n private final int top;\n private final LeaderboardConfig leaderboardConfig;\n private final String placeholder;", "score": 0.8667044043540955 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/DescriptionGenerator.java", "retrieved_chunk": " }\n //{top-1-name} {top-1-score} placeholders\n Map<String, Double> playerScores = topList.getTopListAsMap();\n Pattern pattern = Pattern.compile(\"\\\\{top-(\\\\d+)-(name|score)\\\\}\");\n Matcher matcher = pattern.matcher(description);\n while (matcher.find()) {\n int position = Integer.parseInt(matcher.group(1));\n String placeholderType = matcher.group(2);\n Comparator<Map.Entry<String, Double>> scoreComparator;\n if (isHigherBetter) {", "score": 0.8518480658531189 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/TopList.java", "retrieved_chunk": " private final String leaderboardname;\n String placeholderColumnName;\n private int numberOfFloatingPoints;\n public TopList(LeaderboardConfig leaderboardConfig) {\n this.leaderboardConfig = leaderboardConfig;\n top = leaderboardConfig.getTop();\n placeholder = leaderboardConfig.getPlaceholder();\n leaderboardname = leaderboardConfig.getName();\n placeholderColumnName = leaderboardConfig.getPlaceholder().substring(1, leaderboardConfig.getPlaceholder().length() - 1);\n numberOfFloatingPoints = leaderboardConfig.getFloatingpoints();", "score": 0.8476851582527161 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/UserData.java", "retrieved_chunk": " List<String> leaderboardnamelist = mainConfig.getLeaderboardsList();\n for (String lbname : leaderboardnamelist){\n Leaderboard leaderboard = new Leaderboard(lbname);\n UserData userData = new UserData(player, leaderboard.getConfig().getPlaceholder());\n userData.addToDatabase();\n }\n }\n //One Player All Placeholders\n public void addUserDataToDBAllPlaceholders(OfflinePlayer offlinePlayer){\n MainConfig mainConfig = new MainConfig();", "score": 0.8440186977386475 } ]
java
String databaseName = mainConfig.getStorageType();
package me.khajiitos.servercountryflags.common; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.mojang.blaze3d.platform.NativeImage; import me.khajiitos.servercountryflags.common.config.Config; import me.khajiitos.servercountryflags.common.util.APIResponse; import me.khajiitos.servercountryflags.common.util.LocationInfo; import me.khajiitos.servercountryflags.common.util.NetworkChangeDetector; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ServerList; import net.minecraft.client.multiplayer.resolver.ResolvedServerAddress; import net.minecraft.client.multiplayer.resolver.ServerAddress; import net.minecraft.client.multiplayer.resolver.ServerAddressResolver; import net.minecraft.client.multiplayer.resolver.ServerRedirectHandler; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; public class ServerCountryFlags { public static final String MOD_ID = "servercountryflags"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); public static final String API_NAME = "http://ip-api.com/json/"; public static final int API_FIELDS = 541395; public static String apiLanguage = null; public static ServerList serverList; // Servers from the server list public static HashMap<String, APIResponse> servers = new HashMap<>(); // Servers' flags public static HashMap<String, Float> flagAspectRatios = new HashMap<>(); public static boolean flagAspectRatiosLoaded = false; public static ServerRedirectHandler redirectResolver = ServerRedirectHandler.createDnsSrvRedirectHandler(); public static LocationInfo localLocation = null; static <T> T last(T[] arr) { return arr[arr.length - 1]; } public static void init() { Config.init(); NetworkChangeDetector.check(); Minecraft.getInstance().execute(() -> { ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); Map<ResourceLocation, Resource> resourceLocations = resourceManager.listResources("textures/flags", path -> true); Thread flagThread = new Thread(() -> { for (Map.Entry<ResourceLocation, Resource> entry : resourceLocations.entrySet()) { if (!entry.getKey().getNamespace().equals(MOD_ID)) { continue; } try { if (entry.getValue() == null) { ServerCountryFlags.LOGGER.error("Failed to load resource " + entry.getKey().getPath()); continue; } try (InputStream inputStream = entry.getValue().open()) { NativeImage image = NativeImage.read(inputStream); String code = last(entry.getKey().getPath().split("/")); code = code.substring(0, code.length() - 4); flagAspectRatios.put(code, (float)image.getWidth() / (float)image.getHeight()); } } catch (IOException e) { LOGGER.error(e.getMessage()); } } flagAspectRatiosLoaded = true; }); flagThread.setName("Flag load thread"); flagThread.start(); }); updateLocalLocationInfo(); } public static void updateAPILanguage(String language) { final String oldApiLanguage = apiLanguage; if (Config.cfg.forceEnglish) { apiLanguage = null; } else if (language != null) { if (language.startsWith("en")) apiLanguage = null; else if (language.startsWith("de")) apiLanguage = "de"; else if (language.startsWith("es")) apiLanguage = "es"; else if (language.startsWith("pt")) apiLanguage = "pt-BR"; else if (language.startsWith("fr")) apiLanguage = "fr"; else if (language.startsWith("ja")) apiLanguage = "ja"; else if (language.startsWith("zn")) apiLanguage = "zn-CN"; else if (language.startsWith("ru")) apiLanguage = "ru"; else apiLanguage = null; } if (!Objects.equals(apiLanguage, oldApiLanguage)) { servers.clear(); } } public static @NotNull APIResponse getAPIResponse(String ip) { // If the IP is empty, the API will give us our location if (APITimeoutManager.isOnCooldown()) { return new APIResponse(APIResponse.Status.COOLDOWN, null); } String apiUrlStr = API_NAME + ip + "?fields=" + API_FIELDS; if (apiLanguage != null) { apiUrlStr += "&lang=" + apiLanguage; } try { APITimeoutManager.incrementRequestsSent(); URL apiUrl = new URL(apiUrlStr); URLConnection con = apiUrl.openConnection(); con.setConnectTimeout(3000); int requestsLeft = con.getHeaderFieldInt("X-Rl", -1); int secondsLeft = con.getHeaderFieldInt("X-Ttl", -1); APITimeoutManager.decrementRequestsSent(); if (requestsLeft != -1 && secondsLeft != -1) { APITimeoutManager.setRequestsLeft(requestsLeft - APITimeoutManager.getRequestsSent());
APITimeoutManager.setSecondsLeftUntilReset(secondsLeft);
} BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); JsonElement jsonElement = JsonParser.parseReader(reader); if (jsonElement == null) { ServerCountryFlags.LOGGER.error("Received something that's not JSON"); return new APIResponse(APIResponse.Status.UNKNOWN, null); } if (jsonElement.isJsonObject()) { return new APIResponse(APIResponse.Status.SUCCESS, new LocationInfo((JsonObject) jsonElement)); } else { ServerCountryFlags.LOGGER.error("Received JSON element, but it's not an object: " + jsonElement); return new APIResponse(APIResponse.Status.UNKNOWN, null); } } catch (MalformedURLException e) { ServerCountryFlags.LOGGER.error("Malformed API Url: " + apiUrlStr); } catch (UnknownHostException e) { ServerCountryFlags.LOGGER.error("Unknown host - no internet?"); } catch (IOException e) { ServerCountryFlags.LOGGER.error(e.getMessage()); } APITimeoutManager.decrementRequestsSent(); return new APIResponse(APIResponse.Status.UNKNOWN, null); } public static boolean isIpLocal(InetAddress address) { return address.isLoopbackAddress() || address.isLinkLocalAddress() || address.isSiteLocalAddress(); } public static void updateServerLocationInfo(String serverAddress) { CompletableFuture.runAsync(() -> { ServerAddress address = ServerAddress.parseString(serverAddress); if (Config.cfg.resolveRedirects) { Optional<ServerAddress> redirect = redirectResolver.lookupRedirect(address); if (redirect.isPresent()) { address = redirect.get(); } } Optional<ResolvedServerAddress> resolvedAddress = ServerAddressResolver.SYSTEM.resolve(address); if (resolvedAddress.isPresent()) { InetSocketAddress socketAddress = resolvedAddress.get().asInetSocketAddress(); String stringHostAddress = isIpLocal(socketAddress.getAddress()) ? "" : socketAddress.getAddress().getHostAddress(); APIResponse response = getAPIResponse(stringHostAddress); APIResponse oldResponse = servers.get(serverAddress); if (oldResponse == null || (oldResponse.unknown() || !response.unknown()) || (oldResponse.cooldown() && response.locationInfo() != null)) { servers.putIfAbsent(serverAddress, response); } } }); } public static void updateLocalLocationInfo() { CompletableFuture.runAsync(() -> { APIResponse response = getAPIResponse(""); if (response.locationInfo() != null) { localLocation = response.locationInfo(); for (APIResponse serverResponse : servers.values()) { if (!serverResponse.cooldown()) { serverResponse.locationInfo().updateDistanceFromLocal(); } } } }); } }
Common/src/main/java/me/khajiitos/servercountryflags/common/ServerCountryFlags.java
Khajiitos-ServerCountryFlags-e056c80
[ { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": "package me.khajiitos.servercountryflags.common;\npublic class APITimeoutManager {\n private static int requestsLeft = 45;\n private static long cooldownReset = -1;\n private static int requestsSent = 0;\n public static boolean isOnCooldown() {\n return requestsLeft <= 0 && System.currentTimeMillis() < cooldownReset;\n }\n public static int getRequestsSent() {\n return requestsSent;", "score": 0.8442250490188599 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": " }\n public static void incrementRequestsSent() {\n requestsSent++;\n }\n public static void decrementRequestsSent() {\n requestsSent--;\n }\n public static void setRequestsLeft(int apiRequestsLeft) {\n requestsLeft = apiRequestsLeft;\n }", "score": 0.8423455953598022 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": " public static void setSecondsLeftUntilReset(int apiSecondsLeft) {\n cooldownReset = System.currentTimeMillis() + apiSecondsLeft * 1000L;\n }\n}", "score": 0.8133068084716797 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/mixin/OnlineServerEntryMixin.java", "retrieved_chunk": " return;\n }\n toolTip = Component.translatable(\"locationInfo.cooldown\");\n countryCode = \"timeout\";\n } else if (apiResponse.unknown()) {\n if (!Config.cfg.displayUnknownFlag && Config.cfg.flagPosition.equalsIgnoreCase(\"behindname\")) {\n this.serverData.name = originalName;\n context.drawString(Minecraft.getInstance().font, this.serverData.name, x + 35, y + 1, 16777215, false);\n return;\n }", "score": 0.7504634857177734 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/util/APIResponse.java", "retrieved_chunk": "package me.khajiitos.servercountryflags.common.util;\npublic record APIResponse(Status status, LocationInfo locationInfo) {\n public boolean cooldown() {\n return status == Status.COOLDOWN;\n }\n public boolean unknown() {\n return status == Status.UNKNOWN;\n }\n public enum Status {\n SUCCESS,", "score": 0.7462871074676514 } ]
java
APITimeoutManager.setSecondsLeftUntilReset(secondsLeft);
package me.khajiitos.servercountryflags.common; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.mojang.blaze3d.platform.NativeImage; import me.khajiitos.servercountryflags.common.config.Config; import me.khajiitos.servercountryflags.common.util.APIResponse; import me.khajiitos.servercountryflags.common.util.LocationInfo; import me.khajiitos.servercountryflags.common.util.NetworkChangeDetector; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ServerList; import net.minecraft.client.multiplayer.resolver.ResolvedServerAddress; import net.minecraft.client.multiplayer.resolver.ServerAddress; import net.minecraft.client.multiplayer.resolver.ServerAddressResolver; import net.minecraft.client.multiplayer.resolver.ServerRedirectHandler; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; public class ServerCountryFlags { public static final String MOD_ID = "servercountryflags"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); public static final String API_NAME = "http://ip-api.com/json/"; public static final int API_FIELDS = 541395; public static String apiLanguage = null; public static ServerList serverList; // Servers from the server list public static HashMap<String, APIResponse> servers = new HashMap<>(); // Servers' flags public static HashMap<String, Float> flagAspectRatios = new HashMap<>(); public static boolean flagAspectRatiosLoaded = false; public static ServerRedirectHandler redirectResolver = ServerRedirectHandler.createDnsSrvRedirectHandler(); public static LocationInfo localLocation = null; static <T> T last(T[] arr) { return arr[arr.length - 1]; } public static void init() { Config.init(); NetworkChangeDetector.check(); Minecraft.getInstance().execute(() -> { ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); Map<ResourceLocation, Resource> resourceLocations = resourceManager.listResources("textures/flags", path -> true); Thread flagThread = new Thread(() -> { for (Map.Entry<ResourceLocation, Resource> entry : resourceLocations.entrySet()) { if (!entry.getKey().getNamespace().equals(MOD_ID)) { continue; } try { if (entry.getValue() == null) { ServerCountryFlags.LOGGER.error("Failed to load resource " + entry.getKey().getPath()); continue; } try (InputStream inputStream = entry.getValue().open()) { NativeImage image = NativeImage.read(inputStream); String code = last(entry.getKey().getPath().split("/")); code = code.substring(0, code.length() - 4); flagAspectRatios.put(code, (float)image.getWidth() / (float)image.getHeight()); } } catch (IOException e) { LOGGER.error(e.getMessage()); } } flagAspectRatiosLoaded = true; }); flagThread.setName("Flag load thread"); flagThread.start(); }); updateLocalLocationInfo(); } public static void updateAPILanguage(String language) { final String oldApiLanguage = apiLanguage; if (Config.cfg.forceEnglish) { apiLanguage = null; } else if (language != null) { if (language.startsWith("en")) apiLanguage = null; else if (language.startsWith("de")) apiLanguage = "de"; else if (language.startsWith("es")) apiLanguage = "es"; else if (language.startsWith("pt")) apiLanguage = "pt-BR"; else if (language.startsWith("fr")) apiLanguage = "fr"; else if (language.startsWith("ja")) apiLanguage = "ja"; else if (language.startsWith("zn")) apiLanguage = "zn-CN"; else if (language.startsWith("ru")) apiLanguage = "ru"; else apiLanguage = null; } if (!Objects.equals(apiLanguage, oldApiLanguage)) { servers.clear(); } } public static @NotNull APIResponse getAPIResponse(String ip) { // If the IP is empty, the API will give us our location if
(APITimeoutManager.isOnCooldown()) {
return new APIResponse(APIResponse.Status.COOLDOWN, null); } String apiUrlStr = API_NAME + ip + "?fields=" + API_FIELDS; if (apiLanguage != null) { apiUrlStr += "&lang=" + apiLanguage; } try { APITimeoutManager.incrementRequestsSent(); URL apiUrl = new URL(apiUrlStr); URLConnection con = apiUrl.openConnection(); con.setConnectTimeout(3000); int requestsLeft = con.getHeaderFieldInt("X-Rl", -1); int secondsLeft = con.getHeaderFieldInt("X-Ttl", -1); APITimeoutManager.decrementRequestsSent(); if (requestsLeft != -1 && secondsLeft != -1) { APITimeoutManager.setRequestsLeft(requestsLeft - APITimeoutManager.getRequestsSent()); APITimeoutManager.setSecondsLeftUntilReset(secondsLeft); } BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); JsonElement jsonElement = JsonParser.parseReader(reader); if (jsonElement == null) { ServerCountryFlags.LOGGER.error("Received something that's not JSON"); return new APIResponse(APIResponse.Status.UNKNOWN, null); } if (jsonElement.isJsonObject()) { return new APIResponse(APIResponse.Status.SUCCESS, new LocationInfo((JsonObject) jsonElement)); } else { ServerCountryFlags.LOGGER.error("Received JSON element, but it's not an object: " + jsonElement); return new APIResponse(APIResponse.Status.UNKNOWN, null); } } catch (MalformedURLException e) { ServerCountryFlags.LOGGER.error("Malformed API Url: " + apiUrlStr); } catch (UnknownHostException e) { ServerCountryFlags.LOGGER.error("Unknown host - no internet?"); } catch (IOException e) { ServerCountryFlags.LOGGER.error(e.getMessage()); } APITimeoutManager.decrementRequestsSent(); return new APIResponse(APIResponse.Status.UNKNOWN, null); } public static boolean isIpLocal(InetAddress address) { return address.isLoopbackAddress() || address.isLinkLocalAddress() || address.isSiteLocalAddress(); } public static void updateServerLocationInfo(String serverAddress) { CompletableFuture.runAsync(() -> { ServerAddress address = ServerAddress.parseString(serverAddress); if (Config.cfg.resolveRedirects) { Optional<ServerAddress> redirect = redirectResolver.lookupRedirect(address); if (redirect.isPresent()) { address = redirect.get(); } } Optional<ResolvedServerAddress> resolvedAddress = ServerAddressResolver.SYSTEM.resolve(address); if (resolvedAddress.isPresent()) { InetSocketAddress socketAddress = resolvedAddress.get().asInetSocketAddress(); String stringHostAddress = isIpLocal(socketAddress.getAddress()) ? "" : socketAddress.getAddress().getHostAddress(); APIResponse response = getAPIResponse(stringHostAddress); APIResponse oldResponse = servers.get(serverAddress); if (oldResponse == null || (oldResponse.unknown() || !response.unknown()) || (oldResponse.cooldown() && response.locationInfo() != null)) { servers.putIfAbsent(serverAddress, response); } } }); } public static void updateLocalLocationInfo() { CompletableFuture.runAsync(() -> { APIResponse response = getAPIResponse(""); if (response.locationInfo() != null) { localLocation = response.locationInfo(); for (APIResponse serverResponse : servers.values()) { if (!serverResponse.cooldown()) { serverResponse.locationInfo().updateDistanceFromLocal(); } } } }); } }
Common/src/main/java/me/khajiitos/servercountryflags/common/ServerCountryFlags.java
Khajiitos-ServerCountryFlags-e056c80
[ { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/screen/ServerMapScreen.java", "retrieved_chunk": " points.clear();\n ServerCountryFlags.servers.clear();\n ServerCountryFlags.localLocation = null;\n }\n if (ServerCountryFlags.localLocation == null || NetworkChangeDetector.check()) {\n ServerCountryFlags.updateLocalLocationInfo();\n }\n for (int i = 0; i < ServerCountryFlags.serverList.size(); i++) {\n if (ServerCountryFlags.servers.containsKey(ServerCountryFlags.serverList.get(i).ip)) {\n continue;", "score": 0.8096064329147339 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/mixin/OnlineServerEntryMixin.java", "retrieved_chunk": " return;\n }\n toolTip = Component.translatable(\"locationInfo.cooldown\");\n countryCode = \"timeout\";\n } else if (apiResponse.unknown()) {\n if (!Config.cfg.displayUnknownFlag && Config.cfg.flagPosition.equalsIgnoreCase(\"behindname\")) {\n this.serverData.name = originalName;\n context.drawString(Minecraft.getInstance().font, this.serverData.name, x + 35, y + 1, 16777215, false);\n return;\n }", "score": 0.8017075061798096 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/config/Config.java", "retrieved_chunk": " ServerCountryFlags.updateAPILanguage(null);\n } else {\n LanguageManager languageManager = Minecraft.getInstance().getLanguageManager();\n // IntelliJ claims that languageManager will never be null\n // but that's actually not the case\n if (languageManager != null) {\n ServerCountryFlags.updateAPILanguage(languageManager.getSelected());\n }\n }\n // So that the map button appears/disappears without having to reopen the screen", "score": 0.7958509922027588 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/mixin/OnlineServerEntryMixin.java", "retrieved_chunk": " Component toolTip;\n String countryCode;\n APIResponse apiResponse = ServerCountryFlags.servers.get(serverData.ip);\n LocationInfo locationInfo = null;\n if (apiResponse != null) {\n locationInfo = apiResponse.locationInfo();\n if (apiResponse.cooldown()) {\n if (!Config.cfg.displayCooldownFlag && Config.cfg.flagPosition.equalsIgnoreCase(\"behindname\")) {\n this.serverData.name = originalName;\n context.drawString(Minecraft.getInstance().font, this.serverData.name, x + 35, y + 1, 16777215, false);", "score": 0.7909605503082275 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": "package me.khajiitos.servercountryflags.common;\npublic class APITimeoutManager {\n private static int requestsLeft = 45;\n private static long cooldownReset = -1;\n private static int requestsSent = 0;\n public static boolean isOnCooldown() {\n return requestsLeft <= 0 && System.currentTimeMillis() < cooldownReset;\n }\n public static int getRequestsSent() {\n return requestsSent;", "score": 0.7909064292907715 } ]
java
(APITimeoutManager.isOnCooldown()) {
package me.khajiitos.servercountryflags.common; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.mojang.blaze3d.platform.NativeImage; import me.khajiitos.servercountryflags.common.config.Config; import me.khajiitos.servercountryflags.common.util.APIResponse; import me.khajiitos.servercountryflags.common.util.LocationInfo; import me.khajiitos.servercountryflags.common.util.NetworkChangeDetector; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ServerList; import net.minecraft.client.multiplayer.resolver.ResolvedServerAddress; import net.minecraft.client.multiplayer.resolver.ServerAddress; import net.minecraft.client.multiplayer.resolver.ServerAddressResolver; import net.minecraft.client.multiplayer.resolver.ServerRedirectHandler; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; public class ServerCountryFlags { public static final String MOD_ID = "servercountryflags"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); public static final String API_NAME = "http://ip-api.com/json/"; public static final int API_FIELDS = 541395; public static String apiLanguage = null; public static ServerList serverList; // Servers from the server list public static HashMap<String, APIResponse> servers = new HashMap<>(); // Servers' flags public static HashMap<String, Float> flagAspectRatios = new HashMap<>(); public static boolean flagAspectRatiosLoaded = false; public static ServerRedirectHandler redirectResolver = ServerRedirectHandler.createDnsSrvRedirectHandler(); public static LocationInfo localLocation = null; static <T> T last(T[] arr) { return arr[arr.length - 1]; } public static void init() { Config.init(); NetworkChangeDetector.check(); Minecraft.getInstance().execute(() -> { ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); Map<ResourceLocation, Resource> resourceLocations = resourceManager.listResources("textures/flags", path -> true); Thread flagThread = new Thread(() -> { for (Map.Entry<ResourceLocation, Resource> entry : resourceLocations.entrySet()) { if (!entry.getKey().getNamespace().equals(MOD_ID)) { continue; } try { if (entry.getValue() == null) { ServerCountryFlags.LOGGER.error("Failed to load resource " + entry.getKey().getPath()); continue; } try (InputStream inputStream = entry.getValue().open()) { NativeImage image = NativeImage.read(inputStream); String code = last(entry.getKey().getPath().split("/")); code = code.substring(0, code.length() - 4); flagAspectRatios.put(code, (float)image.getWidth() / (float)image.getHeight()); } } catch (IOException e) { LOGGER.error(e.getMessage()); } } flagAspectRatiosLoaded = true; }); flagThread.setName("Flag load thread"); flagThread.start(); }); updateLocalLocationInfo(); } public static void updateAPILanguage(String language) { final String oldApiLanguage = apiLanguage; if (Config.cfg.forceEnglish) { apiLanguage = null; } else if (language != null) { if (language.startsWith("en")) apiLanguage = null; else if (language.startsWith("de")) apiLanguage = "de"; else if (language.startsWith("es")) apiLanguage = "es"; else if (language.startsWith("pt")) apiLanguage = "pt-BR"; else if (language.startsWith("fr")) apiLanguage = "fr"; else if (language.startsWith("ja")) apiLanguage = "ja"; else if (language.startsWith("zn")) apiLanguage = "zn-CN"; else if (language.startsWith("ru")) apiLanguage = "ru"; else apiLanguage = null; } if (!Objects.equals(apiLanguage, oldApiLanguage)) { servers.clear(); } } public static @NotNull APIResponse getAPIResponse(String ip) { // If the IP is empty, the API will give us our location if (APITimeoutManager.isOnCooldown()) { return new APIResponse(APIResponse.Status.COOLDOWN, null); } String apiUrlStr = API_NAME + ip + "?fields=" + API_FIELDS; if (apiLanguage != null) { apiUrlStr += "&lang=" + apiLanguage; } try { APITimeoutManager.incrementRequestsSent(); URL apiUrl = new URL(apiUrlStr); URLConnection con = apiUrl.openConnection(); con.setConnectTimeout(3000); int requestsLeft = con.getHeaderFieldInt("X-Rl", -1); int secondsLeft = con.getHeaderFieldInt("X-Ttl", -1);
APITimeoutManager.decrementRequestsSent();
if (requestsLeft != -1 && secondsLeft != -1) { APITimeoutManager.setRequestsLeft(requestsLeft - APITimeoutManager.getRequestsSent()); APITimeoutManager.setSecondsLeftUntilReset(secondsLeft); } BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); JsonElement jsonElement = JsonParser.parseReader(reader); if (jsonElement == null) { ServerCountryFlags.LOGGER.error("Received something that's not JSON"); return new APIResponse(APIResponse.Status.UNKNOWN, null); } if (jsonElement.isJsonObject()) { return new APIResponse(APIResponse.Status.SUCCESS, new LocationInfo((JsonObject) jsonElement)); } else { ServerCountryFlags.LOGGER.error("Received JSON element, but it's not an object: " + jsonElement); return new APIResponse(APIResponse.Status.UNKNOWN, null); } } catch (MalformedURLException e) { ServerCountryFlags.LOGGER.error("Malformed API Url: " + apiUrlStr); } catch (UnknownHostException e) { ServerCountryFlags.LOGGER.error("Unknown host - no internet?"); } catch (IOException e) { ServerCountryFlags.LOGGER.error(e.getMessage()); } APITimeoutManager.decrementRequestsSent(); return new APIResponse(APIResponse.Status.UNKNOWN, null); } public static boolean isIpLocal(InetAddress address) { return address.isLoopbackAddress() || address.isLinkLocalAddress() || address.isSiteLocalAddress(); } public static void updateServerLocationInfo(String serverAddress) { CompletableFuture.runAsync(() -> { ServerAddress address = ServerAddress.parseString(serverAddress); if (Config.cfg.resolveRedirects) { Optional<ServerAddress> redirect = redirectResolver.lookupRedirect(address); if (redirect.isPresent()) { address = redirect.get(); } } Optional<ResolvedServerAddress> resolvedAddress = ServerAddressResolver.SYSTEM.resolve(address); if (resolvedAddress.isPresent()) { InetSocketAddress socketAddress = resolvedAddress.get().asInetSocketAddress(); String stringHostAddress = isIpLocal(socketAddress.getAddress()) ? "" : socketAddress.getAddress().getHostAddress(); APIResponse response = getAPIResponse(stringHostAddress); APIResponse oldResponse = servers.get(serverAddress); if (oldResponse == null || (oldResponse.unknown() || !response.unknown()) || (oldResponse.cooldown() && response.locationInfo() != null)) { servers.putIfAbsent(serverAddress, response); } } }); } public static void updateLocalLocationInfo() { CompletableFuture.runAsync(() -> { APIResponse response = getAPIResponse(""); if (response.locationInfo() != null) { localLocation = response.locationInfo(); for (APIResponse serverResponse : servers.values()) { if (!serverResponse.cooldown()) { serverResponse.locationInfo().updateDistanceFromLocal(); } } } }); } }
Common/src/main/java/me/khajiitos/servercountryflags/common/ServerCountryFlags.java
Khajiitos-ServerCountryFlags-e056c80
[ { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": " }\n public static void incrementRequestsSent() {\n requestsSent++;\n }\n public static void decrementRequestsSent() {\n requestsSent--;\n }\n public static void setRequestsLeft(int apiRequestsLeft) {\n requestsLeft = apiRequestsLeft;\n }", "score": 0.8068625330924988 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": "package me.khajiitos.servercountryflags.common;\npublic class APITimeoutManager {\n private static int requestsLeft = 45;\n private static long cooldownReset = -1;\n private static int requestsSent = 0;\n public static boolean isOnCooldown() {\n return requestsLeft <= 0 && System.currentTimeMillis() < cooldownReset;\n }\n public static int getRequestsSent() {\n return requestsSent;", "score": 0.8063445091247559 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/config/Config.java", "retrieved_chunk": " ServerCountryFlags.updateAPILanguage(null);\n } else {\n LanguageManager languageManager = Minecraft.getInstance().getLanguageManager();\n // IntelliJ claims that languageManager will never be null\n // but that's actually not the case\n if (languageManager != null) {\n ServerCountryFlags.updateAPILanguage(languageManager.getSelected());\n }\n }\n // So that the map button appears/disappears without having to reopen the screen", "score": 0.7906663417816162 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/util/LocationInfo.java", "retrieved_chunk": " ServerCountryFlags.LOGGER.error(apiObject.toString());\n return;\n }\n } else {\n ServerCountryFlags.LOGGER.error(\"API Object doesn't include the field 'status'\");\n ServerCountryFlags.LOGGER.error(apiObject.toString());\n return;\n }\n if (apiObject.keySet().containsAll(List.of(\"country\", \"countryCode\", \"city\", \"lon\", \"lat\", \"district\", \"isp\"))) {\n this.countryName = apiObject.get(\"country\").getAsString();", "score": 0.7849688529968262 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": " public static void setSecondsLeftUntilReset(int apiSecondsLeft) {\n cooldownReset = System.currentTimeMillis() + apiSecondsLeft * 1000L;\n }\n}", "score": 0.7782588005065918 } ]
java
APITimeoutManager.decrementRequestsSent();
package org.kasun.discordleaderboards.Commands; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.entity.Player; import org.kasun.discordleaderboards.Configs.MainConfig; import org.kasun.discordleaderboards.Database.UserData; import org.kasun.discordleaderboards.DiscordLeaderboards; import org.kasun.discordleaderboards.Leaderboard.Leaderboard; import org.kasun.discordleaderboards.Leaderboard.LeaderboardConfig; import org.kasun.discordleaderboards.Utils.DiscordWebhook; import org.kasun.discordleaderboards.Utils.PlayerUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.CompletableFuture; public class DLCommand implements TabExecutor { private final CommandsManager commandsManager; public DLCommand(CommandsManager commandsManager) { this.commandsManager = commandsManager; } private final DiscordLeaderboards plugin = DiscordLeaderboards.getInstance(); @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length == 0) { return true; } //Webhook Test Command if (args[0].equalsIgnoreCase("testwebhook")) { if (!sender.hasPermission("dl.testwebhook") && !sender.hasPermission("dl.admin")) { sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "No Permission ! [dl.testwebhook], [dl.admin]"); return true; } String url = (String) plugin.getConfig().get("webhook-url"); DiscordWebhook w = new DiscordWebhook(url); DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject(); if (url == null || url.equalsIgnoreCase("-")) { sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Webhook Url not Configured"); return true; } embed.setTitle("Dleaderboards"); embed.setDescription("Your Webhook is Working"); w.addEmbed(embed); sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GRAY + "Sending Webhook Message...."); try { w.execute(); } catch (FileNotFoundException e) { sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Invalid Webhook Url [code : 04]"); } catch (IOException ee) { sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "embed not ready yet, internal plugin issue pleace contact plugin developer [code : 05]"); } } //Force Leaderboard Send if (args[0].equalsIgnoreCase("forcesend")) { if (!sender.hasPermission("dl.forcesend") && !sender.hasPermission("dl.admin")) { sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "No Permission ! [dl.forcesend], [dl.admin]"); return true; } if (args.length != 2) { sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Wrong Command Usage !"); sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GRAY + "/dl forcesend leaderboard"); return true; } CompletableFuture.runAsync(() -> { Leaderboard leaderboard = new Leaderboard(args[1]); leaderboard.send(); }); sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GREEN + "Leaderboard Sent!"); } //Create Command if (args[0].equalsIgnoreCase("create")) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "You cant use this command here"); return true; } Player p = (Player) sender; if (args.length != 5) { p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Wrong Command Usage !"); p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GRAY + "/dl create name 5 %placeholder% Daily"); } //name top placeholder delay if (!p.hasPermission("dl.create") && !p.hasPermission("dl.admin")) { p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "No Permission ! [dl.create], [dl.admin]"); return true; } try { Double.parseDouble(PlaceholderAPI.setPlaceholders(p, args[3])); new Leaderboard(args[1], Integer.parseInt(args[2]), args[3], Leaderboard.WebhookDelay.valueOf(args[4])); p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GREEN + "Starting Leaderboard Setup!"); plugin.reloadConfig(); UserData userData = new UserData(p, args[3]); userData.addToDatabase(); p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.YELLOW + "Starting to Sync Offline Player Data... Please Wait!"); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
userData.addUserDataToDBAllPlayersThisPlaceholder();
Bukkit.getScheduler().runTask(plugin, () -> { p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.YELLOW + "Synchronization Complete !"); p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GREEN + "Leaderboard Created!"); p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GRAY + "you can change the settings from plugins\\DiscordLeaderboards\\leaderboard\\" + args[1] + ".yml"); }); }); //getting random offline player List<OfflinePlayer> players = PlayerUtils.getAllPlayers(); players.remove(p); Random random = new Random(); int randomIndex = random.nextInt(players.size()); OfflinePlayer randomPlayer = players.get(randomIndex); //checking placeholder if they supports offline players try { Double.parseDouble(PlaceholderAPI.setPlaceholders(randomPlayer, args[3])); } catch (NumberFormatException ex) { p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GOLD + "[Warning!] " + args[3] + " may not support offline players. [code : 17]"); } } catch (NumberFormatException e) { p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Placeholder " + args[3] + " Unsupported, Expansion Not Installed or Doesn't output Number value"); } } //View Command if (args[0].equalsIgnoreCase("view")) { if (!sender.hasPermission("dl.view") && !sender.hasPermission("dl.admin")) { sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "No Permission ! [dl.view], [dl.admin]"); return true; } if (args.length != 2) { sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "Wrong Command Usage !"); sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GRAY + "/dl view leaderboard"); return true; } CompletableFuture.runAsync(() -> { Leaderboard leaderboard = new Leaderboard(args[1]); String leaderboardstring = leaderboard.toString(); sender.sendMessage(ChatColor.GRAY + leaderboardstring); }); } //Sync All Players if (args[0].equalsIgnoreCase("syncall")) { if (!(sender instanceof Player)) { plugin.getLogger().info(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "you cant use that command here."); return true; } Player p = (Player) sender; if (!p.hasPermission("dl.syncall") && !p.hasPermission("dl.admin")) { p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "No Permission ! [dl.syncall], [dl.admin]"); return true; } p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.YELLOW + "Synchronization Starting..."); UserData userData = new UserData(); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { userData.addUserDataToDBAllPlayersAllPlaceholders(); Bukkit.getScheduler().runTask(plugin, () -> { p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.YELLOW + "Synchronization Complete !"); }); }); //getting random offline player List<OfflinePlayer> players = PlayerUtils.getAllPlayers(); players.remove(p); Random random = new Random(); int randomIndex = random.nextInt(players.size()); OfflinePlayer randomPlayer = players.get(randomIndex); //checking placeholders if they supports offline players MainConfig mainConfig = new MainConfig(); List<String> lblist = mainConfig.getLeaderboardsList(); for (String lbname : lblist) { LeaderboardConfig leaderboardConfig = new LeaderboardConfig(lbname); String ph = leaderboardConfig.getPlaceholder(); try { Double.parseDouble(PlaceholderAPI.setPlaceholders(randomPlayer, ph)); } catch (NumberFormatException ex) { p.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GOLD + "[WARNING!] " + ph + " may not support offline players. [code : 17]"); } } } if (args[0].equalsIgnoreCase("reload")) { if (!sender.hasPermission("dl.reload") && !sender.hasPermission("dl.admin")) { sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.RED + "No Permission ! [dl.reload], [dl.admin]"); return true; } commandsManager.getMainManager().reload(); sender.sendMessage(ChatColor.AQUA + "[Dleaderboards] " + ChatColor.GREEN + "Reloaded!"); } return true; } @Override public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) { if (args.length == 1) { List<String> arguments = new ArrayList<>(); arguments.add("testwebhook"); arguments.add("forcesend"); arguments.add("create"); arguments.add("view"); arguments.add("syncall"); arguments.add("reload"); return arguments; } if (args[0].equalsIgnoreCase("forcesend")) { if (args.length == 2) { MainConfig mainConfig = new MainConfig(); return mainConfig.getLeaderboardsList(); } } if (args[0].equalsIgnoreCase("create")) { if (args.length == 2) { List<String> arguments = new ArrayList<>(); arguments.add("name"); return arguments; } if (args.length == 3) { List<String> arguments = new ArrayList<>(); arguments.add("3"); arguments.add("5"); arguments.add("10"); arguments.add("15"); arguments.add("20"); return arguments; } if (args.length == 4) { List<String> arguments = new ArrayList<>(); arguments.add("%placeholder%"); return arguments; } if (args.length == 5) { List<String> arguments = new ArrayList<>(); arguments.add("None"); arguments.add("Live"); arguments.add("Hourly"); arguments.add("Daily"); arguments.add("Weekly"); arguments.add("Monthly"); return arguments; } } if (args[0].equalsIgnoreCase("view")) { if (args.length == 2) { MainConfig mainConfig = new MainConfig(); return mainConfig.getLeaderboardsList(); } } if (args[0].equalsIgnoreCase("reload")) { if (args.length == 2) { return null; } } return null; } }
src/main/java/org/kasun/discordleaderboards/Commands/DLCommand.java
ka0un-DiscordLeaderboards-ffaaf38
[ { "filename": "src/main/java/org/kasun/discordleaderboards/Database/UserData.java", "retrieved_chunk": " List<String> leaderboardnamelist = mainConfig.getLeaderboardsList();\n for (String lbname : leaderboardnamelist){\n Leaderboard leaderboard = new Leaderboard(lbname);\n String valuestring = PlaceholderAPI.setPlaceholders(offlinePlayer, leaderboard.getConfig().getPlaceholder());\n if (valuestring != null && valuestring != \"\"){\n UserData userData = new UserData(offlinePlayer, leaderboard.getConfig().getPlaceholder());\n userData.addToDatabase();\n }\n }\n }", "score": 0.8638969659805298 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " } catch (SQLException ex) {\n Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.RED + \"Issue while adding UserData to database [code : 09.3]\");\n ex.printStackTrace();\n }\n }\n }\n public static Map<String, Double> getTopPlayerMap(String placeholderColumnName, int top, boolean ishigherbetter) {\n Map<String, Double> topPlayerScores = new LinkedHashMap<>();\n MainConfig mainConfig = new MainConfig();\n try {", "score": 0.856469988822937 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Leaderboard/Leaderboard.java", "retrieved_chunk": "package org.kasun.discordleaderboards.Leaderboard;\nimport org.bukkit.Bukkit;\nimport org.bukkit.ChatColor;\nimport org.kasun.discordleaderboards.DiscordLeaderboards;\nimport org.kasun.discordleaderboards.Utils.DiscordWebhook;\nimport org.kasun.discordleaderboards.Configs.MainConfig;\nimport java.awt.*;\nimport java.io.IOException;\nimport java.util.List;\npublic class Leaderboard {", "score": 0.8514827489852905 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Utils/SqlUtils.java", "retrieved_chunk": " Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + \"[Dleaderboards] \" + ChatColor.RED + \"Issue while adding UserData to database [code : 09.1]\");\n ex.printStackTrace();\n }\n } else if (mainConfig.getStorageType().equalsIgnoreCase(\"mysql\")) {\n try {\n Connection connection = database.getConnection();\n Statement statement = connection.createStatement();\n // Check if the column exists in the table\n ResultSet resultSet = statement.executeQuery(\"SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'UserData' AND COLUMN_NAME = '\" + placeholderColumnName + \"'\");\n if (!resultSet.next()) {", "score": 0.851213276386261 }, { "filename": "src/main/java/org/kasun/discordleaderboards/Database/UserData.java", "retrieved_chunk": " List<String> leaderboardnamelist = mainConfig.getLeaderboardsList();\n for (String lbname : leaderboardnamelist){\n Leaderboard leaderboard = new Leaderboard(lbname);\n UserData userData = new UserData(player, leaderboard.getConfig().getPlaceholder());\n userData.addToDatabase();\n }\n }\n //One Player All Placeholders\n public void addUserDataToDBAllPlaceholders(OfflinePlayer offlinePlayer){\n MainConfig mainConfig = new MainConfig();", "score": 0.8511803150177002 } ]
java
userData.addUserDataToDBAllPlayersThisPlaceholder();
package me.khajiitos.servercountryflags.common; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.mojang.blaze3d.platform.NativeImage; import me.khajiitos.servercountryflags.common.config.Config; import me.khajiitos.servercountryflags.common.util.APIResponse; import me.khajiitos.servercountryflags.common.util.LocationInfo; import me.khajiitos.servercountryflags.common.util.NetworkChangeDetector; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ServerList; import net.minecraft.client.multiplayer.resolver.ResolvedServerAddress; import net.minecraft.client.multiplayer.resolver.ServerAddress; import net.minecraft.client.multiplayer.resolver.ServerAddressResolver; import net.minecraft.client.multiplayer.resolver.ServerRedirectHandler; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; public class ServerCountryFlags { public static final String MOD_ID = "servercountryflags"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); public static final String API_NAME = "http://ip-api.com/json/"; public static final int API_FIELDS = 541395; public static String apiLanguage = null; public static ServerList serverList; // Servers from the server list public static HashMap<String, APIResponse> servers = new HashMap<>(); // Servers' flags public static HashMap<String, Float> flagAspectRatios = new HashMap<>(); public static boolean flagAspectRatiosLoaded = false; public static ServerRedirectHandler redirectResolver = ServerRedirectHandler.createDnsSrvRedirectHandler(); public static LocationInfo localLocation = null; static <T> T last(T[] arr) { return arr[arr.length - 1]; } public static void init() { Config.init(); NetworkChangeDetector.check(); Minecraft.getInstance().execute(() -> { ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); Map<ResourceLocation, Resource> resourceLocations = resourceManager.listResources("textures/flags", path -> true); Thread flagThread = new Thread(() -> { for (Map.Entry<ResourceLocation, Resource> entry : resourceLocations.entrySet()) { if (!entry.getKey().getNamespace().equals(MOD_ID)) { continue; } try { if (entry.getValue() == null) { ServerCountryFlags.LOGGER.error("Failed to load resource " + entry.getKey().getPath()); continue; } try (InputStream inputStream = entry.getValue().open()) { NativeImage image = NativeImage.read(inputStream); String code = last(entry.getKey().getPath().split("/")); code = code.substring(0, code.length() - 4); flagAspectRatios.put(code, (float)image.getWidth() / (float)image.getHeight()); } } catch (IOException e) { LOGGER.error(e.getMessage()); } } flagAspectRatiosLoaded = true; }); flagThread.setName("Flag load thread"); flagThread.start(); }); updateLocalLocationInfo(); } public static void updateAPILanguage(String language) { final String oldApiLanguage = apiLanguage; if (Config.cfg.forceEnglish) { apiLanguage = null; } else if (language != null) { if (language.startsWith("en")) apiLanguage = null; else if (language.startsWith("de")) apiLanguage = "de"; else if (language.startsWith("es")) apiLanguage = "es"; else if (language.startsWith("pt")) apiLanguage = "pt-BR"; else if (language.startsWith("fr")) apiLanguage = "fr"; else if (language.startsWith("ja")) apiLanguage = "ja"; else if (language.startsWith("zn")) apiLanguage = "zn-CN"; else if (language.startsWith("ru")) apiLanguage = "ru"; else apiLanguage = null; } if (!Objects.equals(apiLanguage, oldApiLanguage)) { servers.clear(); } } public static @NotNull APIResponse getAPIResponse(String ip) { // If the IP is empty, the API will give us our location if (APITimeoutManager.isOnCooldown()) { return new APIResponse(APIResponse.Status.COOLDOWN, null); } String apiUrlStr = API_NAME + ip + "?fields=" + API_FIELDS; if (apiLanguage != null) { apiUrlStr += "&lang=" + apiLanguage; } try {
APITimeoutManager.incrementRequestsSent();
URL apiUrl = new URL(apiUrlStr); URLConnection con = apiUrl.openConnection(); con.setConnectTimeout(3000); int requestsLeft = con.getHeaderFieldInt("X-Rl", -1); int secondsLeft = con.getHeaderFieldInt("X-Ttl", -1); APITimeoutManager.decrementRequestsSent(); if (requestsLeft != -1 && secondsLeft != -1) { APITimeoutManager.setRequestsLeft(requestsLeft - APITimeoutManager.getRequestsSent()); APITimeoutManager.setSecondsLeftUntilReset(secondsLeft); } BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); JsonElement jsonElement = JsonParser.parseReader(reader); if (jsonElement == null) { ServerCountryFlags.LOGGER.error("Received something that's not JSON"); return new APIResponse(APIResponse.Status.UNKNOWN, null); } if (jsonElement.isJsonObject()) { return new APIResponse(APIResponse.Status.SUCCESS, new LocationInfo((JsonObject) jsonElement)); } else { ServerCountryFlags.LOGGER.error("Received JSON element, but it's not an object: " + jsonElement); return new APIResponse(APIResponse.Status.UNKNOWN, null); } } catch (MalformedURLException e) { ServerCountryFlags.LOGGER.error("Malformed API Url: " + apiUrlStr); } catch (UnknownHostException e) { ServerCountryFlags.LOGGER.error("Unknown host - no internet?"); } catch (IOException e) { ServerCountryFlags.LOGGER.error(e.getMessage()); } APITimeoutManager.decrementRequestsSent(); return new APIResponse(APIResponse.Status.UNKNOWN, null); } public static boolean isIpLocal(InetAddress address) { return address.isLoopbackAddress() || address.isLinkLocalAddress() || address.isSiteLocalAddress(); } public static void updateServerLocationInfo(String serverAddress) { CompletableFuture.runAsync(() -> { ServerAddress address = ServerAddress.parseString(serverAddress); if (Config.cfg.resolveRedirects) { Optional<ServerAddress> redirect = redirectResolver.lookupRedirect(address); if (redirect.isPresent()) { address = redirect.get(); } } Optional<ResolvedServerAddress> resolvedAddress = ServerAddressResolver.SYSTEM.resolve(address); if (resolvedAddress.isPresent()) { InetSocketAddress socketAddress = resolvedAddress.get().asInetSocketAddress(); String stringHostAddress = isIpLocal(socketAddress.getAddress()) ? "" : socketAddress.getAddress().getHostAddress(); APIResponse response = getAPIResponse(stringHostAddress); APIResponse oldResponse = servers.get(serverAddress); if (oldResponse == null || (oldResponse.unknown() || !response.unknown()) || (oldResponse.cooldown() && response.locationInfo() != null)) { servers.putIfAbsent(serverAddress, response); } } }); } public static void updateLocalLocationInfo() { CompletableFuture.runAsync(() -> { APIResponse response = getAPIResponse(""); if (response.locationInfo() != null) { localLocation = response.locationInfo(); for (APIResponse serverResponse : servers.values()) { if (!serverResponse.cooldown()) { serverResponse.locationInfo().updateDistanceFromLocal(); } } } }); } }
Common/src/main/java/me/khajiitos/servercountryflags/common/ServerCountryFlags.java
Khajiitos-ServerCountryFlags-e056c80
[ { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/APITimeoutManager.java", "retrieved_chunk": "package me.khajiitos.servercountryflags.common;\npublic class APITimeoutManager {\n private static int requestsLeft = 45;\n private static long cooldownReset = -1;\n private static int requestsSent = 0;\n public static boolean isOnCooldown() {\n return requestsLeft <= 0 && System.currentTimeMillis() < cooldownReset;\n }\n public static int getRequestsSent() {\n return requestsSent;", "score": 0.7956457138061523 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/mixin/OnlineServerEntryMixin.java", "retrieved_chunk": " return;\n }\n toolTip = Component.translatable(\"locationInfo.cooldown\");\n countryCode = \"timeout\";\n } else if (apiResponse.unknown()) {\n if (!Config.cfg.displayUnknownFlag && Config.cfg.flagPosition.equalsIgnoreCase(\"behindname\")) {\n this.serverData.name = originalName;\n context.drawString(Minecraft.getInstance().font, this.serverData.name, x + 35, y + 1, 16777215, false);\n return;\n }", "score": 0.7897675037384033 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/util/LocationInfo.java", "retrieved_chunk": " ServerCountryFlags.LOGGER.error(apiObject.toString());\n return;\n }\n } else {\n ServerCountryFlags.LOGGER.error(\"API Object doesn't include the field 'status'\");\n ServerCountryFlags.LOGGER.error(apiObject.toString());\n return;\n }\n if (apiObject.keySet().containsAll(List.of(\"country\", \"countryCode\", \"city\", \"lon\", \"lat\", \"district\", \"isp\"))) {\n this.countryName = apiObject.get(\"country\").getAsString();", "score": 0.7863162755966187 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/mixin/OnlineServerEntryMixin.java", "retrieved_chunk": " Component toolTip;\n String countryCode;\n APIResponse apiResponse = ServerCountryFlags.servers.get(serverData.ip);\n LocationInfo locationInfo = null;\n if (apiResponse != null) {\n locationInfo = apiResponse.locationInfo();\n if (apiResponse.cooldown()) {\n if (!Config.cfg.displayCooldownFlag && Config.cfg.flagPosition.equalsIgnoreCase(\"behindname\")) {\n this.serverData.name = originalName;\n context.drawString(Minecraft.getInstance().font, this.serverData.name, x + 35, y + 1, 16777215, false);", "score": 0.7836337089538574 }, { "filename": "Common/src/main/java/me/khajiitos/servercountryflags/common/util/APIResponse.java", "retrieved_chunk": "package me.khajiitos.servercountryflags.common.util;\npublic record APIResponse(Status status, LocationInfo locationInfo) {\n public boolean cooldown() {\n return status == Status.COOLDOWN;\n }\n public boolean unknown() {\n return status == Status.UNKNOWN;\n }\n public enum Status {\n SUCCESS,", "score": 0.7831073999404907 } ]
java
APITimeoutManager.incrementRequestsSent();
package com.konloch.http.webserver; import com.konloch.disklib.DiskReader; import com.konloch.http.request.Request; import com.konloch.http.request.RequestListener; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; /** * The web server is a higher level abstraction of the HTTP server. * * If you define a public folder it will attempt to serve static files. * * You can also define pages that return a byte array or a String to make development easier * * @author Konloch * @since 3/8/2023 */ public class WebServer implements RequestListener { private static final byte[] defaultError404 = "Error 404 file not found".getBytes(StandardCharsets.UTF_8); private static final byte[] defaultError500 = "Error 500 internal server issue".getBytes(StandardCharsets.UTF_8); private final File publicFolder; private byte[] error404 = defaultError404; private byte[] error500 = defaultError500; public WebServer(File publicFolder) { this.publicFolder = publicFolder; } @Override public byte[] request(Request request) { final File file = new File(publicFolder, request.getPath()); final String fileNormalized = file.getAbsolutePath(); final String publicFolderNormalized = publicFolder.getAbsolutePath(); //prevent escaping from the public directory by normalizing the paths if(fileNormalized.startsWith(publicFolderNormalized) && file.exists()) try { return DiskReader.readBytes(file); } catch (IOException e) { e.printStackTrace();
request.setReturnCode(500);
return error500; } request.setReturnCode(404); return error404; } public byte[] getError404() { return error404; } public WebServer setError404(byte[] error404) { this.error404 = error404; return this; } public byte[] getError500() { return error500; } public WebServer setError500(byte[] error500) { this.error500 = error500; return this; } }
src/main/java/com/konloch/http/webserver/WebServer.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/test/java/com/konloch/TestHTTPServer.java", "retrieved_chunk": "\t\t\t\tdefault:\n\t\t\t\t\tFile parent = new File(\"./public\");\n\t\t\t\t\tFile file = new File(parent, request.getPath());\n\t\t\t\t\t//prevent escaping from the public directory by normalizing the paths\n\t\t\t\t\tif(file.getAbsolutePath().startsWith(parent.getAbsolutePath())\n\t\t\t\t\t\t\t&& file.exists())\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn DiskReader.readBytes(file);\n\t\t\t\t\t\t}", "score": 0.9136071801185608 }, { "filename": "src/test/java/com/konloch/TestHTTPServer.java", "retrieved_chunk": "package com.konloch;\nimport com.konloch.disklib.DiskReader;\nimport com.konloch.http.HTTPdLib;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n/**\n * @author Konloch\n * @since 2/28/2023\n */", "score": 0.7929070591926575 }, { "filename": "src/test/java/com/konloch/TestHTTPServer.java", "retrieved_chunk": "\t\t\t\t\t\tcatch (IOException e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\trequest.setReturnCode(404);\n\t\t\t\t\treturn \"Error 404 file not found\".getBytes(StandardCharsets.UTF_8);\n\t\t\t}\n\t\t});\n\t\twebserver.start();\n\t\tSystem.out.println(\"Running on http://localhost:\" + webserver.getServer().getPort() + \"/\");", "score": 0.7890482544898987 }, { "filename": "src/test/java/com/konloch/TestHTTPServer.java", "retrieved_chunk": "\t\t\t\tcase \"/hello\":\n\t\t\t\t\treturn \"Bye\".getBytes(StandardCharsets.UTF_8);\n\t\t\t\tcase \"/get\":\n\t\t\t\t\trequest.setContentType(\"text/html; charset=utf-8\");\n\t\t\t\t\treturn (\"<html><form action=\\\"\\\" method=\\\"get\\\">\\n\" + \" <label for=\\\"fname\\\">First name:</label>\\n\" + \" <input type=\\\"text\\\" id=\\\"fname\\\" name=\\\"fname\\\"><br><br>\\n\" + \" <label for=\\\"lname\\\">Last name:</label>\\n\" + \" <input type=\\\"text\\\" id=\\\"lname\\\" name=\\\"lname\\\"><br><br>\\n\" + \" <input type=\\\"submit\\\" value=\\\"Submit\\\">\\n\" + \"</form></html>\").getBytes(StandardCharsets.UTF_8);\n\t\t\t\tcase \"/post\":\n\t\t\t\t\trequest.setContentType(\"text/html; charset=utf-8\");\n\t\t\t\t\treturn (\"<html><form action=\\\"\\\" method=\\\"post\\\">\\n\" + \" <label for=\\\"fname\\\">First name:</label>\\n\" + \" <input type=\\\"text\\\" id=\\\"fname\\\" name=\\\"fname\\\"><br><br>\\n\" + \" <label for=\\\"lname\\\">Last name:</label>\\n\" + \" <input type=\\\"text\\\" id=\\\"lname\\\" name=\\\"lname\\\"><br><br>\\n\" + \" <input type=\\\"submit\\\" value=\\\"Submit\\\">\\n\" + \"</form></html>\").getBytes(StandardCharsets.UTF_8);\n\t\t\t\tcase \"/upload\":\n\t\t\t\t\trequest.setContentType(\"text/html; charset=utf-8\");", "score": 0.7803030014038086 }, { "filename": "src/test/java/com/konloch/TestHTTPServer.java", "retrieved_chunk": "\t\t\t\t\treturn (\"<form action=\\\"\\\">\\n\" + \" <input type=\\\"file\\\" id=\\\"myFile\\\" name=\\\"filename\\\">\\n\" + \" <input type=\\\"submit\\\">\\n\" + \"</form>\").getBytes(StandardCharsets.UTF_8);\n\t\t\t\tcase \"/upload2\":\n\t\t\t\t\trequest.setContentType(\"text/html; charset=utf-8\");\n\t\t\t\t\treturn (\"<form action=\\\"\\\" method=\\\"post\\\" enctype=\\\"multipart/form-data\\\">\\n\" + \" Select image to upload:\\n\" + \" <input type=\\\"file\\\" name=\\\"fileToUpload\\\" id=\\\"fileToUpload\\\">\\n\" + \" <input type=\\\"submit\\\" value=\\\"Upload Image\\\" name=\\\"submit\\\">\\n\" + \"</form>\").getBytes(StandardCharsets.UTF_8);\n\t\t\t\tcase \"/upload3\":\n\t\t\t\t\trequest.setContentType(\"text/html; charset=utf-8\");\n\t\t\t\t\treturn (\"<form action=\\\"\\\" method=\\\"post\\\" enctype=\\\"application/x-www-form-urlencoded\\\">\\n\" + \" Select image to upload:\\n\" + \" <input type=\\\"file\\\" name=\\\"fileToUpload\\\" id=\\\"fileToUpload\\\">\\n\" + \" <input type=\\\"submit\\\" value=\\\"Upload Image\\\" name=\\\"submit\\\">\\n\" + \"</form>\").getBytes(StandardCharsets.UTF_8);\n\t\t\t\tcase \"/upload4\":\n\t\t\t\t\trequest.setContentType(\"text/html; charset=utf-8\");\n\t\t\t\t\treturn (\"<form action=\\\"\\\" method=\\\"post\\\" enctype=\\\"text/plain\\\">\\n\" + \" Select image to upload:\\n\" + \" <input type=\\\"file\\\" name=\\\"fileToUpload\\\" id=\\\"fileToUpload\\\">\\n\" + \" <input type=\\\"submit\\\" value=\\\"Upload Image\\\" name=\\\"submit\\\">\\n\" + \"</form>\").getBytes(StandardCharsets.UTF_8);", "score": 0.7780613899230957 } ]
java
request.setReturnCode(500);
package com.konloch.http.protocol.decoder; import com.konloch.http.HTTPdLib; import java.util.HashMap; /** * @author Konloch * @since 3/1/2023 */ public class RequestDecoder { private final HTTPdLib server; public RequestDecoder(HTTPdLib server) { this.server = server; } /** * Decode the headers from a raw web request, this will respect the security limits set on the webserver * * @param buffer any byte array as the buffer containing the request data * @return a HashMap String, String key-value pair containing the headers */ public HashMap<String, String> decodeHeaders(byte[] buffer) { HashMap<String, String> parameters = new HashMap<>(); StringBuilder key = new StringBuilder(" :"); StringBuilder value = new StringBuilder(); boolean keyFlag = false; int parameterCreationCount = 0; for(byte b : buffer) { char c = (char) b; //verify ascii only //TODO may want to just stop the request entirely and throw a 500 if(!isAscii(c)) continue; //looking for key if(keyFlag) { if(c == ':') keyFlag = false; else key.append(c); } //end of value else if(c == '\n' || c == '\r') { if(parameterCreationCount++
>= server.getMaximumHeaderParameterCount()) return parameters;
if(key.length() > 0 && value.length() > 0) parameters.put(key.substring(1), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; } //looking for value else if(value.length() < server.getMaximumHeaderParameterSize()) value.append(c); } return parameters; } /** * Decode request parameters, this will respect the security limits set on the webserver * * @param rawParameters any String representing the raw parameters to be parsed * @return a HashMap String, String key-value pair containing the parsed parameters */ public HashMap<String, String> decodeParameters(String rawParameters) { HashMap<String, String> parameters = new HashMap<>(); char[] chars = rawParameters.toCharArray(); StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); boolean keyFlag = true; for(char c : chars) { //verify ascii only //TODO may want to just stop the request entirely and throw a 500 if(!isAscii(c)) continue; //looking for the key if(keyFlag) { //skip all spaces in the key if(c == ' ') continue; //no longer a key when the '=' character is found if(c == '=') keyFlag = false; else key.append(c); } //looking for value else { //end of value search if(c == '&') { if(key.length() > 0 && value.length() > 0) parameters.put(key.toString(), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; if(parameters.size() >= server.getMaximumHeaderParameterSize()) break; } else value.append(c); } } //add the last key / value in the buffer as long as it's valid if(!keyFlag && parameters.size() < server.getMaximumHeaderParameterSize()) { if(key.length() > 0 && value.length() > 0) parameters.put(key.toString(), value.toString()); } return parameters; } /** * Decode sent cookies, this will respect the security limits set on the webserver * * @param rawCookies any String to represent the cookie header * @return a HashMap String, String key-value pair containing the cookies */ public HashMap<String, String> decodeCookies(String rawCookies) { HashMap<String, String> cookies = new HashMap<>(); if(rawCookies == null || rawCookies.isEmpty()) return cookies; char[] chars = rawCookies.toCharArray(); StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); boolean keyFlag = true; for(char c : chars) { //looking for the key if(keyFlag) { //skip all spaces in the key if(c == ' ') continue; //no longer a key when the '=' character is found if(c == '=') keyFlag = false; else key.append(c); } //looking for value else { //end of value search if(c == ';') { if(key.length() > 0 && value.length() > 0) cookies.put(key.toString(), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; if(cookies.size() >= server.getMaximumCookieCount()) break; } else value.append(c); } } //add the last key / value in the buffer as long as it's valid if(!keyFlag && cookies.size() < server.getMaximumCookieCount()) { if(key.length() > 0 && value.length() > 0) cookies.put(key.toString(), value.toString()); } return cookies; } /** * A very fast O(1) lookup table to return if a character is ascii * * @param c any character * @return true if the character is ascii */ public static boolean isAscii(char c) { switch(c) { //symbols case ' ': case '!': case '@': case '#': case '$': case '%': case '^': case '&': case '*': case '(': case ')': case '[': case ']': case '{': case '}': case '+': case '=': case '-': case '_': case '`': case '~': case ';': case ':': case '"': case '\'': case '?': case '<': case '>': case ',': case '.': case '\\': case '/': case '|': case '\r': case '\n': //numbers case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': //alphabet lowercase case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': //alphabet uppercase case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': return true; } return false; } }
src/main/java/com/konloch/http/protocol/decoder/RequestDecoder.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": "\t\t\t\tif(returnCarriage)\n\t\t\t\t{\n\t\t\t\t\tif (returnCarriageCount++ >= 2)\n\t\t\t\t\t\thasReachedEOL = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturnCarriage = true;\n\t\t\t}\n\t\t\telse if(returnCarriage)\n\t\t\t{", "score": 0.790606677532196 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\tfinal String header = parameters.get(\":\");\n\t\t//malformed request\n\t\tif(header == null)\n\t\t\treturn null;\n\t\t//split the header parameters\n\t\tfinal String[] headerParams = FastStringUtils.split(header, \" \", 3);\n\t\t//only return the request if it's valid\n\t\tif(headerParams.length == 3)\n\t\t{\n\t\t\tString method = headerParams[0];", "score": 0.7755792737007141 }, { "filename": "src/main/java/com/konloch/http/HTTPdLib.java", "retrieved_chunk": "\t\t\t\t\tcatch (IOException e)\n\t\t\t\t\t{\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tif(buffer.hasReachedEOL)\n\t\t\t\t\t\tclient.setState(3);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\t//TODO\n\t\t\t\t\t// at some point the headers will have to be processed and we will have to verify it its a post request", "score": 0.7728358507156372 }, { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": "\t\tint returnCarriageCount = 0;\n\t\tboolean returnCarriage = false;\n\t\tint EOLIndex = 0;\n\t\tfor(byte b : bytes)\n\t\t{\n\t\t\tif(!hasReachedEOL)\n\t\t\t\tEOLIndex++;\n\t\t\tchar c = (char) b;\n\t\t\tif(c == '\\n' || c == '\\r')\n\t\t\t{", "score": 0.7714260816574097 }, { "filename": "src/main/java/com/konloch/http/HTTPdLib.java", "retrieved_chunk": "\t{\n\t\tthis.maximumHeaderParameterCount = maximumHeaderParameterCount;\n\t\treturn this;\n\t}\n\tpublic int getMaximumHeaderParameterSize()\n\t{\n\t\treturn maximumHeaderParameterSize;\n\t}\n\tpublic void setMaximumHeaderParameterSize(int maximumHeaderParameterSize)\n\t{", "score": 0.7679590582847595 } ]
java
>= server.getMaximumHeaderParameterCount()) return parameters;
package com.konloch.http.protocol.encoder; import com.konloch.http.HTTPdLib; import com.konloch.http.request.Request; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.HashSet; /** * @author Konloch * @since 3/1/2023 */ public class RequestEncoder { private final HTTPdLib server; public RequestEncoder(HTTPdLib server) { this.server = server; } public byte[] generateResponse(Request request, byte[] message) { HashMap<String, String> headers = request.getResponseHeaders(); HashSet<String> sentHeaders = new HashSet<>(); StringBuilder header = new StringBuilder(); //default version and status code if(!headers.containsKey(":")) headers.put(":", "HTTP/1.1 " + request.getReturnCode()); //default content-type if(!headers.containsKey("Content-Type")) headers.put("Content-Type",
request.getContentType());
//default date (now) if(!headers.containsKey("Date")) headers.put("Date", ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME)); //send version sentHeaders.add(":"); header.append(headers.get(":")).append("\n"); //send content-type sentHeaders.add("Content-Type"); header.append("Content-Type: ").append(headers.get("Content-Type")).append("\n"); //send date sentHeaders.add("Date"); header.append("Date: ").append(headers.get("Date")).append("\n"); //send content-length sentHeaders.add("Content-Length"); header.append("Content-Length: ").append(headers.get("Content-Length")).append("\n"); //send any user supplied headers for(String headerName : headers.keySet()) { //skip all headers that have already been crafted if(sentHeaders.contains(headerName)) continue; header.append(headerName).append(": ").append(headers.get(headerName)).append("\n"); } //TODO // Cache Control / ETag // XSS-Protection / CORS // write cookies //send EOF so the web client can parse the message body header.append("\n"); //create the response output stream ByteArrayOutputStream response = new ByteArrayOutputStream(); //build the response try { response.write(header.toString().getBytes(StandardCharsets.UTF_8)); response.write(message); } catch (Exception e) { e.printStackTrace(); } //return the response as a byte array return response.toByteArray(); } }
src/main/java/com/konloch/http/protocol/encoder/RequestEncoder.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/request/Request.java", "retrieved_chunk": "\t\treturn requestHeaders;\n\t}\n\tpublic HashMap<String, String> getResponseHeaders()\n\t{\n\t\treturn responseHeaders;\n\t}\n\tpublic HashMap<String, String> getRequestCookies()\n\t{\n\t\treturn requestCookies;\n\t}", "score": 0.8456259965896606 }, { "filename": "src/main/java/com/konloch/http/request/Request.java", "retrieved_chunk": "\tpublic String getPath()\n\t{\n\t\treturn path;\n\t}\n\tpublic String getVersion()\n\t{\n\t\treturn version;\n\t}\n\tpublic HashMap<String, String> getRequestHeaders()\n\t{", "score": 0.8249916434288025 }, { "filename": "src/main/java/com/konloch/http/request/Request.java", "retrieved_chunk": "\tprivate final HashMap<String, String> get;\n\tprivate final HashMap<String, String> post;\n\tprivate int returnCode = 200;\n\tprivate String contentType = \"text/plain; charset=utf-8\";\n\tprivate File[] uploads;\n\tpublic Request(String remoteIP, RequestType method, String path, String version,\n\t HashMap<String, String> requestHeaders, HashMap<String, String> cookies,\n\t HashMap<String, String> get, HashMap<String, String> post)\n\t{\n\t\tthis.remoteIP = remoteIP;", "score": 0.813368558883667 }, { "filename": "src/main/java/com/konloch/http/request/Request.java", "retrieved_chunk": "public class Request\n{\n\tprivate final String remoteIP;\n\tprivate final RequestType method;\n\tprivate final String path;\n\tprivate final String version;\n\tprivate final HashMap<String, String> requestHeaders;\n\tprivate final HashMap<String, String> responseHeaders;\n\tprivate final HashMap<String, String> requestCookies;\n\tprivate final HashMap<String, Cookie> responseCookies;", "score": 0.8091684579849243 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\tthis.encoder = new RequestEncoder(server);\n\t}\n\tpublic Request build(SocketClient client, ClientBuffer buffer)\n\t{\n\t\tfinal byte[] request = buffer.headerBuffer.toByteArray();\n\t\t//decode the initial request parameters\n\t\tfinal HashMap<String, String> parameters = decoder.decodeHeaders(request);\n\t\tHashMap<String, String> cookies;\n\t\tHashMap<String, String> post;\n\t\tHashMap<String, String> get;", "score": 0.8083957433700562 } ]
java
request.getContentType());
package com.konloch.http.protocol.decoder; import com.konloch.http.HTTPdLib; import java.util.HashMap; /** * @author Konloch * @since 3/1/2023 */ public class RequestDecoder { private final HTTPdLib server; public RequestDecoder(HTTPdLib server) { this.server = server; } /** * Decode the headers from a raw web request, this will respect the security limits set on the webserver * * @param buffer any byte array as the buffer containing the request data * @return a HashMap String, String key-value pair containing the headers */ public HashMap<String, String> decodeHeaders(byte[] buffer) { HashMap<String, String> parameters = new HashMap<>(); StringBuilder key = new StringBuilder(" :"); StringBuilder value = new StringBuilder(); boolean keyFlag = false; int parameterCreationCount = 0; for(byte b : buffer) { char c = (char) b; //verify ascii only //TODO may want to just stop the request entirely and throw a 500 if(!isAscii(c)) continue; //looking for key if(keyFlag) { if(c == ':') keyFlag = false; else key.append(c); } //end of value else if(c == '\n' || c == '\r') { if(parameterCreationCount++ >= server.getMaximumHeaderParameterCount()) return parameters; if(key.length() > 0 && value.length() > 0) parameters.put(key.substring(1), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; } //looking for value else if(value.length() < server.getMaximumHeaderParameterSize()) value.append(c); } return parameters; } /** * Decode request parameters, this will respect the security limits set on the webserver * * @param rawParameters any String representing the raw parameters to be parsed * @return a HashMap String, String key-value pair containing the parsed parameters */ public HashMap<String, String> decodeParameters(String rawParameters) { HashMap<String, String> parameters = new HashMap<>(); char[] chars = rawParameters.toCharArray(); StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); boolean keyFlag = true; for(char c : chars) { //verify ascii only //TODO may want to just stop the request entirely and throw a 500 if(!isAscii(c)) continue; //looking for the key if(keyFlag) { //skip all spaces in the key if(c == ' ') continue; //no longer a key when the '=' character is found if(c == '=') keyFlag = false; else key.append(c); } //looking for value else { //end of value search if(c == '&') { if(key.length() > 0 && value.length() > 0) parameters.put(key.toString(), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; if(parameters.size() >= server.getMaximumHeaderParameterSize()) break; } else value.append(c); } } //add the last key / value in the buffer as long as it's valid if(!keyFlag && parameters.size() < server.getMaximumHeaderParameterSize()) { if(key.length() > 0 && value.length() > 0) parameters.put(key.toString(), value.toString()); } return parameters; } /** * Decode sent cookies, this will respect the security limits set on the webserver * * @param rawCookies any String to represent the cookie header * @return a HashMap String, String key-value pair containing the cookies */ public HashMap<String, String> decodeCookies(String rawCookies) { HashMap<String, String> cookies = new HashMap<>(); if(rawCookies == null || rawCookies.isEmpty()) return cookies; char[] chars = rawCookies.toCharArray(); StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); boolean keyFlag = true; for(char c : chars) { //looking for the key if(keyFlag) { //skip all spaces in the key if(c == ' ') continue; //no longer a key when the '=' character is found if(c == '=') keyFlag = false; else key.append(c); } //looking for value else { //end of value search if(c == ';') { if(key.length() > 0 && value.length() > 0) cookies.put(key.toString(), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true;
if(cookies.size() >= server.getMaximumCookieCount()) break;
} else value.append(c); } } //add the last key / value in the buffer as long as it's valid if(!keyFlag && cookies.size() < server.getMaximumCookieCount()) { if(key.length() > 0 && value.length() > 0) cookies.put(key.toString(), value.toString()); } return cookies; } /** * A very fast O(1) lookup table to return if a character is ascii * * @param c any character * @return true if the character is ascii */ public static boolean isAscii(char c) { switch(c) { //symbols case ' ': case '!': case '@': case '#': case '$': case '%': case '^': case '&': case '*': case '(': case ')': case '[': case ']': case '{': case '}': case '+': case '=': case '-': case '_': case '`': case '~': case ';': case ':': case '"': case '\'': case '?': case '<': case '>': case ',': case '.': case '\\': case '/': case '|': case '\r': case '\n': //numbers case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': //alphabet lowercase case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': //alphabet uppercase case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': return true; } return false; } }
src/main/java/com/konloch/http/protocol/decoder/RequestDecoder.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/request/cookies/Cookie.java", "retrieved_chunk": "package com.konloch.http.request.cookies;\n/**\n * @author Konloch\n * @since 3/8/2023\n */\npublic class Cookie\n{\n\tprivate final String name;\n\tprivate final String value;\n\tprivate String expires; //the date this cookie is set to expire at", "score": 0.7852387428283691 }, { "filename": "src/main/java/com/konloch/http/request/cookies/Cookie.java", "retrieved_chunk": "\tprivate boolean httpOnly; //means javascript cannot access this cookie\n\tprivate boolean secure; //only accessible VIA https or localhost\n\tprivate String domain; //locks the cookie to specific domains, subdomains are included by default\n\tprivate String path; //only accessible if the request path starts with the specific path\n\tprivate String sameSite; //cross site forgery request protectio\n\tpublic Cookie(String name, String value)\n\t{\n\t\tthis.name = name;\n\t\tthis.value = value;\n\t}", "score": 0.7845135927200317 }, { "filename": "src/main/java/com/konloch/http/protocol/encoder/RequestEncoder.java", "retrieved_chunk": "\t\t\tif(sentHeaders.contains(headerName))\n\t\t\t\tcontinue;\n\t\t\theader.append(headerName).append(\": \").append(headers.get(headerName)).append(\"\\n\");\n\t\t}\n\t\t//TODO\n\t\t// Cache Control / ETag\n\t\t// XSS-Protection / CORS\n\t\t// write cookies\n\t\t//send EOF so the web client can parse the message body\n\t\theader.append(\"\\n\");", "score": 0.7649444341659546 }, { "filename": "src/main/java/com/konloch/http/HTTPdLib.java", "retrieved_chunk": "\t\tthis.maximumHeaderParameterSize = maximumHeaderParameterSize;\n\t}\n\tpublic int getMaximumCookieCount()\n\t{\n\t\treturn maximumCookieCount;\n\t}\n\tpublic void setMaximumCookieCount(int maximumCookieCount)\n\t{\n\t\tthis.maximumCookieCount = maximumCookieCount;\n\t}", "score": 0.7643811702728271 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\t\t}\n\t\t\telse\n\t\t\t\tget = new HashMap<>();\n\t\t\t// decode POST\n\t\t\tif(methodType == Request.RequestType.POST)\n\t\t\t\tpost = decoder.decodeParameters(new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8));\n\t\t\telse\n\t\t\t\tpost = new HashMap<>();\n\t\t\t//decode cookies\n\t\t\tif(parameters.containsKey(\"Cookie\"))", "score": 0.763600766658783 } ]
java
if(cookies.size() >= server.getMaximumCookieCount()) break;
package com.konloch.http.protocol.decoder; import com.konloch.http.HTTPdLib; import java.util.HashMap; /** * @author Konloch * @since 3/1/2023 */ public class RequestDecoder { private final HTTPdLib server; public RequestDecoder(HTTPdLib server) { this.server = server; } /** * Decode the headers from a raw web request, this will respect the security limits set on the webserver * * @param buffer any byte array as the buffer containing the request data * @return a HashMap String, String key-value pair containing the headers */ public HashMap<String, String> decodeHeaders(byte[] buffer) { HashMap<String, String> parameters = new HashMap<>(); StringBuilder key = new StringBuilder(" :"); StringBuilder value = new StringBuilder(); boolean keyFlag = false; int parameterCreationCount = 0; for(byte b : buffer) { char c = (char) b; //verify ascii only //TODO may want to just stop the request entirely and throw a 500 if(!isAscii(c)) continue; //looking for key if(keyFlag) { if(c == ':') keyFlag = false; else key.append(c); } //end of value else if(c == '\n' || c == '\r') { if(parameterCreationCount++ >= server.getMaximumHeaderParameterCount()) return parameters; if(key.length() > 0 && value.length() > 0) parameters.put(key.substring(1), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; } //looking for value else if(value.length() < server.getMaximumHeaderParameterSize()) value.append(c); } return parameters; } /** * Decode request parameters, this will respect the security limits set on the webserver * * @param rawParameters any String representing the raw parameters to be parsed * @return a HashMap String, String key-value pair containing the parsed parameters */ public HashMap<String, String> decodeParameters(String rawParameters) { HashMap<String, String> parameters = new HashMap<>(); char[] chars = rawParameters.toCharArray(); StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); boolean keyFlag = true; for(char c : chars) { //verify ascii only //TODO may want to just stop the request entirely and throw a 500 if(!isAscii(c)) continue; //looking for the key if(keyFlag) { //skip all spaces in the key if(c == ' ') continue; //no longer a key when the '=' character is found if(c == '=') keyFlag = false; else key.append(c); } //looking for value else { //end of value search if(c == '&') { if(key.length() > 0 && value.length() > 0) parameters.put(key.toString(), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; if(parameters.
size() >= server.getMaximumHeaderParameterSize()) break;
} else value.append(c); } } //add the last key / value in the buffer as long as it's valid if(!keyFlag && parameters.size() < server.getMaximumHeaderParameterSize()) { if(key.length() > 0 && value.length() > 0) parameters.put(key.toString(), value.toString()); } return parameters; } /** * Decode sent cookies, this will respect the security limits set on the webserver * * @param rawCookies any String to represent the cookie header * @return a HashMap String, String key-value pair containing the cookies */ public HashMap<String, String> decodeCookies(String rawCookies) { HashMap<String, String> cookies = new HashMap<>(); if(rawCookies == null || rawCookies.isEmpty()) return cookies; char[] chars = rawCookies.toCharArray(); StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); boolean keyFlag = true; for(char c : chars) { //looking for the key if(keyFlag) { //skip all spaces in the key if(c == ' ') continue; //no longer a key when the '=' character is found if(c == '=') keyFlag = false; else key.append(c); } //looking for value else { //end of value search if(c == ';') { if(key.length() > 0 && value.length() > 0) cookies.put(key.toString(), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; if(cookies.size() >= server.getMaximumCookieCount()) break; } else value.append(c); } } //add the last key / value in the buffer as long as it's valid if(!keyFlag && cookies.size() < server.getMaximumCookieCount()) { if(key.length() > 0 && value.length() > 0) cookies.put(key.toString(), value.toString()); } return cookies; } /** * A very fast O(1) lookup table to return if a character is ascii * * @param c any character * @return true if the character is ascii */ public static boolean isAscii(char c) { switch(c) { //symbols case ' ': case '!': case '@': case '#': case '$': case '%': case '^': case '&': case '*': case '(': case ')': case '[': case ']': case '{': case '}': case '+': case '=': case '-': case '_': case '`': case '~': case ';': case ':': case '"': case '\'': case '?': case '<': case '>': case ',': case '.': case '\\': case '/': case '|': case '\r': case '\n': //numbers case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': //alphabet lowercase case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': //alphabet uppercase case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': return true; } return false; } }
src/main/java/com/konloch/http/protocol/decoder/RequestDecoder.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\tfinal String header = parameters.get(\":\");\n\t\t//malformed request\n\t\tif(header == null)\n\t\t\treturn null;\n\t\t//split the header parameters\n\t\tfinal String[] headerParams = FastStringUtils.split(header, \" \", 3);\n\t\t//only return the request if it's valid\n\t\tif(headerParams.length == 3)\n\t\t{\n\t\t\tString method = headerParams[0];", "score": 0.8057439923286438 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\t\t}\n\t\t\telse\n\t\t\t\tget = new HashMap<>();\n\t\t\t// decode POST\n\t\t\tif(methodType == Request.RequestType.POST)\n\t\t\t\tpost = decoder.decodeParameters(new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8));\n\t\t\telse\n\t\t\t\tpost = new HashMap<>();\n\t\t\t//decode cookies\n\t\t\tif(parameters.containsKey(\"Cookie\"))", "score": 0.7979717254638672 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\t\tString path = headerParams[1];\n\t\t\tString version = headerParams[2];\n\t\t\tfinal Request.RequestType methodType = Request.RequestType.from(method);\n\t\t\t//decode GET\n\t\t\tfinal int getIndex = path.indexOf('?');\n\t\t\tif(getIndex != -1)\n\t\t\t{\n\t\t\t\tpath = path.substring(0, getIndex);\n\t\t\t\tfinal String getData = path.substring(getIndex);\n\t\t\t\tget = decoder.decodeParameters(getData);", "score": 0.7964410781860352 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\tthis.encoder = new RequestEncoder(server);\n\t}\n\tpublic Request build(SocketClient client, ClientBuffer buffer)\n\t{\n\t\tfinal byte[] request = buffer.headerBuffer.toByteArray();\n\t\t//decode the initial request parameters\n\t\tfinal HashMap<String, String> parameters = decoder.decodeHeaders(request);\n\t\tHashMap<String, String> cookies;\n\t\tHashMap<String, String> post;\n\t\tHashMap<String, String> get;", "score": 0.7742034792900085 }, { "filename": "src/main/java/com/konloch/http/HTTPdLib.java", "retrieved_chunk": "\t{\n\t\tthis.maximumHeaderParameterCount = maximumHeaderParameterCount;\n\t\treturn this;\n\t}\n\tpublic int getMaximumHeaderParameterSize()\n\t{\n\t\treturn maximumHeaderParameterSize;\n\t}\n\tpublic void setMaximumHeaderParameterSize(int maximumHeaderParameterSize)\n\t{", "score": 0.7727258205413818 } ]
java
size() >= server.getMaximumHeaderParameterSize()) break;
package com.konloch.http.protocol.decoder; import com.konloch.http.HTTPdLib; import java.util.HashMap; /** * @author Konloch * @since 3/1/2023 */ public class RequestDecoder { private final HTTPdLib server; public RequestDecoder(HTTPdLib server) { this.server = server; } /** * Decode the headers from a raw web request, this will respect the security limits set on the webserver * * @param buffer any byte array as the buffer containing the request data * @return a HashMap String, String key-value pair containing the headers */ public HashMap<String, String> decodeHeaders(byte[] buffer) { HashMap<String, String> parameters = new HashMap<>(); StringBuilder key = new StringBuilder(" :"); StringBuilder value = new StringBuilder(); boolean keyFlag = false; int parameterCreationCount = 0; for(byte b : buffer) { char c = (char) b; //verify ascii only //TODO may want to just stop the request entirely and throw a 500 if(!isAscii(c)) continue; //looking for key if(keyFlag) { if(c == ':') keyFlag = false; else key.append(c); } //end of value else if(c == '\n' || c == '\r') { if(parameterCreationCount++ >= server.getMaximumHeaderParameterCount()) return parameters; if(key.length() > 0 && value.length() > 0) parameters.put(key.substring(1), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; } //looking for value else
if(value.length() < server.getMaximumHeaderParameterSize()) value.append(c);
} return parameters; } /** * Decode request parameters, this will respect the security limits set on the webserver * * @param rawParameters any String representing the raw parameters to be parsed * @return a HashMap String, String key-value pair containing the parsed parameters */ public HashMap<String, String> decodeParameters(String rawParameters) { HashMap<String, String> parameters = new HashMap<>(); char[] chars = rawParameters.toCharArray(); StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); boolean keyFlag = true; for(char c : chars) { //verify ascii only //TODO may want to just stop the request entirely and throw a 500 if(!isAscii(c)) continue; //looking for the key if(keyFlag) { //skip all spaces in the key if(c == ' ') continue; //no longer a key when the '=' character is found if(c == '=') keyFlag = false; else key.append(c); } //looking for value else { //end of value search if(c == '&') { if(key.length() > 0 && value.length() > 0) parameters.put(key.toString(), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; if(parameters.size() >= server.getMaximumHeaderParameterSize()) break; } else value.append(c); } } //add the last key / value in the buffer as long as it's valid if(!keyFlag && parameters.size() < server.getMaximumHeaderParameterSize()) { if(key.length() > 0 && value.length() > 0) parameters.put(key.toString(), value.toString()); } return parameters; } /** * Decode sent cookies, this will respect the security limits set on the webserver * * @param rawCookies any String to represent the cookie header * @return a HashMap String, String key-value pair containing the cookies */ public HashMap<String, String> decodeCookies(String rawCookies) { HashMap<String, String> cookies = new HashMap<>(); if(rawCookies == null || rawCookies.isEmpty()) return cookies; char[] chars = rawCookies.toCharArray(); StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); boolean keyFlag = true; for(char c : chars) { //looking for the key if(keyFlag) { //skip all spaces in the key if(c == ' ') continue; //no longer a key when the '=' character is found if(c == '=') keyFlag = false; else key.append(c); } //looking for value else { //end of value search if(c == ';') { if(key.length() > 0 && value.length() > 0) cookies.put(key.toString(), value.toString()); key = new StringBuilder(); value = new StringBuilder(); keyFlag = true; if(cookies.size() >= server.getMaximumCookieCount()) break; } else value.append(c); } } //add the last key / value in the buffer as long as it's valid if(!keyFlag && cookies.size() < server.getMaximumCookieCount()) { if(key.length() > 0 && value.length() > 0) cookies.put(key.toString(), value.toString()); } return cookies; } /** * A very fast O(1) lookup table to return if a character is ascii * * @param c any character * @return true if the character is ascii */ public static boolean isAscii(char c) { switch(c) { //symbols case ' ': case '!': case '@': case '#': case '$': case '%': case '^': case '&': case '*': case '(': case ')': case '[': case ']': case '{': case '}': case '+': case '=': case '-': case '_': case '`': case '~': case ';': case ':': case '"': case '\'': case '?': case '<': case '>': case ',': case '.': case '\\': case '/': case '|': case '\r': case '\n': //numbers case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': //alphabet lowercase case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': //alphabet uppercase case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': return true; } return false; } }
src/main/java/com/konloch/http/protocol/decoder/RequestDecoder.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\tfinal String header = parameters.get(\":\");\n\t\t//malformed request\n\t\tif(header == null)\n\t\t\treturn null;\n\t\t//split the header parameters\n\t\tfinal String[] headerParams = FastStringUtils.split(header, \" \", 3);\n\t\t//only return the request if it's valid\n\t\tif(headerParams.length == 3)\n\t\t{\n\t\t\tString method = headerParams[0];", "score": 0.807770311832428 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\t\tString path = headerParams[1];\n\t\t\tString version = headerParams[2];\n\t\t\tfinal Request.RequestType methodType = Request.RequestType.from(method);\n\t\t\t//decode GET\n\t\t\tfinal int getIndex = path.indexOf('?');\n\t\t\tif(getIndex != -1)\n\t\t\t{\n\t\t\t\tpath = path.substring(0, getIndex);\n\t\t\t\tfinal String getData = path.substring(getIndex);\n\t\t\t\tget = decoder.decodeParameters(getData);", "score": 0.8020027875900269 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\t\t}\n\t\t\telse\n\t\t\t\tget = new HashMap<>();\n\t\t\t// decode POST\n\t\t\tif(methodType == Request.RequestType.POST)\n\t\t\t\tpost = decoder.decodeParameters(new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8));\n\t\t\telse\n\t\t\t\tpost = new HashMap<>();\n\t\t\t//decode cookies\n\t\t\tif(parameters.containsKey(\"Cookie\"))", "score": 0.7994276881217957 }, { "filename": "src/main/java/com/konloch/http/HTTPdLib.java", "retrieved_chunk": "\t{\n\t\tthis.maximumHeaderParameterCount = maximumHeaderParameterCount;\n\t\treturn this;\n\t}\n\tpublic int getMaximumHeaderParameterSize()\n\t{\n\t\treturn maximumHeaderParameterSize;\n\t}\n\tpublic void setMaximumHeaderParameterSize(int maximumHeaderParameterSize)\n\t{", "score": 0.7800331115722656 }, { "filename": "src/main/java/com/konloch/http/protocol/encoder/RequestEncoder.java", "retrieved_chunk": "\t\t\tif(sentHeaders.contains(headerName))\n\t\t\t\tcontinue;\n\t\t\theader.append(headerName).append(\": \").append(headers.get(headerName)).append(\"\\n\");\n\t\t}\n\t\t//TODO\n\t\t// Cache Control / ETag\n\t\t// XSS-Protection / CORS\n\t\t// write cookies\n\t\t//send EOF so the web client can parse the message body\n\t\theader.append(\"\\n\");", "score": 0.7781926989555359 } ]
java
if(value.length() < server.getMaximumHeaderParameterSize()) value.append(c);
package com.konloch.http; import com.konloch.http.client.ClientBuffer; import com.konloch.http.request.Request; import com.konloch.http.request.RequestBuilder; import com.konloch.http.request.RequestListener; import com.konloch.socket.SocketClient; import com.konloch.socket.SocketServer; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.concurrent.atomic.AtomicLong; /** * A minified HTTP 1.1 compliant webserver. * * @author Konloch * @since 2/28/2023 */ public class HTTPdLib { private final RequestBuilder requestBuilder; private final SocketServer server; private final HashMap<Long, ClientBuffer> connected = new HashMap<>(); private final HashMap<String, AtomicLong> simultaneousConnectionMap = new HashMap<>(); private int maximumSimultaneousConnections = 10; private int maximumHeaderParameterCount = 100; private int maximumHeaderParameterSize = 1024 * 1024; private int maximumCookieCount = 100; public HTTPdLib(int port, RequestListener requestListener) throws IOException { this(port, 1, requestListener); } public HTTPdLib(int port, int threadPool, RequestListener requestListener) throws IOException { requestBuilder = new RequestBuilder(this); server = new SocketServer(port, threadPool, //setup the request filter client -> { //only allow X simultaneous connections if(simultaneousConnectionMap.containsKey(client.getRemoteAddress())) return simultaneousConnectionMap.get(client.getRemoteAddress()).incrementAndGet() <= maximumSimultaneousConnections; else { //no other simultaneous connections simultaneousConnectionMap.put(client.getRemoteAddress(), new AtomicLong(1)); return true; } }, //process the client IO client -> { ClientBuffer buffer = getBuffer(client); switch(client.getState()) { //signal we want to start reading into the buffer case 0: //signal that we want to start reading and to fill up the buffer client.setInputRead(true); //advance to stage 1 client.setState(1); break; //wait until the stream has signalled the buffer has reached the end case 1: //when the buffer is full advance to stage 2 if(!client.isInputRead()) client.setState(2); break; //read the buffer and look for EOF, if we haven't reached it yet, go back to state 0 case 2: //skip empty buffer if(client.getInputBuffer().size() == 0) break; //get the bytes written byte[] bytes = client.getInputBuffer().toByteArray(); //reset the input buffer client.getInputBuffer().reset(); try { buffer.writeHeader(bytes); } catch (IOException e) { e.printStackTrace(); } if(buffer.hasReachedEOL) client.setState(3); break; case 3: //TODO // at some point the headers will have to be processed and we will have to verify it its a post request // if it's a post request, we will need to download X bytes and then process them // this same piece of code is how we handle multi-form uploads and single form uploads // keep-alive is also handled in that same chunk of code if(buffer.request == null) buffer.request = requestBuilder.build(client, buffer); if(buffer.request != null) { if(buffer.request.getMethod() == Request.RequestType.POST) { client.setState(10); break; } client.setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request))); } client.setState(100); break; //read post request case 10: //get the bytes written bytes = client.getInputBuffer().toByteArray(); //reset the input buffer client.getInputBuffer().reset(); //TODO // before multi parts, the body data should be saved for post requests // look for multi parts, if they exist, parse them, log, and save the bytes to file // if it was previously in a multi part parse, it should continue writing to that last file try { System.out.println("SONG: " + new String(bytes, StandardCharsets.UTF_8));
buffer.writeBody(bytes);
} catch (IOException e) { e.printStackTrace(); } if(!client.isInputRead()) { System.out.println("ALL DONE: " + new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8)); if(buffer.request != null) client.setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request))); client.setState(100); } break; //wait for the data to be sent case 100: if(client.getOutputBuffer().size() == 0 && System.currentTimeMillis() - client.getLastNetworkActivityWrite() >= 100) { try { client.getSocket().close(); } catch (IOException e) { e.printStackTrace(); } } break; } }, //on client disconnect remove the cached data client -> { connected.remove(client.getUID()); if(simultaneousConnectionMap.get(client.getRemoteAddress()).decrementAndGet() <= 0) simultaneousConnectionMap.remove(client.getRemoteAddress()); }); } public ClientBuffer getBuffer(SocketClient client) { if(!connected.containsKey(client.getUID())) connected.put(client.getUID(), new ClientBuffer()); return connected.get(client.getUID()); } public void start() { server.start(); } public void stop() { server.stopSocketServer(); } public SocketServer getServer() { return server; } public int getMaximumSimultaneousConnections() { return maximumSimultaneousConnections; } public void setMaximumSimultaneousConnections(int maximumSimultaneousConnections) { this.maximumSimultaneousConnections = maximumSimultaneousConnections; } public int getMaximumHeaderParameterCount() { return maximumHeaderParameterCount; } public HTTPdLib setMaximumHeaderParameterCount(int maximumHeaderParameterCount) { this.maximumHeaderParameterCount = maximumHeaderParameterCount; return this; } public int getMaximumHeaderParameterSize() { return maximumHeaderParameterSize; } public void setMaximumHeaderParameterSize(int maximumHeaderParameterSize) { this.maximumHeaderParameterSize = maximumHeaderParameterSize; } public int getMaximumCookieCount() { return maximumCookieCount; } public void setMaximumCookieCount(int maximumCookieCount) { this.maximumCookieCount = maximumCookieCount; } }
src/main/java/com/konloch/http/HTTPdLib.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": "\t\tint EOLIndex = getEOL(bytes);\n\t\tif(EOLIndex > 0)\n\t\t{\n\t\t\theaderBuffer.write(bytes, 0, EOLIndex);\n\t\t\tbodyBuffer.write(bytes, EOLIndex, bytes.length - EOLIndex);\n\t\t}\n\t\telse\n\t\t{\n\t\t\theaderBuffer.write(bytes);\n\t\t\t//requests that have the EOL sent in chunks need to be handled by processing the entire buffer", "score": 0.8307874798774719 }, { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": " * @since 3/1/2023\n */\npublic class ClientBuffer\n{\n\tpublic final ByteArrayOutputStream headerBuffer = new ByteArrayOutputStream();\n\tpublic final ByteArrayOutputStream bodyBuffer = new ByteArrayOutputStream();\n\tpublic boolean hasReachedEOL;\n\tpublic Request request;\n\tpublic void writeHeader(byte[] bytes) throws IOException\n\t{", "score": 0.8090986609458923 }, { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": "\t\t\tif(!hasReachedEOL)\n\t\t\t\tgetEOL(headerBuffer.toByteArray());\n\t\t}\n\t}\n\tpublic void writeBody(byte[] bytes) throws IOException\n\t{\n\t\tbodyBuffer.write(bytes);\n\t}\n\tprivate int getEOL(byte[] bytes)\n\t{", "score": 0.8028380274772644 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\tthis.encoder = new RequestEncoder(server);\n\t}\n\tpublic Request build(SocketClient client, ClientBuffer buffer)\n\t{\n\t\tfinal byte[] request = buffer.headerBuffer.toByteArray();\n\t\t//decode the initial request parameters\n\t\tfinal HashMap<String, String> parameters = decoder.decodeHeaders(request);\n\t\tHashMap<String, String> cookies;\n\t\tHashMap<String, String> post;\n\t\tHashMap<String, String> get;", "score": 0.7854078412055969 }, { "filename": "src/main/java/com/konloch/http/protocol/decoder/MultiPartDecoder.java", "retrieved_chunk": "package com.konloch.http.protocol.decoder;\nimport java.util.HashMap;\n/**\n * @author Konloch\n * @since 3/8/2023\n */\npublic class MultiPartDecoder\n{\n\tprivate final byte[] multipart;\n\tprivate HashMap<String, MultiPart> parts = new HashMap<>();", "score": 0.7843880653381348 } ]
java
buffer.writeBody(bytes);
package com.konloch.http; import com.konloch.http.client.ClientBuffer; import com.konloch.http.request.Request; import com.konloch.http.request.RequestBuilder; import com.konloch.http.request.RequestListener; import com.konloch.socket.SocketClient; import com.konloch.socket.SocketServer; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.concurrent.atomic.AtomicLong; /** * A minified HTTP 1.1 compliant webserver. * * @author Konloch * @since 2/28/2023 */ public class HTTPdLib { private final RequestBuilder requestBuilder; private final SocketServer server; private final HashMap<Long, ClientBuffer> connected = new HashMap<>(); private final HashMap<String, AtomicLong> simultaneousConnectionMap = new HashMap<>(); private int maximumSimultaneousConnections = 10; private int maximumHeaderParameterCount = 100; private int maximumHeaderParameterSize = 1024 * 1024; private int maximumCookieCount = 100; public HTTPdLib(int port, RequestListener requestListener) throws IOException { this(port, 1, requestListener); } public HTTPdLib(int port, int threadPool, RequestListener requestListener) throws IOException { requestBuilder = new RequestBuilder(this); server = new SocketServer(port, threadPool, //setup the request filter client -> { //only allow X simultaneous connections if(simultaneousConnectionMap.containsKey(client.getRemoteAddress())) return simultaneousConnectionMap.get(client.getRemoteAddress()).incrementAndGet() <= maximumSimultaneousConnections; else { //no other simultaneous connections simultaneousConnectionMap.put(client.getRemoteAddress(), new AtomicLong(1)); return true; } }, //process the client IO client -> { ClientBuffer buffer = getBuffer(client); switch(client.getState()) { //signal we want to start reading into the buffer case 0: //signal that we want to start reading and to fill up the buffer client.setInputRead(true); //advance to stage 1 client.setState(1); break; //wait until the stream has signalled the buffer has reached the end case 1: //when the buffer is full advance to stage 2 if(!client.isInputRead()) client.setState(2); break; //read the buffer and look for EOF, if we haven't reached it yet, go back to state 0 case 2: //skip empty buffer if(client.getInputBuffer().size() == 0) break; //get the bytes written byte[] bytes = client.getInputBuffer().toByteArray(); //reset the input buffer client.getInputBuffer().reset(); try {
buffer.writeHeader(bytes);
} catch (IOException e) { e.printStackTrace(); } if(buffer.hasReachedEOL) client.setState(3); break; case 3: //TODO // at some point the headers will have to be processed and we will have to verify it its a post request // if it's a post request, we will need to download X bytes and then process them // this same piece of code is how we handle multi-form uploads and single form uploads // keep-alive is also handled in that same chunk of code if(buffer.request == null) buffer.request = requestBuilder.build(client, buffer); if(buffer.request != null) { if(buffer.request.getMethod() == Request.RequestType.POST) { client.setState(10); break; } client.setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request))); } client.setState(100); break; //read post request case 10: //get the bytes written bytes = client.getInputBuffer().toByteArray(); //reset the input buffer client.getInputBuffer().reset(); //TODO // before multi parts, the body data should be saved for post requests // look for multi parts, if they exist, parse them, log, and save the bytes to file // if it was previously in a multi part parse, it should continue writing to that last file try { System.out.println("SONG: " + new String(bytes, StandardCharsets.UTF_8)); buffer.writeBody(bytes); } catch (IOException e) { e.printStackTrace(); } if(!client.isInputRead()) { System.out.println("ALL DONE: " + new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8)); if(buffer.request != null) client.setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request))); client.setState(100); } break; //wait for the data to be sent case 100: if(client.getOutputBuffer().size() == 0 && System.currentTimeMillis() - client.getLastNetworkActivityWrite() >= 100) { try { client.getSocket().close(); } catch (IOException e) { e.printStackTrace(); } } break; } }, //on client disconnect remove the cached data client -> { connected.remove(client.getUID()); if(simultaneousConnectionMap.get(client.getRemoteAddress()).decrementAndGet() <= 0) simultaneousConnectionMap.remove(client.getRemoteAddress()); }); } public ClientBuffer getBuffer(SocketClient client) { if(!connected.containsKey(client.getUID())) connected.put(client.getUID(), new ClientBuffer()); return connected.get(client.getUID()); } public void start() { server.start(); } public void stop() { server.stopSocketServer(); } public SocketServer getServer() { return server; } public int getMaximumSimultaneousConnections() { return maximumSimultaneousConnections; } public void setMaximumSimultaneousConnections(int maximumSimultaneousConnections) { this.maximumSimultaneousConnections = maximumSimultaneousConnections; } public int getMaximumHeaderParameterCount() { return maximumHeaderParameterCount; } public HTTPdLib setMaximumHeaderParameterCount(int maximumHeaderParameterCount) { this.maximumHeaderParameterCount = maximumHeaderParameterCount; return this; } public int getMaximumHeaderParameterSize() { return maximumHeaderParameterSize; } public void setMaximumHeaderParameterSize(int maximumHeaderParameterSize) { this.maximumHeaderParameterSize = maximumHeaderParameterSize; } public int getMaximumCookieCount() { return maximumCookieCount; } public void setMaximumCookieCount(int maximumCookieCount) { this.maximumCookieCount = maximumCookieCount; } }
src/main/java/com/konloch/http/HTTPdLib.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": " * @since 3/1/2023\n */\npublic class ClientBuffer\n{\n\tpublic final ByteArrayOutputStream headerBuffer = new ByteArrayOutputStream();\n\tpublic final ByteArrayOutputStream bodyBuffer = new ByteArrayOutputStream();\n\tpublic boolean hasReachedEOL;\n\tpublic Request request;\n\tpublic void writeHeader(byte[] bytes) throws IOException\n\t{", "score": 0.8419778943061829 }, { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": "\t\tint EOLIndex = getEOL(bytes);\n\t\tif(EOLIndex > 0)\n\t\t{\n\t\t\theaderBuffer.write(bytes, 0, EOLIndex);\n\t\t\tbodyBuffer.write(bytes, EOLIndex, bytes.length - EOLIndex);\n\t\t}\n\t\telse\n\t\t{\n\t\t\theaderBuffer.write(bytes);\n\t\t\t//requests that have the EOL sent in chunks need to be handled by processing the entire buffer", "score": 0.8337052464485168 }, { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": "\t\t\tif(!hasReachedEOL)\n\t\t\t\tgetEOL(headerBuffer.toByteArray());\n\t\t}\n\t}\n\tpublic void writeBody(byte[] bytes) throws IOException\n\t{\n\t\tbodyBuffer.write(bytes);\n\t}\n\tprivate int getEOL(byte[] bytes)\n\t{", "score": 0.8160736560821533 }, { "filename": "src/main/java/com/konloch/http/protocol/decoder/RequestDecoder.java", "retrieved_chunk": "\t\t\t\t\tkeyFlag = true;\n\t\t\t\t\tif(parameters.size() >= server.getMaximumHeaderParameterSize())\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tvalue.append(c);\n\t\t\t}\n\t\t}\n\t\t//add the last key / value in the buffer as long as it's valid\n\t\tif(!keyFlag && parameters.size() < server.getMaximumHeaderParameterSize())", "score": 0.8099536895751953 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\tthis.encoder = new RequestEncoder(server);\n\t}\n\tpublic Request build(SocketClient client, ClientBuffer buffer)\n\t{\n\t\tfinal byte[] request = buffer.headerBuffer.toByteArray();\n\t\t//decode the initial request parameters\n\t\tfinal HashMap<String, String> parameters = decoder.decodeHeaders(request);\n\t\tHashMap<String, String> cookies;\n\t\tHashMap<String, String> post;\n\t\tHashMap<String, String> get;", "score": 0.8089573383331299 } ]
java
buffer.writeHeader(bytes);
package com.konloch.http.request; import com.konloch.http.HTTPdLib; import com.konloch.http.client.ClientBuffer; import com.konloch.http.protocol.encoder.RequestEncoder; import com.konloch.http.protocol.decoder.RequestDecoder; import com.konloch.socket.SocketClient; import com.konloch.util.FastStringUtils; import java.nio.charset.StandardCharsets; import java.util.HashMap; /** * @author Konloch * @since 3/1/2023 */ public class RequestBuilder { private final RequestDecoder decoder; private final RequestEncoder encoder; public RequestBuilder(HTTPdLib server) { this.decoder = new RequestDecoder(server); this.encoder = new RequestEncoder(server); } public Request build(SocketClient client, ClientBuffer buffer) { final byte[] request = buffer.headerBuffer.toByteArray(); //decode the initial request parameters final HashMap<String, String> parameters = decoder.decodeHeaders(request); HashMap<String, String> cookies; HashMap<String, String> post; HashMap<String, String> get; final String header = parameters.get(":"); //malformed request if(header == null) return null; //split the header parameters final String[] headerParams = FastStringUtils.split(header, " ", 3); //only return the request if it's valid if(headerParams.length == 3) { String method = headerParams[0]; String path = headerParams[1]; String version = headerParams[2]; final Request.RequestType methodType = Request.RequestType.from(method); //decode GET final int getIndex = path.indexOf('?'); if(getIndex != -1) { path = path.substring(0, getIndex); final String getData = path.substring(getIndex); get = decoder.decodeParameters(getData); } else get = new HashMap<>(); // decode POST if(methodType == Request.RequestType.POST) post
= decoder.decodeParameters(new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8));
else post = new HashMap<>(); //decode cookies if(parameters.containsKey("Cookie")) cookies = decoder.decodeCookies(parameters.get("Cookie")); else cookies = new HashMap<>(); return new Request(client.getRemoteAddress(), methodType, path, version, parameters, cookies, get, post); } return null; } public RequestDecoder getDecoder() { return decoder; } public RequestEncoder getEncoder() { return encoder; } }
src/main/java/com/konloch/http/request/RequestBuilder.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/protocol/decoder/RequestDecoder.java", "retrieved_chunk": "\tpublic HashMap<String, String> decodeHeaders(byte[] buffer)\n\t{\n\t\tHashMap<String, String> parameters = new HashMap<>();\n\t\tStringBuilder key = new StringBuilder(\" :\");\n\t\tStringBuilder value = new StringBuilder();\n\t\tboolean keyFlag = false;\n\t\tint parameterCreationCount = 0;\n\t\tfor(byte b : buffer)\n\t\t{\n\t\t\tchar c = (char) b;", "score": 0.8196977376937866 }, { "filename": "src/main/java/com/konloch/http/request/Request.java", "retrieved_chunk": "\tprivate final HashMap<String, String> get;\n\tprivate final HashMap<String, String> post;\n\tprivate int returnCode = 200;\n\tprivate String contentType = \"text/plain; charset=utf-8\";\n\tprivate File[] uploads;\n\tpublic Request(String remoteIP, RequestType method, String path, String version,\n\t HashMap<String, String> requestHeaders, HashMap<String, String> cookies,\n\t HashMap<String, String> get, HashMap<String, String> post)\n\t{\n\t\tthis.remoteIP = remoteIP;", "score": 0.8004339933395386 }, { "filename": "src/main/java/com/konloch/http/request/Request.java", "retrieved_chunk": "\t\tthis.path = path;\n\t\tthis.method = method;\n\t\tthis.version = version;\n\t\tthis.requestHeaders = requestHeaders;\n\t\tthis.get = get;\n\t\tthis.post = post;\n\t\tthis.responseHeaders = new HashMap<>();\n\t\tthis.requestCookies = cookies;\n\t\tthis.responseCookies = new HashMap<>();\n\t}", "score": 0.7967166900634766 }, { "filename": "src/main/java/com/konloch/http/HTTPdLib.java", "retrieved_chunk": "\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tclient.setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request)));\n\t\t\t\t\t}\n\t\t\t\t\tclient.setState(100);\n\t\t\t\t\tbreak;\n\t\t\t\t//read post request\n\t\t\t\tcase 10:\n\t\t\t\t\t//get the bytes written\n\t\t\t\t\tbytes = client.getInputBuffer().toByteArray();", "score": 0.7912644147872925 }, { "filename": "src/main/java/com/konloch/http/protocol/decoder/RequestDecoder.java", "retrieved_chunk": "package com.konloch.http.protocol.decoder;\nimport com.konloch.http.HTTPdLib;\nimport java.util.HashMap;\n/**\n * @author Konloch\n * @since 3/1/2023\n */\npublic class RequestDecoder\n{\n\tprivate final HTTPdLib server;", "score": 0.7893191576004028 } ]
java
= decoder.decodeParameters(new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8));
package com.konloch.http; import com.konloch.http.client.ClientBuffer; import com.konloch.http.request.Request; import com.konloch.http.request.RequestBuilder; import com.konloch.http.request.RequestListener; import com.konloch.socket.SocketClient; import com.konloch.socket.SocketServer; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.concurrent.atomic.AtomicLong; /** * A minified HTTP 1.1 compliant webserver. * * @author Konloch * @since 2/28/2023 */ public class HTTPdLib { private final RequestBuilder requestBuilder; private final SocketServer server; private final HashMap<Long, ClientBuffer> connected = new HashMap<>(); private final HashMap<String, AtomicLong> simultaneousConnectionMap = new HashMap<>(); private int maximumSimultaneousConnections = 10; private int maximumHeaderParameterCount = 100; private int maximumHeaderParameterSize = 1024 * 1024; private int maximumCookieCount = 100; public HTTPdLib(int port, RequestListener requestListener) throws IOException { this(port, 1, requestListener); } public HTTPdLib(int port, int threadPool, RequestListener requestListener) throws IOException { requestBuilder = new RequestBuilder(this); server = new SocketServer(port, threadPool, //setup the request filter client -> { //only allow X simultaneous connections if(simultaneousConnectionMap.containsKey(client.getRemoteAddress())) return simultaneousConnectionMap.get(client.getRemoteAddress()).incrementAndGet() <= maximumSimultaneousConnections; else { //no other simultaneous connections simultaneousConnectionMap.put(client.getRemoteAddress(), new AtomicLong(1)); return true; } }, //process the client IO client -> { ClientBuffer buffer = getBuffer(client); switch(client.getState()) { //signal we want to start reading into the buffer case 0: //signal that we want to start reading and to fill up the buffer client.setInputRead(true); //advance to stage 1 client.setState(1); break; //wait until the stream has signalled the buffer has reached the end case 1: //when the buffer is full advance to stage 2 if(!client.isInputRead()) client.setState(2); break; //read the buffer and look for EOF, if we haven't reached it yet, go back to state 0 case 2: //skip empty buffer if(client.getInputBuffer().size() == 0) break; //get the bytes written byte[] bytes = client.getInputBuffer().toByteArray(); //reset the input buffer client.getInputBuffer().reset(); try { buffer.writeHeader(bytes); } catch (IOException e) { e.printStackTrace(); } if(buffer.hasReachedEOL) client.setState(3); break; case 3: //TODO // at some point the headers will have to be processed and we will have to verify it its a post request // if it's a post request, we will need to download X bytes and then process them // this same piece of code is how we handle multi-form uploads and single form uploads // keep-alive is also handled in that same chunk of code if(buffer.request == null) buffer.request = requestBuilder.build(client, buffer); if(buffer.request != null) { if(buffer.request.getMethod() == Request.RequestType.POST) { client.setState(10); break; }
client.setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request)));
} client.setState(100); break; //read post request case 10: //get the bytes written bytes = client.getInputBuffer().toByteArray(); //reset the input buffer client.getInputBuffer().reset(); //TODO // before multi parts, the body data should be saved for post requests // look for multi parts, if they exist, parse them, log, and save the bytes to file // if it was previously in a multi part parse, it should continue writing to that last file try { System.out.println("SONG: " + new String(bytes, StandardCharsets.UTF_8)); buffer.writeBody(bytes); } catch (IOException e) { e.printStackTrace(); } if(!client.isInputRead()) { System.out.println("ALL DONE: " + new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8)); if(buffer.request != null) client.setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request))); client.setState(100); } break; //wait for the data to be sent case 100: if(client.getOutputBuffer().size() == 0 && System.currentTimeMillis() - client.getLastNetworkActivityWrite() >= 100) { try { client.getSocket().close(); } catch (IOException e) { e.printStackTrace(); } } break; } }, //on client disconnect remove the cached data client -> { connected.remove(client.getUID()); if(simultaneousConnectionMap.get(client.getRemoteAddress()).decrementAndGet() <= 0) simultaneousConnectionMap.remove(client.getRemoteAddress()); }); } public ClientBuffer getBuffer(SocketClient client) { if(!connected.containsKey(client.getUID())) connected.put(client.getUID(), new ClientBuffer()); return connected.get(client.getUID()); } public void start() { server.start(); } public void stop() { server.stopSocketServer(); } public SocketServer getServer() { return server; } public int getMaximumSimultaneousConnections() { return maximumSimultaneousConnections; } public void setMaximumSimultaneousConnections(int maximumSimultaneousConnections) { this.maximumSimultaneousConnections = maximumSimultaneousConnections; } public int getMaximumHeaderParameterCount() { return maximumHeaderParameterCount; } public HTTPdLib setMaximumHeaderParameterCount(int maximumHeaderParameterCount) { this.maximumHeaderParameterCount = maximumHeaderParameterCount; return this; } public int getMaximumHeaderParameterSize() { return maximumHeaderParameterSize; } public void setMaximumHeaderParameterSize(int maximumHeaderParameterSize) { this.maximumHeaderParameterSize = maximumHeaderParameterSize; } public int getMaximumCookieCount() { return maximumCookieCount; } public void setMaximumCookieCount(int maximumCookieCount) { this.maximumCookieCount = maximumCookieCount; } }
src/main/java/com/konloch/http/HTTPdLib.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\tthis.encoder = new RequestEncoder(server);\n\t}\n\tpublic Request build(SocketClient client, ClientBuffer buffer)\n\t{\n\t\tfinal byte[] request = buffer.headerBuffer.toByteArray();\n\t\t//decode the initial request parameters\n\t\tfinal HashMap<String, String> parameters = decoder.decodeHeaders(request);\n\t\tHashMap<String, String> cookies;\n\t\tHashMap<String, String> post;\n\t\tHashMap<String, String> get;", "score": 0.8514612913131714 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "package com.konloch.http.request;\nimport com.konloch.http.HTTPdLib;\nimport com.konloch.http.client.ClientBuffer;\nimport com.konloch.http.protocol.encoder.RequestEncoder;\nimport com.konloch.http.protocol.decoder.RequestDecoder;\nimport com.konloch.socket.SocketClient;\nimport com.konloch.util.FastStringUtils;\nimport java.nio.charset.StandardCharsets;\nimport java.util.HashMap;\n/**", "score": 0.8260632753372192 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\t\t}\n\t\t\telse\n\t\t\t\tget = new HashMap<>();\n\t\t\t// decode POST\n\t\t\tif(methodType == Request.RequestType.POST)\n\t\t\t\tpost = decoder.decodeParameters(new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8));\n\t\t\telse\n\t\t\t\tpost = new HashMap<>();\n\t\t\t//decode cookies\n\t\t\tif(parameters.containsKey(\"Cookie\"))", "score": 0.8154144287109375 }, { "filename": "src/main/java/com/konloch/http/protocol/encoder/RequestEncoder.java", "retrieved_chunk": "\tpublic byte[] generateResponse(Request request, byte[] message)\n\t{\n\t\tHashMap<String, String> headers = request.getResponseHeaders();\n\t\tHashSet<String> sentHeaders = new HashSet<>();\n\t\tStringBuilder header = new StringBuilder();\n\t\t//default version and status code\n\t\tif(!headers.containsKey(\":\"))\n\t\t\theaders.put(\":\", \"HTTP/1.1 \" + request.getReturnCode());\n\t\t//default content-type\n\t\tif(!headers.containsKey(\"Content-Type\"))", "score": 0.8046500086784363 }, { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": "package com.konloch.http.client;\nimport com.konloch.http.request.Request;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\n/**\n * The client buffer represents any incoming socket connection.\n *\n * Until the request has reached the EOL terminator it won't be treated as a http request.\n *\n * @author Konloch", "score": 0.7965754270553589 } ]
java
client.setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request)));
package com.konloch.http; import com.konloch.http.client.ClientBuffer; import com.konloch.http.request.Request; import com.konloch.http.request.RequestBuilder; import com.konloch.http.request.RequestListener; import com.konloch.socket.SocketClient; import com.konloch.socket.SocketServer; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.concurrent.atomic.AtomicLong; /** * A minified HTTP 1.1 compliant webserver. * * @author Konloch * @since 2/28/2023 */ public class HTTPdLib { private final RequestBuilder requestBuilder; private final SocketServer server; private final HashMap<Long, ClientBuffer> connected = new HashMap<>(); private final HashMap<String, AtomicLong> simultaneousConnectionMap = new HashMap<>(); private int maximumSimultaneousConnections = 10; private int maximumHeaderParameterCount = 100; private int maximumHeaderParameterSize = 1024 * 1024; private int maximumCookieCount = 100; public HTTPdLib(int port, RequestListener requestListener) throws IOException { this(port, 1, requestListener); } public HTTPdLib(int port, int threadPool, RequestListener requestListener) throws IOException { requestBuilder = new RequestBuilder(this); server = new SocketServer(port, threadPool, //setup the request filter client -> { //only allow X simultaneous connections if(simultaneousConnectionMap.containsKey(client.getRemoteAddress())) return simultaneousConnectionMap.get(client.getRemoteAddress()).incrementAndGet() <= maximumSimultaneousConnections; else { //no other simultaneous connections simultaneousConnectionMap.put(client.getRemoteAddress(), new AtomicLong(1)); return true; } }, //process the client IO client -> { ClientBuffer buffer = getBuffer(client); switch(client.getState()) { //signal we want to start reading into the buffer case 0: //signal that we want to start reading and to fill up the buffer client.setInputRead(true); //advance to stage 1 client.setState(1); break; //wait until the stream has signalled the buffer has reached the end case 1: //when the buffer is full advance to stage 2 if(!client.isInputRead()) client.setState(2); break; //read the buffer and look for EOF, if we haven't reached it yet, go back to state 0 case 2: //skip empty buffer if(client.getInputBuffer().size() == 0) break; //get the bytes written byte[] bytes = client.getInputBuffer().toByteArray(); //reset the input buffer client.getInputBuffer().reset(); try { buffer.writeHeader(bytes); } catch (IOException e) { e.printStackTrace(); } if(buffer.hasReachedEOL) client.setState(3); break; case 3: //TODO // at some point the headers will have to be processed and we will have to verify it its a post request // if it's a post request, we will need to download X bytes and then process them // this same piece of code is how we handle multi-form uploads and single form uploads // keep-alive is also handled in that same chunk of code if(buffer.request == null) buffer.request = requestBuilder.build(client, buffer); if(buffer.request != null) { if(buffer.request.getMethod() == Request.RequestType.POST) { client.setState(10); break; } client.setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request))); } client.setState(100); break; //read post request case 10: //get the bytes written bytes = client.getInputBuffer().toByteArray(); //reset the input buffer client.getInputBuffer().reset(); //TODO // before multi parts, the body data should be saved for post requests // look for multi parts, if they exist, parse them, log, and save the bytes to file // if it was previously in a multi part parse, it should continue writing to that last file try { System.out.println("SONG: " + new String(bytes, StandardCharsets.UTF_8)); buffer.writeBody(bytes); } catch (IOException e) { e.printStackTrace(); } if(!client.isInputRead()) { System.out.println("ALL DONE: " + new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8)); if(buffer.request != null) client.
setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request)));
client.setState(100); } break; //wait for the data to be sent case 100: if(client.getOutputBuffer().size() == 0 && System.currentTimeMillis() - client.getLastNetworkActivityWrite() >= 100) { try { client.getSocket().close(); } catch (IOException e) { e.printStackTrace(); } } break; } }, //on client disconnect remove the cached data client -> { connected.remove(client.getUID()); if(simultaneousConnectionMap.get(client.getRemoteAddress()).decrementAndGet() <= 0) simultaneousConnectionMap.remove(client.getRemoteAddress()); }); } public ClientBuffer getBuffer(SocketClient client) { if(!connected.containsKey(client.getUID())) connected.put(client.getUID(), new ClientBuffer()); return connected.get(client.getUID()); } public void start() { server.start(); } public void stop() { server.stopSocketServer(); } public SocketServer getServer() { return server; } public int getMaximumSimultaneousConnections() { return maximumSimultaneousConnections; } public void setMaximumSimultaneousConnections(int maximumSimultaneousConnections) { this.maximumSimultaneousConnections = maximumSimultaneousConnections; } public int getMaximumHeaderParameterCount() { return maximumHeaderParameterCount; } public HTTPdLib setMaximumHeaderParameterCount(int maximumHeaderParameterCount) { this.maximumHeaderParameterCount = maximumHeaderParameterCount; return this; } public int getMaximumHeaderParameterSize() { return maximumHeaderParameterSize; } public void setMaximumHeaderParameterSize(int maximumHeaderParameterSize) { this.maximumHeaderParameterSize = maximumHeaderParameterSize; } public int getMaximumCookieCount() { return maximumCookieCount; } public void setMaximumCookieCount(int maximumCookieCount) { this.maximumCookieCount = maximumCookieCount; } }
src/main/java/com/konloch/http/HTTPdLib.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "\t\tthis.encoder = new RequestEncoder(server);\n\t}\n\tpublic Request build(SocketClient client, ClientBuffer buffer)\n\t{\n\t\tfinal byte[] request = buffer.headerBuffer.toByteArray();\n\t\t//decode the initial request parameters\n\t\tfinal HashMap<String, String> parameters = decoder.decodeHeaders(request);\n\t\tHashMap<String, String> cookies;\n\t\tHashMap<String, String> post;\n\t\tHashMap<String, String> get;", "score": 0.8094792366027832 }, { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": "\t\tint EOLIndex = getEOL(bytes);\n\t\tif(EOLIndex > 0)\n\t\t{\n\t\t\theaderBuffer.write(bytes, 0, EOLIndex);\n\t\t\tbodyBuffer.write(bytes, EOLIndex, bytes.length - EOLIndex);\n\t\t}\n\t\telse\n\t\t{\n\t\t\theaderBuffer.write(bytes);\n\t\t\t//requests that have the EOL sent in chunks need to be handled by processing the entire buffer", "score": 0.8007420897483826 }, { "filename": "src/main/java/com/konloch/http/client/ClientBuffer.java", "retrieved_chunk": " * @since 3/1/2023\n */\npublic class ClientBuffer\n{\n\tpublic final ByteArrayOutputStream headerBuffer = new ByteArrayOutputStream();\n\tpublic final ByteArrayOutputStream bodyBuffer = new ByteArrayOutputStream();\n\tpublic boolean hasReachedEOL;\n\tpublic Request request;\n\tpublic void writeHeader(byte[] bytes) throws IOException\n\t{", "score": 0.7976894974708557 }, { "filename": "src/main/java/com/konloch/http/request/RequestBuilder.java", "retrieved_chunk": "package com.konloch.http.request;\nimport com.konloch.http.HTTPdLib;\nimport com.konloch.http.client.ClientBuffer;\nimport com.konloch.http.protocol.encoder.RequestEncoder;\nimport com.konloch.http.protocol.decoder.RequestDecoder;\nimport com.konloch.socket.SocketClient;\nimport com.konloch.util.FastStringUtils;\nimport java.nio.charset.StandardCharsets;\nimport java.util.HashMap;\n/**", "score": 0.7973712682723999 }, { "filename": "src/main/java/com/konloch/http/protocol/encoder/RequestEncoder.java", "retrieved_chunk": "\t\t//create the response output stream\n\t\tByteArrayOutputStream response = new ByteArrayOutputStream();\n\t\t//build the response\n\t\ttry\n\t\t{\n\t\t\tresponse.write(header.toString().getBytes(StandardCharsets.UTF_8));\n\t\t\tresponse.write(message);\n\t\t}\n\t\tcatch (Exception e)\n\t\t{", "score": 0.7963138222694397 } ]
java
setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request)));
package com.konloch.http.request; import com.konloch.http.HTTPdLib; import com.konloch.http.client.ClientBuffer; import com.konloch.http.protocol.encoder.RequestEncoder; import com.konloch.http.protocol.decoder.RequestDecoder; import com.konloch.socket.SocketClient; import com.konloch.util.FastStringUtils; import java.nio.charset.StandardCharsets; import java.util.HashMap; /** * @author Konloch * @since 3/1/2023 */ public class RequestBuilder { private final RequestDecoder decoder; private final RequestEncoder encoder; public RequestBuilder(HTTPdLib server) { this.decoder = new RequestDecoder(server); this.encoder = new RequestEncoder(server); } public Request build(SocketClient client, ClientBuffer buffer) { final byte[] request = buffer.headerBuffer.toByteArray(); //decode the initial request parameters final HashMap<String, String> parameters = decoder.decodeHeaders(request); HashMap<String, String> cookies; HashMap<String, String> post; HashMap<String, String> get; final String header = parameters.get(":"); //malformed request if(header == null) return null; //split the header parameters final String[] headerParams = FastStringUtils.split(header, " ", 3); //only return the request if it's valid if(headerParams.length == 3) { String method = headerParams[0]; String path = headerParams[1]; String version = headerParams[2]; final Request.RequestType methodType = Request.RequestType.from(method); //decode GET final int getIndex = path.indexOf('?'); if(getIndex != -1) { path = path.substring(0, getIndex); final String getData = path.substring(getIndex); get = decoder.decodeParameters(getData); } else get = new HashMap<>(); // decode POST if(methodType == Request.RequestType.POST) post = decoder.decodeParameters(new String(buffer.bodyBuffer.toByteArray(), StandardCharsets.UTF_8)); else post = new HashMap<>(); //decode cookies if(parameters.containsKey("Cookie"))
cookies = decoder.decodeCookies(parameters.get("Cookie"));
else cookies = new HashMap<>(); return new Request(client.getRemoteAddress(), methodType, path, version, parameters, cookies, get, post); } return null; } public RequestDecoder getDecoder() { return decoder; } public RequestEncoder getEncoder() { return encoder; } }
src/main/java/com/konloch/http/request/RequestBuilder.java
Konloch-HTTPdLib-b7a1e2e
[ { "filename": "src/main/java/com/konloch/http/protocol/decoder/RequestDecoder.java", "retrieved_chunk": "\tpublic HashMap<String, String> decodeHeaders(byte[] buffer)\n\t{\n\t\tHashMap<String, String> parameters = new HashMap<>();\n\t\tStringBuilder key = new StringBuilder(\" :\");\n\t\tStringBuilder value = new StringBuilder();\n\t\tboolean keyFlag = false;\n\t\tint parameterCreationCount = 0;\n\t\tfor(byte b : buffer)\n\t\t{\n\t\t\tchar c = (char) b;", "score": 0.8524649143218994 }, { "filename": "src/main/java/com/konloch/http/protocol/decoder/RequestDecoder.java", "retrieved_chunk": "package com.konloch.http.protocol.decoder;\nimport com.konloch.http.HTTPdLib;\nimport java.util.HashMap;\n/**\n * @author Konloch\n * @since 3/1/2023\n */\npublic class RequestDecoder\n{\n\tprivate final HTTPdLib server;", "score": 0.8201876282691956 }, { "filename": "src/main/java/com/konloch/http/request/Request.java", "retrieved_chunk": "\t\tthis.path = path;\n\t\tthis.method = method;\n\t\tthis.version = version;\n\t\tthis.requestHeaders = requestHeaders;\n\t\tthis.get = get;\n\t\tthis.post = post;\n\t\tthis.responseHeaders = new HashMap<>();\n\t\tthis.requestCookies = cookies;\n\t\tthis.responseCookies = new HashMap<>();\n\t}", "score": 0.8196287751197815 }, { "filename": "src/main/java/com/konloch/http/request/Request.java", "retrieved_chunk": "\tprivate final HashMap<String, String> get;\n\tprivate final HashMap<String, String> post;\n\tprivate int returnCode = 200;\n\tprivate String contentType = \"text/plain; charset=utf-8\";\n\tprivate File[] uploads;\n\tpublic Request(String remoteIP, RequestType method, String path, String version,\n\t HashMap<String, String> requestHeaders, HashMap<String, String> cookies,\n\t HashMap<String, String> get, HashMap<String, String> post)\n\t{\n\t\tthis.remoteIP = remoteIP;", "score": 0.818648099899292 }, { "filename": "src/main/java/com/konloch/http/HTTPdLib.java", "retrieved_chunk": "\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tclient.setOutputBufferCache(requestBuilder.getEncoder().generateResponse(buffer.request, requestListener.request(buffer.request)));\n\t\t\t\t\t}\n\t\t\t\t\tclient.setState(100);\n\t\t\t\t\tbreak;\n\t\t\t\t//read post request\n\t\t\t\tcase 10:\n\t\t\t\t\t//get the bytes written\n\t\t\t\t\tbytes = client.getInputBuffer().toByteArray();", "score": 0.8153339624404907 } ]
java
cookies = decoder.decodeCookies(parameters.get("Cookie"));
package com.github.kingschan1204.easycrawl.core.variable; import com.github.kingschan1204.easycrawl.core.variable.impl.TimeStampExpression; import com.github.kingschan1204.easycrawl.helper.regex.RegexHelper; import com.github.kingschan1204.easycrawl.helper.collections.MapUtil; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author kingschan */ public class ScanVariable { private static final Map<String, Expression> elMap; static { elMap = new HashMap<>(); elMap.put("timestamp", new TimeStampExpression()); } /** * 扫描并解析变量 * * @param text 要扫描的文本 * @param map 传入的参数 * @return String */ public static String parser(String text, Map<String, Object> map) { if (null == text) { return null; }
List<String> exps = RegexHelper.find(text, "\\$\\{
(\\w|\\s|\\=)+\\}"); if (null != exps && exps.size() > 0) { for (String el : exps) { String[] els = el.replaceAll("[${}]", "").split("\\s+"); String tag = els[0]; Map<String, String> argsMap = new HashMap<>(10); if (els.length > 1) { for (int i = 1; i < els.length; i++) { String[] token = els[i].split("="); argsMap.put(token[0], token[1]); } } if (elMap.containsKey(tag)) { text = text.replace(el, elMap.get(tag).execute(argsMap)); } if (null != map && map.containsKey(tag)) { text = text.replace(el, String.valueOf(map.get(tag))); } } } return text; } public static void main(String[] args) { String text = "https://xueqiu.com/service/screener/screen?category=CN&exchange=sh_sz&areacode=&indcode=&order_by=symbol&order=desc&page=${page}&size=${pageSize}&only_count=0&current=&pct=&mc=&volume=&_=${timestamp}"; System.out.println(ScanVariable.parser(text, new MapUtil<String, Object>() .put("page", "1") .put("pageSize", "300") .getMap())); } }
src/main/java/com/github/kingschan1204/easycrawl/core/variable/ScanVariable.java
kingschan1204-easycrawl-a5aade8
[ { "filename": "src/main/java/com/github/kingschan1204/easycrawl/plugs/freemarker/FreemarkParser.java", "retrieved_chunk": " * @create 2020-02-13 15:30\n **/\n@Slf4j\npublic class FreemarkParser {\n public String parse(String text, Map<String, Object> valMap) throws Exception {\n return freemarkerParse(text, valMap);\n }\n /**\n * 模板解析\n *", "score": 0.8272386789321899 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/SzseTest.java", "retrieved_chunk": " return null;\n }\n }\n TreeMap<String, Boolean> parserData(String text) {\n JSONObject json = new JSONObject(true);\n json = JSON.parseObject(text);\n JSONArray jsonArray = json.getJSONArray(\"data\");\n TreeMap<String, Boolean> data = new TreeMap<>();\n for (int i = 0; i < jsonArray.size(); i++) {\n data.put(", "score": 0.8216021060943604 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/plugs/freemarker/FreemarkParser.java", "retrieved_chunk": " * @param text\n * @param valMap\n * @return\n * @throws Exception\n */\n public String freemarkerParse(String text, Map<String, Object> valMap) throws Exception {\n Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);\n //<@ts len=10>${v}</@ts>\n configuration.setSharedVariable(\"ts\", new UnixTimeStampTag());\n configuration.setTemplateLoader(new StringTemplateLoader(text));", "score": 0.8142368793487549 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/helper/regex/RegexHelper.java", "retrieved_chunk": " return list;\n } catch (Exception e) {\n e.printStackTrace();\n return list;\n }\n }\n public static String findFirst(String text, String regx) {\n Pattern pattern = Pattern.compile(regx);\n Matcher matcher = pattern.matcher(text);\n if (matcher.find()) {", "score": 0.7971829175949097 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/helper/regex/RegexHelper.java", "retrieved_chunk": " * @return 结果\n */\n public static List<String> find(String text, String regx) {\n List<String> list = new ArrayList<>();\n try {\n Pattern pattern = Pattern.compile(regx);\n Matcher matcher = pattern.matcher(text);\n while (matcher.find()) {\n list.add(matcher.group());\n }", "score": 0.7882398366928101 } ]
java
List<String> exps = RegexHelper.find(text, "\\$\\{
package com.github.kingschan1204.easycrawl.task; import com.github.kingschan1204.easycrawl.core.agent.WebAgent; import com.github.kingschan1204.easycrawl.helper.http.UrlHelper; import com.github.kingschan1204.easycrawl.helper.json.JsonHelper; import com.github.kingschan1204.easycrawl.helper.validation.Assert; import lombok.extern.slf4j.Slf4j; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; @Slf4j public class EasyCrawl<R> { private WebAgent webAgent; private Function<WebAgent, R> parserFunction; public EasyCrawl<R> webAgent(WebAgent webAgent) { this.webAgent = webAgent; return this; } // public static EasyCrawlNew of(WebAgentNew webAgent){ // return new EasyCrawlNew(webAgent); // } public EasyCrawl<R> analyze(Function<WebAgent, R> parserFunction) { this.parserFunction = parserFunction; return this; } public R execute() { return execute(null); } public R execute(Map<String, Object> map) { Assert.notNull(webAgent, "agent对象不能为空!"); Assert.notNull(parserFunction, "解析函数不能为空!"); R result; CompletableFuture<R> cf = CompletableFuture.supplyAsync(() -> { try { return webAgent.execute(map); } catch (Exception e) { e.printStackTrace(); return null; } }).thenApply(parserFunction); try { result = cf.get(); } catch (Exception e) { throw new RuntimeException(e); } return result; } /** * restApi json格式自动获取所有分页 * @param map 运行参数 * @param pageIndexKey 页码key * @param totalKey 总记录条数key * @param pageSize * @return */ public List<R> executePage(Map<String, Object> map, String pageIndexKey, String totalKey, Integer pageSize) { List<R> list = Collections.synchronizedList(new ArrayList<>()); WebAgent data = webAgent.execute(map); JsonHelper json = data.getJson(); int totalRows = json.get(totalKey, Integer.class); int totalPage = (totalRows + pageSize - 1) / pageSize; log.debug("共{}记录,每页展示{}条,共{}页", totalRows, pageSize, totalPage); List<CompletableFuture<R>> cfList = new ArrayList<>(); Consumer<R> consumer = (r) -> { if (r instanceof Collection) { list.addAll((Collection<? extends R>) r); } else { list.add(r); } }; cfList.add(CompletableFuture.supplyAsync(() -> data).thenApply(parserFunction)); cfList.get(0).thenAccept(consumer); for (int i = 2; i <= totalPage; i++) { String url = new UrlHelper(webAgent.getConfig().getUrl()).set(pageIndexKey, String.valueOf(i)).getUrl(); CompletableFuture<R> cf = CompletableFuture.supplyAsync(() -> { try { return
webAgent.url(url).execute(map);
} catch (Exception e) { e.printStackTrace(); return null; } }).thenApply(parserFunction); cf.thenAccept(consumer); cfList.add(cf); } CompletableFuture.allOf(cfList.toArray(new CompletableFuture[]{})).join(); return list; } }
src/main/java/com/github/kingschan1204/easycrawl/task/EasyCrawl.java
kingschan1204-easycrawl-a5aade8
[ { "filename": "src/test/java/com/github/kingschan1204/easycrawl/SzseTest.java", "retrieved_chunk": " cf.thenAccept(System.out::println);\n list.add(cf);\n }\n CompletableFuture.allOf(list.toArray(new CompletableFuture[]{})).join();\n }\n @DisplayName(\"月份交易日数据\")\n @Test\n public void proxyTest() throws Exception {\n String month = \"2023-03\";\n String url = new UrlHelper(apiUrl).set(\"month\", month).getUrl();", "score": 0.8508010506629944 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/SzseTest.java", "retrieved_chunk": " TreeMap<String, Boolean> result = new EasyCrawl< TreeMap<String, Boolean>>()\n .webAgent(WebAgent.defaultAgent().referer(url).useAgent(useAgent).url(apiUrl))\n .analyze(r -> parserData(r.getResult().getBody()))\n .execute();\n System.out.println(result);\n }\n}", "score": 0.8363128900527954 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/XueQiuTest.java", "retrieved_chunk": " String dataUrl = \"https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol=${code}&begin=${begin}&period=day&type=before&count=${count}&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance\";\n List<String> list = new ArrayList<>();\n boolean hasNext = true;\n while (hasNext) {\n JsonHelper jsonHelper = new EasyCrawl<JsonHelper>()\n .webAgent(WebAgent.defaultAgent().url(dataUrl).referer(referer).cookie(cookies))\n .analyze(WebAgent::getJson).execute(map);\n JSONArray columns = jsonHelper.get(\"data.column\", JSONArray.class);\n JSONArray rows = jsonHelper.get(\"data.item\", JSONArray.class);\n StringBuffer sqls = new StringBuffer();", "score": 0.8252984881401062 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/SzseTest.java", "retrieved_chunk": " int end = 2023;\n List<String> month = new ArrayList<>();\n for (int i = year; i <= end; i++) {\n for (int j = 1; j < 13; j++) {\n month.add(String.format(\"%s-%02d\", i, j));\n }\n }\n List<CompletableFuture> list = new ArrayList<>();\n for (String s : month) {\n CompletableFuture cf = CompletableFuture.supplyAsync(() -> getDay(s));", "score": 0.8215625286102295 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/ResponseTypeTest.java", "retrieved_chunk": " public void test() {\n Map<String, String> map = new MapUtil<String, String>()\n .put(\"js\", \"https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js\")\n .put(\"css\", \"https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap-grid.min.css\")\n .put(\"html\", \"https://www.bootcdn.cn/\")\n .put(\"png\", \"https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png\")\n .put(\"pdf\", \"http://notice.10jqka.com.cn/api/pdf/6cb73f7b9c9925c3.pdf\")\n .getMap();\n for (String type : map.keySet()) {\n new EasyCrawl<String>().webAgent(WebAgent.defaultAgent().url(map.get(type))).analyze(WebAgent::getText).execute();", "score": 0.8190565705299377 } ]
java
webAgent.url(url).execute(map);
package com.github.kingschan1204.easycrawl.task; import com.github.kingschan1204.easycrawl.core.agent.WebAgent; import com.github.kingschan1204.easycrawl.helper.http.UrlHelper; import com.github.kingschan1204.easycrawl.helper.json.JsonHelper; import com.github.kingschan1204.easycrawl.helper.validation.Assert; import lombok.extern.slf4j.Slf4j; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; @Slf4j public class EasyCrawl<R> { private WebAgent webAgent; private Function<WebAgent, R> parserFunction; public EasyCrawl<R> webAgent(WebAgent webAgent) { this.webAgent = webAgent; return this; } // public static EasyCrawlNew of(WebAgentNew webAgent){ // return new EasyCrawlNew(webAgent); // } public EasyCrawl<R> analyze(Function<WebAgent, R> parserFunction) { this.parserFunction = parserFunction; return this; } public R execute() { return execute(null); } public R execute(Map<String, Object> map) { Assert.notNull(webAgent, "agent对象不能为空!"); Assert.notNull(parserFunction, "解析函数不能为空!"); R result; CompletableFuture<R> cf = CompletableFuture.supplyAsync(() -> { try { return webAgent.execute(map); } catch (Exception e) { e.printStackTrace(); return null; } }).thenApply(parserFunction); try { result = cf.get(); } catch (Exception e) { throw new RuntimeException(e); } return result; } /** * restApi json格式自动获取所有分页 * @param map 运行参数 * @param pageIndexKey 页码key * @param totalKey 总记录条数key * @param pageSize * @return */ public List<R> executePage(Map<String, Object> map, String pageIndexKey, String totalKey, Integer pageSize) { List<R> list = Collections.synchronizedList(new ArrayList<>()); WebAgent
data = webAgent.execute(map);
JsonHelper json = data.getJson(); int totalRows = json.get(totalKey, Integer.class); int totalPage = (totalRows + pageSize - 1) / pageSize; log.debug("共{}记录,每页展示{}条,共{}页", totalRows, pageSize, totalPage); List<CompletableFuture<R>> cfList = new ArrayList<>(); Consumer<R> consumer = (r) -> { if (r instanceof Collection) { list.addAll((Collection<? extends R>) r); } else { list.add(r); } }; cfList.add(CompletableFuture.supplyAsync(() -> data).thenApply(parserFunction)); cfList.get(0).thenAccept(consumer); for (int i = 2; i <= totalPage; i++) { String url = new UrlHelper(webAgent.getConfig().getUrl()).set(pageIndexKey, String.valueOf(i)).getUrl(); CompletableFuture<R> cf = CompletableFuture.supplyAsync(() -> { try { return webAgent.url(url).execute(map); } catch (Exception e) { e.printStackTrace(); return null; } }).thenApply(parserFunction); cf.thenAccept(consumer); cfList.add(cf); } CompletableFuture.allOf(cfList.toArray(new CompletableFuture[]{})).join(); return list; } }
src/main/java/com/github/kingschan1204/easycrawl/task/EasyCrawl.java
kingschan1204-easycrawl-a5aade8
[ { "filename": "src/test/java/com/github/kingschan1204/easycrawl/XueQiuTest.java", "retrieved_chunk": " .analyze(WebAgent::getText)\n .execute(map);\n System.out.println(data);\n }\n @DisplayName(\"股东人数\")\n @Test\n public void gdrs() {\n String page = \"https://xueqiu.com/snowman/S/${code}/detail#/GDRS\";\n Map<String, Object> map = new MapUtil<String, Object>().put(\"code\", \"SH600887\").getMap();\n Map<String, String> cookies = getXQCookies();", "score": 0.8222663402557373 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/XueQiuTest.java", "retrieved_chunk": " .analyze(WebAgent::getText)\n .execute(new MapUtil<String, Object>().put(\"code\", \"SH600887\").getMap());\n System.out.println(data);\n }\n @DisplayName(\"top10 股东\")\n @Test\n public void top10() {\n Map<String, Object> map = new MapUtil<String, Object>().put(\"code\", \"SH600887\").getMap();\n Map<String, String> cookies = getXQCookies();\n //获取最新的十大股东 及 所有时间列表", "score": 0.8136190176010132 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/SzseTest.java", "retrieved_chunk": " TreeMap<String, Boolean> result = new EasyCrawl< TreeMap<String, Boolean>>()\n .webAgent(WebAgent.defaultAgent().referer(url).useAgent(useAgent).url(apiUrl))\n .analyze(r -> parserData(r.getResult().getBody()))\n .execute();\n System.out.println(result);\n }\n}", "score": 0.8012546300888062 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/XueQiuTest.java", "retrieved_chunk": " String dataUrl = \"https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol=${code}&begin=${begin}&period=day&type=before&count=${count}&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance\";\n List<String> list = new ArrayList<>();\n boolean hasNext = true;\n while (hasNext) {\n JsonHelper jsonHelper = new EasyCrawl<JsonHelper>()\n .webAgent(WebAgent.defaultAgent().url(dataUrl).referer(referer).cookie(cookies))\n .analyze(WebAgent::getJson).execute(map);\n JSONArray columns = jsonHelper.get(\"data.column\", JSONArray.class);\n JSONArray rows = jsonHelper.get(\"data.item\", JSONArray.class);\n StringBuffer sqls = new StringBuffer();", "score": 0.8006668090820312 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/XueQiuTest.java", "retrieved_chunk": " map.put(\"begin\", rows.getJSONArray(0).getLong(0));\n if (rows.size() < Math.abs(pageSize)) {\n System.out.println(\"没有数据了!\");\n hasNext = false;\n break;\n }\n }\n list.forEach(System.err::println);\n }\n @DisplayName(\"个股详情\")", "score": 0.7972796559333801 } ]
java
data = webAgent.execute(map);
package com.github.kingschan1204.easycrawl.helper.http; import com.github.kingschan1204.easycrawl.core.agent.AgentResult; import lombok.extern.slf4j.Slf4j; /** * @author kingschan */ @Slf4j public class ResponseAssertHelper { private AgentResult result; public ResponseAssertHelper(AgentResult agentResult) { this.result = agentResult; } public static ResponseAssertHelper of(AgentResult agentResult) { return new ResponseAssertHelper(agentResult); } public void infer() { statusCode(); contentType(); } public void statusCode() { log.debug("http状态:{}", result.getStatusCode()); if (
!result.getStatusCode().equals(200)) {
if (result.getStatusCode() >= 500) { log.warn("服务器错误!"); } else if (result.getStatusCode() == 404) { log.warn("地址不存在!"); } else if (result.getStatusCode() == 401) { log.warn("401表示未经授权!或者证明登录信息的cookie,token已过期!"); } else if (result.getStatusCode() == 400) { log.warn("传参有问题!一般参数传少了或者不正确!"); }else{ log.warn("未支持的状态码: {}",result.getStatusCode()); } } } public void contentType() { String type = result.getContentType(); String content = "不知道是个啥!"; if (type.matches("text/html.*")) { content = "html"; } else if (type.matches("application/json.*")) { content = "json"; } else if (type.matches("application/vnd.ms-excel.*")) { content = "excel"; } else if (type.matches("text/css.*")) { content = "css"; } else if (type.matches("application/javascript.*")) { content = "js"; } else if (type.matches("image.*")) { content = "图片"; } else if (type.matches("application/pdf.*")) { content = "pdf"; } log.debug("推测 http 响应类型:{}", content); } }
src/main/java/com/github/kingschan1204/easycrawl/helper/http/ResponseAssertHelper.java
kingschan1204-easycrawl-a5aade8
[ { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/agent/interceptor/impl/StatusPrintInterceptorImpl.java", "retrieved_chunk": " ResponseAssertHelper.of(result).infer();\n return result;\n }\n}", "score": 0.8423587679862976 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/agent/GenericHttp1Agent.java", "retrieved_chunk": " ResponseHeadHelper headHelper = ResponseHeadHelper.of(result.getHeaders());\n Assert.isTrue(headHelper.fileContent(), \"非文件流请求,无法输出文件!\");\n String defaultFileName = null;\n File file = null;\n if (result.getStatusCode() != 200) {\n log.error(\"文件下载失败:{}\", this.config.getUrl());\n throw new RuntimeException(String.format(\"文件下载失败:%s 返回码:%s\", this.config.getUrl(), result.getStatusCode()));\n }\n try {\n defaultFileName = headHelper.getFileName();", "score": 0.8318387269973755 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/agent/GenericHttp1Agent.java", "retrieved_chunk": " this.config.getTimeOut(), this.config.getUseAgent(), referer, this.config.getHead(),\n this.config.getCookie(), this.config.getProxy(),\n true, true, this.config.getBody());\n return this;\n }\n @Override\n public AgentResult getResult() {\n return this.result;\n }\n @Override", "score": 0.8272834420204163 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/agent/interceptor/impl/StatusPrintInterceptorImpl.java", "retrieved_chunk": "@Slf4j\npublic class StatusPrintInterceptorImpl implements AfterInterceptor {\n @Override\n public AgentResult interceptor(Map<String, Object> data, WebAgent webAgent) {\n AgentResult result = webAgent.getResult();\n log.debug(\"ContentType : {}\", result.getContentType());\n log.debug(\"编码 {} \",result.getCharset());\n log.debug(\"Headers : {}\", result.getHeaders());\n log.debug(\"Cookies : {}\", result.getCookies());\n log.debug(\"耗时 {} 毫秒\",result.getTimeMillis());", "score": 0.8271029591560364 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/agent/GenericHttp1AgentProxy.java", "retrieved_chunk": " }\n @Override\n public AgentResult getResult() {\n //优先拿自身对象的agentResult\n return null == result ? this.webAgent.getResult() : result;\n }\n @Override\n public JsonHelper getJson() {\n return this.webAgent.getJson();\n }", "score": 0.8195058703422546 } ]
java
!result.getStatusCode().equals(200)) {
package com.github.kingschan1204.easycrawl.helper.datetime; import com.github.kingschan1204.easycrawl.helper.validation.Assert; import lombok.extern.slf4j.Slf4j; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; /** * java8日期工具类封装 * * @author kings.chan * @date 2021-9-10 */ @Slf4j public class DateHelper { private LocalDateTime localDateTime; public DateHelper(LocalDateTime localDateTime) { this.localDateTime = localDateTime; } /** * 初始对象 * * @return DateHelperNew */ public static DateHelper now() { return new DateHelper(LocalDateTime.now()); } /** * 初始对象 * * @param timeStamp 时间戳 * @return DateHelperNew */ public static DateHelper of(Long timeStamp) {
Assert.notNull(timeStamp, "时间戳不能为空!");
if (String.valueOf(timeStamp).length() > 10) { timeStamp = timeStamp / 1000; } LocalDateTime time = LocalDateTime.ofEpochSecond(timeStamp, 0, ZoneOffset.ofHours(8)); return new DateHelper(time); } /** * 初始对象 * * @param text 格式:2023-04-01,2023-4-1,2023-04-01 00:00:00,2022-2-1T12:55:00,20230401 * @return DateHelperNew */ public static DateHelper of(String text) { String date = text.contains(".") ? text.replaceAll("\\..*", "") : text; if (date.contains("T")) { date = date.replace("T", " "); } if (date.matches("\\d{4}-\\d{1,2}-\\d{1,2}")) { String[] array = date.split("-"); date = String.format("%s-%02d-%02d 00:00:00", array[0], Integer.valueOf(array[1]), Integer.valueOf(array[2])); } else if (date.matches("\\d{4}-\\d{1,2}-\\d{1,2} \\d{2}:\\d{2}:\\d{2}")) { String[] array = date.replaceAll("\\s.*", "").split("-"); date = String.format("%s-%02d-%02d %s", array[0], Integer.valueOf(array[1]), Integer.valueOf(array[2]), date.split("\\s")[1]); } else if (date.matches("\\d{8}")) { date = String.format("%s-%s-%s 00:00:00", date.substring(0, 4), date.substring(4, 6), date.substring(6)); } else { throw new RuntimeException("不支持的格式:" + text); } LocalDateTime localDate = LocalDateTime.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); return new DateHelper(localDate); } public DateHelper plusYears(long years) { this.localDateTime = localDateTime.plusYears(years); return this; } public DateHelper plusMonths(long months) { this.localDateTime = localDateTime.plusMonths(months); return this; } /** * 日期天数相加 * * @param days 要加的天数 * @return DateHelperNew */ public DateHelper plusDays(long days) { this.localDateTime = localDateTime.plusDays(days); return this; } public DateHelper minusYears(long years) { this.localDateTime = localDateTime.minusYears(years); return this; } public DateHelper minusMonths(long months) { this.localDateTime = localDateTime.minusMonths(months); return this; } /** * 日期天数相减 * * @param days 要减的天数 * @return DateHelperNew */ public DateHelper minusDays(long days) { this.localDateTime = localDateTime.minusDays(days); return this; } /** * 得到当前时间戳 * * @return 10位的时间戳 */ public Long timeStamp() { return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() / 1000; } /** * 返回日期的年 * * @return yyyy年 */ public String year() { return format("yyyy"); } /** * 返回日期的月 * * @return MM月 */ public String month() { return format("MM"); } /** * 返回日期的日 * * @return dd日 */ public String day() { return format("dd"); } /** * 返回日期 * * @return yyyy-MM-dd */ public String date() { return format("yyyy-MM-dd"); } /** * 返回日期 * * @return yyyy-MM-dd HH:mm:ss */ public String dateTime() { return format("yyyy-MM-dd HH:mm:ss"); } /** * 返回时间 * * @return HH:mm:ss */ public String time() { return format("HH:mm:ss"); } /** * 按传入的格式 格式化日期 * * @param format * @return */ public String format(String format) { return DateTimeFormatter.ofPattern(format).format(localDateTime); } public static void main(String[] args) { String[] dates = {"2022-2-1", "2022-12-1", "2022-2-12", "2022-2-1 12:55:00", "2022-2-1T12:55:00", "2022-02-01 00:00:00", "20220201"}; for (String date : dates) { System.out.println(DateHelper.of(date).date()); } } }
src/main/java/com/github/kingschan1204/easycrawl/helper/datetime/DateHelper.java
kingschan1204-easycrawl-a5aade8
[ { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/variable/impl/TimeStampExpression.java", "retrieved_chunk": "package com.github.kingschan1204.easycrawl.core.variable.impl;\nimport com.github.kingschan1204.easycrawl.core.variable.Expression;\nimport com.github.kingschan1204.easycrawl.helper.validation.Assert;\nimport java.util.Map;\n/**\n * 时间戳定义\n * ${timestamp len=10}\n * @author kingschan\n */\npublic class TimeStampExpression implements Expression {", "score": 0.7923551797866821 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/variable/impl/TimeStampExpression.java", "retrieved_chunk": " @Override\n public String execute(Map<String, String> args) {\n //默认输出13位\n String type = args.containsKey(\"len\") ? String.valueOf(args.get(\"len\")) : \"13\";\n Assert.isTrue(type.matches(\"10|13\"), \"时间戳只支持10位或者13位!\");\n long timeStamp = \"13\".equals(type) ? System.currentTimeMillis() : System.currentTimeMillis() / 1000;\n return String.valueOf(timeStamp);\n }\n}", "score": 0.7801315188407898 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/variable/ScanVariable.java", "retrieved_chunk": "package com.github.kingschan1204.easycrawl.core.variable;\nimport com.github.kingschan1204.easycrawl.core.variable.impl.TimeStampExpression;\nimport com.github.kingschan1204.easycrawl.helper.regex.RegexHelper;\nimport com.github.kingschan1204.easycrawl.helper.collections.MapUtil;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n/**\n * @author kingschan\n */", "score": 0.7672234773635864 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/plugs/freemarker/tag/UnixTimeStampTag.java", "retrieved_chunk": "package com.github.kingschan1204.easycrawl.plugs.freemarker.tag;\nimport com.alibaba.fastjson.JSON;\nimport com.github.kingschan1204.easycrawl.helper.validation.Assert;\nimport freemarker.core.Environment;\nimport freemarker.template.*;\nimport lombok.extern.slf4j.Slf4j;\nimport java.io.IOException;\nimport java.util.Map;\n@Slf4j\npublic class UnixTimeStampTag implements TemplateDirectiveModel {", "score": 0.7588014006614685 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/helper/math/MathHelper.java", "retrieved_chunk": " private static final String pattern = \"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?$\";\n public MathHelper(BigDecimal value) {\n this.value = value;\n }\n public static MathHelper of(String text) {\n return new MathHelper(toBigDecimal(text));\n }\n static BigDecimal toBigDecimal(String text) {\n assert null != text;\n assert text.matches(pattern);", "score": 0.7516204118728638 } ]
java
Assert.notNull(timeStamp, "时间戳不能为空!");
package com.github.kingschan1204.easycrawl.core.variable; import com.github.kingschan1204.easycrawl.core.variable.impl.TimeStampExpression; import com.github.kingschan1204.easycrawl.helper.regex.RegexHelper; import com.github.kingschan1204.easycrawl.helper.collections.MapUtil; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author kingschan */ public class ScanVariable { private static final Map<String, Expression> elMap; static { elMap = new HashMap<>(); elMap.put("timestamp", new TimeStampExpression()); } /** * 扫描并解析变量 * * @param text 要扫描的文本 * @param map 传入的参数 * @return String */ public static String parser(String text, Map<String, Object> map) { if (null == text) { return null; } List<String> exps = RegexHelper.find(text, "\\$\\{(\\w|\\s|\\=)+\\}"); if (null != exps && exps.size() > 0) { for (String el : exps) { String[] els = el.replaceAll("[${}]", "").split("\\s+"); String tag = els[0]; Map<String, String> argsMap = new HashMap<>(10); if (els.length > 1) { for (int i = 1; i < els.length; i++) { String[] token = els[i].split("="); argsMap.put(token[0], token[1]); } } if (elMap.containsKey(tag)) {
text = text.replace(el, elMap.get(tag).execute(argsMap));
} if (null != map && map.containsKey(tag)) { text = text.replace(el, String.valueOf(map.get(tag))); } } } return text; } public static void main(String[] args) { String text = "https://xueqiu.com/service/screener/screen?category=CN&exchange=sh_sz&areacode=&indcode=&order_by=symbol&order=desc&page=${page}&size=${pageSize}&only_count=0&current=&pct=&mc=&volume=&_=${timestamp}"; System.out.println(ScanVariable.parser(text, new MapUtil<String, Object>() .put("page", "1") .put("pageSize", "300") .getMap())); } }
src/main/java/com/github/kingschan1204/easycrawl/core/variable/ScanVariable.java
kingschan1204-easycrawl-a5aade8
[ { "filename": "src/main/java/com/github/kingschan1204/easycrawl/plugs/freemarker/FreemarkParser.java", "retrieved_chunk": " * @param text\n * @param valMap\n * @return\n * @throws Exception\n */\n public String freemarkerParse(String text, Map<String, Object> valMap) throws Exception {\n Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);\n //<@ts len=10>${v}</@ts>\n configuration.setSharedVariable(\"ts\", new UnixTimeStampTag());\n configuration.setTemplateLoader(new StringTemplateLoader(text));", "score": 0.776363730430603 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/plugs/freemarker/FreemarkParser.java", "retrieved_chunk": " }\n return writer.toString();\n }\n public static void main(String[] args) throws Exception {\n String text = \"<@ts>${v}</@ts>\";\n String result = new FreemarkParser().parse(text, null);\n System.out.println(result);\n }\n}", "score": 0.7761070728302002 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/variable/Expression.java", "retrieved_chunk": "package com.github.kingschan1204.easycrawl.core.variable;\nimport java.util.Map;\npublic interface Expression {\n /**\n *\n * @param args 参数\n * @return 解析表达式后的结果\n */\n String execute(Map<String, String> args);\n}", "score": 0.7753893136978149 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/plugs/freemarker/FreemarkParser.java", "retrieved_chunk": " configuration.setDefaultEncoding(\"UTF-8\");\n configuration.setNumberFormat(\"#.####\");\n Template template = configuration.getTemplate(\"\");\n StringWriter writer = new StringWriter();\n try {\n template.process(valMap, writer);\n } catch (Exception e) {\n System.out.println(JSON.toJSONString(valMap));\n System.out.println(text);\n throw e;", "score": 0.7727874517440796 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/plugs/freemarker/FreemarkParser.java", "retrieved_chunk": " * @create 2020-02-13 15:30\n **/\n@Slf4j\npublic class FreemarkParser {\n public String parse(String text, Map<String, Object> valMap) throws Exception {\n return freemarkerParse(text, valMap);\n }\n /**\n * 模板解析\n *", "score": 0.7713481783866882 } ]
java
text = text.replace(el, elMap.get(tag).execute(argsMap));
package dev.klepto.unreflect.reflection; import dev.klepto.unreflect.bytecode.asm.AccessorGenerator; import dev.klepto.unreflect.property.Reflectable; import dev.klepto.unreflect.bytecode.BytecodeContructorAccess; import dev.klepto.unreflect.UnreflectType; import dev.klepto.unreflect.ConstructorAccess; import dev.klepto.unreflect.ParameterAccess; import dev.klepto.unreflect.util.Parameters; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.With; import lombok.val; import one.util.streamex.StreamEx; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; /** * Reflection-based implementation of {@link ConstructorAccess}. * * @author <a href="http://github.com/klepto">Augustinas R.</a> */ @With @RequiredArgsConstructor public class ReflectionConstructorAccess<T> implements ConstructorAccess<T> { private final Reflectable parent; private final Constructor<T> source; @Override public ConstructorAccess<T> unreflect() { val accessor = AccessorGenerator.getInstance().generateInvokableAccessor(source); return new BytecodeContructorAccess<>(this, accessor); } @Override public ConstructorAccess<T> reflect() { return this; } @Override public ConstructorAccess<T> bind(Object object) { return this; } @Override public int modifiers() { return source.getModifiers(); } @Override public StreamEx<ParameterAccess> parameters() { return StreamEx.of(source.getParameters()) .map(parameter -> new ReflectionParameterAccess(this, parameter)); } @Override public Constructor<T> source() { return source; } @Override public T create(Object... args) { return invoke(args); } @Override @SneakyThrows public T invoke(Object... args) { return source.newInstance(args); } @Override public Reflectable parent() { return parent; } @Override public StreamEx<Annotation> annotations() { return StreamEx.of(source.getDeclaredAnnotations()); } @Override public UnreflectType type() {
return parent.type();
} @Override public String toString() { return type().toClass().getSimpleName() + Parameters.toString(parameters().toList()); } }
src/main/java/dev/klepto/unreflect/reflection/ReflectionConstructorAccess.java
klepto-unreflect-a818c39
[ { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionClassAccess.java", "retrieved_chunk": " @Override\n public Reflectable parent() {\n return new ReflectionClassAccess<>(source.getSuperclass(), object);\n }\n @Override\n public StreamEx<Annotation> annotations() {\n return StreamEx.of(source.getDeclaredAnnotations());\n }\n @Override\n public UnreflectType type() {", "score": 0.9482665657997131 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionParameterAccess.java", "retrieved_chunk": " return (ConstructorAccess<?>) parent();\n }\n @Override\n public MethodAccess method() {\n return (MethodAccess) parent();\n }\n @Override\n public StreamEx<Annotation> annotations() {\n return StreamEx.of(source.getDeclaredAnnotations());\n }", "score": 0.913804292678833 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionMethodAccess.java", "retrieved_chunk": " return StreamEx.of(source.getAnnotations());\n }\n @Override\n public UnreflectType type() {\n return UnreflectType.of(source.getGenericReturnType());\n }\n @Override\n public String name() {\n return source.getName();\n }", "score": 0.9057528376579285 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionFieldAccess.java", "retrieved_chunk": " public UnreflectType type() {\n return UnreflectType.of(source.getGenericType());\n }\n @Override\n public String name() {\n return source.getName();\n }\n @Override\n public Field source() {\n return source;", "score": 0.8814493417739868 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionMethodAccess.java", "retrieved_chunk": " @SneakyThrows\n public <T> T invoke(Object... args) {\n return (T) source.invoke(object, args);\n }\n @Override\n public Reflectable parent() {\n return parent;\n }\n @Override\n public StreamEx<Annotation> annotations() {", "score": 0.8799068927764893 } ]
java
return parent.type();
package dev.klepto.unreflect.reflection; import dev.klepto.unreflect.bytecode.asm.AccessorGenerator; import dev.klepto.unreflect.property.Reflectable; import dev.klepto.unreflect.bytecode.BytecodeMethodAccess; import dev.klepto.unreflect.UnreflectType; import dev.klepto.unreflect.MethodAccess; import dev.klepto.unreflect.ParameterAccess; import dev.klepto.unreflect.util.Parameters; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.With; import lombok.val; import one.util.streamex.StreamEx; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * Reflection-based implementation of {@link MethodAccess}. * * @author <a href="http://github.com/klepto">Augustinas R.</a> */ @With @RequiredArgsConstructor public class ReflectionMethodAccess implements MethodAccess { private final Reflectable parent; private final Method source; private final Object object; @Override @SneakyThrows public MethodAccess unreflect() { val accessor = AccessorGenerator.getInstance().generateInvokableAccessor(source); return new BytecodeMethodAccess(this, accessor); } @Override public MethodAccess reflect() { return this; } @Override public MethodAccess bind(Object object) { return withObject(object); } @Override public int modifiers() { return source.getModifiers(); } @Override public StreamEx<ParameterAccess> parameters() { return StreamEx.of(source.getParameters()) .map(parameter -> new ReflectionParameterAccess(this, parameter)); } @Override @SneakyThrows public <T> T invoke(Object... args) { return (T) source.invoke(object, args); } @Override public Reflectable parent() { return parent; } @Override public StreamEx<Annotation> annotations() { return StreamEx.of(source.getAnnotations()); } @Override public UnreflectType type() { return
UnreflectType.of(source.getGenericReturnType());
} @Override public String name() { return source.getName(); } @Override public Method source() { return source; } public Object object() { return object; } @Override public String toString() { val signature = type().toClass().getSimpleName() + " " + name() + Parameters.toString(parameters().toList()); return isStatic() ? "static " + signature : signature; } }
src/main/java/dev/klepto/unreflect/reflection/ReflectionMethodAccess.java
klepto-unreflect-a818c39
[ { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionConstructorAccess.java", "retrieved_chunk": " @Override\n public Reflectable parent() {\n return parent;\n }\n @Override\n public StreamEx<Annotation> annotations() {\n return StreamEx.of(source.getDeclaredAnnotations());\n }\n @Override\n public UnreflectType type() {", "score": 0.9720636010169983 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionClassAccess.java", "retrieved_chunk": " @Override\n public Reflectable parent() {\n return new ReflectionClassAccess<>(source.getSuperclass(), object);\n }\n @Override\n public StreamEx<Annotation> annotations() {\n return StreamEx.of(source.getDeclaredAnnotations());\n }\n @Override\n public UnreflectType type() {", "score": 0.9350036978721619 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionParameterAccess.java", "retrieved_chunk": " return (ConstructorAccess<?>) parent();\n }\n @Override\n public MethodAccess method() {\n return (MethodAccess) parent();\n }\n @Override\n public StreamEx<Annotation> annotations() {\n return StreamEx.of(source.getDeclaredAnnotations());\n }", "score": 0.9186204671859741 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionFieldAccess.java", "retrieved_chunk": " public UnreflectType type() {\n return UnreflectType.of(source.getGenericType());\n }\n @Override\n public String name() {\n return source.getName();\n }\n @Override\n public Field source() {\n return source;", "score": 0.8868051171302795 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionConstructorAccess.java", "retrieved_chunk": " return source.getModifiers();\n }\n @Override\n public StreamEx<ParameterAccess> parameters() {\n return StreamEx.of(source.getParameters())\n .map(parameter -> new ReflectionParameterAccess(this, parameter));\n }\n @Override\n public Constructor<T> source() {\n return source;", "score": 0.8815524578094482 } ]
java
UnreflectType.of(source.getGenericReturnType());
package com.github.kingschan1204.easycrawl.helper.http; import com.github.kingschan1204.easycrawl.core.agent.AgentResult; import lombok.extern.slf4j.Slf4j; /** * @author kingschan */ @Slf4j public class ResponseAssertHelper { private AgentResult result; public ResponseAssertHelper(AgentResult agentResult) { this.result = agentResult; } public static ResponseAssertHelper of(AgentResult agentResult) { return new ResponseAssertHelper(agentResult); } public void infer() { statusCode(); contentType(); } public void statusCode() { log.debug("http状态:{}", result.getStatusCode()); if (!result.getStatusCode().equals(200)) { if (result.getStatusCode() >= 500) { log.warn("服务器错误!"); } else if (result.getStatusCode() == 404) { log.warn("地址不存在!"); } else if (result.getStatusCode() == 401) { log.warn("401表示未经授权!或者证明登录信息的cookie,token已过期!"); } else
if (result.getStatusCode() == 400) {
log.warn("传参有问题!一般参数传少了或者不正确!"); }else{ log.warn("未支持的状态码: {}",result.getStatusCode()); } } } public void contentType() { String type = result.getContentType(); String content = "不知道是个啥!"; if (type.matches("text/html.*")) { content = "html"; } else if (type.matches("application/json.*")) { content = "json"; } else if (type.matches("application/vnd.ms-excel.*")) { content = "excel"; } else if (type.matches("text/css.*")) { content = "css"; } else if (type.matches("application/javascript.*")) { content = "js"; } else if (type.matches("image.*")) { content = "图片"; } else if (type.matches("application/pdf.*")) { content = "pdf"; } log.debug("推测 http 响应类型:{}", content); } }
src/main/java/com/github/kingschan1204/easycrawl/helper/http/ResponseAssertHelper.java
kingschan1204-easycrawl-a5aade8
[ { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/agent/interceptor/impl/TranscodingInterceptorImpl.java", "retrieved_chunk": " log.warn(\"未获取到编码信息,有可能中文乱码!尝试自动提取编码!\");\n String text = RegexHelper.findFirst(result.getBody(), RegexHelper.REGEX_HTML_CHARSET);\n charset = RegexHelper.findFirst(text, \"(?i)charSet(\\\\s+)?=.*\\\"\").replaceAll(\"(?i)charSet|=|\\\"|\\\\s\", \"\");\n if (!charset.isEmpty()) {\n log.debug(\"编码提取成功,将自动转码:{}\", charset);\n result.setBody(transcoding(result.getBodyAsByes(), charset));\n } else {\n log.warn(\"自动提取编码失败!\");\n }\n }", "score": 0.8292670249938965 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/agent/GenericHttp1Agent.java", "retrieved_chunk": " ResponseHeadHelper headHelper = ResponseHeadHelper.of(result.getHeaders());\n Assert.isTrue(headHelper.fileContent(), \"非文件流请求,无法输出文件!\");\n String defaultFileName = null;\n File file = null;\n if (result.getStatusCode() != 200) {\n log.error(\"文件下载失败:{}\", this.config.getUrl());\n throw new RuntimeException(String.format(\"文件下载失败:%s 返回码:%s\", this.config.getUrl(), result.getStatusCode()));\n }\n try {\n defaultFileName = headHelper.getFileName();", "score": 0.8264539837837219 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/agent/GenericHttp1Agent.java", "retrieved_chunk": " out.write(result.getBodyAsByes());\n } catch (Exception ex) {\n log.error(\"文件下载失败:{} {}\", this.config.getUrl(), ex);\n ex.printStackTrace();\n } finally {\n assert out != null;\n out.close();\n }\n } catch (Exception e) {\n e.printStackTrace();", "score": 0.8246031999588013 }, { "filename": "src/main/java/com/github/kingschan1204/easycrawl/core/agent/interceptor/impl/StatusPrintInterceptorImpl.java", "retrieved_chunk": "@Slf4j\npublic class StatusPrintInterceptorImpl implements AfterInterceptor {\n @Override\n public AgentResult interceptor(Map<String, Object> data, WebAgent webAgent) {\n AgentResult result = webAgent.getResult();\n log.debug(\"ContentType : {}\", result.getContentType());\n log.debug(\"编码 {} \",result.getCharset());\n log.debug(\"Headers : {}\", result.getHeaders());\n log.debug(\"Cookies : {}\", result.getCookies());\n log.debug(\"耗时 {} 毫秒\",result.getTimeMillis());", "score": 0.811403751373291 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/ProxyTest.java", "retrieved_chunk": " .webAgent(WebAgent.defaultAgent().referer(apiUrl).useAgent(useAgent).url(apiUrl).proxy(proxy))\n .analyze(r -> r.getResult().getBody()).execute();\n System.out.println(result);\n }\n}", "score": 0.8034199476242065 } ]
java
if (result.getStatusCode() == 400) {
package dev.klepto.unreflect.bytecode; import dev.klepto.unreflect.ConstructorAccess; import dev.klepto.unreflect.bytecode.asm.InvokableAccessor; import dev.klepto.unreflect.reflection.ReflectionConstructorAccess; import lombok.RequiredArgsConstructor; import lombok.experimental.Delegate; /** * Bytecode access to a constructor of a class. Delegates all functions to {@link ReflectionConstructorAccess} except * the {@link ConstructorAccess#invoke(Object...)} function for which it uses direct accessor. * * @author <a href="http://github.com/klepto">Augustinas R.</a> */ @RequiredArgsConstructor public class BytecodeContructorAccess<T> implements ConstructorAccess<T> { @Delegate(excludes = Overrides.class) private final ReflectionConstructorAccess<T> delegate; private final InvokableAccessor accessor; @Override public ConstructorAccess<T> unreflect() { return this; } @Override public ConstructorAccess<T> reflect() { return delegate; } @Override public T invoke(Object... args) { return
(T) accessor.invoke(null, args);
} @Override public String toString() { return delegate.toString(); } private interface Overrides { void unreflect(); void reflect(); void invoke(Object... args); } }
src/main/java/dev/klepto/unreflect/bytecode/BytecodeContructorAccess.java
klepto-unreflect-a818c39
[ { "filename": "src/main/java/dev/klepto/unreflect/bytecode/BytecodeMethodAccess.java", "retrieved_chunk": " @Override\n public <T> T invoke(Object... args) {\n return (T) accessor.invoke(object(), args);\n }\n @Override\n public String toString() {\n return delegate.toString();\n }\n private interface Overrides {\n void unreflect();", "score": 0.9203998446464539 }, { "filename": "src/main/java/dev/klepto/unreflect/bytecode/BytecodeMethodAccess.java", "retrieved_chunk": " return this;\n }\n @Override\n public MethodAccess reflect() {\n return delegate;\n }\n @Override\n public MethodAccess bind(Object object) {\n return new BytecodeMethodAccess((ReflectionMethodAccess) delegate.bind(object), accessor);\n }", "score": 0.8769828677177429 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionConstructorAccess.java", "retrieved_chunk": " @Override\n public ConstructorAccess<T> reflect() {\n return this;\n }\n @Override\n public ConstructorAccess<T> bind(Object object) {\n return this;\n }\n @Override\n public int modifiers() {", "score": 0.8707537651062012 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionConstructorAccess.java", "retrieved_chunk": "@With\n@RequiredArgsConstructor\npublic class ReflectionConstructorAccess<T> implements ConstructorAccess<T> {\n private final Reflectable parent;\n private final Constructor<T> source;\n @Override\n public ConstructorAccess<T> unreflect() {\n val accessor = AccessorGenerator.getInstance().generateInvokableAccessor(source);\n return new BytecodeContructorAccess<>(this, accessor);\n }", "score": 0.8597992062568665 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionMethodAccess.java", "retrieved_chunk": " return new BytecodeMethodAccess(this, accessor);\n }\n @Override\n public MethodAccess reflect() {\n return this;\n }\n @Override\n public MethodAccess bind(Object object) {\n return withObject(object);\n }", "score": 0.8589783310890198 } ]
java
(T) accessor.invoke(null, args);
package dev.klepto.unreflect.reflection; import dev.klepto.unreflect.property.Reflectable; import dev.klepto.unreflect.UnreflectType; import dev.klepto.unreflect.ClassAccess; import dev.klepto.unreflect.ConstructorAccess; import dev.klepto.unreflect.FieldAccess; import dev.klepto.unreflect.MethodAccess; import dev.klepto.unreflect.bytecode.BytecodeClassAccess; import dev.klepto.unreflect.util.JdkInternals; import lombok.RequiredArgsConstructor; import lombok.With; import one.util.streamex.StreamEx; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; /** * Reflection-based implementation of {@link ClassAccess}. * * @author <a href="http://github.com/klepto">Augustinas R.</a> */ @With @RequiredArgsConstructor public class ReflectionClassAccess<T> implements ClassAccess<T> { private final Class<T> source; private final Object object; @Override public ClassAccess<T> unreflect() { return new BytecodeClassAccess<>(this); } @Override public ClassAccess<T> reflect() { return this; } @Override public ClassAccess<T> bind(Object object) { return withObject(object); } @Override public int modifiers() { return source.getModifiers(); } @Override public Reflectable parent() { return new ReflectionClassAccess<>(source.getSuperclass(), object); } @Override public StreamEx<Annotation> annotations() { return StreamEx.of(source.getDeclaredAnnotations()); } @Override public UnreflectType type() { return
UnreflectType.of(source);
} @Override public Class<T> source() { return source; } @Override public T create(Object... args) { return constructor(args).create(args); } @Override public StreamEx<ConstructorAccess<T>> constructors() { return StreamEx.of(source.getDeclaredConstructors()) .peek(constructor -> JdkInternals.setAccessible(constructor, true)) .map(constructor -> new ReflectionConstructorAccess<>( this, (Constructor<T>) constructor ) ); } @Override public StreamEx<FieldAccess> fields() { return type().subTypes().flatArray(type -> type.toClass().getDeclaredFields()) .peek(field -> JdkInternals.setAccessible(field, true)) .map(field -> new ReflectionFieldAccess( this, field, object ) ); } @Override public StreamEx<MethodAccess> methods() { return type().subTypes().flatArray(type -> type.toClass().getDeclaredMethods()) .peek(method -> JdkInternals.setAccessible(method, true)) .map(method -> new ReflectionMethodAccess( this, method, object ) ); } @Override public String name() { return source.getName(); } @Override public String toString() { return name(); } }
src/main/java/dev/klepto/unreflect/reflection/ReflectionClassAccess.java
klepto-unreflect-a818c39
[ { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionMethodAccess.java", "retrieved_chunk": " return StreamEx.of(source.getAnnotations());\n }\n @Override\n public UnreflectType type() {\n return UnreflectType.of(source.getGenericReturnType());\n }\n @Override\n public String name() {\n return source.getName();\n }", "score": 0.9097821712493896 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionConstructorAccess.java", "retrieved_chunk": " return source.getModifiers();\n }\n @Override\n public StreamEx<ParameterAccess> parameters() {\n return StreamEx.of(source.getParameters())\n .map(parameter -> new ReflectionParameterAccess(this, parameter));\n }\n @Override\n public Constructor<T> source() {\n return source;", "score": 0.9094957709312439 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionConstructorAccess.java", "retrieved_chunk": " @Override\n public Reflectable parent() {\n return parent;\n }\n @Override\n public StreamEx<Annotation> annotations() {\n return StreamEx.of(source.getDeclaredAnnotations());\n }\n @Override\n public UnreflectType type() {", "score": 0.9050737619400024 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionParameterAccess.java", "retrieved_chunk": " return (ConstructorAccess<?>) parent();\n }\n @Override\n public MethodAccess method() {\n return (MethodAccess) parent();\n }\n @Override\n public StreamEx<Annotation> annotations() {\n return StreamEx.of(source.getDeclaredAnnotations());\n }", "score": 0.9049721956253052 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionMethodAccess.java", "retrieved_chunk": " @Override\n public int modifiers() {\n return source.getModifiers();\n }\n @Override\n public StreamEx<ParameterAccess> parameters() {\n return StreamEx.of(source.getParameters())\n .map(parameter -> new ReflectionParameterAccess(this, parameter));\n }\n @Override", "score": 0.9010038375854492 } ]
java
UnreflectType.of(source);
package dev.klepto.unreflect; import com.google.common.reflect.TypeToken; import dev.klepto.unreflect.property.Named; import dev.klepto.unreflect.util.JdkInternals; import lombok.val; import one.util.streamex.StreamEx; import javax.annotation.Nullable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; /** * A wrapper for java types enabling simple generic lookup, instance allocation and superclass and subtype resolving. * * @author <a href="http://github.com/klepto">Augustinas R.</a> */ public class UnreflectType implements Named { private final TypeToken typeToken; private UnreflectType(TypeToken<?> typeToken) { this.typeToken = typeToken; } /** * Returns a reflection-based {@link ClassAccess} for this type. * * @return a reflection access for class that this type represents */ public ClassAccess<?> reflect() { return Unreflect.reflect(toClass()); } /** * Returns a bytecode-based {@link ClassAccess} for this type. * * @return a bytecode access for class that this type represents */ public ClassAccess<?> unreflect() { return Unreflect.unreflect(toClass()); } /** * Allocates a new instance of this type without calling any of its constructors. Enables initialization of any * object of any type regardless of constructor visibility. Note that any important initialization code might be * skipped. * * @param <T> generic type for automatic return value casting * @return a new instance of this type */ public <T> T allocate() {
return (T) JdkInternals.allocateInstance(toClass());
} /** * Returns the name of this type. * * @return the name of this type */ @Override public String name() { return toClass().getName(); } /** * Returns the superclass type of this type, or null if this type represents {@link java.lang.Object}. * * @return the superclass type, or null if superclass doesn't exist */ @Nullable public UnreflectType superType() { val superClass = toClass().getSuperclass(); if (superClass == null) { return null; } val superTypeToken = typeToken.getSupertype(superClass); return UnreflectType.of(superTypeToken); } /** * Returns the superclass type of this type at given index (depth), or null if superclass at given depth doesn't * exist. * * @param index the superclass index * @return the superclass type at a given depth */ @Nullable public UnreflectType superType(int index) { return superTypes().skip(index).findFirst().orElse(null); } /** * Returns a stream of all superclass types up to {@link java.lang.Object}. * * @return a stream containing all superclass types */ public StreamEx<UnreflectType> superTypes() { val result = new ArrayList<UnreflectType>(); UnreflectType superType = this; while ((superType = superType.superType()) != null) { result.add(superType); } return StreamEx.of(result); } /** * Returns a stream of all implemented types, this includes both super classes and implemented interfaces. * * @return a stream containing all implemented types */ public StreamEx<UnreflectType> subTypes() { return StreamEx.of(typeToken.getTypes()).map(UnreflectType::of); } /** * Returns a stream of all generic types associated with this type. Sometimes due to type erasure generics are not * preserved in which case, empty stream will be returned. * * @return a stream containing generic types associated with this type */ public StreamEx<UnreflectType> genericTypes() { val parameterizedType = (ParameterizedType) typeToken.getType(); return StreamEx.of(parameterizedType.getActualTypeArguments()).map(UnreflectType::of); } /** * Returns the first generic type associated with this type, or null if this type has no associated generics * * @return the first generic type associated with this type, or null if unavailable */ @Nullable public UnreflectType genericType() { return genericTypes().findFirst().orElse(null); } /** * Returns the generic type at a given index (slot), or null if generic type is unavailable. For example, if this * type is {@code Map<String, Integer>} calling {@code genericType(1)} will return type of {@link Integer}. Can be * chained to resolve generics at any depth. * * @param index the slot of the generic * @return the generic type at a given slot */ public UnreflectType genericType(int index) { return genericTypes().skip(index).findFirst().orElse(null); } /** * Returns a component type of this type, or null if this type has no component type. Only applicable to array types. * * @return the component type of this array type, or null if no component type present * @see UnreflectType#isArray() */ public UnreflectType componentType() { val componentType = typeToken.getComponentType(); if (componentType == null) { return null; } return of(componentType); } /** * Checks if this type matches the given value or type. * * @param object the value or type * @return true if this type is assignable for a given value or type */ public boolean matches(Object object) { return typeToken.isSupertypeOf(of(object).toClass()); } /** * Checks if this type class matches the given value or type class. * * @param object the value or type * @return true if this type class is the class of given value or type */ public boolean matchesExact(Object object) { return toClass() == of(object).toClass(); } /** * Checks if this type is an array type. * * @return true if this type is an array type */ public boolean isArray() { return typeToken.isArray(); } /** * Checks if this type is a primitive type. * * @return true if this type is a primitive type */ public boolean isPrimitive() { return typeToken.isPrimitive(); } /** * Returns {@link Type} representation of this type. * * @return a reflection representation of this type */ public Type toType() { return typeToken.getType(); } /** * Returns {@link Class} representation of this type. * * @return a class representation of this type */ public Class<?> toClass() { return typeToken.getRawType(); } @Override public String toString() { val type = isArray() ? componentType() : this; val simpleName = type.toClass().getSimpleName(); return simpleName + (isArray() ? "[]" : ""); } @Override public boolean equals(Object object) { return typeToken.equals(object); } @Override public int hashCode() { return typeToken.hashCode(); } /** * Creates a type representation of a given value, value can be class, type, typetoken or just a regular value in * which case it's class is going to be used as type. * * @param object the value * @return the type representation of a given value */ public static UnreflectType of(Object object) { if (object instanceof Class<?>) { return of((Class<?>) object); } if (object instanceof Type) { return of((Type) object); } if (object instanceof TypeToken<?>) { return of((TypeToken<?>) object); } return of(object.getClass()); } /** * Creates a type representation for a given {@link Type}. * * @param type the reflection type * @return the type representation of a given reflection type */ public static UnreflectType of(Type type) { return of(TypeToken.of(type)); } /** * Creates a type representation for a given {@link Class}. * * @param type the class type * @return the type representation of a given class type */ public static UnreflectType of(Class<?> type) { return of(TypeToken.of(type)); } /** * Creates a type representation for a given guava's {@link TypeToken}. * * @param type the guava type * @return the type representation of a given guava type */ public static UnreflectType of(TypeToken<?> type) { return new UnreflectType(type); } }
src/main/java/dev/klepto/unreflect/UnreflectType.java
klepto-unreflect-a818c39
[ { "filename": "src/main/java/dev/klepto/unreflect/util/JdkInternals.java", "retrieved_chunk": " /**\n * Allocates a new instance of a {@link java.lang.Class} without invoking any constructors.\n *\n * @param type the class type\n * @return the instantiated object\n */\n @SneakyThrows\n public static Object allocateInstance(Class<?> type) {\n return unsafe.allocateInstance(type);\n }", "score": 0.8607853055000305 }, { "filename": "src/main/java/dev/klepto/unreflect/Unreflect.java", "retrieved_chunk": " * @param <T> type that represents the class\n * @return a class accessor that will use code-generation rather than reflection for accessing its members\n */\n public static <T> ClassAccess<T> unreflect(Class<T> targetClass) {\n return reflect(targetClass).unreflect();\n }\n /**\n * Creates {@link ClassAccess} for a given object that use reflection API to access its members. This method\n * automatically calls {@link Accessible#bind(Object)} on created accessor in order to skip on supplying instance\n * every time you want to access its members.", "score": 0.7726234197616577 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionClassAccess.java", "retrieved_chunk": " @Override\n public StreamEx<ConstructorAccess<T>> constructors() {\n return StreamEx.of(source.getDeclaredConstructors())\n .peek(constructor -> JdkInternals.setAccessible(constructor, true))\n .map(constructor ->\n new ReflectionConstructorAccess<>(\n this,\n (Constructor<T>) constructor\n )\n );", "score": 0.7692474722862244 }, { "filename": "src/main/java/dev/klepto/unreflect/util/JdkInternals.java", "retrieved_chunk": " *\n * @author <a href=\"http://github.com/klepto\">Augustinas R.</a>\n */\npublic class JdkInternals {\n private static final Unsafe unsafe;\n private static final int accessibleFlagIndex;\n @Getter private static final Class<?> magicAccessorImpl;\n private static final Class<?> classDefiner;\n private static final Method defineClassMethod;\n static {", "score": 0.7684624791145325 }, { "filename": "src/main/java/dev/klepto/unreflect/bytecode/BytecodeContructorAccess.java", "retrieved_chunk": " }\n @Override\n public ConstructorAccess<T> reflect() {\n return delegate;\n }\n @Override\n public T invoke(Object... args) {\n return (T) accessor.invoke(null, args);\n }\n @Override", "score": 0.7681292295455933 } ]
java
return (T) JdkInternals.allocateInstance(toClass());
package dev.klepto.unreflect.bytecode; import dev.klepto.unreflect.FieldAccess; import dev.klepto.unreflect.bytecode.asm.MutableAccessor; import dev.klepto.unreflect.reflection.ReflectionFieldAccess; import lombok.RequiredArgsConstructor; import lombok.experimental.Delegate; /** * Bytecode access to a field of a class. Delegates all functions to {@link ReflectionFieldAccess} except the * {@link FieldAccess#set(Object)} and {@link FieldAccess#get()} functions for which it uses direct accessor. * * @author <a href="http://github.com/klepto">Augustinas R.</a> */ @RequiredArgsConstructor public class BytecodeFieldAccess implements FieldAccess { @Delegate(excludes = Overrides.class) private final ReflectionFieldAccess delegate; private final MutableAccessor accessor; @Override public FieldAccess unreflect() { return this; } @Override public FieldAccess reflect() { return delegate; } @Override public FieldAccess bind(Object object) {
return new BytecodeFieldAccess((ReflectionFieldAccess) delegate.bind(object), accessor);
} @Override public <T> T get() { return (T) accessor.get(object()); } @Override public void set(Object value) { accessor.set(object(), value); } @Override public String toString() { return delegate.toString(); } private interface Overrides { void unreflect(); void reflect(); void bind(Object object); void get(); void set(Object value); } }
src/main/java/dev/klepto/unreflect/bytecode/BytecodeFieldAccess.java
klepto-unreflect-a818c39
[ { "filename": "src/main/java/dev/klepto/unreflect/bytecode/BytecodeMethodAccess.java", "retrieved_chunk": " return this;\n }\n @Override\n public MethodAccess reflect() {\n return delegate;\n }\n @Override\n public MethodAccess bind(Object object) {\n return new BytecodeMethodAccess((ReflectionMethodAccess) delegate.bind(object), accessor);\n }", "score": 0.9511169195175171 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionMethodAccess.java", "retrieved_chunk": " return new BytecodeMethodAccess(this, accessor);\n }\n @Override\n public MethodAccess reflect() {\n return this;\n }\n @Override\n public MethodAccess bind(Object object) {\n return withObject(object);\n }", "score": 0.9281892776489258 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionFieldAccess.java", "retrieved_chunk": " val accessor = AccessorGenerator.getInstance().generateMutableAccessor(source);\n return new BytecodeFieldAccess(this, accessor);\n }\n @Override\n public FieldAccess reflect() {\n return this;\n }\n @Override\n public FieldAccess bind(Object object) {\n return withObject(object);", "score": 0.9277341961860657 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionClassAccess.java", "retrieved_chunk": "@RequiredArgsConstructor\npublic class ReflectionClassAccess<T> implements ClassAccess<T> {\n private final Class<T> source;\n private final Object object;\n @Override\n public ClassAccess<T> unreflect() {\n return new BytecodeClassAccess<>(this);\n }\n @Override\n public ClassAccess<T> reflect() {", "score": 0.8951617479324341 }, { "filename": "src/main/java/dev/klepto/unreflect/bytecode/BytecodeClassAccess.java", "retrieved_chunk": " }\n @Override\n public ClassAccess<T> bind(Object object) {\n return delegate.bind(object).unreflect();\n }\n @Override\n public Reflectable parent() {\n return ((ClassAccess<?>)delegate.parent()).unreflect();\n }\n @Override", "score": 0.8936631083488464 } ]
java
return new BytecodeFieldAccess((ReflectionFieldAccess) delegate.bind(object), accessor);
package dev.klepto.unreflect.reflection; import dev.klepto.unreflect.bytecode.asm.AccessorGenerator; import dev.klepto.unreflect.property.Reflectable; import dev.klepto.unreflect.bytecode.BytecodeFieldAccess; import dev.klepto.unreflect.UnreflectType; import dev.klepto.unreflect.FieldAccess; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.With; import lombok.val; import one.util.streamex.StreamEx; import java.lang.annotation.Annotation; import java.lang.reflect.Field; /** * Reflection-based implementation of {@link FieldAccess}. * * @author <a href="http://github.com/klepto">Augustinas R.</a> */ @With @RequiredArgsConstructor public class ReflectionFieldAccess implements FieldAccess { private final Reflectable parent; private final Field source; private final Object object; @Override public Reflectable parent() { return parent; } @Override public FieldAccess unreflect() { val accessor = AccessorGenerator.getInstance().generateMutableAccessor(source); return new BytecodeFieldAccess(this, accessor); } @Override public FieldAccess reflect() { return this; } @Override public FieldAccess bind(Object object) { return withObject(object); } @Override public int modifiers() { return source.getModifiers(); } @Override @SneakyThrows public <T> T get() { return (T) source.get(object); } @Override @SneakyThrows public void set(Object value) { source.set(object, value); } @Override public StreamEx<Annotation> annotations() { return StreamEx.of(source.getDeclaredAnnotations()); } @Override public UnreflectType type() {
return UnreflectType.of(source.getGenericType());
} @Override public String name() { return source.getName(); } @Override public Field source() { return source; } public Object object() { return object; } @Override public String toString() { val signature = type().toString() + " " + name(); return isStatic() ? "static " + signature : signature; } }
src/main/java/dev/klepto/unreflect/reflection/ReflectionFieldAccess.java
klepto-unreflect-a818c39
[ { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionMethodAccess.java", "retrieved_chunk": " return StreamEx.of(source.getAnnotations());\n }\n @Override\n public UnreflectType type() {\n return UnreflectType.of(source.getGenericReturnType());\n }\n @Override\n public String name() {\n return source.getName();\n }", "score": 0.8674399852752686 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionConstructorAccess.java", "retrieved_chunk": " @Override\n public Reflectable parent() {\n return parent;\n }\n @Override\n public StreamEx<Annotation> annotations() {\n return StreamEx.of(source.getDeclaredAnnotations());\n }\n @Override\n public UnreflectType type() {", "score": 0.863111674785614 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionClassAccess.java", "retrieved_chunk": " @Override\n public Reflectable parent() {\n return new ReflectionClassAccess<>(source.getSuperclass(), object);\n }\n @Override\n public StreamEx<Annotation> annotations() {\n return StreamEx.of(source.getDeclaredAnnotations());\n }\n @Override\n public UnreflectType type() {", "score": 0.8625552654266357 }, { "filename": "src/main/java/dev/klepto/unreflect/reflection/ReflectionMethodAccess.java", "retrieved_chunk": " @SneakyThrows\n public <T> T invoke(Object... args) {\n return (T) source.invoke(object, args);\n }\n @Override\n public Reflectable parent() {\n return parent;\n }\n @Override\n public StreamEx<Annotation> annotations() {", "score": 0.8414332866668701 }, { "filename": "benchmark/src/main/java/dev/klepto/unreflect/benchmark/FieldBenchmarks.java", "retrieved_chunk": " @Override\n public void set(Object value) {\n subject.value = (int) value;\n }\n };\n this.reflect = Unreflect.reflect(subject).field(\"value\");\n this.unreflect = Unreflect.unreflect(subject).field(\"value\");\n }\n @Benchmark\n public void direct() {", "score": 0.8392212390899658 } ]
java
return UnreflectType.of(source.getGenericType());
package com.github.kingschan1204.easycrawl.task; import com.github.kingschan1204.easycrawl.core.agent.WebAgent; import com.github.kingschan1204.easycrawl.helper.http.UrlHelper; import com.github.kingschan1204.easycrawl.helper.json.JsonHelper; import com.github.kingschan1204.easycrawl.helper.validation.Assert; import lombok.extern.slf4j.Slf4j; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; @Slf4j public class EasyCrawl<R> { private WebAgent webAgent; private Function<WebAgent, R> parserFunction; public EasyCrawl<R> webAgent(WebAgent webAgent) { this.webAgent = webAgent; return this; } // public static EasyCrawlNew of(WebAgentNew webAgent){ // return new EasyCrawlNew(webAgent); // } public EasyCrawl<R> analyze(Function<WebAgent, R> parserFunction) { this.parserFunction = parserFunction; return this; } public R execute() { return execute(null); } public R execute(Map<String, Object> map) { Assert.notNull(webAgent, "agent对象不能为空!"); Assert.notNull(parserFunction, "解析函数不能为空!"); R result; CompletableFuture<R> cf = CompletableFuture.supplyAsync(() -> { try { return webAgent.execute(map); } catch (Exception e) { e.printStackTrace(); return null; } }).thenApply(parserFunction); try { result = cf.get(); } catch (Exception e) { throw new RuntimeException(e); } return result; } /** * restApi json格式自动获取所有分页 * @param map 运行参数 * @param pageIndexKey 页码key * @param totalKey 总记录条数key * @param pageSize * @return */ public List<R> executePage(Map<String, Object> map, String pageIndexKey, String totalKey, Integer pageSize) { List<R> list = Collections.synchronizedList(new ArrayList<>()); WebAgent data = webAgent.execute(map); JsonHelper json = data.getJson(); int totalRows = json.get(totalKey, Integer.class); int totalPage = (totalRows + pageSize - 1) / pageSize; log.debug("共{}记录,每页展示{}条,共{}页", totalRows, pageSize, totalPage); List<CompletableFuture<R>> cfList = new ArrayList<>(); Consumer<R> consumer = (r) -> { if (r instanceof Collection) { list.addAll((Collection<? extends R>) r); } else { list.add(r); } }; cfList.add(CompletableFuture.supplyAsync(() -> data).thenApply(parserFunction)); cfList.get(0).thenAccept(consumer); for (int i = 2; i <= totalPage; i++) { String url = new UrlHelper(
webAgent.getConfig().getUrl()).set(pageIndexKey, String.valueOf(i)).getUrl();
CompletableFuture<R> cf = CompletableFuture.supplyAsync(() -> { try { return webAgent.url(url).execute(map); } catch (Exception e) { e.printStackTrace(); return null; } }).thenApply(parserFunction); cf.thenAccept(consumer); cfList.add(cf); } CompletableFuture.allOf(cfList.toArray(new CompletableFuture[]{})).join(); return list; } }
src/main/java/com/github/kingschan1204/easycrawl/task/EasyCrawl.java
kingschan1204-easycrawl-a5aade8
[ { "filename": "src/test/java/com/github/kingschan1204/easycrawl/SzseTest.java", "retrieved_chunk": " cf.thenAccept(System.out::println);\n list.add(cf);\n }\n CompletableFuture.allOf(list.toArray(new CompletableFuture[]{})).join();\n }\n @DisplayName(\"月份交易日数据\")\n @Test\n public void proxyTest() throws Exception {\n String month = \"2023-03\";\n String url = new UrlHelper(apiUrl).set(\"month\", month).getUrl();", "score": 0.8351761102676392 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/SzseTest.java", "retrieved_chunk": " TreeMap<String, Boolean> result = new EasyCrawl< TreeMap<String, Boolean>>()\n .webAgent(WebAgent.defaultAgent().referer(url).useAgent(useAgent).url(apiUrl))\n .analyze(r -> parserData(r.getResult().getBody()))\n .execute();\n System.out.println(result);\n }\n}", "score": 0.8073892593383789 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/XueQiuTest.java", "retrieved_chunk": " String dataUrl = \"https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol=${code}&begin=${begin}&period=day&type=before&count=${count}&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance\";\n List<String> list = new ArrayList<>();\n boolean hasNext = true;\n while (hasNext) {\n JsonHelper jsonHelper = new EasyCrawl<JsonHelper>()\n .webAgent(WebAgent.defaultAgent().url(dataUrl).referer(referer).cookie(cookies))\n .analyze(WebAgent::getJson).execute(map);\n JSONArray columns = jsonHelper.get(\"data.column\", JSONArray.class);\n JSONArray rows = jsonHelper.get(\"data.item\", JSONArray.class);\n StringBuffer sqls = new StringBuffer();", "score": 0.8044286370277405 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/SzseTest.java", "retrieved_chunk": " int end = 2023;\n List<String> month = new ArrayList<>();\n for (int i = year; i <= end; i++) {\n for (int j = 1; j < 13; j++) {\n month.add(String.format(\"%s-%02d\", i, j));\n }\n }\n List<CompletableFuture> list = new ArrayList<>();\n for (String s : month) {\n CompletableFuture cf = CompletableFuture.supplyAsync(() -> getDay(s));", "score": 0.8038257360458374 }, { "filename": "src/test/java/com/github/kingschan1204/easycrawl/ProxyTest.java", "retrieved_chunk": " .webAgent(WebAgent.defaultAgent().referer(apiUrl).useAgent(useAgent).url(apiUrl).proxy(proxy))\n .analyze(r -> r.getResult().getBody()).execute();\n System.out.println(result);\n }\n}", "score": 0.7948563098907471 } ]
java
webAgent.getConfig().getUrl()).set(pageIndexKey, String.valueOf(i)).getUrl();