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.minivv.pilot.ui;
import com.intellij.icons.AllIcons;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.ui.AnActionButton;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.AnActionLink;
import com.minivv.pilot.constants.SysConstants;
import com.minivv.pilot.model.AppSettings;
import com.minivv.pilot.model.Prompt;
import com.minivv.pilot.model.Prompts;
import com.minivv.pilot.utils.ActionLinkUtils;
import com.minivv.pilot.utils.Donate;
import com.minivv.pilot.utils.GPTClient;
import com.minivv.pilot.utils.NotifyUtils;
import com.theokanning.openai.completion.CompletionChoice;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Objects;
/**
* todo 超时时间配置
* todo 更换NotifyUtils
* todo 限制代码量
*/
public class AppPluginSettingsPage {
private JPanel rootPane;
private JTextField gptKey;
private JTextField gptModel;
private JSpinner gptMaxToken;
private JCheckBox isReplace;
private JRadioButton enableProxy;
private JRadioButton httpProxy;
private JRadioButton socketProxy;
private JTextField proxyHost;
private JSpinner proxyPort;
private AnActionLink gptKeyLink;
private AnActionLink gptModelsLink;
private AnActionLink gptUsageLink;
private JTextField testConnMsg;
private JButton testConnButton;
private JPanel promptsPane;
private JSpinner maxWaitSeconds;
private JButton donatePaypal;
private JButton donateWx;
// private JPanel locale;
private AppSettings settings;
private final PromptsTable promptsTable;
public AppPluginSettingsPage(AppSettings original) {
this.settings
|
= original.clone();
|
this.promptsTable = new PromptsTable();
promptsPane.add(ToolbarDecorator.createDecorator(promptsTable)
.setRemoveAction(button -> promptsTable.removeSelectedPrompts())
.setAddAction(button -> promptsTable.addPrompt(Prompt.of("Option" + promptsTable.getRowCount(), "Snippet:{query}")))
.addExtraAction(new AnActionButton("Reset Default Prompts", AllIcons.Actions.Rollback) {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
promptsTable.resetDefaultAliases();
}
})
.createPanel());
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent e) {
return promptsTable.editPrompt();
}
}.installOn(promptsTable);
// ComboBox<Locale> comboBox = new ComboBox<>();
// Locale[] locales = Locale.getAvailableLocales();
// for (Locale locale : locales) {
// comboBox.addItem(locale);
// }
// locale.add(comboBox);
Donate.initUrl(donatePaypal, "https://www.paypal.me/kuweiguge");
// Donate.initImage(donateWx,"images/wechat_donate.png");
}
private void createUIComponents() {
gptMaxToken = new JSpinner(new SpinnerNumberModel(2048, 128, 2048, 128));
proxyPort = new JSpinner(new SpinnerNumberModel(1087, 1, 65535, 1));
maxWaitSeconds = new JSpinner(new SpinnerNumberModel(60, 5, 600, 5));
gptKeyLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/api-keys");
gptModelsLink = ActionLinkUtils.newActionLink("https://platform.openai.com/docs/models/overview");
gptUsageLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/usage");
}
public AppSettings getSettings() {
promptsTable.commit(settings);
getData(settings);
return settings;
}
private void getData(AppSettings settings) {
settings.gptKey = gptKey.getText();
settings.gptModel = gptModel.getText();
settings.gptMaxTokens = (int) gptMaxToken.getValue();
settings.isReplace = isReplace.isSelected();
settings.enableProxy = enableProxy.isSelected();
settings.proxyHost = proxyHost.getText();
settings.proxyPort = (int) proxyPort.getValue();
settings.maxWaitSeconds = (int) maxWaitSeconds.getValue();
settings.proxyType = httpProxy.isSelected() ? SysConstants.httpProxyType : SysConstants.socketProxyType;
settings.testConnMsg = testConnMsg.getText();
settings.prompts = new Prompts(promptsTable.prompts);
}
public void importForm(AppSettings state) {
this.settings = state.clone();
setData(settings);
promptsTable.reset(settings);
}
private void setData(AppSettings settings) {
gptKey.setText(settings.gptKey);
gptModel.setText(settings.gptModel);
gptMaxToken.setValue(settings.gptMaxTokens);
isReplace.setSelected(settings.isReplace);
testConnMsg.setText(settings.testConnMsg);
httpProxy.setSelected(Objects.equals(settings.proxyType, SysConstants.httpProxyType));
socketProxy.setSelected(Objects.equals(settings.proxyType, SysConstants.socketProxyType));
proxyHost.setText(settings.proxyHost);
proxyPort.setValue(settings.proxyPort);
maxWaitSeconds.setValue(settings.maxWaitSeconds);
enableProxy.addChangeListener(e -> {
if (enableProxy.isSelected()) {
httpProxy.setEnabled(true);
socketProxy.setEnabled(true);
proxyHost.setEnabled(true);
proxyPort.setEnabled(true);
} else {
httpProxy.setEnabled(false);
socketProxy.setEnabled(false);
proxyHost.setEnabled(false);
proxyPort.setEnabled(false);
}
});
httpProxy.addChangeListener(e -> {
socketProxy.setSelected(!httpProxy.isSelected());
});
socketProxy.addChangeListener(e -> {
httpProxy.setSelected(!socketProxy.isSelected());
});
enableProxy.setSelected(settings.enableProxy);
testConnButton.addActionListener(e -> {
String msg = StringUtils.isBlank(testConnMsg.getText()) ? SysConstants.testConnMsg : testConnMsg.getText();
boolean hasError = checkSettings();
if (hasError) {
return;
}
List<CompletionChoice> choices = GPTClient.callChatGPT(msg, settings);
if (GPTClient.isSuccessful(choices)) {
NotifyUtils.notifyMessage(AppSettings.getProject(), "Test connection successfully!ChatGPT answer:" + GPTClient.toString(choices), NotificationType.INFORMATION);
} else {
NotifyUtils.notifyMessage(AppSettings.getProject(), "Test connection failed!", NotificationType.ERROR);
}
});
}
/**
* 保存设置
*
* @return 是否有错误
*/
private boolean checkSettings() {
StringBuilder error = new StringBuilder();
if (StringUtils.isBlank(gptKey.getText())) {
error.append("GPT Key is required.").append("\n");
}
if (StringUtils.isBlank(gptModel.getText())) {
error.append("GPT Model is required.").append("\n");
}
if (gptMaxToken.getValue() == null || (int) gptMaxToken.getValue() <= 0 || (int) gptMaxToken.getValue() > 2048) {
error.append("GPT Max Token is required and should be between 1 and 2048.").append("\n");
}
if (enableProxy.isSelected()) {
if (StringUtils.isBlank(proxyHost.getText())) {
error.append("Proxy Host is required.").append("\n");
}
if (proxyPort.getValue() == null || (int) proxyPort.getValue() <= 0 || (int) proxyPort.getValue() > 65535) {
error.append("Proxy Port is required and should be between 1 and 65535.").append("\n");
}
if (maxWaitSeconds.getValue() == null || (int) maxWaitSeconds.getValue() <= 0 || (int) maxWaitSeconds.getValue() > 600) {
error.append("Max Wait Seconds is required and should be between 5 and 600.").append("\n");
}
}
if (promptsTable.getRowCount() <= 0) {
error.append("Prompts is required.").append("\n");
}
if (promptsTable.prompts.stream().anyMatch(p -> !StringUtils.contains(p.getSnippet(), "{query}"))) {
error.append("Prompts should contain {query}.").append("\n");
}
if (StringUtils.isNotBlank(error)) {
NotifyUtils.notifyMessage(AppSettings.getProject(), error.toString(), NotificationType.ERROR);
return true;
} else {
return false;
}
}
public boolean isSettingsModified(AppSettings state) {
if (promptsTable.isModified(state)) return true;
return !this.settings.equals(state) || isModified(state);
}
private boolean isModified(AppSettings state) {
return !gptKey.getText().equals(state.gptKey) ||
!gptModel.getText().equals(state.gptModel) ||
!gptMaxToken.getValue().equals(state.gptMaxTokens) ||
isReplace.isSelected() != state.isReplace ||
enableProxy.isSelected() != state.enableProxy ||
!proxyHost.getText().equals(state.proxyHost) ||
!proxyPort.getValue().equals(state.proxyPort) ||
!maxWaitSeconds.getValue().equals(state.maxWaitSeconds) ||
!httpProxy.isSelected() == Objects.equals(state.proxyType, SysConstants.httpProxyType) ||
!socketProxy.isSelected() == Objects.equals(state.proxyType, SysConstants.socketProxyType) ||
!testConnMsg.getText().equals(state.testConnMsg);
}
public JPanel getRootPane() {
return rootPane;
}
public JTextField getGptKey() {
return gptKey;
}
}
|
src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java
|
minivv-gpt-copilot-b16ad12
|
[
{
"filename": "src/main/java/com/minivv/pilot/AppConfigurable.java",
"retrieved_chunk": " return \"gpt-copilot\";\n }\n @Override\n public @Nullable JComponent createComponent() {\n form = new AppPluginSettingsPage(state);\n return form.getRootPane();\n }\n @Override\n public boolean isModified() {\n return form != null && form.isSettingsModified(state);",
"score": 0.8556729555130005
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": "package com.minivv.pilot.ui;\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.minivv.pilot.model.Prompt;\nimport com.minivv.pilot.model.AppSettings;\nimport org.jetbrains.annotations.NotNull;\nimport javax.swing.*;\nimport javax.swing.table.AbstractTableModel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;",
"score": 0.8410054445266724
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n }\n public void reset(AppSettings settings) {\n obtainPrompts(prompts, settings);\n promptTableModel.fireTableDataChanged();\n }\n public boolean isModified(AppSettings settings) {\n final ArrayList<Prompt> _prompts = new ArrayList<>();\n obtainPrompts(_prompts, settings);\n return !_prompts.equals(prompts);",
"score": 0.8383584022521973
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {\n prompts.clear();\n prompts.addAll(settings.prompts.getPrompts());\n }\n public void addPrompt(Prompt prompt) {\n prompts.add(prompt);\n promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);\n }\n public void commit(AppSettings settings) {",
"score": 0.828488290309906
},
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " public Prompts prompts = new Prompts();\n public AppSettings() {\n this.addDefaultPrompts(this.prompts);\n }\n @NotNull\n public static Project getProject() {\n return AppSettingsStorage.getProject();\n }\n @NotNull\n public static AppSettings get() {",
"score": 0.8271863460540771
}
] |
java
|
= original.clone();
|
package org.example.hmwk1.service.concretes;
import org.example.hmwk1.adapter.CheckService;
import org.example.hmwk1.entity.Customer;
import org.example.hmwk1.service.abstracts.UserService;
import java.util.ArrayList;
import java.util.List;
public class UserManager implements UserService {
private final CheckService checkService;
List<Customer> customers = new ArrayList<>();
public UserManager(CheckService checkService) {
this.checkService = checkService;
}
@Override
public void addUser(Customer customer) {
if (!checkService.checkUser(customer)) {
System.err.println("Invalid Process by Mernis");
System.exit(1);
}
if (customers.contains(customer)) {
System.err.println("User already exist");
} else {
customers.add(customer);
System.out.println("User is added.");
}
}
public Customer getCustomer(int id ){
for (Customer customer : customers) {
if(customer.getId() == id){
return customer;
}
}
throw new RuntimeException("Invalid id");
}
@Override
public List<Customer> getUsers() {
return customers;
}
@Override
public void deleteUser(Customer user) {
if (customers.contains(user)) {
customers.remove(user);
System.out.println("User: " + user.getId() + " is deleted.");
}
System.out.println("User is not in database.");
}
@Override
public void updateUser(int id, Customer customer) {
Customer userToUpdate;
for (Customer user2 : customers) {
if (user2.getId() == id) {
System.out.println(user2.getName() +" is updated to " + customer.getName());
userToUpdate = user2;
userToUpdate.setId(customer.getId());
userToUpdate.setPassword(customer.getPassword());
userToUpdate.setEmail(customer.getEmail());
userToUpdate.setName(customer.getName());
userToUpdate.setSurName(customer.getSurName());
userToUpdate.
|
setBirthYear(customer.getBirthYear());
|
userToUpdate.setTc(customer.getTc());
}
return;
}
System.out.println("Customer can not found.");
}
}
|
src/main/java/org/example/hmwk1/service/concretes/UserManager.java
|
MuhammetTahaDemiryol-Turkcell-Homework-39026c6
|
[
{
"filename": "src/main/java/org/example/hmwk1/adapter/MernisService.java",
"retrieved_chunk": " }\n @Override\n public boolean checkUser(Customer customer) {\n for (Customer customer2 : userList) {\n if (customer2.getTc().equals(customer.getTc()) &&\n customer2.getName().equals(customer.getName()) &&\n customer2.getSurName().equals(customer.getSurName()) &&\n customer2.getBirthYear() == customer.getBirthYear()) {\n return true;\n }",
"score": 0.8330474495887756
},
{
"filename": "src/main/java/org/example/hmwk1/Main.java",
"retrieved_chunk": " userManager.addUser(john);\n userManager.addUser(harry);\n userManager.addUser(weasley);\n userManager.addUser(weasley);\n userManager.getUsers().stream().forEach(System.out::println);\n userManager.deleteUser(harry);\n userManager.getUsers().stream().forEach(System.out::println);\n userManager.updateUser(1,new Customer(1,\"7676@gmail.com\",\"4321\",\"Christopher\",\"Lee\",\"767676767676\",1932));\n userManager.getUsers().stream().forEach(System.out::println);\n System.out.println(\"***************************************************\");",
"score": 0.8258967995643616
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/GameManager.java",
"retrieved_chunk": " @Override\n public void updateGame(int id, Game game) {\n Game updateToGame;\n for(Game game1: games){\n if(game1.getId()==id){\n updateToGame = game1;\n updateToGame.setId(game.getId());\n updateToGame.setDescription(game.getDescription());\n updateToGame.setCost(game.getCost());\n updateToGame.setName(game.getName());",
"score": 0.8199918270111084
},
{
"filename": "src/main/java/org/example/hmwk1/entity/Customer.java",
"retrieved_chunk": " super(id, email, password);\n this.name = name;\n this.surName = surName;\n this.tc = tc;\n this.birthYear = birthYear;\n }\n public Customer(int id, String email, String password, String name, String surName, String tc, int birthYear, Game game ) {\n super(id, email, password);\n this.name = name;\n this.surName = surName;",
"score": 0.8187114000320435
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/CampaignManager.java",
"retrieved_chunk": " @Override\n public void updateCampaign(int id, Campaign campaign) {\n Campaign updateToCampaign = null;\n for(Campaign campaign1: campaigns){\n if(campaign1.getId()==id){\n updateToCampaign = campaign1;\n updateToCampaign.setGame(campaign.getGames().get(id));\n updateToCampaign.setDiscountAmount(campaign.getDiscountAmount());\n updateToCampaign.setDayTime(campaign.getDayTime());\n }else{",
"score": 0.8182905912399292
}
] |
java
|
setBirthYear(customer.getBirthYear());
|
package org.example.hmwk1.service.concretes;
import org.example.hmwk1.adapter.CheckService;
import org.example.hmwk1.entity.Customer;
import org.example.hmwk1.service.abstracts.UserService;
import java.util.ArrayList;
import java.util.List;
public class UserManager implements UserService {
private final CheckService checkService;
List<Customer> customers = new ArrayList<>();
public UserManager(CheckService checkService) {
this.checkService = checkService;
}
@Override
public void addUser(Customer customer) {
if (!checkService.checkUser(customer)) {
System.err.println("Invalid Process by Mernis");
System.exit(1);
}
if (customers.contains(customer)) {
System.err.println("User already exist");
} else {
customers.add(customer);
System.out.println("User is added.");
}
}
public Customer getCustomer(int id ){
for (Customer customer : customers) {
if(customer.getId() == id){
return customer;
}
}
throw new RuntimeException("Invalid id");
}
@Override
public List<Customer> getUsers() {
return customers;
}
@Override
public void deleteUser(Customer user) {
if (customers.contains(user)) {
customers.remove(user);
System.out.println("User: " + user.getId() + " is deleted.");
}
System.out.println("User is not in database.");
}
@Override
public void updateUser(int id, Customer customer) {
Customer userToUpdate;
for (Customer user2 : customers) {
if (user2.getId() == id) {
System.out.
|
println(user2.getName() +" is updated to " + customer.getName());
|
userToUpdate = user2;
userToUpdate.setId(customer.getId());
userToUpdate.setPassword(customer.getPassword());
userToUpdate.setEmail(customer.getEmail());
userToUpdate.setName(customer.getName());
userToUpdate.setSurName(customer.getSurName());
userToUpdate.setBirthYear(customer.getBirthYear());
userToUpdate.setTc(customer.getTc());
}
return;
}
System.out.println("Customer can not found.");
}
}
|
src/main/java/org/example/hmwk1/service/concretes/UserManager.java
|
MuhammetTahaDemiryol-Turkcell-Homework-39026c6
|
[
{
"filename": "src/main/java/org/example/hmwk1/adapter/MernisService.java",
"retrieved_chunk": " }\n @Override\n public boolean checkUser(Customer customer) {\n for (Customer customer2 : userList) {\n if (customer2.getTc().equals(customer.getTc()) &&\n customer2.getName().equals(customer.getName()) &&\n customer2.getSurName().equals(customer.getSurName()) &&\n customer2.getBirthYear() == customer.getBirthYear()) {\n return true;\n }",
"score": 0.8435871601104736
},
{
"filename": "src/main/java/org/example/hmwk1/Main.java",
"retrieved_chunk": " userManager.addUser(john);\n userManager.addUser(harry);\n userManager.addUser(weasley);\n userManager.addUser(weasley);\n userManager.getUsers().stream().forEach(System.out::println);\n userManager.deleteUser(harry);\n userManager.getUsers().stream().forEach(System.out::println);\n userManager.updateUser(1,new Customer(1,\"7676@gmail.com\",\"4321\",\"Christopher\",\"Lee\",\"767676767676\",1932));\n userManager.getUsers().stream().forEach(System.out::println);\n System.out.println(\"***************************************************\");",
"score": 0.842715859413147
},
{
"filename": "src/main/java/org/example/hmwk1/service/abstracts/UserService.java",
"retrieved_chunk": "package org.example.hmwk1.service.abstracts;\nimport org.example.hmwk1.entity.Customer;\nimport java.util.List;\npublic interface UserService {\n void addUser(Customer user);\n List<Customer> getUsers();\n void deleteUser(Customer user);\n void updateUser(int id,Customer user);\n}",
"score": 0.8416837453842163
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/CampaignManager.java",
"retrieved_chunk": " }\n @Override\n public void deleteCampaignById(int id) {\n for (Campaign campaign : campaigns) {\n if(campaign.getId() == id){\n campaigns.remove(campaign);\n System.out.println(\"Campaign deleted\");\n }\n }\n }",
"score": 0.8208432197570801
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/CampaignManager.java",
"retrieved_chunk": " @Override\n public void updateCampaign(int id, Campaign campaign) {\n Campaign updateToCampaign = null;\n for(Campaign campaign1: campaigns){\n if(campaign1.getId()==id){\n updateToCampaign = campaign1;\n updateToCampaign.setGame(campaign.getGames().get(id));\n updateToCampaign.setDiscountAmount(campaign.getDiscountAmount());\n updateToCampaign.setDayTime(campaign.getDayTime());\n }else{",
"score": 0.8200792670249939
}
] |
java
|
println(user2.getName() +" is updated to " + customer.getName());
|
package org.example.hmwk1.service.concretes;
import org.example.hmwk1.entity.Campaign;
import org.example.hmwk1.service.abstracts.CampaignService;
import java.util.ArrayList;
import java.util.List;
public class CampaignManager implements CampaignService {
List<Campaign> campaigns = new ArrayList<>();
@Override
public void addCampaign(Campaign campaign) {
if(campaigns.contains(campaign)){
System.out.println("Campaign already exist.");
}else{
campaigns.add(campaign);
System.out.println("Campaign added.");
}
}
@Override
public void deleteCampaign(Campaign campaign) {
campaigns.remove(campaign);
System.out.println("Campaign deleted");
}
@Override
public void deleteCampaignById(int id) {
for (Campaign campaign : campaigns) {
if(campaign.getId() == id){
campaigns.remove(campaign);
System.out.println("Campaign deleted");
}
}
}
@Override
public void updateCampaign(int id, Campaign campaign) {
Campaign updateToCampaign = null;
for(Campaign campaign1: campaigns){
|
if(campaign1.getId()==id){
|
updateToCampaign = campaign1;
updateToCampaign.setGame(campaign.getGames().get(id));
updateToCampaign.setDiscountAmount(campaign.getDiscountAmount());
updateToCampaign.setDayTime(campaign.getDayTime());
}else{
System.out.println("Campaign is not found and also not updated");
}
}
}
@Override
public List<Campaign> getCampaigns() {
return campaigns;
}
}
|
src/main/java/org/example/hmwk1/service/concretes/CampaignManager.java
|
MuhammetTahaDemiryol-Turkcell-Homework-39026c6
|
[
{
"filename": "src/main/java/org/example/hmwk1/Main.java",
"retrieved_chunk": " gameManager.getGames().stream().forEach(System.out::println);\n gameManager.deleteGame(game);\n gameManager.getGames().stream().forEach(System.out::println);\n gameManager.updateGame(1,new Game(1,\"Run\",250,\"Run\",0));\n System.out.println(\"***************************************************\");\n Campaign campaign = new Campaign(1,75,15,game4);\n Campaign campaign2 = new Campaign(2,75,15,game2);\n campaignManager.addCampaign(campaign);\n campaignManager.addCampaign(campaign2);\n campaignManager.getCampaigns().stream().forEach(System.out::println);",
"score": 0.865952730178833
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/GameManager.java",
"retrieved_chunk": " @Override\n public void updateGame(int id, Game game) {\n Game updateToGame;\n for(Game game1: games){\n if(game1.getId()==id){\n updateToGame = game1;\n updateToGame.setId(game.getId());\n updateToGame.setDescription(game.getDescription());\n updateToGame.setCost(game.getCost());\n updateToGame.setName(game.getName());",
"score": 0.8582545518875122
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/UserManager.java",
"retrieved_chunk": " customers.remove(user);\n System.out.println(\"User: \" + user.getId() + \" is deleted.\");\n }\n System.out.println(\"User is not in database.\");\n }\n @Override\n public void updateUser(int id, Customer customer) {\n Customer userToUpdate;\n for (Customer user2 : customers) {\n if (user2.getId() == id) {",
"score": 0.8561508655548096
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/GameManager.java",
"retrieved_chunk": " }\n @Override\n public void deleteGameById(int id) {\n for (Game game : games) {\n if(game.getId() == id){\n games.remove(game);\n System.out.println(\"Game deleted\");\n }\n }\n }",
"score": 0.8486369848251343
},
{
"filename": "src/main/java/org/example/hmwk1/service/abstracts/CampaignService.java",
"retrieved_chunk": "package org.example.hmwk1.service.abstracts;\nimport org.example.hmwk1.entity.Campaign;\nimport java.util.List;\npublic interface CampaignService {\n void addCampaign(Campaign campaign);\n void deleteCampaign(Campaign campaign);\n void deleteCampaignById(int id);\n void updateCampaign(int id,Campaign campaign);\n List<Campaign> getCampaigns();\n}",
"score": 0.8425703644752502
}
] |
java
|
if(campaign1.getId()==id){
|
package com.xxf.i18n.plugin.action;
import com.xxf.i18n.plugin.bean.StringEntity;
import com.xxf.i18n.plugin.utils.FileUtils;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.vfs.VirtualFile;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
public class ToStringXml extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
VirtualFile file = e.getData(PlatformDataKeys.VIRTUAL_FILE);
if (file == null) {
showHint("找不到目标文件");
return;
}
String extension = file.getExtension();
if (extension != null && extension.equalsIgnoreCase("xml")) {
if (!file.getParent().getName().startsWith("layout")) {
showError("请选择布局文件");
return;
}
}
//获取当前编辑器对象
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
//获取选择的数据模型
SelectionModel selectionModel = editor.getSelectionModel();
//获取当前选择的文本
String selectedText = selectionModel.getSelectedText();
StringBuilder sb = new StringBuilder();
try {
StringEntity singleStrings;
StringBuilder oldContent = new StringBuilder(); //整个file字串
try {
oldContent.append(new String(file.contentsToByteArray(), "utf-8")); //源文件整体字符串
} catch (IOException e1) {
e1.printStackTrace();
}
InputStream is = null;
try {
is = file.getInputStream(); //源文件layout下面的xml
singleStrings = extraStringEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent,
selectionModel.getSelectionEndPosition().line,selectedText);
if (singleStrings != null) {
sb.
|
append("\n <string name=\"" + singleStrings.getId() + "\">" + singleStrings.getValue() + "</string>");
|
FileUtils.replaceContentToFile(file.getPath(), oldContent.toString()); //保存到layout.xml
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
FileUtils.closeQuietly(is);
}
}catch (Exception ioException) {
ioException.printStackTrace();
}
//保存到strings.xml
VirtualFile resDir = file.getParent().getParent();//获取layout文件夹的父文件夹,看是不是res
//获取res文件夹下面的values
if (resDir.getName().equalsIgnoreCase("res")) {
VirtualFile[] chids = resDir.getChildren(); //获取res文件夹下面文件夹列表
for (VirtualFile chid : chids) { //遍历寻找values文件夹下面的strings文件
if (chid.getName().startsWith("values")) {
if (chid.isDirectory()) {
VirtualFile[] values = chid.getChildren();
for (VirtualFile value : values) {
if (value.getName().startsWith("strings")) { //找到第一个strings文件
try {
String content = new String(value.contentsToByteArray(), "utf-8"); //源文件内容
System.out.println("utf-8=" + content);
String result = content.replace("</resources>", sb.toString() + "\n</resources>"); //在最下方加上新的字串
FileUtils.replaceContentToFile(value.getPath(), result);//替换文件
showHint("转换成功!");
} catch (IOException e1) {
e1.printStackTrace();
showError(e1.getMessage());
}
}
}
}
}
}
}
//System.out.println(selectedText);
}
private int index = 0;
/* private void layoutChild(VirtualFile file, StringBuilder sb) {
index = 0;
String extension = file.getExtension();
if (extension != null && extension.equalsIgnoreCase("xml")) {
if (!file.getParent().getName().startsWith("layout")) {
showError("请选择布局文件");
return;
}
}
List<StringEntity> strings;
StringBuilder oldContent = new StringBuilder(); //整个file字串
try {
oldContent.append(new String(file.contentsToByteArray(), "utf-8")); //源文件整体字符串
} catch (IOException e1) {
e1.printStackTrace();
}
InputStream is = null;
try {
is = file.getInputStream(); //源文件layout下面的xml
strings = extraStringEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent);
if (strings != null) {
for (StringEntity string : strings) { //创建字符串
sb.append("\n <string name=\"" + string.getId() + "\">" + string.getValue() + "</string>");
}
FileUtils.replaceContentToFile(file.getPath(), oldContent.toString());
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
FileUtils.closeQuietly(is);
}
}*/
/*
* 传入源xml的文件流。文件名称,文件字符串
* */
private StringEntity extraStringEntity(InputStream is, String fileName, StringBuilder oldContent,int line,String oricontent) {
try {
return generateStrings(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is), fileName, oldContent,line, oricontent);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
/*
* 传入
* */
private StringEntity generateStrings(Node node, String fileName, StringBuilder oldContent,int line,String oricontent) {
StringEntity result = new StringEntity();
if (node.getNodeType() == Node.ELEMENT_NODE) {//文件换行节点
Node stringNode = node.getAttributes().getNamedItem("android:text"); //获取该名字的节点
if (stringNode != null) { //有值
String value = stringNode.getNodeValue();
if (!value.contains("@string")&&value.contains(oricontent)) { //判断是否已经是@字符串
final String id = fileName + "_text_" + (line); //命名方式:文件名称_text+_index
result=new StringEntity(id, value);
String newContent = oldContent.toString().replaceFirst("\"" + value + "\"", "\"@string/" + id + "\"");
oldContent = oldContent.replace(0, oldContent.length(), newContent);
return result;
}
}
Node hintNode = node.getAttributes().getNamedItem("android:hint");
if (hintNode != null) {
String value = hintNode.getNodeValue();
if (!value.contains("@string")&&value.contains(oricontent)) {
final String id = fileName + "_hint_text_" + (line);
result=new StringEntity(id, value);
String newContent = oldContent.toString().replaceFirst("\"" + value + "\"", "\"@string/" + id + "\"");
oldContent = oldContent.replace(0, oldContent.length(), newContent);
return result;
}
}
}
NodeList children = node.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
StringEntity itemresult = generateStrings(children.item(j), fileName, oldContent,line,oricontent);
if (itemresult!=null){
return itemresult;
}
}
return null;
}
private void showHint(String msg) {
Notifications.Bus.notify(new Notification("DavidString", "DavidString", msg, NotificationType.WARNING));
}
private void showError(String msg) {
Notifications.Bus.notify(new Notification("DavidString", "DavidString", msg, NotificationType.ERROR));
}
}
|
src/com/xxf/i18n/plugin/action/ToStringXml.java
|
NBXXF-XXFi18nPlugin-065127d
|
[
{
"filename": "src/com/xxf/i18n/plugin/action/IosDirAction.java",
"retrieved_chunk": " e1.printStackTrace();\n }\n InputStream is = null;\n try {\n is = file.getInputStream();\n //ios 文件名可以有+号\n strings = extraClassEntity(is, file.getNameWithoutExtension().toLowerCase().replaceAll(\"\\\\+\",\"_\"), oldContent,strDistinctMap);\n if (strings != null) {\n for (StringEntity string : strings) {\n sb.append(\"\\n\\\"\"+string.getId() + \"\\\"=\\\"\" + string.getValue() + \"\\\";\");",
"score": 0.9102635383605957
},
{
"filename": "src/com/xxf/i18n/plugin/action/AndroidDirAction.java",
"retrieved_chunk": " StringBuilder oldContent = new StringBuilder();\n try {\n oldContent.append(new String(file.contentsToByteArray(), \"utf-8\"));\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n InputStream is = null;\n try {\n is = file.getInputStream();\n strings = extraStringEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent);",
"score": 0.9079304933547974
},
{
"filename": "src/com/xxf/i18n/plugin/action/AndroidDirAction.java",
"retrieved_chunk": " if (strings != null) {\n for (StringEntity string : strings) {\n sb.append(\"\\n <string name=\\\"\" + string.getId() + \"\\\">\" + string.getValue() + \"</string>\");\n }\n FileUtils.replaceContentToFile(file.getPath(), oldContent.toString());\n }\n } catch (IOException e1) {\n e1.printStackTrace();\n } finally {\n FileUtils.closeQuietly(is);",
"score": 0.8980234265327454
},
{
"filename": "src/com/xxf/i18n/plugin/action/AndroidDirAction.java",
"retrieved_chunk": " try {\n oldContent.append(new String(file.contentsToByteArray(), \"utf-8\"));\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n InputStream is = null;\n try {\n is = file.getInputStream();\n strings = extraClassEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent, valueKeyMap);\n if (strings != null) {",
"score": 0.8958446979522705
},
{
"filename": "src/com/xxf/i18n/plugin/action/AndroidDirAction.java",
"retrieved_chunk": " layoutChild(eventFile, sb);\n }else{\n //遍历所有 kt文件,然后获取其中的字串写到stringbuilder里面去\n classChild(eventFile, sb);\n }\n int resultCount= valueKeyMap.size()-resultStart;\n try {\n if(!sb.isEmpty()) {\n String content = new String(targetStringFile.contentsToByteArray(), \"utf-8\"); //源文件内容\n String result = content.replace(\"</resources>\", sb.toString() + \"\\n</resources>\"); //在最下方加上新的字串",
"score": 0.8856374621391296
}
] |
java
|
append("\n <string name=\"" + singleStrings.getId() + "\">" + singleStrings.getValue() + "</string>");
|
package org.example.hmwk1.service.concretes;
import org.example.hmwk1.entity.Campaign;
import org.example.hmwk1.service.abstracts.CampaignService;
import java.util.ArrayList;
import java.util.List;
public class CampaignManager implements CampaignService {
List<Campaign> campaigns = new ArrayList<>();
@Override
public void addCampaign(Campaign campaign) {
if(campaigns.contains(campaign)){
System.out.println("Campaign already exist.");
}else{
campaigns.add(campaign);
System.out.println("Campaign added.");
}
}
@Override
public void deleteCampaign(Campaign campaign) {
campaigns.remove(campaign);
System.out.println("Campaign deleted");
}
@Override
public void deleteCampaignById(int id) {
for (Campaign campaign : campaigns) {
if
|
(campaign.getId() == id){
|
campaigns.remove(campaign);
System.out.println("Campaign deleted");
}
}
}
@Override
public void updateCampaign(int id, Campaign campaign) {
Campaign updateToCampaign = null;
for(Campaign campaign1: campaigns){
if(campaign1.getId()==id){
updateToCampaign = campaign1;
updateToCampaign.setGame(campaign.getGames().get(id));
updateToCampaign.setDiscountAmount(campaign.getDiscountAmount());
updateToCampaign.setDayTime(campaign.getDayTime());
}else{
System.out.println("Campaign is not found and also not updated");
}
}
}
@Override
public List<Campaign> getCampaigns() {
return campaigns;
}
}
|
src/main/java/org/example/hmwk1/service/concretes/CampaignManager.java
|
MuhammetTahaDemiryol-Turkcell-Homework-39026c6
|
[
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/GameManager.java",
"retrieved_chunk": " }\n @Override\n public void deleteGameById(int id) {\n for (Game game : games) {\n if(game.getId() == id){\n games.remove(game);\n System.out.println(\"Game deleted\");\n }\n }\n }",
"score": 0.8868666887283325
},
{
"filename": "src/main/java/org/example/hmwk1/service/abstracts/CampaignService.java",
"retrieved_chunk": "package org.example.hmwk1.service.abstracts;\nimport org.example.hmwk1.entity.Campaign;\nimport java.util.List;\npublic interface CampaignService {\n void addCampaign(Campaign campaign);\n void deleteCampaign(Campaign campaign);\n void deleteCampaignById(int id);\n void updateCampaign(int id,Campaign campaign);\n List<Campaign> getCampaigns();\n}",
"score": 0.8673889636993408
},
{
"filename": "src/main/java/org/example/hmwk1/Main.java",
"retrieved_chunk": " gameManager.getGames().stream().forEach(System.out::println);\n gameManager.deleteGame(game);\n gameManager.getGames().stream().forEach(System.out::println);\n gameManager.updateGame(1,new Game(1,\"Run\",250,\"Run\",0));\n System.out.println(\"***************************************************\");\n Campaign campaign = new Campaign(1,75,15,game4);\n Campaign campaign2 = new Campaign(2,75,15,game2);\n campaignManager.addCampaign(campaign);\n campaignManager.addCampaign(campaign2);\n campaignManager.getCampaigns().stream().forEach(System.out::println);",
"score": 0.8646870851516724
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/GameManager.java",
"retrieved_chunk": " System.out.println(\"Game already exist.\");\n }else{\n games.add(game);\n System.out.println(\"Game added.\");\n }\n }\n @Override\n public void deleteGame(Game game) {\n games.remove(game);\n System.out.println(\"Game deleted\");",
"score": 0.8505672216415405
},
{
"filename": "src/main/java/org/example/hmwk1/service/abstracts/GameService.java",
"retrieved_chunk": "package org.example.hmwk1.service.abstracts;\nimport org.example.hmwk1.entity.Campaign;\nimport org.example.hmwk1.entity.Game;\nimport java.util.List;\npublic interface GameService {\n void addGame(Game game);\n void deleteGame(Game game);\n void deleteGameById(int id);\n void updateGame(int id, Game game);\n List<Game> getGames();",
"score": 0.842220664024353
}
] |
java
|
(campaign.getId() == id){
|
package org.example.hmwk1.service.concretes;
import org.example.hmwk1.entity.Game;
import org.example.hmwk1.entity.Campaign;
import org.example.hmwk1.entity.Customer;
import org.example.hmwk1.service.abstracts.CampaignService;
import org.example.hmwk1.service.abstracts.SellingService;
import org.example.hmwk1.service.abstracts.UserService;
public class SellingManager implements SellingService {
private final CampaignService campaignService;
private final UserService userService;
public SellingManager(CampaignService campaignService,UserService userService) {
this.campaignService = campaignService;
this.userService = userService;
}
public void sell(Customer customer, Game game) {
if(customer.getGames().contains(game)){
System.out.println("bu oyuna zaten sahipsin");
return;
}
for(Campaign campaign:campaignService.getCampaigns()){
if(campaign.getGames().contains(game) ){
game.setCost(game.getCost()-(game.getCost()*campaign.getDiscountAmount()/100));
game.setCountOwner(game.getCountOwner()+1);
System.out.println("New Cost "+ game.getName()+" is "+game.getCost());
System.out.println("Game " + game.getName() + " sold to " + customer.getName());
customer.addGame(game);
}
}
if(
|
!(customer.getGames().contains(game))){
|
game.setCountOwner(game.getCountOwner() + 1);
customer.addGame(game);
System.out.println("Game " + game.getName() + " sold to " + customer.getName()+" cost: "+game.getCost());
}
}
}
|
src/main/java/org/example/hmwk1/service/concretes/SellingManager.java
|
MuhammetTahaDemiryol-Turkcell-Homework-39026c6
|
[
{
"filename": "src/main/java/org/example/hmwk1/Main.java",
"retrieved_chunk": " gameManager.getGames().stream().forEach(System.out::println);\n gameManager.deleteGame(game);\n gameManager.getGames().stream().forEach(System.out::println);\n gameManager.updateGame(1,new Game(1,\"Run\",250,\"Run\",0));\n System.out.println(\"***************************************************\");\n Campaign campaign = new Campaign(1,75,15,game4);\n Campaign campaign2 = new Campaign(2,75,15,game2);\n campaignManager.addCampaign(campaign);\n campaignManager.addCampaign(campaign2);\n campaignManager.getCampaigns().stream().forEach(System.out::println);",
"score": 0.8611319065093994
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/GameManager.java",
"retrieved_chunk": " System.out.println(\"Game already exist.\");\n }else{\n games.add(game);\n System.out.println(\"Game added.\");\n }\n }\n @Override\n public void deleteGame(Game game) {\n games.remove(game);\n System.out.println(\"Game deleted\");",
"score": 0.8602722883224487
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/CampaignManager.java",
"retrieved_chunk": " @Override\n public void updateCampaign(int id, Campaign campaign) {\n Campaign updateToCampaign = null;\n for(Campaign campaign1: campaigns){\n if(campaign1.getId()==id){\n updateToCampaign = campaign1;\n updateToCampaign.setGame(campaign.getGames().get(id));\n updateToCampaign.setDiscountAmount(campaign.getDiscountAmount());\n updateToCampaign.setDayTime(campaign.getDayTime());\n }else{",
"score": 0.850099503993988
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/CampaignManager.java",
"retrieved_chunk": " System.out.println(\"Campaign already exist.\");\n }else{\n campaigns.add(campaign);\n System.out.println(\"Campaign added.\");\n }\n }\n @Override\n public void deleteCampaign(Campaign campaign) {\n campaigns.remove(campaign);\n System.out.println(\"Campaign deleted\");",
"score": 0.8489354252815247
},
{
"filename": "src/main/java/org/example/hmwk1/Main.java",
"retrieved_chunk": " System.out.println(\"***************************************************\");\n sellingManager.sell(weasley,game);\n sellingManager.sell(weasley,game2);\n sellingManager.sell(weasley,game4);\n sellingManager.sell(weasley,game3);\n System.out.println(weasley);\n userManager.getCustomer(3).getGames().stream().forEach(System.out::println);\n }\n}",
"score": 0.8481254577636719
}
] |
java
|
!(customer.getGames().contains(game))){
|
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
System.out.println(playlist1.execute());
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator = player.createIterator();
|
while (iterator.temProximo()) {
|
PlaylistItem playlistItem = iterator.proximo();
String content = playlistItem.execute();
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
iterator = player.createIterator();
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
}
}
|
br/edu/ifba/inf011/Aplicacao.java
|
nando-cezar-design-patterns-music-19ebdb3
|
[
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerAllIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.iterator.PlaylistIterator;\n/* Concrete Iterator: Iterator pattern */\npublic class PlayerAllIterator implements PlaylistIterator {\n private final List<PlaylistItem> items;\n private Integer index;\n public PlayerAllIterator(List<PlaylistItem> items) {\n this.items = items;",
"score": 0.845517635345459
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerIterable.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Aggregate: Iterator pattern */\npublic interface PlayerIterable {\n\tvoid addItem(PlaylistItem item);\n\tvoid removeItem(PlaylistItem item);\n\tPlaylistIterator createIterator();\n}",
"score": 0.8449488878250122
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlaylistIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Iterator: Iterator pattern */\npublic interface PlaylistIterator {\n boolean temProximo();\n PlaylistItem proximo();\n}",
"score": 0.842876672744751
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.ArrayList;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.observer.PlayerListener;\n/* Concrete Aggregate: Iterator pattern */\n/* Subject: Observer pattern */\npublic class Player implements PlayerIterable {\n\tprivate final List<PlaylistItem> items;\n\tprivate final List<PlayerListener> listeners;",
"score": 0.8352901935577393
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerMode.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\npublic enum PlayerMode {\n\tPlayerAll {\n\t\t@Override\n\t\tpublic PlaylistIterator createIterator(List<PlaylistItem> items) {\n\t\t\treturn new PlayerAllIterator(items);\n\t\t}\n\t}, RepeatAll {",
"score": 0.8293448686599731
}
] |
java
|
while (iterator.temProximo()) {
|
package com.xxf.i18n.plugin.action;
import com.google.common.collect.Lists;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.StandardFileSystems;
import com.intellij.openapi.vfs.VirtualFile;
import com.xxf.i18n.plugin.bean.StringEntity;
import com.xxf.i18n.plugin.utils.FileUtils;
import com.xxf.i18n.plugin.utils.MessageUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 支持ios的.m文件自动抽取字符串
* Created by xyw on 2023/5/23.
*/
public class IosDirAction extends AnAction {
private int index = 0;
//避免重复 key 中文字符串 value 为已经生成的id
Map<String,String> valueKeyMap = new HashMap();
@Override
public void actionPerformed(AnActionEvent e) {
Project currentProject = e.getProject();
//检查项目的配置
String path= FileUtils.getConfigPathValue(currentProject);
if(path==null||path.length()<=0){
MessageUtils.showAlert(e,String.format("请在%s\n目录下面创建%s文件,且设置有效的生成文件路径(xxx.strings)",
FileUtils.getConfigPathDir(currentProject).getPath(),
FileUtils.getConfigPathFileName()));
return;
}
VirtualFile targetStringFile = StandardFileSystems.local().findFileByPath(path);
if (targetStringFile == null||!targetStringFile.exists()) {
MessageUtils.showAlert(e,String.format("请在%s\n目录下面创建%s文件,且设置有效的生成文件路径(xxx.strings)",
FileUtils.getConfigPathDir(currentProject).getPath(),
FileUtils.getConfigPathFileName()));
return;
}
String extension = targetStringFile.getExtension();
if (extension == null || !extension.equalsIgnoreCase("strings")) {
MessageUtils.showAlert(e,"生成的文件类型必须是strings");
return;
}
VirtualFile eventFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
if (eventFile == null) {
MessageUtils.showAlert(e,"找不到目标文件");
return;
}
valueKeyMap.clear();
//读取已经存在的 复用,这里建议都是按中文来
readFileToDict(targetStringFile);
StringBuilder sb = new StringBuilder();
int resultStart= valueKeyMap.size();
//扫描.m文件
classChild(eventFile,sb, valueKeyMap);
int resultCount= valueKeyMap.size()-resultStart;
try {
if(!sb.isEmpty()){
String content = new String(targetStringFile.contentsToByteArray(), "utf-8"); //源文件内容
String result = content+sb.toString();
FileUtils.replaceContentToFile(targetStringFile.getPath(), result);//替换文件
}
MessageUtils.showAlert(e,String.format("国际化执行完成,新生成(%d)条结果",resultCount));
} catch (IOException ex) {
ex.printStackTrace();
MessageUtils.showAlert(e,ex.getMessage());
}
e.getActionManager().getAction(IdeActions.ACTION_SYNCHRONIZE).actionPerformed(e);
}
/**
* 将已经存在字符串读取到字典里面 避免重复
* @param file
*/
private void readFileToDict( VirtualFile file){
try {
BufferedReader br
= new BufferedReader(new InputStreamReader(file.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
//"email_input_hint"="请输入邮箱";
if(line.endsWith(";")){
String[] split = line.split("=");
if(split!=null&&split.length==2){
String key=split[0].trim();
String value=split[1].trim();
if(key.startsWith("\"")&&key.endsWith("\"")){
key=key.substring(1,key.length()-1);
}
if(value.startsWith("\"")&&value.endsWith("\";")){
value=value.substring(1,value.length()-2);
}
if(!valueKeyMap.containsKey(value)){
valueKeyMap.put(value,key);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 执行 .m文件
* @param file
* @param sb
*/
private void classChild(VirtualFile file, StringBuilder sb,Map<String,String> strDistinctMap){
index = 0;
if(file.isDirectory()){
VirtualFile[] children = file.getChildren();
for (VirtualFile child : children) {
classChild(child,sb,strDistinctMap);
}
}else{
String extension = file.getExtension();
if (extension != null && extension.equalsIgnoreCase("m")) {
List<StringEntity> strings;
StringBuilder oldContent = new StringBuilder();
try {
oldContent.append(new String(file.contentsToByteArray(), "utf-8"));
} catch (IOException e1) {
e1.printStackTrace();
}
InputStream is = null;
try {
is = file.getInputStream();
//ios 文件名可以有+号
strings = extraClassEntity(is, file.getNameWithoutExtension().toLowerCase().replaceAll("\\+","_"), oldContent,strDistinctMap);
if (strings != null) {
for (StringEntity string : strings) {
sb.append("\n\""+string.getId() +
|
"\"=\"" + string.getValue() + "\";
|
");
}
FileUtils.replaceContentToFile(file.getPath(), oldContent.toString());
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
FileUtils.closeQuietly(is);
}
}
}
}
private List<StringEntity> extraClassEntity(InputStream is, String fileName, StringBuilder oldContent,Map<String,String> strDistinctMap) {
List<StringEntity> strings = Lists.newArrayList();
String resultText=replaceUsingSB(fileName,oldContent.toString(),strings,strDistinctMap);
oldContent = oldContent.replace(0, oldContent.length(), resultText);
return strings;
}
public String replaceUsingSB(String fileName, String str, List<StringEntity> strings,Map<String,String> strDistinctMap) {
StringBuilder sb = new StringBuilder(str.length());
Pattern p = Pattern.compile("(?=@\".{1,150}\")@\"[^$+,\\n\"{}]*[\\u4E00-\\u9FFF]+[^$+,\\n\"{}]*\"");
Matcher m = p.matcher(str);
int lastIndex = 0;
while (m.find()) {
sb.append(str, lastIndex, m.start());
String subStr=m.group();
//去除前后的双引号
if(subStr.startsWith("@\"")&&subStr.endsWith("\"")){
//这里截取
subStr=subStr.substring(2,subStr.length()-1);
}
//复用已经存在的
String id=strDistinctMap.get(subStr);
if(id==null||id.length()<=0){
//生成新的id
id = currentIdString(fileName);
strDistinctMap.put(subStr,id);
strings.add(new StringEntity(id, subStr));
}
sb.append("R.string.localized_"+id+"");
lastIndex = m.end();
}
sb.append(str.substring(lastIndex));
return sb.toString();
}
private String currentIdString(String fileName){
//需要加时间 多次生成的key避免错位和冲突,key 一样 内容不一样 合并风险太高
final String id = fileName +"_"+ System.currentTimeMillis() +"_" + (index++);
return id;
}
}
|
src/com/xxf/i18n/plugin/action/IosDirAction.java
|
NBXXF-XXFi18nPlugin-065127d
|
[
{
"filename": "src/com/xxf/i18n/plugin/action/AndroidDirAction.java",
"retrieved_chunk": " try {\n oldContent.append(new String(file.contentsToByteArray(), \"utf-8\"));\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n InputStream is = null;\n try {\n is = file.getInputStream();\n strings = extraClassEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent, valueKeyMap);\n if (strings != null) {",
"score": 0.9346883296966553
},
{
"filename": "src/com/xxf/i18n/plugin/action/AndroidDirAction.java",
"retrieved_chunk": " StringBuilder oldContent = new StringBuilder();\n try {\n oldContent.append(new String(file.contentsToByteArray(), \"utf-8\"));\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n InputStream is = null;\n try {\n is = file.getInputStream();\n strings = extraStringEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent);",
"score": 0.9163603186607361
},
{
"filename": "src/com/xxf/i18n/plugin/action/ToStringXml.java",
"retrieved_chunk": " } catch (IOException e1) {\n e1.printStackTrace();\n }\n InputStream is = null;\n try {\n is = file.getInputStream(); //源文件layout下面的xml\n strings = extraStringEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent);\n if (strings != null) {\n for (StringEntity string : strings) { //创建字符串\n sb.append(\"\\n <string name=\\\"\" + string.getId() + \"\\\">\" + string.getValue() + \"</string>\");",
"score": 0.915745735168457
},
{
"filename": "src/com/xxf/i18n/plugin/action/AndroidDirAction.java",
"retrieved_chunk": " }\n }\n }\n private List<StringEntity> extraClassEntity(InputStream is, String fileName, StringBuilder oldContent,Map<String,String> strDistinctMap) {\n List<StringEntity> strings = Lists.newArrayList();\n String resultText=replaceUsingSB(fileName,oldContent.toString(),strings,strDistinctMap);\n oldContent = oldContent.replace(0, oldContent.length(), resultText);\n return strings;\n }\n public String replaceUsingSB(String fileName, String str, List<StringEntity> strings,Map<String,String> strDistinctMap) {",
"score": 0.9107934236526489
},
{
"filename": "src/com/xxf/i18n/plugin/action/ToStringXml.java",
"retrieved_chunk": " InputStream is = null;\n try {\n is = file.getInputStream(); //源文件layout下面的xml\n singleStrings = extraStringEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent,\n selectionModel.getSelectionEndPosition().line,selectedText);\n if (singleStrings != null) {\n sb.append(\"\\n <string name=\\\"\" + singleStrings.getId() + \"\\\">\" + singleStrings.getValue() + \"</string>\");\n FileUtils.replaceContentToFile(file.getPath(), oldContent.toString()); //保存到layout.xml\n }\n } catch (IOException e1) {",
"score": 0.903560996055603
}
] |
java
|
"\"=\"" + string.getValue() + "\";
|
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
System.out
|
.println(playlist1.execute());
|
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator = player.createIterator();
while (iterator.temProximo()) {
PlaylistItem playlistItem = iterator.proximo();
String content = playlistItem.execute();
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
iterator = player.createIterator();
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
}
}
|
br/edu/ifba/inf011/Aplicacao.java
|
nando-cezar-design-patterns-music-19ebdb3
|
[
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaComNotaLetra = new MusicaNotas(musica);\n\t\tMusicaLetraOriginal musicaLetraOriginal = new MusicaLetraOriginal(musicaComNotaLetra);\n\t\treturn musicaLetraOriginal;\n\t}\n\tpublic MusicaBase createMusicaComNotaLetraOriginalTraduzida(String nome, String extensao)\n\t\t\tthrows IOException {\n\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaComNotaLetraOriginalTraduzida = new MusicaNotas(musica);\n\t\tMusicaLetraOriginal musicaLetraOriginal = new MusicaLetraOriginal(",
"score": 0.8392917513847351
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "\t\t\tResourceLoader.loader = new ResourceLoader();\n\t\t}\n\t\treturn ResourceLoader.loader;\n\t}\n\tpublic MusicaBase createMusicaSomenteComNota(String nome) throws IOException {\n\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaSomenteComNota = new MusicaNotas(musica);\n\t\treturn musicaSomenteComNota;\n\t}\n\tpublic MusicaBase createMusicaComNotaLetra(String nome) throws IOException {",
"score": 0.823941171169281
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "\t\t\t\tmusicaComNotaLetraOriginalTraduzida);\n\t\treturn new MusicaLetraTraduzida(musicaLetraOriginal, \"pt\");\n\t}\n\tpublic List<String> loadNotas(String nome) throws IOException {\n\t\treturn this.loadResource(nome, \"notas\");\n\t}\n\tpublic List<String> loadLetra(String nome) throws IOException {\n\t\treturn this.loadResource(nome, \"letra\");\n\t}\n\tpublic List<String> loadTraducao(String nome, String extensao) throws IOException {",
"score": 0.8196945190429688
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.resources;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.decorator.Musica;\nimport br.edu.ifba.inf011.model.decorator.MusicaNome;",
"score": 0.8049477338790894
},
{
"filename": "br/edu/ifba/inf011/model/composite/PlaylistItem.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.composite;\n/* Component: Composite pattern */\npublic interface PlaylistItem {\n\tString getNome();\n\tString execute();\n}",
"score": 0.7969263792037964
}
] |
java
|
.println(playlist1.execute());
|
package br.edu.ifba.inf011.model.iterator;
import java.util.ArrayList;
import java.util.List;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.observer.PlayerListener;
/* Concrete Aggregate: Iterator pattern */
/* Subject: Observer pattern */
public class Player implements PlayerIterable {
private final List<PlaylistItem> items;
private final List<PlayerListener> listeners;
private PlayerMode mode;
public Player() {
this.items = new ArrayList<>();
this.listeners = new ArrayList<>();
this.mode = PlayerMode.PlayerAll;
}
@Override
public void addItem(PlaylistItem item) {
this.items.add(item);
}
@Override
public void removeItem(PlaylistItem item) {
this.items.remove(item);
}
@Override
public PlaylistIterator createIterator() {
return this.mode.createIterator(items);
}
public void setMode(PlayerMode mode) {
this.mode = mode;
notificar();
}
public PlayerMode getMode(){
return this.mode;
}
public void addListeners(PlayerListener listener) {
this.listeners.add(listener);
}
public void removeListener(PlayerListener listener) {
this.listeners.remove(listener);
}
public void notificar() {
for (PlayerListener listener : listeners) {
|
listener.onChangeMode();
|
}
}
}
|
br/edu/ifba/inf011/model/iterator/Player.java
|
nando-cezar-design-patterns-music-19ebdb3
|
[
{
"filename": "br/edu/ifba/inf011/model/observer/PlayerListener.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.observer;\n/* Observer: Observer pattern */\n@FunctionalInterface\npublic interface PlayerListener {\n void onChangeMode();\n}",
"score": 0.8612325191497803
},
{
"filename": "br/edu/ifba/inf011/Aplicacao.java",
"retrieved_chunk": "\tpublic void onChangeMode() {\n\t\tSystem.out.printf(\"\\n::::::::::::\\nModo: %s, está ativado!\\n\", player.getMode());\n\t}\n}",
"score": 0.8440595865249634
},
{
"filename": "br/edu/ifba/inf011/Aplicacao.java",
"retrieved_chunk": "import br.edu.ifba.inf011.model.resources.ResourceLoader;\n/* Concrete Observer: Observer pattern */\npublic class Aplicacao implements PlayerListener {\n\tprivate final Player player;\n\tpublic Aplicacao() {\n\t\tthis.player = new Player();\n\t\tthis.player.addListeners(this);\n\t}\n\tpublic static void main(String[] args) throws IOException, InterruptedException {\n\t\tAplicacao app = new Aplicacao();",
"score": 0.8001726865768433
},
{
"filename": "br/edu/ifba/inf011/Aplicacao.java",
"retrieved_chunk": "\t\t\tif (numero % 5 == 0){\n\t\t\t\tplayer.setMode(PlayerMode.RepeatAll);\n\t\t\t\titerator = player.createIterator();\n\t\t\t}else if (numero % 7 == 0){\n\t\t\t\tplayer.setMode(PlayerMode.RandomMode);\n\t\t\t\titerator = player.createIterator();\n\t\t\t}\n\t\t}\n\t}\n\t@Override",
"score": 0.7827455997467041
},
{
"filename": "br/edu/ifba/inf011/Aplicacao.java",
"retrieved_chunk": "package br.edu.ifba.inf011;\nimport java.io.IOException;\nimport java.util.Random;\nimport br.edu.ifba.inf011.model.iterator.Player;\nimport br.edu.ifba.inf011.model.iterator.PlayerMode;\nimport br.edu.ifba.inf011.model.composite.Playlist;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.iterator.PlaylistIterator;\nimport br.edu.ifba.inf011.model.decorator.MusicaBase;\nimport br.edu.ifba.inf011.model.observer.PlayerListener;",
"score": 0.7751895785331726
}
] |
java
|
listener.onChangeMode();
|
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
System.out.println(playlist1.execute());
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator = player.createIterator();
while (iterator.temProximo()) {
PlaylistItem playlistItem = iterator.proximo();
String content
|
= playlistItem.execute();
|
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
iterator = player.createIterator();
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
}
}
|
br/edu/ifba/inf011/Aplicacao.java
|
nando-cezar-design-patterns-music-19ebdb3
|
[
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "\t\t}\n\t\treturn playlistItem;\n\t}\n\t@Override\n\tpublic String execute() {\n\t\tStringBuffer str = new StringBuffer();\n\t\tfor (PlaylistItem item : items) {\n\t\t\tstr.append(item.execute());\n\t\t}\n\t\treturn str.toString();",
"score": 0.8150676488876343
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerAllIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.iterator.PlaylistIterator;\n/* Concrete Iterator: Iterator pattern */\npublic class PlayerAllIterator implements PlaylistIterator {\n private final List<PlaylistItem> items;\n private Integer index;\n public PlayerAllIterator(List<PlaylistItem> items) {\n this.items = items;",
"score": 0.8135125637054443
},
{
"filename": "br/edu/ifba/inf011/model/composite/PlaylistItem.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.composite;\n/* Component: Composite pattern */\npublic interface PlaylistItem {\n\tString getNome();\n\tString execute();\n}",
"score": 0.8117917776107788
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerIterable.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Aggregate: Iterator pattern */\npublic interface PlayerIterable {\n\tvoid addItem(PlaylistItem item);\n\tvoid removeItem(PlaylistItem item);\n\tPlaylistIterator createIterator();\n}",
"score": 0.8107470273971558
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaComNotaLetra = new MusicaNotas(musica);\n\t\tMusicaLetraOriginal musicaLetraOriginal = new MusicaLetraOriginal(musicaComNotaLetra);\n\t\treturn musicaLetraOriginal;\n\t}\n\tpublic MusicaBase createMusicaComNotaLetraOriginalTraduzida(String nome, String extensao)\n\t\t\tthrows IOException {\n\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaComNotaLetraOriginalTraduzida = new MusicaNotas(musica);\n\t\tMusicaLetraOriginal musicaLetraOriginal = new MusicaLetraOriginal(",
"score": 0.8086854219436646
}
] |
java
|
= playlistItem.execute();
|
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
|
playlist1.insert(playlist2);
|
System.out.println(playlist1.execute());
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator = player.createIterator();
while (iterator.temProximo()) {
PlaylistItem playlistItem = iterator.proximo();
String content = playlistItem.execute();
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
iterator = player.createIterator();
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
}
}
|
br/edu/ifba/inf011/Aplicacao.java
|
nando-cezar-design-patterns-music-19ebdb3
|
[
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaComNotaLetra = new MusicaNotas(musica);\n\t\tMusicaLetraOriginal musicaLetraOriginal = new MusicaLetraOriginal(musicaComNotaLetra);\n\t\treturn musicaLetraOriginal;\n\t}\n\tpublic MusicaBase createMusicaComNotaLetraOriginalTraduzida(String nome, String extensao)\n\t\t\tthrows IOException {\n\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaComNotaLetraOriginalTraduzida = new MusicaNotas(musica);\n\t\tMusicaLetraOriginal musicaLetraOriginal = new MusicaLetraOriginal(",
"score": 0.866515040397644
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "\t\t\tResourceLoader.loader = new ResourceLoader();\n\t\t}\n\t\treturn ResourceLoader.loader;\n\t}\n\tpublic MusicaBase createMusicaSomenteComNota(String nome) throws IOException {\n\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaSomenteComNota = new MusicaNotas(musica);\n\t\treturn musicaSomenteComNota;\n\t}\n\tpublic MusicaBase createMusicaComNotaLetra(String nome) throws IOException {",
"score": 0.8451119661331177
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "\t\t\t\tmusicaComNotaLetraOriginalTraduzida);\n\t\treturn new MusicaLetraTraduzida(musicaLetraOriginal, \"pt\");\n\t}\n\tpublic List<String> loadNotas(String nome) throws IOException {\n\t\treturn this.loadResource(nome, \"notas\");\n\t}\n\tpublic List<String> loadLetra(String nome) throws IOException {\n\t\treturn this.loadResource(nome, \"letra\");\n\t}\n\tpublic List<String> loadTraducao(String nome, String extensao) throws IOException {",
"score": 0.8401357531547546
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.resources;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.decorator.Musica;\nimport br.edu.ifba.inf011.model.decorator.MusicaNome;",
"score": 0.8270137310028076
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "import br.edu.ifba.inf011.model.decorator.MusicaBase;\nimport br.edu.ifba.inf011.model.decorator.MusicaLetraOriginal;\nimport br.edu.ifba.inf011.model.decorator.MusicaLetraTraduzida;\nimport br.edu.ifba.inf011.model.decorator.MusicaNotas;\npublic class ResourceLoader {\n\tprivate static final String DIR_NAME =\n\t\t\tSystem.getProperty(\"user.dir\") + \"\\\\br\\\\edu\\\\ifba\\\\inf011\\\\model\\\\resources\\\\data\\\\\";\n\tprivate static ResourceLoader loader = null;\n\tpublic static ResourceLoader instance() {\n\t\tif (ResourceLoader.loader == null) {",
"score": 0.8094629645347595
}
] |
java
|
playlist1.insert(playlist2);
|
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
System.out.println(playlist1.execute());
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator = player.createIterator();
while (iterator.temProximo()) {
PlaylistItem playlistItem = iterator.proximo();
String content = playlistItem.execute();
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
|
iterator = player.createIterator();
|
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
}
}
|
br/edu/ifba/inf011/Aplicacao.java
|
nando-cezar-design-patterns-music-19ebdb3
|
[
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerMode.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\npublic enum PlayerMode {\n\tPlayerAll {\n\t\t@Override\n\t\tpublic PlaylistIterator createIterator(List<PlaylistItem> items) {\n\t\t\treturn new PlayerAllIterator(items);\n\t\t}\n\t}, RepeatAll {",
"score": 0.8375027179718018
},
{
"filename": "br/edu/ifba/inf011/model/iterator/RandomModeIterator.java",
"retrieved_chunk": "\tpublic RandomModeIterator(List<PlaylistItem> items) {\n\t\tthis.items = items;\n\t\tthis.random = new Random();\n\t}\n\t@Override\n\tpublic boolean temProximo() {\n\t\treturn true;\n\t}\n\t@Override\n\tpublic PlaylistItem proximo() {",
"score": 0.8355669379234314
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerAllIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.iterator.PlaylistIterator;\n/* Concrete Iterator: Iterator pattern */\npublic class PlayerAllIterator implements PlaylistIterator {\n private final List<PlaylistItem> items;\n private Integer index;\n public PlayerAllIterator(List<PlaylistItem> items) {\n this.items = items;",
"score": 0.8321067690849304
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlaylistIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Iterator: Iterator pattern */\npublic interface PlaylistIterator {\n boolean temProximo();\n PlaylistItem proximo();\n}",
"score": 0.8273404836654663
},
{
"filename": "br/edu/ifba/inf011/model/iterator/RepeatAllIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.iterator.PlaylistIterator;\n/* Concrete Iterator: Iterator pattern */\npublic class RepeatAllIterator implements PlaylistIterator {\n\tprivate final List<PlaylistItem> items;\n\tprivate Integer index;\n\tpublic RepeatAllIterator(List<PlaylistItem> items) {\n\t\tthis.items = items;",
"score": 0.8269243836402893
}
] |
java
|
iterator = player.createIterator();
|
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
System.out.println(playlist1.execute());
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator = player.createIterator();
while (iterator.temProximo()) {
PlaylistItem
|
playlistItem = iterator.proximo();
|
String content = playlistItem.execute();
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
iterator = player.createIterator();
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
}
}
|
br/edu/ifba/inf011/Aplicacao.java
|
nando-cezar-design-patterns-music-19ebdb3
|
[
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerAllIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.iterator.PlaylistIterator;\n/* Concrete Iterator: Iterator pattern */\npublic class PlayerAllIterator implements PlaylistIterator {\n private final List<PlaylistItem> items;\n private Integer index;\n public PlayerAllIterator(List<PlaylistItem> items) {\n this.items = items;",
"score": 0.8313134908676147
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerIterable.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Aggregate: Iterator pattern */\npublic interface PlayerIterable {\n\tvoid addItem(PlaylistItem item);\n\tvoid removeItem(PlaylistItem item);\n\tPlaylistIterator createIterator();\n}",
"score": 0.8296089172363281
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlaylistIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Iterator: Iterator pattern */\npublic interface PlaylistIterator {\n boolean temProximo();\n PlaylistItem proximo();\n}",
"score": 0.8258705139160156
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.ArrayList;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.observer.PlayerListener;\n/* Concrete Aggregate: Iterator pattern */\n/* Subject: Observer pattern */\npublic class Player implements PlayerIterable {\n\tprivate final List<PlaylistItem> items;\n\tprivate final List<PlayerListener> listeners;",
"score": 0.8207036256790161
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaComNotaLetra = new MusicaNotas(musica);\n\t\tMusicaLetraOriginal musicaLetraOriginal = new MusicaLetraOriginal(musicaComNotaLetra);\n\t\treturn musicaLetraOriginal;\n\t}\n\tpublic MusicaBase createMusicaComNotaLetraOriginalTraduzida(String nome, String extensao)\n\t\t\tthrows IOException {\n\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaComNotaLetraOriginalTraduzida = new MusicaNotas(musica);\n\t\tMusicaLetraOriginal musicaLetraOriginal = new MusicaLetraOriginal(",
"score": 0.8202858567237854
}
] |
java
|
playlistItem = iterator.proximo();
|
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
System.out.println(playlist1.execute());
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator = player.createIterator();
while (iterator.temProximo()) {
PlaylistItem playlistItem = iterator.proximo();
String content = playlistItem.execute();
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
iterator = player.createIterator();
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf
|
("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
|
}
}
|
br/edu/ifba/inf011/Aplicacao.java
|
nando-cezar-design-patterns-music-19ebdb3
|
[
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "\t}\n\tpublic void notificar() {\n\t\tfor (PlayerListener listener : listeners) {\n\t\t\tlistener.onChangeMode();\n\t\t}\n\t}\n}",
"score": 0.8456860780715942
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "\t\tnotificar();\n\t}\n\tpublic PlayerMode getMode(){\n\t\treturn this.mode;\n\t}\n\tpublic void addListeners(PlayerListener listener) {\n\t\tthis.listeners.add(listener);\n\t}\n\tpublic void removeListener(PlayerListener listener) {\n\t\tthis.listeners.remove(listener);",
"score": 0.8226176500320435
},
{
"filename": "br/edu/ifba/inf011/model/observer/PlayerListener.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.observer;\n/* Observer: Observer pattern */\n@FunctionalInterface\npublic interface PlayerListener {\n void onChangeMode();\n}",
"score": 0.8194929957389832
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerMode.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\npublic enum PlayerMode {\n\tPlayerAll {\n\t\t@Override\n\t\tpublic PlaylistIterator createIterator(List<PlaylistItem> items) {\n\t\t\treturn new PlayerAllIterator(items);\n\t\t}\n\t}, RepeatAll {",
"score": 0.8016670346260071
},
{
"filename": "br/edu/ifba/inf011/model/decorator/MusicaNome.java",
"retrieved_chunk": "\t\treturn this.linha > 0;\n\t}\n\t@Override\n\tpublic String play() {\n\t\tif (!this.finish()) {\n\t\t\tthis.linha++;\n\t\t\treturn \"\\n---------: \\t\\t\" + this.getNome() + \"\\n\";\n\t\t}\n\t\treturn this.execute();\n\t}",
"score": 0.7973144054412842
}
] |
java
|
("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
|
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
System.out.println(playlist1.execute());
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator =
|
player.createIterator();
|
while (iterator.temProximo()) {
PlaylistItem playlistItem = iterator.proximo();
String content = playlistItem.execute();
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
iterator = player.createIterator();
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
}
}
|
br/edu/ifba/inf011/Aplicacao.java
|
nando-cezar-design-patterns-music-19ebdb3
|
[
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerIterable.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Aggregate: Iterator pattern */\npublic interface PlayerIterable {\n\tvoid addItem(PlaylistItem item);\n\tvoid removeItem(PlaylistItem item);\n\tPlaylistIterator createIterator();\n}",
"score": 0.8432663679122925
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerAllIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.iterator.PlaylistIterator;\n/* Concrete Iterator: Iterator pattern */\npublic class PlayerAllIterator implements PlaylistIterator {\n private final List<PlaylistItem> items;\n private Integer index;\n public PlayerAllIterator(List<PlaylistItem> items) {\n this.items = items;",
"score": 0.8432484865188599
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.ArrayList;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.observer.PlayerListener;\n/* Concrete Aggregate: Iterator pattern */\n/* Subject: Observer pattern */\npublic class Player implements PlayerIterable {\n\tprivate final List<PlaylistItem> items;\n\tprivate final List<PlayerListener> listeners;",
"score": 0.8364377617835999
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlaylistIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Iterator: Iterator pattern */\npublic interface PlaylistIterator {\n boolean temProximo();\n PlaylistItem proximo();\n}",
"score": 0.8323221206665039
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaComNotaLetra = new MusicaNotas(musica);\n\t\tMusicaLetraOriginal musicaLetraOriginal = new MusicaLetraOriginal(musicaComNotaLetra);\n\t\treturn musicaLetraOriginal;\n\t}\n\tpublic MusicaBase createMusicaComNotaLetraOriginalTraduzida(String nome, String extensao)\n\t\t\tthrows IOException {\n\t\tMusica musica = new MusicaNome(nome);\n\t\tMusicaNotas musicaComNotaLetraOriginalTraduzida = new MusicaNotas(musica);\n\t\tMusicaLetraOriginal musicaLetraOriginal = new MusicaLetraOriginal(",
"score": 0.829332709312439
}
] |
java
|
player.createIterator();
|
package com.xxf.i18n.plugin.action;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.StandardFileSystems;
import com.xxf.i18n.plugin.bean.StringEntity;
import com.xxf.i18n.plugin.utils.AndroidStringFileUtils;
import com.xxf.i18n.plugin.utils.FileUtils;
import com.google.common.collect.Lists;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.vfs.VirtualFile;
import com.xxf.i18n.plugin.utils.MessageUtils;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* layout或者java(仅支持kt)文件夹转成strings
* Created by xyw on 2023/5/21.
*/
public class AndroidDirAction extends AnAction {
/**
*解析的属性名
*/
private List<String> textAttributeNamesList = Arrays.asList("android:text","android:hint","app:leftText","app:rightText","app:titleText");
private int index = 0;
//避免重复 key 中文字符串 value 为已经生成的id
Map<String,String> valueKeyMap = new HashMap();
@Override
public void actionPerformed(AnActionEvent e) {
Project currentProject = e.getProject();
//检查项目的配置
String path= FileUtils.getConfigPathValue(currentProject);
if(path==null||path.length()<=0){
MessageUtils.showAlert(e,String.format("请在%s\n目录下面创建%s文件,且设置有效的生成文件路径(string.xml)",
FileUtils.getConfigPathDir(currentProject).getPath(),
FileUtils.getConfigPathFileName()));
return;
}
VirtualFile targetStringFile = StandardFileSystems.local().findFileByPath(path);
if (targetStringFile == null||!targetStringFile.exists()) {
MessageUtils.showAlert(e,String.format("请在%s\n目录下面创建%s文件,且设置有效的生成文件路径(string.xml)",
FileUtils.getConfigPathDir(currentProject).getPath(),
FileUtils.getConfigPathFileName()));
return;
}
String extension = targetStringFile.getExtension();
if (extension == null || !extension.equalsIgnoreCase("xml")) {
MessageUtils.showAlert(e,"生成的文件类型必须是string.xml");
return;
}
VirtualFile eventFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
if (eventFile == null) {
MessageUtils.showAlert(e,"找不到目标文件");
return;
}
valueKeyMap.clear();
//读取已经存在的 复用,这里建议都是按中文来
readFileToDict(targetStringFile);
int resultStart= valueKeyMap.size();
StringBuilder sb = new StringBuilder();
//layout 目录 可能是pad layout_s600dp等等
if(eventFile.isDirectory() && eventFile.getName().startsWith("layout")) {
//遍历所有layout文件,然后获取其中的字串写到stringbuilder里面去
VirtualFile[] children = eventFile.getChildren();
for (VirtualFile child : children) {
layoutChild(child, sb);
}
}else if(eventFile.getExtension()!=null && eventFile.getExtension().equalsIgnoreCase("xml")){
//可能是layout布局文件
layoutChild(eventFile, sb);
}else{
//遍历所有 kt文件,然后获取其中的字串写到stringbuilder里面去
classChild(eventFile, sb);
}
int resultCount= valueKeyMap.size()-resultStart;
try {
if(!sb.isEmpty()) {
String content = new String(targetStringFile.contentsToByteArray(), "utf-8"); //源文件内容
String result = content.replace("</resources>", sb.toString() + "\n</resources>"); //在最下方加上新的字串
FileUtils.replaceContentToFile(targetStringFile.getPath(), result);//替换文件
}
Map<String, List<String>> repeatRecords = AndroidStringFileUtils.getRepeatRecords(targetStringFile);
StringBuilder repeatStringBuilder=new StringBuilder("重复条数:"+repeatRecords.size());
if(repeatRecords.size()>0){
repeatStringBuilder.append("\n请确认是否xxf_i18n_plugin_path.txt是中文清单,否则去重没有意义");
repeatStringBuilder.append("\n请确认是否xxf_i18n_plugin_path.txt是中文清单,否则去重没有意义");
}
for(Map.Entry<String,List<String>> entry : repeatRecords.entrySet()){
repeatStringBuilder.append("\nvalue:"+entry.getKey());
repeatStringBuilder.append("\nkeys:");
for (String key:entry.getValue()) {
repeatStringBuilder.append("\n");
repeatStringBuilder.append(key);
}
repeatStringBuilder.append("\n\n");
}
MessageUtils.showAlert(e,String.format("国际化执行完成,新生成(%d)条结果,%s", resultCount,repeatStringBuilder.toString()));
} catch (IOException ex) {
ex.printStackTrace();
MessageUtils.showAlert(e,ex.getMessage());
}
e.getActionManager().getAction(IdeActions.ACTION_SYNCHRONIZE).actionPerformed(e);
}
/**
* 将已经存在字符串读取到字典里面 避免重复
* @param file
*/
private void readFileToDict(VirtualFile file){
InputStream is = null;
try {
is = file.getInputStream();
// String str="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
// "<resources>\n" +
// " <string name=\"flowus_app_name\">FlowUs 息流</string>\n" +
// " <string name=\"app_name\">FlowUs 息流</string>\n" +
// " <string name=\"ok\">确定</string>\n" +
// "</resources>";
// is =new ByteArrayInputStream(str.getBytes());
Node node=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
this.findStringNode(node);
} catch (Throwable ex) {
ex.printStackTrace();
} finally {
FileUtils.closeQuietly(is);
}
}
private void findStringNode(Node node){
if (node.getNodeType() == Node.ELEMENT_NODE
&&"string".equals(node.getNodeName())) {
Node key = node.getAttributes().getNamedItem("name");
if(key!=null) {
String valueKey=node.getTextContent();
if(!this.valueKeyMap.containsKey(valueKey)){
this.valueKeyMap.put(valueKey,key.getNodeValue());
}
}
}
NodeList children = node.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
findStringNode(children.item(j));
}
}
/**
* 执行 java 文件和kt文件
* @param file
* @param sb
*/
private void classChild(VirtualFile file, StringBuilder sb){
index = 0;
if(file.isDirectory()){
VirtualFile[] children = file.getChildren();
for (VirtualFile child : children) {
classChild(child,sb);
}
}else{
String extension = file.getExtension();
if (extension != null && extension.equalsIgnoreCase("kt")) {
List<StringEntity> strings;
StringBuilder oldContent = new StringBuilder();
try {
oldContent.append(new String(file.contentsToByteArray(), "utf-8"));
} catch (IOException e1) {
e1.printStackTrace();
}
InputStream is = null;
try {
is = file.getInputStream();
strings = extraClassEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent, valueKeyMap);
if (strings != null) {
for (StringEntity string : strings) {
sb.append("\n <string name=\"" + string.getId() + "\">" + string.getValue() + "</string>");
}
FileUtils.replaceContentToFile(file.getPath(), oldContent.toString());
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
FileUtils.closeQuietly(is);
}
}
}
}
private List<StringEntity> extraClassEntity(InputStream is, String fileName, StringBuilder oldContent,Map<String,String> strDistinctMap) {
List<StringEntity> strings = Lists.newArrayList();
String resultText=replaceUsingSB(fileName,oldContent.toString(),strings,strDistinctMap);
oldContent = oldContent.replace(0, oldContent.length(), resultText);
return strings;
}
public String replaceUsingSB(String fileName, String str, List<StringEntity> strings,Map<String,String> strDistinctMap) {
StringBuilder sb = new StringBuilder(str.length());
Pattern p = Pattern.compile("(?=\".{1,60}\")\"[^$+,\\n\"{}]*[\\u4E00-\\u9FFF]+[^$+,\\n\"{}]*\"");
Matcher m = p.matcher(str);
int lastIndex = 0;
while (m.find()) {
sb.append(str, lastIndex, m.start());
String value=m.group();
//去除前后的双引号
if(value.startsWith("\"")&&value.endsWith("\"")){
value=value.substring(1,value.length()-1);
}
//复用已经存在的
String id=strDistinctMap.get(value);
if(id==null||id.length()<=0){
//生成新的id
id = currentIdString(fileName);
strDistinctMap.put(value,id);
strings.add(new StringEntity(id, value));
}
sb.append("com.xxf.application.applicationContext.getString(com.next.space.cflow.resources.R.string."+id+")");
lastIndex = m.end();
}
sb.append(str.substring(lastIndex));
return sb.toString();
}
/**
* 递归执行layout xml
* @param file
* @param sb
*/
private void layoutChild(VirtualFile file, StringBuilder sb) {
index = 0;
String extension = file.getExtension();
if (extension != null && extension.equalsIgnoreCase("xml")) {
if (!file.getParent().getName().startsWith("layout")) {
|
MessageUtils.showNotify("请选择布局文件");
|
return;
}
}
List<StringEntity> strings;
StringBuilder oldContent = new StringBuilder();
try {
oldContent.append(new String(file.contentsToByteArray(), "utf-8"));
} catch (IOException e1) {
e1.printStackTrace();
}
InputStream is = null;
try {
is = file.getInputStream();
strings = extraStringEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent);
if (strings != null) {
for (StringEntity string : strings) {
sb.append("\n <string name=\"" + string.getId() + "\">" + string.getValue() + "</string>");
}
FileUtils.replaceContentToFile(file.getPath(), oldContent.toString());
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
FileUtils.closeQuietly(is);
}
}
private List<StringEntity> extraStringEntity(InputStream is, String fileName, StringBuilder oldContent) {
List<StringEntity> strings = Lists.newArrayList();
try {
return generateStrings(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is), strings, fileName, oldContent);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
private String currentIdString(String fileName){
//需要加时间 多次生成的key避免错位和冲突,key 一样 内容不一样 合并风险太高
final String id = fileName +"_"+ System.currentTimeMillis() +"_" + (index++);
return id;
}
private List<StringEntity> generateStrings(Node node, List<StringEntity> strings, String fileName, StringBuilder oldContent) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
NamedNodeMap attributes = node.getAttributes();
for (int i = 0; i <attributes.getLength() ; i++) {
Node item = attributes.item(i);
if(textAttributeNamesList.contains(item.getNodeName())){
String value = item.getNodeValue();
if (value!=null && !value.contains("@string")) {
//复用已经存在的
String id= valueKeyMap.get(value);
if(id==null||id.length()<=0){
//生成新的id
id = currentIdString(fileName);
valueKeyMap.put(value,id);
strings.add(new StringEntity(id, value));
}
String newContent = oldContent.toString().replaceFirst("\"" + value + "\"", "\"@string/" + id + "\"");
oldContent = oldContent.replace(0, oldContent.length(), newContent);
}
}
}
}
NodeList children = node.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
generateStrings(children.item(j), strings, fileName, oldContent);
}
return strings;
}
}
|
src/com/xxf/i18n/plugin/action/AndroidDirAction.java
|
NBXXF-XXFi18nPlugin-065127d
|
[
{
"filename": "src/com/xxf/i18n/plugin/action/ToStringXml.java",
"retrieved_chunk": " if (extension != null && extension.equalsIgnoreCase(\"xml\")) {\n if (!file.getParent().getName().startsWith(\"layout\")) {\n showError(\"请选择布局文件\");\n return;\n }\n }\n List<StringEntity> strings;\n StringBuilder oldContent = new StringBuilder(); //整个file字串\n try {\n oldContent.append(new String(file.contentsToByteArray(), \"utf-8\")); //源文件整体字符串",
"score": 0.8884577751159668
},
{
"filename": "src/com/xxf/i18n/plugin/action/ToStringXml.java",
"retrieved_chunk": " }\n }\n }\n }\n //System.out.println(selectedText);\n }\n private int index = 0;\n /* private void layoutChild(VirtualFile file, StringBuilder sb) {\n index = 0;\n String extension = file.getExtension();",
"score": 0.884000837802887
},
{
"filename": "src/com/xxf/i18n/plugin/action/IosDirAction.java",
"retrieved_chunk": " /**\n * 执行 .m文件\n * @param file\n * @param sb\n */\n private void classChild(VirtualFile file, StringBuilder sb,Map<String,String> strDistinctMap){\n index = 0;\n if(file.isDirectory()){\n VirtualFile[] children = file.getChildren();\n for (VirtualFile child : children) {",
"score": 0.8590154051780701
},
{
"filename": "src/com/xxf/i18n/plugin/action/ToStringXml.java",
"retrieved_chunk": " InputStream is = null;\n try {\n is = file.getInputStream(); //源文件layout下面的xml\n singleStrings = extraStringEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent,\n selectionModel.getSelectionEndPosition().line,selectedText);\n if (singleStrings != null) {\n sb.append(\"\\n <string name=\\\"\" + singleStrings.getId() + \"\\\">\" + singleStrings.getValue() + \"</string>\");\n FileUtils.replaceContentToFile(file.getPath(), oldContent.toString()); //保存到layout.xml\n }\n } catch (IOException e1) {",
"score": 0.84996098279953
},
{
"filename": "src/com/xxf/i18n/plugin/action/ToStringXml.java",
"retrieved_chunk": " if (!file.getParent().getName().startsWith(\"layout\")) {\n showError(\"请选择布局文件\");\n return;\n }\n }\n //获取当前编辑器对象\n Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);\n //获取选择的数据模型\n SelectionModel selectionModel = editor.getSelectionModel();\n //获取当前选择的文本",
"score": 0.8482226729393005
}
] |
java
|
MessageUtils.showNotify("请选择布局文件");
|
package core;
import statements.Statement;
import java.awt.*;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
long time;
long compileTime;
long writeTime;
File inputFile;
String outPutDirectory = "VirtualMachine/";
if (args.length == 1) {
inputFile = new File(args[0]);
} else if (args.length == 2) {
inputFile = new File(args[0]);
outPutDirectory = args[1];
} else inputFile = new File(selectFile());
time = System.nanoTime();
List<Lexer.Token> tokens = tokenizeFile(inputFile);
Parser parser = new Parser(tokens);
Queue<Statement> statements = parser.getStatements();
compileTime = ((System.nanoTime() - time) / 1_000_000);
time = System.nanoTime();
generateBytecodeFile(outPutDirectory + inputFile.getName(), statements);
writeTime = ((System.nanoTime() - time) / 1_000_000);
System.out.println("Compile time: " + compileTime + "ms");
System.out.println("Writing time: " + writeTime + "ms");
System.out.println("Total time: " + (compileTime + writeTime) + "ms");
System.exit(0);
}
// Returns a list of tokens which got generated based on provided file
private static List<Lexer.Token> tokenizeFile(File file) {
List<Lexer.Token> tokens = new LinkedList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String s;
while ((s = reader.readLine()) != null)
|
tokens.addAll(Lexer.tokenize(s));
|
reader.close();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
return tokens;
}
private static void generateBytecodeFile(String fileIdentifier, Queue<Statement> statements) {
File byteCode = new File(fileIdentifier.substring(0, fileIdentifier.length() - 3) + ".sks");
try (FileWriter writer = new FileWriter(byteCode)) {
while (!statements.isEmpty())
writer.write(statements.poll().toString() + "\n");
} catch (IOException exception) {
exception.printStackTrace();
}
}
private static String selectFile() {
FileDialog dialog = new FileDialog(new Frame(), "Select .sk File");
dialog.setMode(FileDialog.LOAD);
dialog.setFilenameFilter((dir, name) -> name.endsWith(".sk"));
dialog.setVisible(true);
return dialog.getDirectory() + dialog.getFile();
}
}
|
Compiler/src/core/Main.java
|
MrMystery10-del-Slirik-b1c532b
|
[
{
"filename": "Compiler/src/core/Lexer.java",
"retrieved_chunk": "package core;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class Lexer {\n public enum TokenType {\n TYPE, IDENTIFIER, EQUALS, NUMBER, BINARY_OPERATOR, OPEN_PAREN, CLOSE_PAREN, OPEN_HEAD, CLOSE_HEAD, END,\n KEYWORD, FUNCTION, CONDITION\n }\n protected static List<Token> tokenize(String s) {\n List<Token> tokenList = new ArrayList<>();",
"score": 0.8154406547546387
},
{
"filename": "Compiler/src/core/Trees.java",
"retrieved_chunk": " }\n }\n return statements;\n }\n // Creates a keyword tree from a stream of tokens\n protected static List<Statement> keywordTree(Iterator<Lexer.Token> tokens) {\n List<Statement> statements = new LinkedList<>();\n Lexer.Token token = tokens.next();\n String keyword = token.value();\n token = tokens.next();",
"score": 0.791869044303894
},
{
"filename": "Compiler/src/core/Trees.java",
"retrieved_chunk": " // Adds tokens if they're in parenthesis\n while (closedParensAvailable != 0) {\n expressionTokens.add(token);\n token = tokens.next();\n if (token.tokenType() == Lexer.TokenType.OPEN_PAREN)\n closedParensAvailable++;\n else if (token.tokenType() == Lexer.TokenType.CLOSE_PAREN)\n closedParensAvailable--;\n }\n statements.addAll(identifyToken(expressionTokens.iterator()));",
"score": 0.788311243057251
},
{
"filename": "Compiler/src/core/Parser.java",
"retrieved_chunk": " private Queue<Statement> statements = new LinkedList<>();\n // Current index of the given tokens\n private int index = 0;\n protected Parser(List<Lexer.Token> tokens) {\n this.tokens = tokens;\n }\n /**\n * @return a new Queue of generated bytecode statements based on the tokens given to the Parser object\n */\n protected Queue<Statement> getStatements() {",
"score": 0.7824329733848572
},
{
"filename": "Compiler/src/core/Parser.java",
"retrieved_chunk": "package core;\nimport statements.*;\nimport java.util.Deque;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\npublic class Parser {\n // List of the Lexer generated tokens from the source code\n private final List<Lexer.Token> tokens;\n // Queue of generated bytecode statements",
"score": 0.7796822190284729
}
] |
java
|
tokens.addAll(Lexer.tokenize(s));
|
package ru.jbimer.core.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.jbimer.core.dao.CollisionDAO;
import ru.jbimer.core.models.Project;
import ru.jbimer.core.repositories.CollisionsRepository;
import ru.jbimer.core.models.Collision;
import ru.jbimer.core.models.Engineer;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class CollisionsService {
private final CollisionsRepository collisionsRepository;
private final CollisionDAO collisionDAO;
private final ProjectService projectService;
@Autowired
public CollisionsService(CollisionsRepository collisionsRepository, CollisionDAO collisionDAO, ProjectService projectService) {
this.collisionsRepository = collisionsRepository;
this.collisionDAO = collisionDAO;
this.projectService = projectService;
}
public List<Collision> findByEngineer(Engineer engineer) {
return collisionsRepository.findByEngineer(engineer);
}
public List<Collision> findAllByProject(Project project) {
return collisionsRepository.findAllByProjectBase(project);
}
public Collision findOne(int id) {
Optional<Collision> foundCollision = collisionsRepository.findById(id);
return foundCollision.orElse(null);
}
public Collision findOneAndEngineer(int id) {
Optional<Collision> foundCollision = collisionsRepository.findByIdFetchEngineer(id);
return foundCollision.orElse(null);
}
@Transactional
public void save(Collision collision) {
collisionsRepository.save(collision);
}
@Transactional
public void saveAll(List<Collision> collisions, Project project) {
String disc1 = collisions.get(0).getDiscipline1();
String disc2 = collisions.get(0).getDiscipline2();
Date currDate = collisions.get(0).getCreatedAt();
for (Collision collision :
collisions) {
Optional<Collision> foundCollisionOptional = collisionsRepository
.findByIdsForValidation(collision.getElementId1(), collision.getElementId2(), project);
if (foundCollisionOptional.isEmpty()) save(collision);
else {
Collision foundCollision = foundCollisionOptional.get();
foundCollision.setCreatedAt(new Date());
}
}
update(currDate, disc1, disc2, project);
}
@Transactional
public void update(Date date, String disc1, String disc2, Project project) {
collisionsRepository.updateStatus(date, disc1, disc2, project);
}
@Transactional
public void delete(int id) {
collisionsRepository.deleteById(id);
}
@Transactional
public void release(int id) {
collisionsRepository.findByIdFetchEngineer(id).ifPresent(
collision -> {
collision.setEngineer(null);
}
);
}
@Transactional
public void assign(int id, Engineer selectedEngineer) {
collisionsRepository.findByIdFetchEngineer(id).ifPresent(
collision -> {
collision.setEngineer(selectedEngineer);
}
);
}
@Transactional
public void addComment(int id, Engineer selectedEngineer, String comment) {
Optional<Collision> optionalCollision = collisionsRepository.findByIdFetchEngineer(id);
if (optionalCollision.isPresent()) {
Collision collision = optionalCollision.get();
String currComment = collision.getComment();
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
String formattedDate = dateFormat.format(currentDate);
if (currComment == null) currComment = formattedDate
|
+ ": "+ selectedEngineer.getFullNameWithDiscipline() + ": " + comment + "#@";
|
else currComment = currComment + formattedDate + ": " + selectedEngineer.getFullNameWithDiscipline() + ": " + comment + "#@";
collision.setComment(currComment);
}
}
public Engineer getCollisionEngineer(int id) {
return collisionsRepository.findById(id).map(Collision::getEngineer).orElse(null);
}
public Page<Collision> findAllWithPagination(int project_id, Pageable paging) {
Project foundProject = projectService.findOne(project_id);
return collisionsRepository.findByProjectBase(foundProject, paging);
}
public Page<Collision> searchByDiscipline(String keyword, int project_id, Pageable pageable) {
Project foundProject = projectService.findOne(project_id);
return collisionsRepository.findByDisciplinesAndProject(keyword, foundProject, pageable);
}
@Transactional
public void markAsFake(int id) {
collisionsRepository.findById(id).ifPresent(
collision -> {
collision.setFake(true);
collision.setEngineer(null);
}
);
}
@Transactional
public void markAsNotFake(int id) {
collisionsRepository.findById(id).ifPresent(
collision -> {
collision.setFake(false);
}
);
}
}
|
src/main/java/ru/jbimer/core/services/CollisionsService.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n EngineerDetails engineerDetails = (EngineerDetails) authentication.getPrincipal();\n collisionsService.addComment(id, engineerDetails.getEngineer(), comment);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }\n}",
"score": 0.8848843574523926
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n String authority = authentication.getAuthorities().stream().findFirst().orElse(null).getAuthority();\n Collision collision = collisionsService.findOneAndEngineer(id);\n Engineer collisionOwner = collision.getEngineer();\n model.addAttribute(\"collision\", collision);\n model.addAttribute(\"comments\", collision.getComments());\n model.addAttribute(\"role\", authority);\n if (collisionOwner != null){\n model.addAttribute(\"owner\", collisionOwner);\n }",
"score": 0.8402484059333801
},
{
"filename": "src/main/java/ru/jbimer/core/services/EngineersService.java",
"retrieved_chunk": " engineersRepository.save(originalEngineer);\n }\n @Transactional\n public void delete(int id) {\n engineersRepository.deleteById(id);\n }\n public List<Collision> getCollisionsByEngineerId(int id) {\n Optional<Engineer> engineer = engineersRepository.findById(id);\n if (engineer.isPresent()) {\n Hibernate.initialize(engineer.get().getCollisions());",
"score": 0.8229479193687439
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " }\n @GetMapping(\"/{id}/not-fake\")\n public String markAsNotFake(@PathVariable(\"id\") int id, @PathVariable(\"project_id\") int project_id) {\n collisionsService.markAsNotFake(id);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }\n @PostMapping(\"/{id}/add-comment\")\n public String addComment(@PathVariable(\"id\") int id,\n @RequestParam(\"comment\") String comment,\n @PathVariable(\"project_id\") int project_id) {",
"score": 0.8200182318687439
},
{
"filename": "src/main/java/ru/jbimer/core/services/EngineersService.java",
"retrieved_chunk": " }\n public Engineer findOne(int id) {\n Optional<Engineer> foundEngineer = engineersRepository.findById(id);\n return foundEngineer.orElse(null);\n }\n public Engineer findByIdFetchCollisions(int id) {\n Optional<Engineer> foundEngineer = engineersRepository.findByIdFetchCollisions(id);\n return foundEngineer.orElse(null);\n }\n @Transactional",
"score": 0.8044556379318237
}
] |
java
|
+ ": "+ selectedEngineer.getFullNameWithDiscipline() + ": " + comment + "#@";
|
package ru.jbimer.core.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.jbimer.core.dao.CollisionDAO;
import ru.jbimer.core.models.Project;
import ru.jbimer.core.repositories.CollisionsRepository;
import ru.jbimer.core.models.Collision;
import ru.jbimer.core.models.Engineer;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class CollisionsService {
private final CollisionsRepository collisionsRepository;
private final CollisionDAO collisionDAO;
private final ProjectService projectService;
@Autowired
public CollisionsService(CollisionsRepository collisionsRepository, CollisionDAO collisionDAO, ProjectService projectService) {
this.collisionsRepository = collisionsRepository;
this.collisionDAO = collisionDAO;
this.projectService = projectService;
}
public List<Collision> findByEngineer(Engineer engineer) {
return collisionsRepository.findByEngineer(engineer);
}
public List<Collision> findAllByProject(Project project) {
return collisionsRepository.findAllByProjectBase(project);
}
public Collision findOne(int id) {
Optional<Collision> foundCollision = collisionsRepository.findById(id);
return foundCollision.orElse(null);
}
public Collision findOneAndEngineer(int id) {
Optional<Collision
|
> foundCollision = collisionsRepository.findByIdFetchEngineer(id);
|
return foundCollision.orElse(null);
}
@Transactional
public void save(Collision collision) {
collisionsRepository.save(collision);
}
@Transactional
public void saveAll(List<Collision> collisions, Project project) {
String disc1 = collisions.get(0).getDiscipline1();
String disc2 = collisions.get(0).getDiscipline2();
Date currDate = collisions.get(0).getCreatedAt();
for (Collision collision :
collisions) {
Optional<Collision> foundCollisionOptional = collisionsRepository
.findByIdsForValidation(collision.getElementId1(), collision.getElementId2(), project);
if (foundCollisionOptional.isEmpty()) save(collision);
else {
Collision foundCollision = foundCollisionOptional.get();
foundCollision.setCreatedAt(new Date());
}
}
update(currDate, disc1, disc2, project);
}
@Transactional
public void update(Date date, String disc1, String disc2, Project project) {
collisionsRepository.updateStatus(date, disc1, disc2, project);
}
@Transactional
public void delete(int id) {
collisionsRepository.deleteById(id);
}
@Transactional
public void release(int id) {
collisionsRepository.findByIdFetchEngineer(id).ifPresent(
collision -> {
collision.setEngineer(null);
}
);
}
@Transactional
public void assign(int id, Engineer selectedEngineer) {
collisionsRepository.findByIdFetchEngineer(id).ifPresent(
collision -> {
collision.setEngineer(selectedEngineer);
}
);
}
@Transactional
public void addComment(int id, Engineer selectedEngineer, String comment) {
Optional<Collision> optionalCollision = collisionsRepository.findByIdFetchEngineer(id);
if (optionalCollision.isPresent()) {
Collision collision = optionalCollision.get();
String currComment = collision.getComment();
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
String formattedDate = dateFormat.format(currentDate);
if (currComment == null) currComment = formattedDate + ": "+ selectedEngineer.getFullNameWithDiscipline() + ": " + comment + "#@";
else currComment = currComment + formattedDate + ": " + selectedEngineer.getFullNameWithDiscipline() + ": " + comment + "#@";
collision.setComment(currComment);
}
}
public Engineer getCollisionEngineer(int id) {
return collisionsRepository.findById(id).map(Collision::getEngineer).orElse(null);
}
public Page<Collision> findAllWithPagination(int project_id, Pageable paging) {
Project foundProject = projectService.findOne(project_id);
return collisionsRepository.findByProjectBase(foundProject, paging);
}
public Page<Collision> searchByDiscipline(String keyword, int project_id, Pageable pageable) {
Project foundProject = projectService.findOne(project_id);
return collisionsRepository.findByDisciplinesAndProject(keyword, foundProject, pageable);
}
@Transactional
public void markAsFake(int id) {
collisionsRepository.findById(id).ifPresent(
collision -> {
collision.setFake(true);
collision.setEngineer(null);
}
);
}
@Transactional
public void markAsNotFake(int id) {
collisionsRepository.findById(id).ifPresent(
collision -> {
collision.setFake(false);
}
);
}
}
|
src/main/java/ru/jbimer/core/services/CollisionsService.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/repositories/CollisionsRepository.java",
"retrieved_chunk": " @Param(\"project\") Project project);\n Page<Collision> findByProjectBase(Project project, Pageable pageable);\n List<Collision> findAllByProjectBase(Project project);\n}",
"score": 0.9094581007957458
},
{
"filename": "src/main/java/ru/jbimer/core/services/EngineersService.java",
"retrieved_chunk": " public List<Engineer> findAllOnProject(int project_id) {\n return engineersRepository.findAllOnProject(project_id);\n }\n public List<Engineer> findAllSortedByCollisionsSize() {\n List<Engineer> engineers = new ArrayList<>(engineerDAO.index());\n engineers.sort((e1, e2) -> {\n int collisionsComparison = Integer.compare(e2.getCollisions().size(), e1.getCollisions().size());\n if (collisionsComparison != 0) {\n return collisionsComparison;\n } else {",
"score": 0.9047933220863342
},
{
"filename": "src/main/java/ru/jbimer/core/services/HtmlReportService.java",
"retrieved_chunk": " collisionsService.saveAll(collisions, project);\n return collisions.size();\n }\n public List<HtmlReportData> findAllByProject(Project project) {\n return htmlReportDataRepository.findAllByProject(project);\n }\n}",
"score": 0.9032005071640015
},
{
"filename": "src/main/java/ru/jbimer/core/repositories/CollisionsRepository.java",
"retrieved_chunk": " @Param(\"project\") Project project,\n Pageable pageable);\n @Query(\"SELECT c FROM Collision c LEFT JOIN FETCH c.engineer WHERE c.id = :id\")\n Optional<Collision> findByIdFetchEngineer(@Param(\"id\") int id);\n @Query(\"SELECT c FROM Collision c LEFT JOIN FETCH c.engineer ORDER BY c.id\")\n List<Collision> findAllFetchEngineers();\n List<Collision> findByEngineer(Engineer engineer);\n @Query(\"SELECT c FROM Collision c LEFT JOIN FETCH c.projectBase WHERE c.projectBase = :project and \" +\n \"(c.elementId1 =: elemId1 and c.elementId2 = :elemId2\" +\n \" or c.elementId1 = :elemId2 and c.elementId2 = :elemId1)\")",
"score": 0.8984221816062927
},
{
"filename": "src/main/java/ru/jbimer/core/repositories/CollisionsRepository.java",
"retrieved_chunk": "import ru.jbimer.core.models.Engineer;\nimport ru.jbimer.core.models.Project;\nimport javax.swing.text.html.Option;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Optional;\n@Repository\npublic interface CollisionsRepository extends JpaRepository<Collision, Integer> {\n @Query(\"SELECT c FROM Collision c LEFT JOIN c.projectBase p WHERE p = :project and (c.discipline1 = :discipline or c.discipline2 = :discipline)\")\n Page<Collision> findByDisciplinesAndProject(@Param(\"discipline\") String discipline,",
"score": 0.8897380828857422
}
] |
java
|
> foundCollision = collisionsRepository.findByIdFetchEngineer(id);
|
package ru.jbimer.core.controllers;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.jbimer.core.security.EngineerDetails;
import ru.jbimer.core.util.EngineerValidator;
import ru.jbimer.core.models.Engineer;
import ru.jbimer.core.services.EngineersService;
import java.util.*;
@Controller
@RequestMapping("/engineers")
public class EngineersController {
private final EngineerValidator engineerValidator;
private final EngineersService engineersService;
@Autowired
public EngineersController(EngineerValidator engineerValidator, EngineersService engineersService) {
this.engineerValidator = engineerValidator;
this.engineersService = engineersService;
}
@GetMapping()
public String index(Model model) {
List<Engineer> engineers = engineersService.findAllSortedByCollisionsSize();
model.addAttribute("engineers", engineers);
return "engineers/index";
}
@GetMapping("/{id}")
public String show(@PathVariable("id") int id, Model model) {
Engineer engineer = engineersService.findByIdFetchCollisions(id);
model.addAttribute("engineer", engineer);
model.addAttribute("collisions", engineer.getCollisions());
return "engineers/show";
}
@GetMapping("/{id}/edit")
public String edit(Model model, @PathVariable("id") int id) {
model.addAttribute("engineer", engineersService.findOne(id));
return "engineers/edit";
}
@PatchMapping("/{id}")
public String update(@ModelAttribute("engineer") @Valid Engineer updatedEngineer,
BindingResult bindingResult,
@PathVariable("id") int id) {
if (bindingResult.hasErrors()) return "engineers/edit";
Engineer
|
originalEngineer = engineersService.findOne(id);
|
engineersService.update(id, updatedEngineer, originalEngineer);
return "redirect:/engineers";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") int id) {
engineersService.delete(id);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(null);
}
return "redirect:/logout";
}
}
|
src/main/java/ru/jbimer/core/controllers/EngineersController.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " when(engineersService.findOne(id)).thenReturn(originalEngineer);\n String viewName = engineersController.update(updatedEngineer, bindingResult, id);\n assertEquals(\"redirect:/engineers\", viewName);\n verify(engineersService).update(id, updatedEngineer, originalEngineer);\n }\n @Test\n public void testDelete() throws Exception {\n int id = 1;\n Authentication authentication = mock(Authentication.class);\n SecurityContextHolder.getContext().setAuthentication(authentication);",
"score": 0.9220776557922363
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " return \"redirect:/projects\";\n }\n @GetMapping(\"/{id}/edit\")\n public String edit(Model model, @PathVariable(\"id\") int id) {\n model.addAttribute(\"project\", projectService.findOne(id));\n model.addAttribute(\"engineers\", engineersService.findAll());\n return \"projects/edit\";\n }\n @PatchMapping(\"/{id}\")\n public String update(@ModelAttribute(\"project\") @Valid Project project,",
"score": 0.9119661450386047
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " @Test\n public void testEdit() throws Exception {\n int id = 1;\n Engineer engineer = new Engineer();\n when(engineersService.findOne(id)).thenReturn(engineer);\n Model model = new ExtendedModelMap();\n String viewName = engineersController.edit(model, id);\n assertEquals(\"engineers/edit\", viewName);\n assertTrue(model.containsAttribute(\"engineer\"));\n assertSame(engineer, model.getAttribute(\"engineer\"));",
"score": 0.9025847315788269
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " verify(engineersService).findOne(id);\n }\n @Test\n public void testUpdate() throws Exception {\n int id = 1;\n Engineer updatedEngineer = new Engineer();\n updatedEngineer.setId(id);\n BindingResult bindingResult = mock(BindingResult.class);\n when(bindingResult.hasErrors()).thenReturn(false);\n Engineer originalEngineer = mock(Engineer.class);",
"score": 0.9023972153663635
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"message\", e.getMessage());\n }\n return \"collisions/index\";\n }\n @GetMapping(\"/{id}\")\n public String show(@PathVariable(\"id\") int id,\n @PathVariable(\"project_id\") int project_id,\n Model model,\n @ModelAttribute(\"engineer\") Engineer engineer) {",
"score": 0.8792378902435303
}
] |
java
|
originalEngineer = engineersService.findOne(id);
|
package ru.jbimer.core.controllers;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.jbimer.core.models.Engineer;
import ru.jbimer.core.models.Project;
import ru.jbimer.core.services.CollisionsService;
import ru.jbimer.core.services.EngineersService;
import ru.jbimer.core.services.HtmlReportService;
import ru.jbimer.core.services.ProjectService;
import java.util.List;
@Controller
@RequestMapping("/projects")
public class ProjectController {
private final ProjectService projectService;
private final EngineersService engineersService;
private final HtmlReportService htmlReportService;
private final CollisionsService collisionsService;
@Autowired
public ProjectController(ProjectService projectService, EngineersService engineersService, HtmlReportService htmlReportService, CollisionsService collisionsService) {
this.projectService = projectService;
this.engineersService = engineersService;
this.htmlReportService = htmlReportService;
this.collisionsService = collisionsService;
}
@GetMapping()
public String index(Model model) {
List<Project> projects = projectService.findAll();
model.addAttribute("projects", projects);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String authority = authentication.getAuthorities().stream().findFirst().orElse(null).getAuthority();
model.addAttribute("role", authority);
return "projects/index";
}
@GetMapping("/{id}")
public String show(@PathVariable("id") int project_id, Model model) {
Project project = projectService.findOne(project_id);
List<Engineer> engineers = project.getEngineersOnProject();
model.addAttribute("project", project);
model.addAttribute("engineers", engineers);
model.addAttribute("reports", htmlReportService.findAllByProject(project));
return "projects/show";
}
@GetMapping("/new")
public String newProject(Model model,
@ModelAttribute("project") Project project) {
model.addAttribute(
|
"engineers", engineersService.findAll());
|
return "projects/new";
}
@PostMapping
public String create(@ModelAttribute("project") @Valid Project project,
BindingResult bindingResult, Model model) {
model.addAttribute("engineers", engineersService.findAll());
if (bindingResult.hasErrors()) return "projects/new";
projectService.save(project);
return "redirect:/projects";
}
@GetMapping("/{id}/edit")
public String edit(Model model, @PathVariable("id") int id) {
model.addAttribute("project", projectService.findOne(id));
model.addAttribute("engineers", engineersService.findAll());
return "projects/edit";
}
@PatchMapping("/{id}")
public String update(@ModelAttribute("project") @Valid Project project,
BindingResult bindingResult,
@PathVariable("id") int id) {
if (bindingResult.hasErrors()) return "projects/edit";
projectService.save(project);
return "redirect:/projects/" + id;
}
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") int id){
projectService.delete(id);
return "redirect:/projects";
}
}
|
src/main/java/ru/jbimer/core/controllers/ProjectController.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/test/java/ru/jbimer/core/controllers/ProjectControllerTest.java",
"retrieved_chunk": " public void testNewProject() {\n Model model = Mockito.mock(Model.class);\n Project project = new Project();\n List<Engineer> engineers = Arrays.asList(new Engineer(), new Engineer(), new Engineer());\n Mockito.when(engineersService.findAll()).thenReturn(engineers);\n String viewName = projectController.newProject(model, project);\n assertEquals(\"projects/new\", viewName);\n Mockito.verify(model).addAttribute(\"project\", project);\n Mockito.verify(model).addAttribute(\"engineers\", engineers);\n }",
"score": 0.9056298732757568
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/ProjectControllerTest.java",
"retrieved_chunk": " List<Engineer> engineers = Arrays.asList(new Engineer(), new Engineer(), new Engineer());\n project.setEngineersOnProject(engineers);\n int projectId = 1;\n Mockito.when(projectService.findOne(projectId)).thenReturn(project);\n String viewName = projectController.show(projectId, model);\n assertEquals(\"projects/show\", viewName);\n Mockito.verify(model).addAttribute(\"project\", project);\n Mockito.verify(model).addAttribute(\"engineers\", engineers);\n }\n @Test",
"score": 0.8999487161636353
},
{
"filename": "src/main/java/ru/jbimer/core/exception/ProjectExceptionHandler.java",
"retrieved_chunk": " modelAndView.setViewName(\"projects/new\");\n modelAndView.addObject(\"errorMessage\", \"Choose at least 1 engineer\");\n return modelAndView;\n }\n}",
"score": 0.8969731330871582
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " else\n model.addAttribute(\"engineers\", engineersService.findAllOnProject(project_id));\n return \"collisions/show\";\n }\n @GetMapping(\"/upload\")\n public String uploadCollisionsReportPage(Model model, @PathVariable(\"project_id\") int project_id) {\n model.addAttribute(\"project\", projectService.findOne(project_id));\n return \"collisions/upload\";\n }\n @DeleteMapping(\"/{id}\")",
"score": 0.8794656991958618
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"message\", e.getMessage());\n }\n return \"collisions/index\";\n }\n @GetMapping(\"/{id}\")\n public String show(@PathVariable(\"id\") int id,\n @PathVariable(\"project_id\") int project_id,\n Model model,\n @ModelAttribute(\"engineer\") Engineer engineer) {",
"score": 0.8779749870300293
}
] |
java
|
"engineers", engineersService.findAll());
|
package ru.jbimer.core.controllers;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.jbimer.core.models.Engineer;
import ru.jbimer.core.security.EngineerDetails;
import ru.jbimer.core.services.CollisionsService;
import ru.jbimer.core.services.EngineersService;
import ru.jbimer.core.services.ProjectService;
@Controller
@RequestMapping("/")
public class HomeController {
private final EngineersService engineersService;
private final CollisionsService collisionsService;
private final ProjectService projectService;
public HomeController(EngineersService engineersService, CollisionsService collisionsService, ProjectService projectService) {
this.engineersService = engineersService;
this.collisionsService = collisionsService;
this.projectService = projectService;
}
@GetMapping
public String index() {
return "index_main";
}
@GetMapping("/account")
public String showUserAccount(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
EngineerDetails engineerDetails = (EngineerDetails) authentication.getPrincipal();
Engineer engineer = engineersService
|
.findByIdFetchCollisions(engineerDetails.getEngineer().getId());
|
model.addAttribute("engineer", engineer);
model.addAttribute("collisions", engineer.getCollisions());
return "profile/profile_page";
}
@GetMapping("/admin")
public String adminPage() {
return "admin";
}
}
|
src/main/java/ru/jbimer/core/controllers/HomeController.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " public EngineersController(EngineerValidator engineerValidator, EngineersService engineersService) {\n this.engineerValidator = engineerValidator;\n this.engineersService = engineersService;\n }\n @GetMapping()\n public String index(Model model) {\n List<Engineer> engineers = engineersService.findAllSortedByCollisionsSize();\n model.addAttribute(\"engineers\", engineers);\n return \"engineers/index\";\n }",
"score": 0.9056702852249146
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " @GetMapping()\n public String index(Model model) {\n List<Project> projects = projectService.findAll();\n model.addAttribute(\"projects\", projects);\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n String authority = authentication.getAuthorities().stream().findFirst().orElse(null).getAuthority();\n model.addAttribute(\"role\", authority);\n return \"projects/index\";\n }\n @GetMapping(\"/{id}\")",
"score": 0.9052043557167053
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/AuthController.java",
"retrieved_chunk": " @GetMapping(\"/login\")\n public String loginPage() {\n return \"auth/login\";\n }\n @GetMapping(\"/registration\")\n public String registrationPage(@ModelAttribute(\"engineer\") Engineer engineer) {\n return \"auth/registration\";\n }\n @PostMapping(\"/registration\")\n public String performRegistration(@ModelAttribute(\"engineer\") @Valid Engineer engineer,",
"score": 0.894828200340271
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"message\", e.getMessage());\n }\n return \"collisions/index\";\n }\n @GetMapping(\"/{id}\")\n public String show(@PathVariable(\"id\") int id,\n @PathVariable(\"project_id\") int project_id,\n Model model,\n @ModelAttribute(\"engineer\") Engineer engineer) {",
"score": 0.8859502077102661
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " @GetMapping(\"/{id}\")\n public String show(@PathVariable(\"id\") int id, Model model) {\n Engineer engineer = engineersService.findByIdFetchCollisions(id);\n model.addAttribute(\"engineer\", engineer);\n model.addAttribute(\"collisions\", engineer.getCollisions());\n return \"engineers/show\";\n }\n @GetMapping(\"/{id}/edit\")\n public String edit(Model model, @PathVariable(\"id\") int id) {\n model.addAttribute(\"engineer\", engineersService.findOne(id));",
"score": 0.8823757171630859
}
] |
java
|
.findByIdFetchCollisions(engineerDetails.getEngineer().getId());
|
package ru.jbimer.core.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.jbimer.core.dao.CollisionDAO;
import ru.jbimer.core.models.Project;
import ru.jbimer.core.repositories.CollisionsRepository;
import ru.jbimer.core.models.Collision;
import ru.jbimer.core.models.Engineer;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class CollisionsService {
private final CollisionsRepository collisionsRepository;
private final CollisionDAO collisionDAO;
private final ProjectService projectService;
@Autowired
public CollisionsService(CollisionsRepository collisionsRepository, CollisionDAO collisionDAO, ProjectService projectService) {
this.collisionsRepository = collisionsRepository;
this.collisionDAO = collisionDAO;
this.projectService = projectService;
}
public List<Collision> findByEngineer(Engineer engineer) {
return collisionsRepository.findByEngineer(engineer);
}
public List<Collision> findAllByProject(Project project) {
return collisionsRepository.findAllByProjectBase(project);
}
public Collision findOne(int id) {
Optional<Collision> foundCollision = collisionsRepository.findById(id);
return foundCollision.orElse(null);
}
public Collision findOneAndEngineer(int id) {
Optional<Collision> foundCollision = collisionsRepository.findByIdFetchEngineer(id);
return foundCollision.orElse(null);
}
@Transactional
public void save(Collision collision) {
collisionsRepository.save(collision);
}
@Transactional
public void saveAll(List<Collision> collisions, Project project) {
String disc1 = collisions.get(0).getDiscipline1();
String disc2 = collisions.get(0).getDiscipline2();
Date currDate = collisions.get(0).getCreatedAt();
for (Collision collision :
collisions) {
Optional<Collision> foundCollisionOptional = collisionsRepository
.findByIdsForValidation(collision.getElementId1(), collision.getElementId2(), project);
if (foundCollisionOptional.isEmpty()) save(collision);
else {
Collision foundCollision = foundCollisionOptional.get();
foundCollision.setCreatedAt(new Date());
}
}
update(currDate, disc1, disc2, project);
}
@Transactional
public void update(Date date, String disc1, String disc2, Project project) {
collisionsRepository.updateStatus(date, disc1, disc2, project);
}
@Transactional
public void delete(int id) {
collisionsRepository.deleteById(id);
}
@Transactional
public void release(int id) {
collisionsRepository.findByIdFetchEngineer(id).ifPresent(
collision -> {
collision.setEngineer(null);
}
);
}
@Transactional
public void assign(int id, Engineer selectedEngineer) {
collisionsRepository.findByIdFetchEngineer(id).ifPresent(
collision -> {
collision.setEngineer(selectedEngineer);
}
);
}
@Transactional
public void addComment(int id, Engineer selectedEngineer, String comment) {
|
Optional<Collision> optionalCollision = collisionsRepository.findByIdFetchEngineer(id);
|
if (optionalCollision.isPresent()) {
Collision collision = optionalCollision.get();
String currComment = collision.getComment();
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
String formattedDate = dateFormat.format(currentDate);
if (currComment == null) currComment = formattedDate + ": "+ selectedEngineer.getFullNameWithDiscipline() + ": " + comment + "#@";
else currComment = currComment + formattedDate + ": " + selectedEngineer.getFullNameWithDiscipline() + ": " + comment + "#@";
collision.setComment(currComment);
}
}
public Engineer getCollisionEngineer(int id) {
return collisionsRepository.findById(id).map(Collision::getEngineer).orElse(null);
}
public Page<Collision> findAllWithPagination(int project_id, Pageable paging) {
Project foundProject = projectService.findOne(project_id);
return collisionsRepository.findByProjectBase(foundProject, paging);
}
public Page<Collision> searchByDiscipline(String keyword, int project_id, Pageable pageable) {
Project foundProject = projectService.findOne(project_id);
return collisionsRepository.findByDisciplinesAndProject(keyword, foundProject, pageable);
}
@Transactional
public void markAsFake(int id) {
collisionsRepository.findById(id).ifPresent(
collision -> {
collision.setFake(true);
collision.setEngineer(null);
}
);
}
@Transactional
public void markAsNotFake(int id) {
collisionsRepository.findById(id).ifPresent(
collision -> {
collision.setFake(false);
}
);
}
}
|
src/main/java/ru/jbimer/core/services/CollisionsService.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/services/EngineersService.java",
"retrieved_chunk": " engineersRepository.save(originalEngineer);\n }\n @Transactional\n public void delete(int id) {\n engineersRepository.deleteById(id);\n }\n public List<Collision> getCollisionsByEngineerId(int id) {\n Optional<Engineer> engineer = engineersRepository.findById(id);\n if (engineer.isPresent()) {\n Hibernate.initialize(engineer.get().getCollisions());",
"score": 0.8928546905517578
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " @PatchMapping(\"/{id}/assign\")\n public String assign(@PathVariable(\"id\") int id, @ModelAttribute(\"engineer\")Engineer engineer,\n @PathVariable(\"project_id\") int project_id) {\n collisionsService.assign(id, engineer);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }\n @GetMapping(\"/{id}/fake\")\n public String markAsFake(@PathVariable(\"id\") int id, @PathVariable(\"project_id\") int project_id) {\n collisionsService.markAsFake(id);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;",
"score": 0.8736087679862976
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n EngineerDetails engineerDetails = (EngineerDetails) authentication.getPrincipal();\n collisionsService.addComment(id, engineerDetails.getEngineer(), comment);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }\n}",
"score": 0.8715051412582397
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n String authority = authentication.getAuthorities().stream().findFirst().orElse(null).getAuthority();\n Collision collision = collisionsService.findOneAndEngineer(id);\n Engineer collisionOwner = collision.getEngineer();\n model.addAttribute(\"collision\", collision);\n model.addAttribute(\"comments\", collision.getComments());\n model.addAttribute(\"role\", authority);\n if (collisionOwner != null){\n model.addAttribute(\"owner\", collisionOwner);\n }",
"score": 0.8690639734268188
},
{
"filename": "src/main/java/ru/jbimer/core/services/EngineersService.java",
"retrieved_chunk": " }\n public Engineer findOne(int id) {\n Optional<Engineer> foundEngineer = engineersRepository.findById(id);\n return foundEngineer.orElse(null);\n }\n public Engineer findByIdFetchCollisions(int id) {\n Optional<Engineer> foundEngineer = engineersRepository.findByIdFetchCollisions(id);\n return foundEngineer.orElse(null);\n }\n @Transactional",
"score": 0.8642509579658508
}
] |
java
|
Optional<Collision> optionalCollision = collisionsRepository.findByIdFetchEngineer(id);
|
package ru.jbimer.core.controllers;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.jbimer.core.security.EngineerDetails;
import ru.jbimer.core.util.EngineerValidator;
import ru.jbimer.core.models.Engineer;
import ru.jbimer.core.services.EngineersService;
import java.util.*;
@Controller
@RequestMapping("/engineers")
public class EngineersController {
private final EngineerValidator engineerValidator;
private final EngineersService engineersService;
@Autowired
public EngineersController(EngineerValidator engineerValidator, EngineersService engineersService) {
this.engineerValidator = engineerValidator;
this.engineersService = engineersService;
}
@GetMapping()
public String index(Model model) {
List<Engineer> engineers = engineersService.findAllSortedByCollisionsSize();
model.addAttribute("engineers", engineers);
return "engineers/index";
}
@GetMapping("/{id}")
public String show(@PathVariable("id") int id, Model model) {
Engineer engineer
|
= engineersService.findByIdFetchCollisions(id);
|
model.addAttribute("engineer", engineer);
model.addAttribute("collisions", engineer.getCollisions());
return "engineers/show";
}
@GetMapping("/{id}/edit")
public String edit(Model model, @PathVariable("id") int id) {
model.addAttribute("engineer", engineersService.findOne(id));
return "engineers/edit";
}
@PatchMapping("/{id}")
public String update(@ModelAttribute("engineer") @Valid Engineer updatedEngineer,
BindingResult bindingResult,
@PathVariable("id") int id) {
if (bindingResult.hasErrors()) return "engineers/edit";
Engineer originalEngineer = engineersService.findOne(id);
engineersService.update(id, updatedEngineer, originalEngineer);
return "redirect:/engineers";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") int id) {
engineersService.delete(id);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(null);
}
return "redirect:/logout";
}
}
|
src/main/java/ru/jbimer/core/controllers/EngineersController.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"message\", e.getMessage());\n }\n return \"collisions/index\";\n }\n @GetMapping(\"/{id}\")\n public String show(@PathVariable(\"id\") int id,\n @PathVariable(\"project_id\") int project_id,\n Model model,\n @ModelAttribute(\"engineer\") Engineer engineer) {",
"score": 0.9454929828643799
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " @MockBean\n private EngineersController engineersController;\n @Test\n public void testIndex() throws Exception {\n List<Engineer> engineers = new ArrayList<>();\n engineers.add(new Engineer());\n when(engineersService.findAllSortedByCollisionsSize()).thenReturn(engineers);\n Model model = new ExtendedModelMap();\n String viewName = engineersController.index(model);\n assertEquals(\"engineers/index\", viewName);",
"score": 0.9148697853088379
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " public CollisionsController(EngineersService engineersService, CollisionsService collisionsService, HtmlReportService service, ProjectService projectService) {\n this.engineersService = engineersService;\n this.collisionsService = collisionsService;\n this.service = service;\n this.projectService = projectService;\n }\n @GetMapping()\n public String index(Model model,\n @PathVariable(\"project_id\") int project_id,\n @RequestParam(required = false) String keyword,",
"score": 0.9049383401870728
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/HomeController.java",
"retrieved_chunk": " EngineerDetails engineerDetails = (EngineerDetails) authentication.getPrincipal();\n Engineer engineer = engineersService\n .findByIdFetchCollisions(engineerDetails.getEngineer().getId());\n model.addAttribute(\"engineer\", engineer);\n model.addAttribute(\"collisions\", engineer.getCollisions());\n return \"profile/profile_page\";\n }\n @GetMapping(\"/admin\")\n public String adminPage() {\n return \"admin\";",
"score": 0.8934223651885986
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " else\n model.addAttribute(\"engineers\", engineersService.findAllOnProject(project_id));\n return \"collisions/show\";\n }\n @GetMapping(\"/upload\")\n public String uploadCollisionsReportPage(Model model, @PathVariable(\"project_id\") int project_id) {\n model.addAttribute(\"project\", projectService.findOne(project_id));\n return \"collisions/upload\";\n }\n @DeleteMapping(\"/{id}\")",
"score": 0.8921620845794678
}
] |
java
|
= engineersService.findByIdFetchCollisions(id);
|
package ru.jbimer.core.controllers;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.jbimer.core.security.EngineerDetails;
import ru.jbimer.core.util.EngineerValidator;
import ru.jbimer.core.models.Engineer;
import ru.jbimer.core.services.EngineersService;
import java.util.*;
@Controller
@RequestMapping("/engineers")
public class EngineersController {
private final EngineerValidator engineerValidator;
private final EngineersService engineersService;
@Autowired
public EngineersController(EngineerValidator engineerValidator, EngineersService engineersService) {
this.engineerValidator = engineerValidator;
this.engineersService = engineersService;
}
@GetMapping()
public String index(Model model) {
List<Engineer> engineers = engineersService.findAllSortedByCollisionsSize();
model.addAttribute("engineers", engineers);
return "engineers/index";
}
@GetMapping("/{id}")
public String show(@PathVariable("id") int id, Model model) {
Engineer engineer = engineersService.findByIdFetchCollisions(id);
model.addAttribute("engineer", engineer);
model.addAttribute("collisions", engineer.getCollisions());
return "engineers/show";
}
@GetMapping("/{id}/edit")
public String edit(Model model, @PathVariable("id") int id) {
model.addAttribute(
|
"engineer", engineersService.findOne(id));
|
return "engineers/edit";
}
@PatchMapping("/{id}")
public String update(@ModelAttribute("engineer") @Valid Engineer updatedEngineer,
BindingResult bindingResult,
@PathVariable("id") int id) {
if (bindingResult.hasErrors()) return "engineers/edit";
Engineer originalEngineer = engineersService.findOne(id);
engineersService.update(id, updatedEngineer, originalEngineer);
return "redirect:/engineers";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") int id) {
engineersService.delete(id);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(null);
}
return "redirect:/logout";
}
}
|
src/main/java/ru/jbimer/core/controllers/EngineersController.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"message\", e.getMessage());\n }\n return \"collisions/index\";\n }\n @GetMapping(\"/{id}\")\n public String show(@PathVariable(\"id\") int id,\n @PathVariable(\"project_id\") int project_id,\n Model model,\n @ModelAttribute(\"engineer\") Engineer engineer) {",
"score": 0.9458436369895935
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " when(engineersService.findByIdFetchCollisions(id)).thenReturn(engineer);\n Model model = new ExtendedModelMap();\n String viewName = engineersController.show(id, model);\n assertEquals(\"engineers/show\", viewName);\n assertTrue(model.containsAttribute(\"engineer\"));\n assertSame(engineer, model.getAttribute(\"engineer\"));\n assertTrue(model.containsAttribute(\"collisions\"));\n assertSame(collisions, model.getAttribute(\"collisions\"));\n verify(engineersService).findByIdFetchCollisions(id);\n }",
"score": 0.9134107828140259
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " public String show(@PathVariable(\"id\") int project_id, Model model) {\n Project project = projectService.findOne(project_id);\n List<Engineer> engineers = project.getEngineersOnProject();\n model.addAttribute(\"project\", project);\n model.addAttribute(\"engineers\", engineers);\n model.addAttribute(\"reports\", htmlReportService.findAllByProject(project));\n return \"projects/show\";\n }\n @GetMapping(\"/new\")\n public String newProject(Model model,",
"score": 0.9074975252151489
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " else\n model.addAttribute(\"engineers\", engineersService.findAllOnProject(project_id));\n return \"collisions/show\";\n }\n @GetMapping(\"/upload\")\n public String uploadCollisionsReportPage(Model model, @PathVariable(\"project_id\") int project_id) {\n model.addAttribute(\"project\", projectService.findOne(project_id));\n return \"collisions/upload\";\n }\n @DeleteMapping(\"/{id}\")",
"score": 0.8918284177780151
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " return \"redirect:/projects\";\n }\n @GetMapping(\"/{id}/edit\")\n public String edit(Model model, @PathVariable(\"id\") int id) {\n model.addAttribute(\"project\", projectService.findOne(id));\n model.addAttribute(\"engineers\", engineersService.findAll());\n return \"projects/edit\";\n }\n @PatchMapping(\"/{id}\")\n public String update(@ModelAttribute(\"project\") @Valid Project project,",
"score": 0.8898810744285583
}
] |
java
|
"engineer", engineersService.findOne(id));
|
package ru.jbimer.core.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.jbimer.core.dao.CollisionDAO;
import ru.jbimer.core.models.Project;
import ru.jbimer.core.repositories.CollisionsRepository;
import ru.jbimer.core.models.Collision;
import ru.jbimer.core.models.Engineer;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class CollisionsService {
private final CollisionsRepository collisionsRepository;
private final CollisionDAO collisionDAO;
private final ProjectService projectService;
@Autowired
public CollisionsService(CollisionsRepository collisionsRepository, CollisionDAO collisionDAO, ProjectService projectService) {
this.collisionsRepository = collisionsRepository;
this.collisionDAO = collisionDAO;
this.projectService = projectService;
}
public List<Collision> findByEngineer(Engineer engineer) {
return collisionsRepository.findByEngineer(engineer);
}
public List<Collision> findAllByProject(Project project) {
return collisionsRepository.findAllByProjectBase(project);
}
public Collision findOne(int id) {
Optional<Collision> foundCollision = collisionsRepository.findById(id);
return foundCollision.orElse(null);
}
public Collision findOneAndEngineer(int id) {
Optional<Collision> foundCollision = collisionsRepository.findByIdFetchEngineer(id);
return foundCollision.orElse(null);
}
@Transactional
public void save(Collision collision) {
collisionsRepository.save(collision);
}
@Transactional
public void saveAll(List<Collision> collisions, Project project) {
String disc1 = collisions.get(0).getDiscipline1();
String disc2 = collisions.get(0).getDiscipline2();
Date currDate = collisions.get(0).getCreatedAt();
for (Collision collision :
collisions) {
Optional<Collision> foundCollisionOptional = collisionsRepository
.findByIdsForValidation(collision.getElementId1(), collision.getElementId2(), project);
if (foundCollisionOptional.isEmpty()) save(collision);
else {
Collision foundCollision = foundCollisionOptional.get();
foundCollision.setCreatedAt(new Date());
}
}
update(currDate, disc1, disc2, project);
}
@Transactional
public void update(Date date, String disc1, String disc2, Project project) {
collisionsRepository.updateStatus(date, disc1, disc2, project);
}
@Transactional
public void delete(int id) {
collisionsRepository.deleteById(id);
}
@Transactional
public void release(int id) {
|
collisionsRepository.findByIdFetchEngineer(id).ifPresent(
collision -> {
|
collision.setEngineer(null);
}
);
}
@Transactional
public void assign(int id, Engineer selectedEngineer) {
collisionsRepository.findByIdFetchEngineer(id).ifPresent(
collision -> {
collision.setEngineer(selectedEngineer);
}
);
}
@Transactional
public void addComment(int id, Engineer selectedEngineer, String comment) {
Optional<Collision> optionalCollision = collisionsRepository.findByIdFetchEngineer(id);
if (optionalCollision.isPresent()) {
Collision collision = optionalCollision.get();
String currComment = collision.getComment();
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
String formattedDate = dateFormat.format(currentDate);
if (currComment == null) currComment = formattedDate + ": "+ selectedEngineer.getFullNameWithDiscipline() + ": " + comment + "#@";
else currComment = currComment + formattedDate + ": " + selectedEngineer.getFullNameWithDiscipline() + ": " + comment + "#@";
collision.setComment(currComment);
}
}
public Engineer getCollisionEngineer(int id) {
return collisionsRepository.findById(id).map(Collision::getEngineer).orElse(null);
}
public Page<Collision> findAllWithPagination(int project_id, Pageable paging) {
Project foundProject = projectService.findOne(project_id);
return collisionsRepository.findByProjectBase(foundProject, paging);
}
public Page<Collision> searchByDiscipline(String keyword, int project_id, Pageable pageable) {
Project foundProject = projectService.findOne(project_id);
return collisionsRepository.findByDisciplinesAndProject(keyword, foundProject, pageable);
}
@Transactional
public void markAsFake(int id) {
collisionsRepository.findById(id).ifPresent(
collision -> {
collision.setFake(true);
collision.setEngineer(null);
}
);
}
@Transactional
public void markAsNotFake(int id) {
collisionsRepository.findById(id).ifPresent(
collision -> {
collision.setFake(false);
}
);
}
}
|
src/main/java/ru/jbimer/core/services/CollisionsService.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " public String delete(@PathVariable(\"id\") int id, @PathVariable(\"project_id\") int project_id) {\n collisionsService.delete(id);\n return \"redirect:/projects/\" + project_id + \"/collisions\";\n }\n @PatchMapping(\"/{id}/release\")\n public String release(@PathVariable(\"id\") int id,\n @PathVariable(\"project_id\") int project_id) {\n collisionsService.release(id);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }",
"score": 0.8914240002632141
},
{
"filename": "src/main/java/ru/jbimer/core/services/EngineersService.java",
"retrieved_chunk": " engineersRepository.save(originalEngineer);\n }\n @Transactional\n public void delete(int id) {\n engineersRepository.deleteById(id);\n }\n public List<Collision> getCollisionsByEngineerId(int id) {\n Optional<Engineer> engineer = engineersRepository.findById(id);\n if (engineer.isPresent()) {\n Hibernate.initialize(engineer.get().getCollisions());",
"score": 0.8782734274864197
},
{
"filename": "src/main/java/ru/jbimer/core/repositories/CollisionsRepository.java",
"retrieved_chunk": " Optional<Collision> findByIdsForValidation(@Param(\"elemId1\") String elemId1,\n @Param(\"elemId2\") String elemId2,\n @Param(\"project\") Project project);\n @Modifying\n @Query(\"update Collision c set c.status = 'Done' where c.projectBase = :project \" +\n \"and c.createdAt < :currDate and (c.discipline1 = :disc1 and c.discipline2 = :disc2 \" +\n \"or c.discipline1 = :disc2 and c.discipline2 = :disc1)\")\n void updateStatus(@Param(\"currDate\") Date date,\n @Param(\"disc1\") String disc1,\n @Param(\"disc2\") String disc2,",
"score": 0.8724728226661682
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " @PatchMapping(\"/{id}/assign\")\n public String assign(@PathVariable(\"id\") int id, @ModelAttribute(\"engineer\")Engineer engineer,\n @PathVariable(\"project_id\") int project_id) {\n collisionsService.assign(id, engineer);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }\n @GetMapping(\"/{id}/fake\")\n public String markAsFake(@PathVariable(\"id\") int id, @PathVariable(\"project_id\") int project_id) {\n collisionsService.markAsFake(id);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;",
"score": 0.8491420745849609
},
{
"filename": "src/main/java/ru/jbimer/core/repositories/CollisionsRepository.java",
"retrieved_chunk": "import ru.jbimer.core.models.Engineer;\nimport ru.jbimer.core.models.Project;\nimport javax.swing.text.html.Option;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Optional;\n@Repository\npublic interface CollisionsRepository extends JpaRepository<Collision, Integer> {\n @Query(\"SELECT c FROM Collision c LEFT JOIN c.projectBase p WHERE p = :project and (c.discipline1 = :discipline or c.discipline2 = :discipline)\")\n Page<Collision> findByDisciplinesAndProject(@Param(\"discipline\") String discipline,",
"score": 0.8450056314468384
}
] |
java
|
collisionsRepository.findByIdFetchEngineer(id).ifPresent(
collision -> {
|
package ru.jbimer.core.services;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.jbimer.core.dao.EngineerDAO;
import ru.jbimer.core.models.Collision;
import ru.jbimer.core.repositories.EngineersRepository;
import ru.jbimer.core.models.Engineer;
import java.util.*;
@Service
@Transactional(readOnly = true)
public class EngineersService{
private final EngineersRepository engineersRepository;
private final EngineerDAO engineerDAO;
private final PasswordEncoder passwordEncoder;
@Autowired
public EngineersService(EngineersRepository engineersRepository, EngineerDAO engineerDAO, PasswordEncoder passwordEncoder) {
this.engineersRepository = engineersRepository;
this.engineerDAO = engineerDAO;
this.passwordEncoder = passwordEncoder;
}
public Optional<Engineer> findByUsername(String username) {
return engineersRepository.findByUsername(username);
}
public List<Engineer> findAll() {
return engineersRepository.findAll();
}
public List<Engineer> findAllOnProject(int project_id) {
return engineersRepository.findAllOnProject(project_id);
}
public List<Engineer> findAllSortedByCollisionsSize() {
List<Engineer> engineers = new ArrayList<>
|
(engineerDAO.index());
|
engineers.sort((e1, e2) -> {
int collisionsComparison = Integer.compare(e2.getCollisions().size(), e1.getCollisions().size());
if (collisionsComparison != 0) {
return collisionsComparison;
} else {
return Integer.compare(e1.getId(), e2.getId());
}
});
return engineers;
}
public Optional<Engineer> findByTelegramUsername(String telegramUsername) {
return engineersRepository.findByTelegramUsername(telegramUsername);
}
public Optional<Engineer> findByEmail(String email) {
return engineersRepository.findByEmail(email);
}
public Engineer findOne(int id) {
Optional<Engineer> foundEngineer = engineersRepository.findById(id);
return foundEngineer.orElse(null);
}
public Engineer findByIdFetchCollisions(int id) {
Optional<Engineer> foundEngineer = engineersRepository.findByIdFetchCollisions(id);
return foundEngineer.orElse(null);
}
@Transactional
public void register(Engineer engineer) {
engineer.setPassword(passwordEncoder.encode(engineer.getPassword()));
engineer.setRole("ROLE_USER");
engineersRepository.save(engineer);
}
@Transactional
public void update(int id, Engineer updatedEngineer, Engineer originalEngineer) {
originalEngineer.setDiscipline(updatedEngineer.getDiscipline());
originalEngineer.setFirstName(updatedEngineer.getFirstName());
originalEngineer.setLastName(updatedEngineer.getLastName());
engineersRepository.save(originalEngineer);
}
@Transactional
public void delete(int id) {
engineersRepository.deleteById(id);
}
public List<Collision> getCollisionsByEngineerId(int id) {
Optional<Engineer> engineer = engineersRepository.findById(id);
if (engineer.isPresent()) {
Hibernate.initialize(engineer.get().getCollisions());
return engineer.get().getCollisions();
}
else {
return Collections.emptyList();
}
}
@Transactional
public void save(Engineer engineer) {
engineersRepository.save(engineer);
}
}
|
src/main/java/ru/jbimer/core/services/EngineersService.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/services/CollisionsService.java",
"retrieved_chunk": " private final CollisionDAO collisionDAO;\n private final ProjectService projectService;\n @Autowired\n public CollisionsService(CollisionsRepository collisionsRepository, CollisionDAO collisionDAO, ProjectService projectService) {\n this.collisionsRepository = collisionsRepository;\n this.collisionDAO = collisionDAO;\n this.projectService = projectService;\n }\n public List<Collision> findByEngineer(Engineer engineer) {\n return collisionsRepository.findByEngineer(engineer);",
"score": 0.8967442512512207
},
{
"filename": "src/main/java/ru/jbimer/core/services/CollisionsService.java",
"retrieved_chunk": " }\n public Engineer getCollisionEngineer(int id) {\n return collisionsRepository.findById(id).map(Collision::getEngineer).orElse(null);\n }\n public Page<Collision> findAllWithPagination(int project_id, Pageable paging) {\n Project foundProject = projectService.findOne(project_id);\n return collisionsRepository.findByProjectBase(foundProject, paging);\n }\n public Page<Collision> searchByDiscipline(String keyword, int project_id, Pageable pageable) {\n Project foundProject = projectService.findOne(project_id);",
"score": 0.8959051370620728
},
{
"filename": "src/main/java/ru/jbimer/core/services/CollisionsService.java",
"retrieved_chunk": " }\n public List<Collision> findAllByProject(Project project) {\n return collisionsRepository.findAllByProjectBase(project);\n }\n public Collision findOne(int id) {\n Optional<Collision> foundCollision = collisionsRepository.findById(id);\n return foundCollision.orElse(null);\n }\n public Collision findOneAndEngineer(int id) {\n Optional<Collision> foundCollision = collisionsRepository.findByIdFetchEngineer(id);",
"score": 0.8941969275474548
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " public EngineersController(EngineerValidator engineerValidator, EngineersService engineersService) {\n this.engineerValidator = engineerValidator;\n this.engineersService = engineersService;\n }\n @GetMapping()\n public String index(Model model) {\n List<Engineer> engineers = engineersService.findAllSortedByCollisionsSize();\n model.addAttribute(\"engineers\", engineers);\n return \"engineers/index\";\n }",
"score": 0.8844631314277649
},
{
"filename": "src/main/java/ru/jbimer/core/dao/EngineerDAO.java",
"retrieved_chunk": "public class EngineerDAO {\n private final EntityManager entityManager;\n @Autowired\n public EngineerDAO(EntityManager entityManager) {\n this.entityManager = entityManager;\n }\n @Transactional(readOnly = true)\n public Set<Engineer> index() {\n Session session = entityManager.unwrap(Session.class);\n return new HashSet<Engineer>(session.createQuery(\"select e from Engineer e \" +",
"score": 0.8754208087921143
}
] |
java
|
(engineerDAO.index());
|
package ru.jbimer.core.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.jbimer.core.models.Collision;
import ru.jbimer.core.models.Engineer;
import ru.jbimer.core.models.Project;
import ru.jbimer.core.security.EngineerDetails;
import ru.jbimer.core.services.CollisionsService;
import ru.jbimer.core.services.EngineersService;
import ru.jbimer.core.services.HtmlReportService;
import ru.jbimer.core.services.ProjectService;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("/projects/{project_id}/collisions")
public class CollisionsController {
private final EngineersService engineersService;
private final CollisionsService collisionsService;
private final HtmlReportService service;
private final ProjectService projectService;
@Autowired
public CollisionsController(EngineersService engineersService, CollisionsService collisionsService, HtmlReportService service, ProjectService projectService) {
this.engineersService = engineersService;
this.collisionsService = collisionsService;
this.service = service;
this.projectService = projectService;
}
@GetMapping()
public String index(Model model,
@PathVariable("project_id") int project_id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
try {
List<Collision> collisions;
Pageable paging = PageRequest.of(page - 1, size, Sort.by("id"));
Page<Collision> collisionPage;
if (keyword == null) {
collisionPage = collisionsService.findAllWithPagination(project_id, paging);
} else {
collisionPage = collisionsService.searchByDiscipline(keyword, project_id, paging);
model.addAttribute("keyword", keyword);
}
collisions = collisionPage.getContent();
Project project = projectService.findOne(project_id);
model.addAttribute("collisions", collisions);
model.addAttribute("currentPage", collisionPage.getNumber() + 1);
model.addAttribute("totalItems", collisionPage.getTotalElements());
model.addAttribute("totalPages", collisionPage.getTotalPages());
model.addAttribute("pageSize", size);
model.addAttribute("project", project);
} catch (Exception e) {
model.addAttribute("message", e.getMessage());
}
return "collisions/index";
}
@GetMapping("/{id}")
public String show(@PathVariable("id") int id,
@PathVariable("project_id") int project_id,
Model model,
@ModelAttribute("engineer") Engineer engineer) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String authority = authentication.getAuthorities().stream().findFirst().orElse(null).getAuthority();
Collision collision = collisionsService.findOneAndEngineer(id);
Engineer collisionOwner = collision.getEngineer();
model.addAttribute("collision", collision);
|
model.addAttribute("comments", collision.getComments());
|
model.addAttribute("role", authority);
if (collisionOwner != null){
model.addAttribute("owner", collisionOwner);
}
else
model.addAttribute("engineers", engineersService.findAllOnProject(project_id));
return "collisions/show";
}
@GetMapping("/upload")
public String uploadCollisionsReportPage(Model model, @PathVariable("project_id") int project_id) {
model.addAttribute("project", projectService.findOne(project_id));
return "collisions/upload";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") int id, @PathVariable("project_id") int project_id) {
collisionsService.delete(id);
return "redirect:/projects/" + project_id + "/collisions";
}
@PatchMapping("/{id}/release")
public String release(@PathVariable("id") int id,
@PathVariable("project_id") int project_id) {
collisionsService.release(id);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@PatchMapping("/{id}/assign")
public String assign(@PathVariable("id") int id, @ModelAttribute("engineer")Engineer engineer,
@PathVariable("project_id") int project_id) {
collisionsService.assign(id, engineer);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@GetMapping("/{id}/fake")
public String markAsFake(@PathVariable("id") int id, @PathVariable("project_id") int project_id) {
collisionsService.markAsFake(id);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@GetMapping("/{id}/not-fake")
public String markAsNotFake(@PathVariable("id") int id, @PathVariable("project_id") int project_id) {
collisionsService.markAsNotFake(id);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@PostMapping("/{id}/add-comment")
public String addComment(@PathVariable("id") int id,
@RequestParam("comment") String comment,
@PathVariable("project_id") int project_id) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
EngineerDetails engineerDetails = (EngineerDetails) authentication.getPrincipal();
collisionsService.addComment(id, engineerDetails.getEngineer(), comment);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
}
|
src/main/java/ru/jbimer/core/controllers/CollisionsController.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " @GetMapping(\"/{id}\")\n public String show(@PathVariable(\"id\") int id, Model model) {\n Engineer engineer = engineersService.findByIdFetchCollisions(id);\n model.addAttribute(\"engineer\", engineer);\n model.addAttribute(\"collisions\", engineer.getCollisions());\n return \"engineers/show\";\n }\n @GetMapping(\"/{id}/edit\")\n public String edit(Model model, @PathVariable(\"id\") int id) {\n model.addAttribute(\"engineer\", engineersService.findOne(id));",
"score": 0.9482026100158691
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " public String show(@PathVariable(\"id\") int project_id, Model model) {\n Project project = projectService.findOne(project_id);\n List<Engineer> engineers = project.getEngineersOnProject();\n model.addAttribute(\"project\", project);\n model.addAttribute(\"engineers\", engineers);\n model.addAttribute(\"reports\", htmlReportService.findAllByProject(project));\n return \"projects/show\";\n }\n @GetMapping(\"/new\")\n public String newProject(Model model,",
"score": 0.9075019359588623
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " when(engineersService.findByIdFetchCollisions(id)).thenReturn(engineer);\n Model model = new ExtendedModelMap();\n String viewName = engineersController.show(id, model);\n assertEquals(\"engineers/show\", viewName);\n assertTrue(model.containsAttribute(\"engineer\"));\n assertSame(engineer, model.getAttribute(\"engineer\"));\n assertTrue(model.containsAttribute(\"collisions\"));\n assertSame(collisions, model.getAttribute(\"collisions\"));\n verify(engineersService).findByIdFetchCollisions(id);\n }",
"score": 0.9013611078262329
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/CollisionsControllerTest.java",
"retrieved_chunk": " .andExpect(model().attribute(\"currentPage\", equalTo(1)))\n .andExpect(model().attribute(\"totalItems\", equalTo(1L)))\n .andExpect(model().attribute(\"totalPages\", equalTo(1)))\n .andExpect(model().attribute(\"pageSize\", equalTo(10)))\n .andExpect(model().attribute(\"project_id\", equalTo(projectId)));\n }\n @Test\n void testShow() throws Exception {\n Collision collision = new Collision();\n when(collisionsService.findOneAndEngineer(1)).thenReturn(collision);",
"score": 0.892474353313446
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " public EngineersController(EngineerValidator engineerValidator, EngineersService engineersService) {\n this.engineerValidator = engineerValidator;\n this.engineersService = engineersService;\n }\n @GetMapping()\n public String index(Model model) {\n List<Engineer> engineers = engineersService.findAllSortedByCollisionsSize();\n model.addAttribute(\"engineers\", engineers);\n return \"engineers/index\";\n }",
"score": 0.8814313411712646
}
] |
java
|
model.addAttribute("comments", collision.getComments());
|
package ru.jbimer.core.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.jbimer.core.models.Collision;
import ru.jbimer.core.models.Engineer;
import ru.jbimer.core.models.Project;
import ru.jbimer.core.security.EngineerDetails;
import ru.jbimer.core.services.CollisionsService;
import ru.jbimer.core.services.EngineersService;
import ru.jbimer.core.services.HtmlReportService;
import ru.jbimer.core.services.ProjectService;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("/projects/{project_id}/collisions")
public class CollisionsController {
private final EngineersService engineersService;
private final CollisionsService collisionsService;
private final HtmlReportService service;
private final ProjectService projectService;
@Autowired
public CollisionsController(EngineersService engineersService, CollisionsService collisionsService, HtmlReportService service, ProjectService projectService) {
this.engineersService = engineersService;
this.collisionsService = collisionsService;
this.service = service;
this.projectService = projectService;
}
@GetMapping()
public String index(Model model,
@PathVariable("project_id") int project_id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
try {
List<Collision> collisions;
Pageable paging = PageRequest.of(page - 1, size, Sort.by("id"));
Page<Collision> collisionPage;
if (keyword == null) {
collisionPage = collisionsService.findAllWithPagination(project_id, paging);
} else {
collisionPage = collisionsService.searchByDiscipline(keyword, project_id, paging);
model.addAttribute("keyword", keyword);
}
collisions = collisionPage.getContent();
Project project = projectService.findOne(project_id);
model.addAttribute("collisions", collisions);
model.addAttribute("currentPage", collisionPage.getNumber() + 1);
model.addAttribute("totalItems", collisionPage.getTotalElements());
model.addAttribute("totalPages", collisionPage.getTotalPages());
model.addAttribute("pageSize", size);
model.addAttribute("project", project);
} catch (Exception e) {
model.addAttribute("message", e.getMessage());
}
return "collisions/index";
}
@GetMapping("/{id}")
public String show(@PathVariable("id") int id,
@PathVariable("project_id") int project_id,
Model model,
@ModelAttribute("engineer") Engineer engineer) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String authority = authentication.getAuthorities().stream().findFirst().orElse(null).getAuthority();
Collision collision
|
= collisionsService.findOneAndEngineer(id);
|
Engineer collisionOwner = collision.getEngineer();
model.addAttribute("collision", collision);
model.addAttribute("comments", collision.getComments());
model.addAttribute("role", authority);
if (collisionOwner != null){
model.addAttribute("owner", collisionOwner);
}
else
model.addAttribute("engineers", engineersService.findAllOnProject(project_id));
return "collisions/show";
}
@GetMapping("/upload")
public String uploadCollisionsReportPage(Model model, @PathVariable("project_id") int project_id) {
model.addAttribute("project", projectService.findOne(project_id));
return "collisions/upload";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") int id, @PathVariable("project_id") int project_id) {
collisionsService.delete(id);
return "redirect:/projects/" + project_id + "/collisions";
}
@PatchMapping("/{id}/release")
public String release(@PathVariable("id") int id,
@PathVariable("project_id") int project_id) {
collisionsService.release(id);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@PatchMapping("/{id}/assign")
public String assign(@PathVariable("id") int id, @ModelAttribute("engineer")Engineer engineer,
@PathVariable("project_id") int project_id) {
collisionsService.assign(id, engineer);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@GetMapping("/{id}/fake")
public String markAsFake(@PathVariable("id") int id, @PathVariable("project_id") int project_id) {
collisionsService.markAsFake(id);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@GetMapping("/{id}/not-fake")
public String markAsNotFake(@PathVariable("id") int id, @PathVariable("project_id") int project_id) {
collisionsService.markAsNotFake(id);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@PostMapping("/{id}/add-comment")
public String addComment(@PathVariable("id") int id,
@RequestParam("comment") String comment,
@PathVariable("project_id") int project_id) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
EngineerDetails engineerDetails = (EngineerDetails) authentication.getPrincipal();
collisionsService.addComment(id, engineerDetails.getEngineer(), comment);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
}
|
src/main/java/ru/jbimer/core/controllers/CollisionsController.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " @GetMapping(\"/{id}\")\n public String show(@PathVariable(\"id\") int id, Model model) {\n Engineer engineer = engineersService.findByIdFetchCollisions(id);\n model.addAttribute(\"engineer\", engineer);\n model.addAttribute(\"collisions\", engineer.getCollisions());\n return \"engineers/show\";\n }\n @GetMapping(\"/{id}/edit\")\n public String edit(Model model, @PathVariable(\"id\") int id) {\n model.addAttribute(\"engineer\", engineersService.findOne(id));",
"score": 0.9600204825401306
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " public String show(@PathVariable(\"id\") int project_id, Model model) {\n Project project = projectService.findOne(project_id);\n List<Engineer> engineers = project.getEngineersOnProject();\n model.addAttribute(\"project\", project);\n model.addAttribute(\"engineers\", engineers);\n model.addAttribute(\"reports\", htmlReportService.findAllByProject(project));\n return \"projects/show\";\n }\n @GetMapping(\"/new\")\n public String newProject(Model model,",
"score": 0.9082343578338623
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " when(engineersService.findByIdFetchCollisions(id)).thenReturn(engineer);\n Model model = new ExtendedModelMap();\n String viewName = engineersController.show(id, model);\n assertEquals(\"engineers/show\", viewName);\n assertTrue(model.containsAttribute(\"engineer\"));\n assertSame(engineer, model.getAttribute(\"engineer\"));\n assertTrue(model.containsAttribute(\"collisions\"));\n assertSame(collisions, model.getAttribute(\"collisions\"));\n verify(engineersService).findByIdFetchCollisions(id);\n }",
"score": 0.904519259929657
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/CollisionsControllerTest.java",
"retrieved_chunk": " .andExpect(model().attribute(\"currentPage\", equalTo(1)))\n .andExpect(model().attribute(\"totalItems\", equalTo(1L)))\n .andExpect(model().attribute(\"totalPages\", equalTo(1)))\n .andExpect(model().attribute(\"pageSize\", equalTo(10)))\n .andExpect(model().attribute(\"project_id\", equalTo(projectId)));\n }\n @Test\n void testShow() throws Exception {\n Collision collision = new Collision();\n when(collisionsService.findOneAndEngineer(1)).thenReturn(collision);",
"score": 0.8995165824890137
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " public EngineersController(EngineerValidator engineerValidator, EngineersService engineersService) {\n this.engineerValidator = engineerValidator;\n this.engineersService = engineersService;\n }\n @GetMapping()\n public String index(Model model) {\n List<Engineer> engineers = engineersService.findAllSortedByCollisionsSize();\n model.addAttribute(\"engineers\", engineers);\n return \"engineers/index\";\n }",
"score": 0.887197732925415
}
] |
java
|
= collisionsService.findOneAndEngineer(id);
|
package ru.jbimer.core.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.jbimer.core.models.Collision;
import ru.jbimer.core.models.Engineer;
import ru.jbimer.core.models.Project;
import ru.jbimer.core.security.EngineerDetails;
import ru.jbimer.core.services.CollisionsService;
import ru.jbimer.core.services.EngineersService;
import ru.jbimer.core.services.HtmlReportService;
import ru.jbimer.core.services.ProjectService;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("/projects/{project_id}/collisions")
public class CollisionsController {
private final EngineersService engineersService;
private final CollisionsService collisionsService;
private final HtmlReportService service;
private final ProjectService projectService;
@Autowired
public CollisionsController(EngineersService engineersService, CollisionsService collisionsService, HtmlReportService service, ProjectService projectService) {
this.engineersService = engineersService;
this.collisionsService = collisionsService;
this.service = service;
this.projectService = projectService;
}
@GetMapping()
public String index(Model model,
@PathVariable("project_id") int project_id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
try {
List<Collision> collisions;
Pageable paging = PageRequest.of(page - 1, size, Sort.by("id"));
Page<Collision> collisionPage;
if (keyword == null) {
collisionPage = collisionsService.findAllWithPagination(project_id, paging);
} else {
collisionPage = collisionsService.searchByDiscipline(keyword, project_id, paging);
model.addAttribute("keyword", keyword);
}
collisions = collisionPage.getContent();
Project project = projectService.findOne(project_id);
model.addAttribute("collisions", collisions);
model.addAttribute("currentPage", collisionPage.getNumber() + 1);
model.addAttribute("totalItems", collisionPage.getTotalElements());
model.addAttribute("totalPages", collisionPage.getTotalPages());
model.addAttribute("pageSize", size);
model.addAttribute("project", project);
} catch (Exception e) {
model.addAttribute("message", e.getMessage());
}
return "collisions/index";
}
@GetMapping("/{id}")
public String show(@PathVariable("id") int id,
@PathVariable("project_id") int project_id,
Model model,
@ModelAttribute("engineer") Engineer engineer) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String authority = authentication.getAuthorities().stream().findFirst().orElse(null).getAuthority();
Collision collision = collisionsService.findOneAndEngineer(id);
Engineer collisionOwner = collision.getEngineer();
model.addAttribute("collision", collision);
model.addAttribute("comments", collision.getComments());
model.addAttribute("role", authority);
if (collisionOwner != null){
model.addAttribute("owner", collisionOwner);
}
else
model.addAttribute("engineers", engineersService.findAllOnProject(project_id));
return "collisions/show";
}
@GetMapping("/upload")
public String uploadCollisionsReportPage(Model model, @PathVariable("project_id") int project_id) {
model.addAttribute("project", projectService.findOne(project_id));
return "collisions/upload";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") int id, @PathVariable("project_id") int project_id) {
collisionsService.delete(id);
return "redirect:/projects/" + project_id + "/collisions";
}
@PatchMapping("/{id}/release")
public String release(@PathVariable("id") int id,
@PathVariable("project_id") int project_id) {
collisionsService.release(id);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@PatchMapping("/{id}/assign")
public String assign(@PathVariable("id") int id, @ModelAttribute("engineer")Engineer engineer,
@PathVariable("project_id") int project_id) {
collisionsService.assign(id, engineer);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@GetMapping("/{id}/fake")
public String markAsFake(@PathVariable("id") int id, @PathVariable("project_id") int project_id) {
collisionsService.markAsFake(id);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@GetMapping("/{id}/not-fake")
public String markAsNotFake(@PathVariable("id") int id, @PathVariable("project_id") int project_id) {
collisionsService.markAsNotFake(id);
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
@PostMapping("/{id}/add-comment")
public String addComment(@PathVariable("id") int id,
@RequestParam("comment") String comment,
@PathVariable("project_id") int project_id) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
EngineerDetails engineerDetails = (EngineerDetails) authentication.getPrincipal();
collisionsService.addComment
|
(id, engineerDetails.getEngineer(), comment);
|
return "redirect:/projects/" + project_id + "/collisions/" + id;
}
}
|
src/main/java/ru/jbimer/core/controllers/CollisionsController.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " return \"redirect:/projects\";\n }\n @GetMapping(\"/{id}/edit\")\n public String edit(Model model, @PathVariable(\"id\") int id) {\n model.addAttribute(\"project\", projectService.findOne(id));\n model.addAttribute(\"engineers\", engineersService.findAll());\n return \"projects/edit\";\n }\n @PatchMapping(\"/{id}\")\n public String update(@ModelAttribute(\"project\") @Valid Project project,",
"score": 0.8790910243988037
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " BindingResult bindingResult,\n @PathVariable(\"id\") int id) {\n if (bindingResult.hasErrors()) return \"projects/edit\";\n projectService.save(project);\n return \"redirect:/projects/\" + id;\n }\n @DeleteMapping(\"/{id}\")\n public String delete(@PathVariable(\"id\") int id){\n projectService.delete(id);\n return \"redirect:/projects\";",
"score": 0.8616969585418701
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ReportUploadController.java",
"retrieved_chunk": " EngineerDetails engineerDetails = (EngineerDetails) authentication.getPrincipal();\n Project project = projectService.findOne(project_id);\n int collisions = htmlReportService.uploadFile(file, engineerDetails.getEngineer(), project);\n model.addAttribute(\"collisionsUpdated\", collisions);\n model.addAttribute(\"project\", project);\n return \"collisions/upload\";\n }\n}",
"score": 0.857577919960022
},
{
"filename": "src/main/java/ru/jbimer/core/services/CollisionsService.java",
"retrieved_chunk": " public void assign(int id, Engineer selectedEngineer) {\n collisionsRepository.findByIdFetchEngineer(id).ifPresent(\n collision -> {\n collision.setEngineer(selectedEngineer);\n }\n );\n }\n @Transactional\n public void addComment(int id, Engineer selectedEngineer, String comment) {\n Optional<Collision> optionalCollision = collisionsRepository.findByIdFetchEngineer(id);",
"score": 0.850767195224762
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " }\n @DeleteMapping(\"/{id}\")\n public String delete(@PathVariable(\"id\") int id) {\n engineersService.delete(id);\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n if (authentication != null && authentication.isAuthenticated()) {\n SecurityContextHolder.getContext().setAuthentication(null);\n }\n return \"redirect:/logout\";\n }",
"score": 0.8502398729324341
}
] |
java
|
(id, engineerDetails.getEngineer(), comment);
|
package ru.jbimer.core.services;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.jbimer.core.dao.EngineerDAO;
import ru.jbimer.core.models.Collision;
import ru.jbimer.core.repositories.EngineersRepository;
import ru.jbimer.core.models.Engineer;
import java.util.*;
@Service
@Transactional(readOnly = true)
public class EngineersService{
private final EngineersRepository engineersRepository;
private final EngineerDAO engineerDAO;
private final PasswordEncoder passwordEncoder;
@Autowired
public EngineersService(EngineersRepository engineersRepository, EngineerDAO engineerDAO, PasswordEncoder passwordEncoder) {
this.engineersRepository = engineersRepository;
this.engineerDAO = engineerDAO;
this.passwordEncoder = passwordEncoder;
}
public Optional<Engineer> findByUsername(String username) {
return engineersRepository.findByUsername(username);
}
public List<Engineer> findAll() {
return engineersRepository.findAll();
}
public List<Engineer> findAllOnProject(int project_id) {
return engineersRepository.findAllOnProject(project_id);
}
public List<Engineer> findAllSortedByCollisionsSize() {
List<Engineer> engineers = new ArrayList<>(engineerDAO.index());
engineers.sort((e1, e2) -> {
int collisionsComparison = Integer.compare(e2.getCollisions().size(), e1.getCollisions().size());
if (collisionsComparison != 0) {
return collisionsComparison;
} else {
return Integer.compare(e1.getId(), e2.getId());
}
});
return engineers;
}
public Optional<Engineer> findByTelegramUsername(String telegramUsername) {
return engineersRepository.findByTelegramUsername(telegramUsername);
}
public Optional<Engineer> findByEmail(String email) {
return engineersRepository.findByEmail(email);
}
public Engineer findOne(int id) {
Optional<Engineer> foundEngineer = engineersRepository.findById(id);
return foundEngineer.orElse(null);
}
public Engineer findByIdFetchCollisions(int id) {
Optional<
|
Engineer> foundEngineer = engineersRepository.findByIdFetchCollisions(id);
|
return foundEngineer.orElse(null);
}
@Transactional
public void register(Engineer engineer) {
engineer.setPassword(passwordEncoder.encode(engineer.getPassword()));
engineer.setRole("ROLE_USER");
engineersRepository.save(engineer);
}
@Transactional
public void update(int id, Engineer updatedEngineer, Engineer originalEngineer) {
originalEngineer.setDiscipline(updatedEngineer.getDiscipline());
originalEngineer.setFirstName(updatedEngineer.getFirstName());
originalEngineer.setLastName(updatedEngineer.getLastName());
engineersRepository.save(originalEngineer);
}
@Transactional
public void delete(int id) {
engineersRepository.deleteById(id);
}
public List<Collision> getCollisionsByEngineerId(int id) {
Optional<Engineer> engineer = engineersRepository.findById(id);
if (engineer.isPresent()) {
Hibernate.initialize(engineer.get().getCollisions());
return engineer.get().getCollisions();
}
else {
return Collections.emptyList();
}
}
@Transactional
public void save(Engineer engineer) {
engineersRepository.save(engineer);
}
}
|
src/main/java/ru/jbimer/core/services/EngineersService.java
|
mitrofmep-JBimer-fd7a0ba
|
[
{
"filename": "src/main/java/ru/jbimer/core/repositories/EngineersRepository.java",
"retrieved_chunk": " Optional<Engineer> findByTelegramUsername(String telegramUsername);\n Optional<Engineer> findByEmail(String email);\n Optional<Engineer> findByUsername(String username);\n @Query(\"SELECT e FROM Engineer e LEFT JOIN FETCH e.collisions WHERE e.id = :id\")\n Optional<Engineer> findByIdFetchCollisions(@Param(\"id\") int id);\n @Query(\"SELECT e FROM Engineer e LEFT JOIN FETCH e.projects p where p.id = :project_id\")\n List<Engineer> findAllOnProject(@Param(\"project_id\") int id);\n}",
"score": 0.9125233888626099
},
{
"filename": "src/main/java/ru/jbimer/core/services/CollisionsService.java",
"retrieved_chunk": " }\n public Engineer getCollisionEngineer(int id) {\n return collisionsRepository.findById(id).map(Collision::getEngineer).orElse(null);\n }\n public Page<Collision> findAllWithPagination(int project_id, Pageable paging) {\n Project foundProject = projectService.findOne(project_id);\n return collisionsRepository.findByProjectBase(foundProject, paging);\n }\n public Page<Collision> searchByDiscipline(String keyword, int project_id, Pageable pageable) {\n Project foundProject = projectService.findOne(project_id);",
"score": 0.8739413022994995
},
{
"filename": "src/main/java/ru/jbimer/core/services/CollisionsService.java",
"retrieved_chunk": " }\n public List<Collision> findAllByProject(Project project) {\n return collisionsRepository.findAllByProjectBase(project);\n }\n public Collision findOne(int id) {\n Optional<Collision> foundCollision = collisionsRepository.findById(id);\n return foundCollision.orElse(null);\n }\n public Collision findOneAndEngineer(int id) {\n Optional<Collision> foundCollision = collisionsRepository.findByIdFetchEngineer(id);",
"score": 0.8618394732475281
},
{
"filename": "src/main/java/ru/jbimer/core/services/EngineerDetailsService.java",
"retrieved_chunk": " Optional<Engineer> engineer = engineersRepository.findByUsername(username);\n if (engineer.isEmpty())\n throw new UsernameNotFoundException(\"User not found\");\n return new EngineerDetails(engineer.get());\n }\n}",
"score": 0.8571863174438477
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " @GetMapping(\"/{id}\")\n public String show(@PathVariable(\"id\") int id, Model model) {\n Engineer engineer = engineersService.findByIdFetchCollisions(id);\n model.addAttribute(\"engineer\", engineer);\n model.addAttribute(\"collisions\", engineer.getCollisions());\n return \"engineers/show\";\n }\n @GetMapping(\"/{id}/edit\")\n public String edit(Model model, @PathVariable(\"id\") int id) {\n model.addAttribute(\"engineer\", engineersService.findOne(id));",
"score": 0.8562516570091248
}
] |
java
|
Engineer> foundEngineer = engineersRepository.findByIdFetchCollisions(id);
|
/*
* Copyright (c) 2023. MyWorld, LLC.
*
* 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 com.myworldvw.buoy.mapping;
import com.myworldvw.buoy.Array;
import com.myworldvw.buoy.FieldDef;
import com.myworldvw.buoy.NativeMapper;
import com.myworldvw.buoy.Pointer;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;
public class FieldHandler<T> implements StructMappingHandler<T> {
protected final FieldDef model;
protected final Field field;
protected volatile VarHandle handle;
public FieldHandler(FieldDef model, Field field){
this.model = model;
this.field = field;
}
public VarHandle getHandle(MemoryLayout layout){
return layout.varHandle(MemoryLayout.PathElement.groupElement(model.name()));
}
public MethodHandle getAccessor(MemoryLayout layout, VarHandle.AccessMode mode){
return getHandle(layout).toMethodHandle(mode);
}
public MethodHandle getGetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.GET);
}
public MethodHandle getGetter(MemorySegment ptr, MemoryLayout layout){
return getGetter(layout).bindTo(ptr);
}
public MethodHandle getSetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.SET);
}
public MethodHandle getSetter(MemorySegment ptr, MemoryLayout layout){
return getSetter(layout).bindTo(ptr);
}
@Override
public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {
// Given the field type:
// If it's a VarHandle, we get a handle to the field in the struct
// If it's a MemorySegment, we calculate the field offset and assign it
// If it's an Array, we bind it to the segment
// If it's an object, we determine if it's a nested struct or a pointer to a struct,
// and we populate it with the offset of the field (nested) *or* the memory address
// contained in the field (pointer) as the object's self-pointer segment
if(Util.skipField(field, target)){
return;
}
var fieldType = field.getType();
if(fieldType.equals(VarHandle.class)){
if(handle == null){
|
handle = getHandle(mapper.getLayout(target.getClass()));
|
}
field.set(target, handle);
}else if(fieldType.equals(MemorySegment.class)){
field.set(target, segmentForField(mapper, target, segment));
}else if(fieldType.equals(Array.class)){
field.set(target, new Array<>(
arraySegmentForField(mapper, target, segment),
mapper.getLayout(model.type()),
model.type(),
model.isPointer()
));
} else{
var structDef = mapper.getOrDefineStruct(fieldType);
if(structDef == null){
throw new IllegalArgumentException("Not a mappable type for a field handle: " + fieldType);
}
var structSegment = segmentForField(mapper, target, segment);
if(model.isPointer()){
// If this is a pointer type, we have to construct a new segment starting at the address
// contained in this segment, with the length of the field type.
structSegment = MemorySegment.ofAddress(
Pointer.getAddress(structSegment),
mapper.sizeOf(model.type()),
structSegment.scope());
}
var nestedTarget = field.get(target);
if(nestedTarget != null){
mapper.populate(nestedTarget, structSegment);
}
}
}
protected MemorySegment arraySegmentForField(NativeMapper mapper, Object target, MemorySegment segment){
// 1. If model is a pointer (*type[length]), dereference to get the address of the array.
// 2. Create a segment appropriate to the array type * length
var fieldSegment = segmentForField(mapper, target, segment);
var address = fieldSegment.address();
if(model.isPointer()){
address = Pointer.getAddress(fieldSegment);
}
var elementType = mapper.getLayout(model.type());
return MemorySegment.ofAddress(address, elementType.byteSize() * model.array(), segment.scope());
}
protected MemorySegment segmentForField(NativeMapper mapper, Object target, MemorySegment segment){
var offset = mapper.getLayout(target.getClass()).byteOffset(MemoryLayout.PathElement.groupElement(model.name()));
return model.isPointer()
? segment.asSlice(offset, ValueLayout.ADDRESS.byteSize())
: segment.asSlice(offset, mapper.sizeOf(model));
}
}
|
lib/src/main/java/com/myworldvw/buoy/mapping/FieldHandler.java
|
MyWorldLLC-Buoy-c7d77a1
|
[
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/SelfPointerHandler.java",
"retrieved_chunk": " protected final Field field;\n public SelfPointerHandler(Field field){\n this.field = field;\n }\n @Override\n public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {\n if(!Util.skipField(field, target)){\n field.set(target, segment);\n }\n }",
"score": 0.8644829988479614
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " if(selfPtr != null){\n if(structDef == null){\n throw new IllegalArgumentException(\"Cannot use @SelfPointer on a non-struct class: \" + targetType.getName());\n }\n fieldHandlers.add(new SelfPointerHandler<>(field));\n }\n var fieldHandle = field.getAnnotation(FieldHandle.class);\n if(fieldHandle != null){\n if(structDef == null){\n throw new IllegalArgumentException(\"Cannot use @FieldHandle on a non-struct class: \" + targetType.getName());",
"score": 0.8588978052139282
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " }\n fieldHandlers.add(new FieldHandler<>(structDef.field(fieldHandle.name()), field));\n // Recurse to register nested struct types\n if(!field.getType().equals(VarHandle.class) &&\n !field.getType().equals(MemorySegment.class) &&\n !isRegistered(field.getType())){\n register(field.getType());\n }\n }\n var functionHandle = field.getAnnotation(FunctionHandle.class);",
"score": 0.853620171546936
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " if(isStructType(targetType)){\n structDef = getOrDefineStruct(targetType);\n }\n var fieldHandlers = new ArrayList<StructMappingHandler<T>>();\n var functionHandlers = new ArrayList<FunctionHandler<T>>();\n var globalHandlers = new ArrayList<GlobalHandler<T>>();\n for(var field : targetType.getDeclaredFields()){\n field.setAccessible(true);\n // Handle self pointers\n var selfPtr = field.getAnnotation(SelfPointer.class);",
"score": 0.8517273664474487
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/GlobalHandler.java",
"retrieved_chunk": " this.pointer = pointer;\n if(!field.getType().equals(MemorySegment.class)){\n throw new IllegalArgumentException(\"Globals can only be accessed via MemorySegment\");\n }\n }\n @Override\n public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {\n if(Util.skipField(field, target)){\n return;\n }",
"score": 0.8494304418563843
}
] |
java
|
handle = getHandle(mapper.getLayout(target.getClass()));
|
/*
* Copyright (c) 2023. MyWorld, LLC.
*
* 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 com.myworldvw.buoy.mapping;
import com.myworldvw.buoy.Array;
import com.myworldvw.buoy.FieldDef;
import com.myworldvw.buoy.NativeMapper;
import com.myworldvw.buoy.Pointer;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;
public class FieldHandler<T> implements StructMappingHandler<T> {
protected final FieldDef model;
protected final Field field;
protected volatile VarHandle handle;
public FieldHandler(FieldDef model, Field field){
this.model = model;
this.field = field;
}
public VarHandle getHandle(MemoryLayout layout){
return layout.varHandle(MemoryLayout.PathElement.groupElement(model.name()));
}
public MethodHandle getAccessor(MemoryLayout layout, VarHandle.AccessMode mode){
return getHandle(layout).toMethodHandle(mode);
}
public MethodHandle getGetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.GET);
}
public MethodHandle getGetter(MemorySegment ptr, MemoryLayout layout){
return getGetter(layout).bindTo(ptr);
}
public MethodHandle getSetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.SET);
}
public MethodHandle getSetter(MemorySegment ptr, MemoryLayout layout){
return getSetter(layout).bindTo(ptr);
}
@Override
public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {
// Given the field type:
// If it's a VarHandle, we get a handle to the field in the struct
// If it's a MemorySegment, we calculate the field offset and assign it
// If it's an Array, we bind it to the segment
// If it's an object, we determine if it's a nested struct or a pointer to a struct,
// and we populate it with the offset of the field (nested) *or* the memory address
// contained in the field (pointer) as the object's self-pointer segment
if(Util.skipField(field, target)){
return;
}
var fieldType = field.getType();
if(fieldType.equals(VarHandle.class)){
if(handle == null){
handle = getHandle(mapper.getLayout(target.getClass()));
}
field.set(target, handle);
}else if(fieldType.equals(MemorySegment.class)){
field.set(target, segmentForField(mapper, target, segment));
}else if(fieldType.equals(Array.class)){
field.set(target, new Array<>(
arraySegmentForField(mapper, target, segment),
mapper.getLayout(model.type()),
model.type(),
model.isPointer()
));
} else{
var structDef = mapper.getOrDefineStruct(fieldType);
if(structDef == null){
throw new IllegalArgumentException("Not a mappable type for a field handle: " + fieldType);
}
var structSegment = segmentForField(mapper, target, segment);
if(model.isPointer()){
// If this is a pointer type, we have to construct a new segment starting at the address
// contained in this segment, with the length of the field type.
structSegment = MemorySegment.ofAddress(
Pointer.getAddress(structSegment),
mapper.sizeOf(model.type()),
structSegment.scope());
}
var nestedTarget = field.get(target);
if(nestedTarget != null){
mapper.populate(nestedTarget, structSegment);
}
}
}
protected MemorySegment arraySegmentForField(NativeMapper mapper, Object target, MemorySegment segment){
// 1. If model is a pointer (*type[length]), dereference to get the address of the array.
// 2. Create a segment appropriate to the array type * length
var fieldSegment = segmentForField(mapper, target, segment);
var address = fieldSegment.address();
if(model.isPointer()){
address = Pointer.getAddress(fieldSegment);
}
var elementType = mapper.getLayout(model.type());
return MemorySegment.ofAddress(address, elementType.byteSize() * model.array(), segment.scope());
}
protected MemorySegment segmentForField(NativeMapper mapper, Object target, MemorySegment segment){
var offset =
|
mapper.getLayout(target.getClass()).byteOffset(MemoryLayout.PathElement.groupElement(model.name()));
|
return model.isPointer()
? segment.asSlice(offset, ValueLayout.ADDRESS.byteSize())
: segment.asSlice(offset, mapper.sizeOf(model));
}
}
|
lib/src/main/java/com/myworldvw/buoy/mapping/FieldHandler.java
|
MyWorldLLC-Buoy-c7d77a1
|
[
{
"filename": "lib/src/main/java/com/myworldvw/buoy/Pointer.java",
"retrieved_chunk": " return MemorySegment.ofAddress(p.address(), targetType.byteSize(), p.scope());\n }\n public static MemorySegment cast(MemorySegment p, MemoryLayout targetType, SegmentScope scope){\n return MemorySegment.ofAddress(p.address(), targetType.byteSize(), scope);\n }\n public static long getAddress(MemorySegment p){\n return p.get(ValueLayout.ADDRESS, 0).address();\n }\n public static void setAddress(MemorySegment p, long a){\n p.set(ValueLayout.ADDRESS, 0, MemorySegment.ofAddress(a));",
"score": 0.8709805607795715
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " }\n public <T> Array<T> arrayOf(MemorySegment array, Class<T> type, boolean isPointer, long length, SegmentScope scope){\n var segment = Array.cast(array, getLayout(type), length, scope);\n return arrayOf(segment, type, isPointer);\n }\n public <T> Array<T> arrayOf(MemorySegment array, Class<T> type){\n return arrayOf(array, type, false);\n }\n public <T> Array<T> arrayOf(MemorySegment array, Class<T> type, boolean isPointer){\n return new Array<>(array, getLayout(type), type, isPointer);",
"score": 0.855609118938446
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/Array.java",
"retrieved_chunk": " }\n public MemorySegment get(long index){\n return get(array, typeLayout, index);\n }\n public T get(long index, T target, NativeMapper mapper) throws IllegalAccessException {\n mapper.populate(target, get(index));\n return target;\n }\n public void set(long index, MemorySegment value){\n set(array, typeLayout, index, value);",
"score": 0.855197548866272
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/SelfPointerHandler.java",
"retrieved_chunk": " protected final Field field;\n public SelfPointerHandler(Field field){\n this.field = field;\n }\n @Override\n public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {\n if(!Util.skipField(field, target)){\n field.set(target, segment);\n }\n }",
"score": 0.8550872206687927
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/Array.java",
"retrieved_chunk": " }\n public static MemorySegment cast(MemorySegment p, MemoryLayout targetType, long length, SegmentScope scope){\n return Pointer.cast(p, MemoryLayout.sequenceLayout(length, targetType), scope);\n }\n public static MemorySegment get(MemorySegment p, MemoryLayout type, long index){\n return p.asSlice(type.byteSize() * index, type.byteSize());\n }\n public static void set(MemorySegment p, MemoryLayout type, long index, MemorySegment e){\n MemorySegment.copy(e, 0, p, type.byteSize() * index, type.byteSize());\n }",
"score": 0.8547168374061584
}
] |
java
|
mapper.getLayout(target.getClass()).byteOffset(MemoryLayout.PathElement.groupElement(model.name()));
|
/*
* Copyright (c) 2023. MyWorld, LLC.
*
* 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 com.myworldvw.buoy.mapping;
import com.myworldvw.buoy.Array;
import com.myworldvw.buoy.FieldDef;
import com.myworldvw.buoy.NativeMapper;
import com.myworldvw.buoy.Pointer;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;
public class FieldHandler<T> implements StructMappingHandler<T> {
protected final FieldDef model;
protected final Field field;
protected volatile VarHandle handle;
public FieldHandler(FieldDef model, Field field){
this.model = model;
this.field = field;
}
public VarHandle getHandle(MemoryLayout layout){
return layout.varHandle(MemoryLayout.PathElement.groupElement(model.name()));
}
public MethodHandle getAccessor(MemoryLayout layout, VarHandle.AccessMode mode){
return getHandle(layout).toMethodHandle(mode);
}
public MethodHandle getGetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.GET);
}
public MethodHandle getGetter(MemorySegment ptr, MemoryLayout layout){
return getGetter(layout).bindTo(ptr);
}
public MethodHandle getSetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.SET);
}
public MethodHandle getSetter(MemorySegment ptr, MemoryLayout layout){
return getSetter(layout).bindTo(ptr);
}
@Override
public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {
// Given the field type:
// If it's a VarHandle, we get a handle to the field in the struct
// If it's a MemorySegment, we calculate the field offset and assign it
// If it's an Array, we bind it to the segment
// If it's an object, we determine if it's a nested struct or a pointer to a struct,
// and we populate it with the offset of the field (nested) *or* the memory address
// contained in the field (pointer) as the object's self-pointer segment
if(Util.skipField(field, target)){
return;
}
var fieldType = field.getType();
if(fieldType.equals(VarHandle.class)){
if(handle == null){
handle = getHandle(mapper.getLayout(target.getClass()));
}
field.set(target, handle);
}else if(fieldType.equals(MemorySegment.class)){
field.set(target, segmentForField(mapper, target, segment));
}else if(fieldType.equals(Array.class)){
field.set(target, new Array<>(
arraySegmentForField(mapper, target, segment),
mapper.getLayout(model.type()),
model.type(),
model.isPointer()
));
} else{
|
var structDef = mapper.getOrDefineStruct(fieldType);
|
if(structDef == null){
throw new IllegalArgumentException("Not a mappable type for a field handle: " + fieldType);
}
var structSegment = segmentForField(mapper, target, segment);
if(model.isPointer()){
// If this is a pointer type, we have to construct a new segment starting at the address
// contained in this segment, with the length of the field type.
structSegment = MemorySegment.ofAddress(
Pointer.getAddress(structSegment),
mapper.sizeOf(model.type()),
structSegment.scope());
}
var nestedTarget = field.get(target);
if(nestedTarget != null){
mapper.populate(nestedTarget, structSegment);
}
}
}
protected MemorySegment arraySegmentForField(NativeMapper mapper, Object target, MemorySegment segment){
// 1. If model is a pointer (*type[length]), dereference to get the address of the array.
// 2. Create a segment appropriate to the array type * length
var fieldSegment = segmentForField(mapper, target, segment);
var address = fieldSegment.address();
if(model.isPointer()){
address = Pointer.getAddress(fieldSegment);
}
var elementType = mapper.getLayout(model.type());
return MemorySegment.ofAddress(address, elementType.byteSize() * model.array(), segment.scope());
}
protected MemorySegment segmentForField(NativeMapper mapper, Object target, MemorySegment segment){
var offset = mapper.getLayout(target.getClass()).byteOffset(MemoryLayout.PathElement.groupElement(model.name()));
return model.isPointer()
? segment.asSlice(offset, ValueLayout.ADDRESS.byteSize())
: segment.asSlice(offset, mapper.sizeOf(model));
}
}
|
lib/src/main/java/com/myworldvw/buoy/mapping/FieldHandler.java
|
MyWorldLLC-Buoy-c7d77a1
|
[
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/SelfPointerHandler.java",
"retrieved_chunk": " protected final Field field;\n public SelfPointerHandler(Field field){\n this.field = field;\n }\n @Override\n public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {\n if(!Util.skipField(field, target)){\n field.set(target, segment);\n }\n }",
"score": 0.8596028685569763
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " if(isStructType(targetType)){\n structDef = getOrDefineStruct(targetType);\n }\n var fieldHandlers = new ArrayList<StructMappingHandler<T>>();\n var functionHandlers = new ArrayList<FunctionHandler<T>>();\n var globalHandlers = new ArrayList<GlobalHandler<T>>();\n for(var field : targetType.getDeclaredFields()){\n field.setAccessible(true);\n // Handle self pointers\n var selfPtr = field.getAnnotation(SelfPointer.class);",
"score": 0.8511065244674683
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/GlobalHandler.java",
"retrieved_chunk": " if(symbolPtr == null){\n symbolPtr = mapper.getLookup().find(name)\n .map(symbol -> Pointer.cast(symbol, mapper.getLayout(pointer ? MemorySegment.class : type)))\n .orElseThrow(() -> new IllegalArgumentException(\"Symbol \" + name + \" not found\"));\n }\n field.set(target, symbolPtr);\n }\n}",
"score": 0.8475751876831055
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/GlobalHandler.java",
"retrieved_chunk": " this.pointer = pointer;\n if(!field.getType().equals(MemorySegment.class)){\n throw new IllegalArgumentException(\"Globals can only be accessed via MemorySegment\");\n }\n }\n @Override\n public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {\n if(Util.skipField(field, target)){\n return;\n }",
"score": 0.8474592566490173
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " return target;\n }\n public NativeMapper populateStatic(Class<?> target) throws IllegalAccessException {\n populate(target, null);\n return this;\n }\n public long sizeOf(FieldDef field){\n return field.isPointer() ? sizeOf(MemorySegment.class) : sizeOf(field.type());\n }\n public long sizeOf(Class<?> type){",
"score": 0.8403711318969727
}
] |
java
|
var structDef = mapper.getOrDefineStruct(fieldType);
|
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
|
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
|
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }\n }",
"score": 0.8929663896560669
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " addProxyProtocolHandler(channel, playerAddress);\n instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, velocityServer, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }",
"score": 0.8928642272949219
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {\n channel.close();\n instance.getCore().debug(\"Close connection IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (close / return)\");\n return;\n }\n instance.getCore().debug(\"Adding handler...\");\n if (instance.getCore().isSetup() && Config.isProxyProtocol()) {\n addProxyProtocolHandler(channel, playerAddress);",
"score": 0.8862928748130798
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {\n channel.close();\n instance.getCore().debug(\"Close connection IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (close / return)\");\n return;\n }\n instance.getCore().debug(\"Adding handler...\");\n if (instance.getCore().isSetup() && Config.isProxyProtocol()) {",
"score": 0.8732703924179077
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import java.util.logging.Level;\npublic class ProxyProtocol {\n private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, \"channel\", ChannelWrapper.class);\n private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;\n private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectBungee instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 0.8634110689163208
}
] |
java
|
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
|
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
|
instance.getCore().debug("Adding Handler...");
|
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {\n channel.close();\n instance.getCore().debug(\"Close connection IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (close / return)\");\n return;\n }\n instance.getCore().debug(\"Adding handler...\");\n if (instance.getCore().isSetup() && Config.isProxyProtocol()) {\n addProxyProtocolHandler(channel, playerAddress);",
"score": 0.9268624186515808
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {\n channel.close();\n instance.getCore().debug(\"Close connection IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (close / return)\");\n return;\n }\n instance.getCore().debug(\"Adding handler...\");\n if (instance.getCore().isSetup() && Config.isProxyProtocol()) {",
"score": 0.9179816246032715
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }\n }",
"score": 0.8632475137710571
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " addProxyProtocolHandler(channel, playerAddress);\n instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, velocityServer, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }",
"score": 0.8524670004844666
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " map.get(player.getUsername()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));\n instance.getCore().debug(\"Loading completed\");\n instance.getCore().debug(\" \");\n }\n pingMap.remove(keepAliveResponseKey);\n }\n }\n });\n }\n public static boolean isIPInRange(String ipRange, String ipAddress) {",
"score": 0.8341750502586365
}
] |
java
|
instance.getCore().debug("Adding Handler...");
|
package de.cubeattack.neoprotect.velocity.messageunsign;
import com.velocitypowered.api.event.Continuation;
import com.velocitypowered.api.event.EventTask;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.DisconnectEvent;
import com.velocitypowered.api.event.connection.PostLoginEvent;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.proxy.connection.client.ConnectedPlayer;
import de.cubeattack.neoprotect.velocity.NeoProtectVelocity;
import io.netty.channel.Channel;
public class JoinListener {
NeoProtectVelocity neoProtectVelocity;
public JoinListener(NeoProtectVelocity neoProtectVelocity) {
this.neoProtectVelocity = neoProtectVelocity;
}
@Subscribe
void onJoin(PostLoginEvent event, Continuation continuation) {
injectPlayer(event.getPlayer());
continuation.resume();
}
@Subscribe(order = PostOrder.LAST)
EventTask onDisconnect(DisconnectEvent event) {
if (event.getLoginStatus() == DisconnectEvent.LoginStatus.CONFLICTING_LOGIN)
return null;
return EventTask.async(() -> removePlayer(event.getPlayer()));
}
private void injectPlayer(Player player) {
ConnectedPlayer p = (ConnectedPlayer) player;
p.getConnection()
.getChannel()
.pipeline()
.addBefore("handler", "packetevents", new PlayerChannelHandler(player, neoProtectVelocity.getProxy()
|
.getEventManager(), neoProtectVelocity.getLogger()));
|
}
private void removePlayer(Player player) {
ConnectedPlayer p = (ConnectedPlayer) player;
Channel channel = p.getConnection().getChannel();
channel.eventLoop().submit(() -> channel.pipeline().remove("packetevents"));
}
}
|
src/main/java/de/cubeattack/neoprotect/velocity/messageunsign/JoinListener.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/ChatListener.java",
"retrieved_chunk": " new NeoProtectExecutor.ExecutorBuilder()\n .local(JavaUtils.javaVersionCheck() != 8 ? Locale.forLanguageTag(player.getLocale()) : Locale.ENGLISH)\n .neoProtectPlugin(instance)\n .sender(event.getPlayer())\n .msg(event.getMessage())\n .executeChatEvent();\n }\n}",
"score": 0.8427792191505432
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " addProxyProtocolHandler(channel, playerAddress);\n instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, velocityServer, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }",
"score": 0.8410829305648804
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/ChatListener.java",
"retrieved_chunk": " }\n @Subscribe\n public void onChat(PlayerChatEvent event) {\n Player player = event.getPlayer();\n if (!player.hasPermission(\"neoprotect.admin\") || !instance.getCore().getPlayerInSetup().contains(player))\n return;\n event.setResult(PlayerChatEvent.ChatResult.denied());\n new NeoProtectExecutor.ExecutorBuilder()\n .local(player.getEffectiveLocale())\n .neoProtectPlugin(instance)",
"score": 0.8376302719116211
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.spigot.listener;\nimport de.cubeattack.api.language.Localization;\nimport de.cubeattack.api.util.JavaUtils;\nimport de.cubeattack.api.util.versioning.VersionUtils;\nimport de.cubeattack.neoprotect.core.Config;\nimport de.cubeattack.neoprotect.core.model.Stats;\nimport de.cubeattack.neoprotect.spigot.NeoProtectSpigot;\nimport org.bukkit.entity.Player;\nimport org.bukkit.event.EventHandler;\nimport org.bukkit.event.EventPriority;",
"score": 0.833716630935669
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.velocity;\nimport com.google.inject.Inject;\nimport com.velocitypowered.api.command.CommandSource;\nimport com.velocitypowered.api.event.Subscribe;\nimport com.velocitypowered.api.event.proxy.ProxyInitializeEvent;\nimport com.velocitypowered.api.proxy.Player;\nimport com.velocitypowered.api.proxy.ProxyServer;\nimport com.velocitypowered.proxy.connection.client.ConnectedPlayer;\nimport com.velocitypowered.proxy.protocol.packet.KeepAlive;\nimport de.cubeattack.neoprotect.core.Config;",
"score": 0.8313629627227783
}
] |
java
|
.getEventManager(), neoProtectVelocity.getLogger()));
|
package de.cubeattack.neoprotect.core.request;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Formatter;
import java.util.concurrent.TimeUnit;
public class RestAPIManager {
private final OkHttpClient client = new OkHttpClient();
private final String baseURL = "https://api.neoprotect.net/v2";
private final Core core;
public RestAPIManager(Core core) {
this.core = core;
}
{
client.setConnectTimeout(4, TimeUnit.SECONDS);
}
protected ResponseManager request(RequestType type, RequestBody requestBody, Object... value) {
if (type.toString().startsWith("GET")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).build()));
} else if (type.toString().startsWith("POST")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).post(requestBody).build()));
} else {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).delete().build()));
}
}
protected Response callRequest(Request request) {
try {
return client.newCall(request).execute();
} catch (UnknownHostException | SocketTimeoutException | SocketException connectionException) {
if(!request.url().toString().equals(core.getRestAPI().getStatsServer())) {
core.severe(request + " failed cause (" + connectionException + ")");
}else
core.debug(request + " failed cause (" + connectionException + ")");
} catch (Exception exception) {
|
core.severe(exception.getMessage(), exception);
|
}
return null;
}
protected Request.Builder defaultBuilder() {
return defaultBuilder(Config.getAPIKey());
}
protected Request.Builder defaultBuilder(String apiKey) {
return new Request.Builder()
.addHeader("accept", "*/*")
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json");
}
protected String getSubDirectory(RequestType type, Object... values) {
switch (type) {
case GET_ATTACKS: {
return new Formatter().format("/attacks", values).toString();
}
case GET_ATTACKS_GAMESHIELD: {
return new Formatter().format("/attacks/gameshield/%s", values).toString();
}
case GET_GAMESHIELD_BACKENDS: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_CREATE: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case DELETE_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case POST_GAMESHIELD_BACKEND_AVAILABLE: {
return new Formatter().format("/gameshield/backends/available", values).toString();
}
case GET_GAMESHIELD_DOMAINS: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_CREATE: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_AVAILABLE: {
return new Formatter().format("/gameshields/domains/available", values).toString();
}
case DELETE_GAMESHIELD_DOMAIN: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case GET_GAMESHIELD_FRONTENDS: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case POST_GAMESHIELD_FRONTEND_CREATE: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case GET_GAMESHIELDS: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_CREATE: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_UPDATE: {
return new Formatter().format("/gameshields/%s/settings", values).toString();
}
case POST_GAMESHIELD_UPDATE_REGION: {
return new Formatter().format("/gameshields/%s/region/%s", values).toString();
}
case GET_GAMESHIELD_PLAN: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_PLAN_UPGRADE: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_UPDATE_NAME: {
return new Formatter().format("/gameshields/%s/name", values).toString();
}
case POST_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case DELETE_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case POST_GAMESHIELD_UPDATE_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case DELETE_GAMESHIELD_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case POST_GAMESHIELD_AVAILABLE: {
return new Formatter().format("/gameshields/available", values).toString();
}
case GET_GAMESHIELD_INFO: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case DELETE_GAMESHIELD: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case GET_GAMESHIELD_LASTSTATS: {
return new Formatter().format("/gameshields/%s/lastStats", values).toString();
}
case GET_GAMESHIELD_ISUNDERATTACK: {
return new Formatter().format("/gameshields/%s/isUnderAttack", values).toString();
}
case GET_GAMESHIELD_BANDWIDTH: {
return new Formatter().format("/gameshields/%s/bandwidth", values).toString();
}
case GET_GAMESHIELD_ANALYTICS: {
return new Formatter().format("/gameshields/%s/analytics/%s", values).toString();
}
case GET_FIREWALLS: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case POST_FIREWALL_CREATE: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case DELETE_FIREWALL: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case GET_PLANS_AVAILABLE: {
return new Formatter().format("/plans/gameshield", values).toString();
}
case GET_PROFILE_TRANSACTIONS: {
return new Formatter().format("/profile/transactions", values).toString();
}
case GET_PROFILE_INFOS: {
return new Formatter().format("/profile/infos", values).toString();
}
case GET_PROFILE_GENERALINFORMATION: {
return new Formatter().format("/profile/generalInformation", values).toString();
}
case GET_NEO_SERVER_IPS: {
return new Formatter().format("/public/servers", values).toString();
}
case GET_NEO_SERVER_REGIONS: {
return new Formatter().format("/public/regions", values).toString();
}
case GET_VULNERABILITIES_GAMESHIELD: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case POST_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_VULNERABILITIES_ALL: {
return new Formatter().format("/vulnerabilities", values).toString();
}
case DELETE_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_WEBHOOKS: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_CREATE: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_TEST: {
return new Formatter().format("/webhooks/%s/%s/test", values).toString();
}
case DELETE_WEBHOOK: {
return new Formatter().format("/webhooks/%s/%s", values).toString();
}
default: {
return null;
}
}
}
public String getBaseURL() {
return baseURL;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " public RestAPIRequests(Core core) {\n this.core = core;\n this.rest = new RestAPIManager(core);\n testCredentials();\n attackCheckSchedule();\n statsUpdateSchedule();\n versionCheckSchedule();\n neoServerIPsUpdateSchedule();\n if (Config.isUpdateIP()) {\n backendServerIPUpdater();",
"score": 0.8001394271850586
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/ResponseManager.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\nimport com.squareup.okhttp.Response;\nimport com.squareup.okhttp.ResponseBody;\nimport de.cubeattack.api.libraries.org.json.JSONArray;\nimport de.cubeattack.api.libraries.org.json.JSONException;\nimport de.cubeattack.api.libraries.org.json.JSONObject;\nimport java.io.IOException;\nimport java.net.SocketTimeoutException;\nimport java.util.Objects;\npublic class ResponseManager extends JSONObject {",
"score": 0.7971962690353394
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\nimport com.google.gson.Gson;\nimport com.squareup.okhttp.MediaType;\nimport com.squareup.okhttp.Request;\nimport com.squareup.okhttp.RequestBody;\nimport de.cubeattack.api.libraries.org.json.JSONArray;\nimport de.cubeattack.api.libraries.org.json.JSONObject;\nimport de.cubeattack.api.util.versioning.VersionUtils;\nimport de.cubeattack.neoprotect.core.Config;\nimport de.cubeattack.neoprotect.core.Core;",
"score": 0.7953077554702759
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/ResponseManager.java",
"retrieved_chunk": " private final String responseBody;\n private final Response response;\n private final int code;\n public ResponseManager(Response response) {\n this.responseBody = getBody(response);\n this.response = response;\n this.code = getCode();\n }\n private String getBody(Response response) {\n try (ResponseBody body = response.body()) {",
"score": 0.7770363092422485
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": "import de.cubeattack.neoprotect.core.JsonBuilder;\nimport de.cubeattack.neoprotect.core.Permission;\nimport de.cubeattack.neoprotect.core.model.Backend;\nimport de.cubeattack.neoprotect.core.model.Firewall;\nimport de.cubeattack.neoprotect.core.model.Gameshield;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Timer;\nimport java.util.TimerTask;\npublic class RestAPIRequests {",
"score": 0.7731220722198486
}
] |
java
|
core.severe(exception.getMessage(), exception);
|
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
|
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
|
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {\n channel.close();\n instance.getCore().debug(\"Close connection IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (close / return)\");\n return;\n }\n instance.getCore().debug(\"Adding handler...\");\n if (instance.getCore().isSetup() && Config.isProxyProtocol()) {\n addProxyProtocolHandler(channel, playerAddress);",
"score": 0.9175310134887695
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {\n channel.close();\n instance.getCore().debug(\"Close connection IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (close / return)\");\n return;\n }\n instance.getCore().debug(\"Adding handler...\");\n if (instance.getCore().isSetup() && Config.isProxyProtocol()) {",
"score": 0.9003734588623047
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " protected void initChannel(Channel channel) {\n try {\n instance.getCore().debug(\"Open channel (\" + channel.remoteAddress().toString() + \")\");\n initChannelMethod.getMethod().setAccessible(true);\n initChannelMethod.invoke(oldInitializer, channel);\n AtomicReference<InetSocketAddress> playerAddress = new AtomicReference<>();\n String sourceAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();\n if (channel.localAddress().toString().startsWith(\"local:\") || sourceAddress.equals(Config.getGeyserServerIP())) {\n instance.getCore().debug(\"Detected bedrock player (return)\");\n return;",
"score": 0.8780952095985413
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " protected void initChannel(Channel channel) {\n try {\n instance.getCore().debug(\"Open channel (\" + channel.remoteAddress().toString() + \")\");\n initChannelMethod.invoke(bungeeChannelInitializer, channel);\n AtomicReference<InetSocketAddress> playerAddress = new AtomicReference<>();\n String sourceAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();\n if (channel.localAddress().toString().startsWith(\"local:\") || sourceAddress.equals(Config.getGeyserServerIP())) {\n instance.getCore().debug(\"Detected bedrock player (return)\");\n return;\n }",
"score": 0.8758239150047302
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " addProxyProtocolHandler(channel, playerAddress);\n instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, velocityServer, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }",
"score": 0.874015212059021
}
] |
java
|
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
|
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@SuppressWarnings("unused")
public class Config {
private static String APIKey;
private static String language;
private static boolean proxyProtocol;
private static String gameShieldID;
private static String backendID;
private static String geyserBackendID;
private static boolean updateIP;
private static boolean debugMode;
private static String geyserServerIP;
private static String updateSetting;
private static Core core;
private static FileUtils fileUtils;
public static void loadConfig(Core core, FileUtils config) {
Config.core = core;
fileUtils = config;
APIKey = config.getString("APIKey", "");
language = config.getString("defaultLanguage", Locale.ENGLISH.toLanguageTag());
proxyProtocol = config.getBoolean("ProxyProtocol", true);
gameShieldID = config.getString("gameshield.serverId", "");
backendID = config.getString("gameshield.backendId", "");
geyserBackendID = config.getString("gameshield.geyserBackendId", "");
updateIP = config.getBoolean("gameshield.autoUpdateIP", false);
debugMode = config.getBoolean("DebugMode", false);
geyserServerIP = config.getString("geyserServerIP", "127.0.0.1");
if (APIKey.length() != 64) {
|
core.severe("Failed to load API-Key. Key is null or not valid");
|
return;
}
if (gameShieldID.isEmpty()) {
core.severe("Failed to load GameshieldID. ID is null");
return;
}
if (backendID.isEmpty()) {
core.severe("Failed to load BackendID. ID is null");
return;
}
core.info("API-Key loaded successful '" + "******************************" + APIKey.substring(32) + "'");
core.info("GameshieldID loaded successful '" + gameShieldID + "'");
core.info("BackendID loaded successful '" + backendID + "'");
}
public static String getAPIKey() {
return APIKey;
}
public static String getLanguage() {
return language;
}
public static String getGameShieldID() {
return gameShieldID;
}
public static String getBackendID() {
return backendID;
}
public static String getGeyserBackendID() {
return geyserBackendID;
}
public static boolean isProxyProtocol() {
return proxyProtocol;
}
public static boolean isUpdateIP() {
return updateIP;
}
public static boolean isDebugMode() {
return debugMode;
}
public static String getGeyserServerIP() {
return geyserServerIP;
}
public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {
return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);
}
public static void setAPIKey(String key) {
fileUtils.set("APIKey", key);
fileUtils.save();
APIKey = key;
}
public static void setGameShieldID(String id) {
fileUtils.set("gameshield.serverId", id);
fileUtils.save();
gameShieldID = id;
}
public static void setBackendID(String id) {
fileUtils.set("gameshield.backendId", id);
fileUtils.save();
backendID = id;
}
public static void setGeyserBackendID(String id) {
fileUtils.set("gameshield.geyserBackendId", id);
fileUtils.save();
geyserBackendID = id;
}
public static void addAutoUpdater(boolean basicPlan) {
if (basicPlan) {
fileUtils.remove("AutoUpdater");
} else if (!fileUtils.getConfig().isSet("AutoUpdater")) {
fileUtils.getConfig().set("AutoUpdater", "ENABLED");
}
List<String> description = new ArrayList<>();
description.add("This setting is only for paid costumer and allow you to disable the AutoUpdater");
description.add("'ENABLED' (Recommended/Default) Update/Downgrade plugin to the current version ");
description.add("'DISABLED' AutoUpdater just disabled");
description.add("'DEV' Only update to the latest version (Please never use this)");
fileUtils.getConfig().setComments("AutoUpdater", description);
fileUtils.save();
updateSetting = fileUtils.getString("AutoUpdater", "ENABLED");
}
}
|
src/main/java/de/cubeattack/neoprotect/core/Config.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());",
"score": 0.8613244891166687
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.8353252410888672
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " configuration.load(file);\n configuration.set(\"general.osName\", System.getProperty(\"os.name\"));\n configuration.set(\"general.javaVersion\", System.getProperty(\"java.version\"));\n configuration.set(\"general.pluginVersion\", stats.getPluginVersion());\n configuration.set(\"general.ProxyName\", stats.getServerName());\n configuration.set(\"general.ProxyVersion\", stats.getServerVersion());\n configuration.set(\"general.ProxyPlugins\", instance.getPlugins());\n instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {\n List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);\n long maxPlayerToProxyLatenz = 0;",
"score": 0.8258373141288757
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": " getProxy().getVersion().getVersion(),\n getProxy().getVersion().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),\n System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getPluginVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",",
"score": 0.8214829564094543
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setAPIKey(msg);\n instance.sendMessage(sender, localization.get(locale, \"apikey.valid\"));\n gameshieldSelector();\n }\n private void command(ExecutorBuilder executorBuilder) {\n initials(executorBuilder);\n if (args.length == 0) {\n showHelp();\n return;",
"score": 0.8185139298439026
}
] |
java
|
core.severe("Failed to load API-Key. Key is null or not valid");
|
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
|
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
|
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }\n }",
"score": 0.902603268623352
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " addProxyProtocolHandler(channel, playerAddress);\n instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, velocityServer, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }",
"score": 0.8936058282852173
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " channel.pipeline().addAfter(\"haproxy-decoder\", \"haproxy-handler\", new ChannelInboundHandlerAdapter() {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n if (msg instanceof HAProxyMessage) {\n HAProxyMessage message = (HAProxyMessage) msg;\n Reflection.FieldAccessor<SocketAddress> fieldAccessor = Reflection.getField(MinecraftConnection.class, SocketAddress.class, 0);\n inetAddress.set(new InetSocketAddress(message.sourceAddress(), message.sourcePort()));\n fieldAccessor.set(channel.pipeline().get(Connections.HANDLER), inetAddress.get());\n } else {\n super.channelRead(ctx, msg);",
"score": 0.8792594075202942
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n };\n ServerChannelInitializerHolder newChannelHolder = (ServerChannelInitializerHolder) Reflection.getConstructor(ServerChannelInitializerHolder.class, ChannelInitializer.class).invoke(channelInitializer);\n Reflection.FieldAccessor<ServerChannelInitializerHolder> serverChannelInitializerHolderFieldAccessor = Reflection.getField(ConnectionManager.class, ServerChannelInitializerHolder.class, 0);\n Field channelInitializerHolderField = serverChannelInitializerHolderFieldAccessor.getField();\n channelInitializerHolderField.setAccessible(true);\n channelInitializerHolderField.set(connectionManager, newChannelHolder);\n instance.getLogger().info(\"Found the server channel and added the handler. Injection successfully!\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"An unknown error has occurred\", ex);",
"score": 0.8750616908073425
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " channel.pipeline().names().forEach((n) -> {\n if (n.equals(\"HAProxyMessageDecoder#0\"))\n channel.pipeline().remove(\"HAProxyMessageDecoder#0\");\n });\n channel.pipeline().addFirst(\"haproxy-decoder\", new HAProxyMessageDecoder());\n channel.pipeline().addAfter(\"haproxy-decoder\", \"haproxy-handler\", new ChannelInboundHandlerAdapter() {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n if (msg instanceof HAProxyMessage) {\n HAProxyMessage message = (HAProxyMessage) msg;",
"score": 0.8725810050964355
}
] |
java
|
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
|
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@SuppressWarnings("unused")
public class Config {
private static String APIKey;
private static String language;
private static boolean proxyProtocol;
private static String gameShieldID;
private static String backendID;
private static String geyserBackendID;
private static boolean updateIP;
private static boolean debugMode;
private static String geyserServerIP;
private static String updateSetting;
private static Core core;
private static FileUtils fileUtils;
public static void loadConfig(Core core, FileUtils config) {
Config.core = core;
fileUtils = config;
APIKey = config.getString("APIKey", "");
language = config.getString("defaultLanguage", Locale.ENGLISH.toLanguageTag());
proxyProtocol = config.getBoolean("ProxyProtocol", true);
gameShieldID = config.getString("gameshield.serverId", "");
backendID = config.getString("gameshield.backendId", "");
geyserBackendID = config.getString("gameshield.geyserBackendId", "");
updateIP = config.getBoolean("gameshield.autoUpdateIP", false);
debugMode = config.getBoolean("DebugMode", false);
geyserServerIP = config.getString("geyserServerIP", "127.0.0.1");
if (APIKey.length() != 64) {
core.severe("Failed to load API-Key. Key is null or not valid");
return;
}
if (gameShieldID.isEmpty()) {
core.severe("Failed to load GameshieldID. ID is null");
return;
}
if (backendID.isEmpty()) {
core.severe("Failed to load BackendID. ID is null");
return;
}
core.info("API-Key loaded successful '" + "******************************" + APIKey.substring(32) + "'");
core.info("GameshieldID loaded successful '" + gameShieldID + "'");
|
core.info("BackendID loaded successful '" + backendID + "'");
|
}
public static String getAPIKey() {
return APIKey;
}
public static String getLanguage() {
return language;
}
public static String getGameShieldID() {
return gameShieldID;
}
public static String getBackendID() {
return backendID;
}
public static String getGeyserBackendID() {
return geyserBackendID;
}
public static boolean isProxyProtocol() {
return proxyProtocol;
}
public static boolean isUpdateIP() {
return updateIP;
}
public static boolean isDebugMode() {
return debugMode;
}
public static String getGeyserServerIP() {
return geyserServerIP;
}
public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {
return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);
}
public static void setAPIKey(String key) {
fileUtils.set("APIKey", key);
fileUtils.save();
APIKey = key;
}
public static void setGameShieldID(String id) {
fileUtils.set("gameshield.serverId", id);
fileUtils.save();
gameShieldID = id;
}
public static void setBackendID(String id) {
fileUtils.set("gameshield.backendId", id);
fileUtils.save();
backendID = id;
}
public static void setGeyserBackendID(String id) {
fileUtils.set("gameshield.geyserBackendId", id);
fileUtils.save();
geyserBackendID = id;
}
public static void addAutoUpdater(boolean basicPlan) {
if (basicPlan) {
fileUtils.remove("AutoUpdater");
} else if (!fileUtils.getConfig().isSet("AutoUpdater")) {
fileUtils.getConfig().set("AutoUpdater", "ENABLED");
}
List<String> description = new ArrayList<>();
description.add("This setting is only for paid costumer and allow you to disable the AutoUpdater");
description.add("'ENABLED' (Recommended/Default) Update/Downgrade plugin to the current version ");
description.add("'DISABLED' AutoUpdater just disabled");
description.add("'DEV' Only update to the latest version (Please never use this)");
fileUtils.getConfig().setComments("AutoUpdater", description);
fileUtils.save();
updateSetting = fileUtils.getString("AutoUpdater", "ENABLED");
}
}
|
src/main/java/de/cubeattack/neoprotect/core/Config.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());",
"score": 0.8558900952339172
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.8506889939308167
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " if (args.length == 1 && !isViaConsole) {\n gameshieldSelector();\n } else if (args.length == 2) {\n setGameshield(args);\n } else {\n instance.sendMessage(sender, localization.get(locale, \"usage.setgameshield\"));\n }\n break;\n }\n case \"setbackend\": {",
"score": 0.8340368866920471
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setAPIKey(msg);\n instance.sendMessage(sender, localization.get(locale, \"apikey.valid\"));\n gameshieldSelector();\n }\n private void command(ExecutorBuilder executorBuilder) {\n initials(executorBuilder);\n if (args.length == 0) {\n showHelp();\n return;",
"score": 0.8321362733840942
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n public JSONObject getTraffic() {\n return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();\n }\n public void testCredentials() {\n if (isAPIInvalid(Config.getAPIKey())) {\n core.severe(\"API is not valid! Please run /neoprotect setup to set the API Key\");\n setup = false;\n return;\n } else if (isGameshieldInvalid(Config.getGameShieldID())) {",
"score": 0.823797345161438
}
] |
java
|
core.info("BackendID loaded successful '" + backendID + "'");
|
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@SuppressWarnings("unused")
public class Config {
private static String APIKey;
private static String language;
private static boolean proxyProtocol;
private static String gameShieldID;
private static String backendID;
private static String geyserBackendID;
private static boolean updateIP;
private static boolean debugMode;
private static String geyserServerIP;
private static String updateSetting;
private static Core core;
private static FileUtils fileUtils;
public static void loadConfig(Core core, FileUtils config) {
Config.core = core;
fileUtils = config;
APIKey = config.getString("APIKey", "");
language = config.getString("defaultLanguage", Locale.ENGLISH.toLanguageTag());
proxyProtocol = config.getBoolean("ProxyProtocol", true);
gameShieldID = config.getString("gameshield.serverId", "");
backendID = config.getString("gameshield.backendId", "");
geyserBackendID = config.getString("gameshield.geyserBackendId", "");
updateIP = config.getBoolean("gameshield.autoUpdateIP", false);
debugMode = config.getBoolean("DebugMode", false);
geyserServerIP = config.getString("geyserServerIP", "127.0.0.1");
if (APIKey.length() != 64) {
core.severe("Failed to load API-Key. Key is null or not valid");
return;
}
if (gameShieldID.isEmpty()) {
|
core.severe("Failed to load GameshieldID. ID is null");
|
return;
}
if (backendID.isEmpty()) {
core.severe("Failed to load BackendID. ID is null");
return;
}
core.info("API-Key loaded successful '" + "******************************" + APIKey.substring(32) + "'");
core.info("GameshieldID loaded successful '" + gameShieldID + "'");
core.info("BackendID loaded successful '" + backendID + "'");
}
public static String getAPIKey() {
return APIKey;
}
public static String getLanguage() {
return language;
}
public static String getGameShieldID() {
return gameShieldID;
}
public static String getBackendID() {
return backendID;
}
public static String getGeyserBackendID() {
return geyserBackendID;
}
public static boolean isProxyProtocol() {
return proxyProtocol;
}
public static boolean isUpdateIP() {
return updateIP;
}
public static boolean isDebugMode() {
return debugMode;
}
public static String getGeyserServerIP() {
return geyserServerIP;
}
public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {
return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);
}
public static void setAPIKey(String key) {
fileUtils.set("APIKey", key);
fileUtils.save();
APIKey = key;
}
public static void setGameShieldID(String id) {
fileUtils.set("gameshield.serverId", id);
fileUtils.save();
gameShieldID = id;
}
public static void setBackendID(String id) {
fileUtils.set("gameshield.backendId", id);
fileUtils.save();
backendID = id;
}
public static void setGeyserBackendID(String id) {
fileUtils.set("gameshield.geyserBackendId", id);
fileUtils.save();
geyserBackendID = id;
}
public static void addAutoUpdater(boolean basicPlan) {
if (basicPlan) {
fileUtils.remove("AutoUpdater");
} else if (!fileUtils.getConfig().isSet("AutoUpdater")) {
fileUtils.getConfig().set("AutoUpdater", "ENABLED");
}
List<String> description = new ArrayList<>();
description.add("This setting is only for paid costumer and allow you to disable the AutoUpdater");
description.add("'ENABLED' (Recommended/Default) Update/Downgrade plugin to the current version ");
description.add("'DISABLED' AutoUpdater just disabled");
description.add("'DEV' Only update to the latest version (Please never use this)");
fileUtils.getConfig().setComments("AutoUpdater", description);
fileUtils.save();
updateSetting = fileUtils.getString("AutoUpdater", "ENABLED");
}
}
|
src/main/java/de/cubeattack/neoprotect/core/Config.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());",
"score": 0.869628369808197
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.856776237487793
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n if (geyserBackend != null) {\n if (!ip.equals(geyserBackend.getIp())) {\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"ipv4\", ip).build().toString());\n if (!updateBackend(requestBody, Config.getGeyserBackendID())) {\n core.warn(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' failed\");\n } else {\n core.info(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' success\");\n geyserBackend.setIp(ip);\n }",
"score": 0.8454699516296387
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Backend.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Backend {\n private final String id;\n private String ip;\n private final String port;\n private final boolean geyser;\n public Backend(String id, String ip, String port, boolean geyser) {\n this.id = id;\n this.ip = ip;\n this.port = port;",
"score": 0.8413652777671814
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Backend.java",
"retrieved_chunk": " }\n public boolean isGeyser() {\n return geyser;\n }\n public void setIp(String ip) {\n this.ip = ip;\n }\n public String getPort() {\n return port;\n }",
"score": 0.8316000699996948
}
] |
java
|
core.severe("Failed to load GameshieldID. ID is null");
|
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@SuppressWarnings("unused")
public class Config {
private static String APIKey;
private static String language;
private static boolean proxyProtocol;
private static String gameShieldID;
private static String backendID;
private static String geyserBackendID;
private static boolean updateIP;
private static boolean debugMode;
private static String geyserServerIP;
private static String updateSetting;
private static Core core;
private static FileUtils fileUtils;
public static void loadConfig(Core core, FileUtils config) {
Config.core = core;
fileUtils = config;
APIKey = config.getString("APIKey", "");
language = config.getString("defaultLanguage", Locale.ENGLISH.toLanguageTag());
proxyProtocol = config.getBoolean("ProxyProtocol", true);
gameShieldID = config.getString("gameshield.serverId", "");
backendID = config.getString("gameshield.backendId", "");
geyserBackendID = config.getString("gameshield.geyserBackendId", "");
updateIP = config.getBoolean("gameshield.autoUpdateIP", false);
debugMode = config.getBoolean("DebugMode", false);
geyserServerIP = config.getString("geyserServerIP", "127.0.0.1");
if (APIKey.length() != 64) {
core.severe("Failed to load API-Key. Key is null or not valid");
return;
}
if (gameShieldID.isEmpty()) {
core.severe("Failed to load GameshieldID. ID is null");
return;
}
if (backendID.isEmpty()) {
core.severe("Failed to load BackendID. ID is null");
return;
}
|
core.info("API-Key loaded successful '" + "******************************" + APIKey.substring(32) + "'");
|
core.info("GameshieldID loaded successful '" + gameShieldID + "'");
core.info("BackendID loaded successful '" + backendID + "'");
}
public static String getAPIKey() {
return APIKey;
}
public static String getLanguage() {
return language;
}
public static String getGameShieldID() {
return gameShieldID;
}
public static String getBackendID() {
return backendID;
}
public static String getGeyserBackendID() {
return geyserBackendID;
}
public static boolean isProxyProtocol() {
return proxyProtocol;
}
public static boolean isUpdateIP() {
return updateIP;
}
public static boolean isDebugMode() {
return debugMode;
}
public static String getGeyserServerIP() {
return geyserServerIP;
}
public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {
return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);
}
public static void setAPIKey(String key) {
fileUtils.set("APIKey", key);
fileUtils.save();
APIKey = key;
}
public static void setGameShieldID(String id) {
fileUtils.set("gameshield.serverId", id);
fileUtils.save();
gameShieldID = id;
}
public static void setBackendID(String id) {
fileUtils.set("gameshield.backendId", id);
fileUtils.save();
backendID = id;
}
public static void setGeyserBackendID(String id) {
fileUtils.set("gameshield.geyserBackendId", id);
fileUtils.save();
geyserBackendID = id;
}
public static void addAutoUpdater(boolean basicPlan) {
if (basicPlan) {
fileUtils.remove("AutoUpdater");
} else if (!fileUtils.getConfig().isSet("AutoUpdater")) {
fileUtils.getConfig().set("AutoUpdater", "ENABLED");
}
List<String> description = new ArrayList<>();
description.add("This setting is only for paid costumer and allow you to disable the AutoUpdater");
description.add("'ENABLED' (Recommended/Default) Update/Downgrade plugin to the current version ");
description.add("'DISABLED' AutoUpdater just disabled");
description.add("'DEV' Only update to the latest version (Please never use this)");
fileUtils.getConfig().setComments("AutoUpdater", description);
fileUtils.save();
updateSetting = fileUtils.getString("AutoUpdater", "ENABLED");
}
}
|
src/main/java/de/cubeattack/neoprotect/core/Config.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());",
"score": 0.8508469462394714
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.845085620880127
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setAPIKey(msg);\n instance.sendMessage(sender, localization.get(locale, \"apikey.valid\"));\n gameshieldSelector();\n }\n private void command(ExecutorBuilder executorBuilder) {\n initials(executorBuilder);\n if (args.length == 0) {\n showHelp();\n return;",
"score": 0.8399277329444885
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n public JSONObject getTraffic() {\n return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();\n }\n public void testCredentials() {\n if (isAPIInvalid(Config.getAPIKey())) {\n core.severe(\"API is not valid! Please run /neoprotect setup to set the API Key\");\n setup = false;\n return;\n } else if (isGameshieldInvalid(Config.getGameShieldID())) {",
"score": 0.8341876268386841
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n public boolean isAPIInvalid(String apiKey) {\n return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);\n }\n public boolean isGameshieldInvalid(String gameshieldID) {\n return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);\n }\n public boolean isBackendInvalid(String backendID) {\n return getBackends().stream().noneMatch(e -> e.compareById(backendID));\n }",
"score": 0.823811411857605
}
] |
java
|
core.info("API-Key loaded successful '" + "******************************" + APIKey.substring(32) + "'");
|
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@SuppressWarnings("unused")
public class Config {
private static String APIKey;
private static String language;
private static boolean proxyProtocol;
private static String gameShieldID;
private static String backendID;
private static String geyserBackendID;
private static boolean updateIP;
private static boolean debugMode;
private static String geyserServerIP;
private static String updateSetting;
private static Core core;
private static FileUtils fileUtils;
public static void loadConfig(Core core, FileUtils config) {
Config.core = core;
fileUtils = config;
APIKey = config.getString("APIKey", "");
language = config.getString("defaultLanguage", Locale.ENGLISH.toLanguageTag());
proxyProtocol = config.getBoolean("ProxyProtocol", true);
gameShieldID = config.getString("gameshield.serverId", "");
backendID = config.getString("gameshield.backendId", "");
geyserBackendID = config.getString("gameshield.geyserBackendId", "");
updateIP = config.getBoolean("gameshield.autoUpdateIP", false);
debugMode = config.getBoolean("DebugMode", false);
geyserServerIP = config.getString("geyserServerIP", "127.0.0.1");
if (APIKey.length() != 64) {
core.severe("Failed to load API-Key. Key is null or not valid");
return;
}
if (gameShieldID.isEmpty()) {
core.severe("Failed to load GameshieldID. ID is null");
return;
}
if (backendID.isEmpty()) {
core.severe("Failed to load BackendID. ID is null");
return;
}
core.info("API-Key loaded successful '" + "******************************" + APIKey.substring(32) + "'");
|
core.info("GameshieldID loaded successful '" + gameShieldID + "'");
|
core.info("BackendID loaded successful '" + backendID + "'");
}
public static String getAPIKey() {
return APIKey;
}
public static String getLanguage() {
return language;
}
public static String getGameShieldID() {
return gameShieldID;
}
public static String getBackendID() {
return backendID;
}
public static String getGeyserBackendID() {
return geyserBackendID;
}
public static boolean isProxyProtocol() {
return proxyProtocol;
}
public static boolean isUpdateIP() {
return updateIP;
}
public static boolean isDebugMode() {
return debugMode;
}
public static String getGeyserServerIP() {
return geyserServerIP;
}
public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {
return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);
}
public static void setAPIKey(String key) {
fileUtils.set("APIKey", key);
fileUtils.save();
APIKey = key;
}
public static void setGameShieldID(String id) {
fileUtils.set("gameshield.serverId", id);
fileUtils.save();
gameShieldID = id;
}
public static void setBackendID(String id) {
fileUtils.set("gameshield.backendId", id);
fileUtils.save();
backendID = id;
}
public static void setGeyserBackendID(String id) {
fileUtils.set("gameshield.geyserBackendId", id);
fileUtils.save();
geyserBackendID = id;
}
public static void addAutoUpdater(boolean basicPlan) {
if (basicPlan) {
fileUtils.remove("AutoUpdater");
} else if (!fileUtils.getConfig().isSet("AutoUpdater")) {
fileUtils.getConfig().set("AutoUpdater", "ENABLED");
}
List<String> description = new ArrayList<>();
description.add("This setting is only for paid costumer and allow you to disable the AutoUpdater");
description.add("'ENABLED' (Recommended/Default) Update/Downgrade plugin to the current version ");
description.add("'DISABLED' AutoUpdater just disabled");
description.add("'DEV' Only update to the latest version (Please never use this)");
fileUtils.getConfig().setComments("AutoUpdater", description);
fileUtils.save();
updateSetting = fileUtils.getString("AutoUpdater", "ENABLED");
}
}
|
src/main/java/de/cubeattack/neoprotect/core/Config.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());",
"score": 0.8581737279891968
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.8513138890266418
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setAPIKey(msg);\n instance.sendMessage(sender, localization.get(locale, \"apikey.valid\"));\n gameshieldSelector();\n }\n private void command(ExecutorBuilder executorBuilder) {\n initials(executorBuilder);\n if (args.length == 0) {\n showHelp();\n return;",
"score": 0.8406269550323486
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n public JSONObject getTraffic() {\n return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();\n }\n public void testCredentials() {\n if (isAPIInvalid(Config.getAPIKey())) {\n core.severe(\"API is not valid! Please run /neoprotect setup to set the API Key\");\n setup = false;\n return;\n } else if (isGameshieldInvalid(Config.getGameShieldID())) {",
"score": 0.8356166481971741
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " if (args.length == 1 && !isViaConsole) {\n gameshieldSelector();\n } else if (args.length == 2) {\n setGameshield(args);\n } else {\n instance.sendMessage(sender, localization.get(locale, \"usage.setgameshield\"));\n }\n break;\n }\n case \"setbackend\": {",
"score": 0.8306174278259277
}
] |
java
|
core.info("GameshieldID loaded successful '" + gameShieldID + "'");
|
package de.cubeattack.neoprotect.core.request;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Formatter;
import java.util.concurrent.TimeUnit;
public class RestAPIManager {
private final OkHttpClient client = new OkHttpClient();
private final String baseURL = "https://api.neoprotect.net/v2";
private final Core core;
public RestAPIManager(Core core) {
this.core = core;
}
{
client.setConnectTimeout(4, TimeUnit.SECONDS);
}
protected ResponseManager request(RequestType type, RequestBody requestBody, Object... value) {
if (type.toString().startsWith("GET")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).build()));
} else if (type.toString().startsWith("POST")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).post(requestBody).build()));
} else {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).delete().build()));
}
}
protected Response callRequest(Request request) {
try {
return client.newCall(request).execute();
} catch (UnknownHostException | SocketTimeoutException | SocketException connectionException) {
if(!request.url().toString()
|
.equals(core.getRestAPI().getStatsServer())) {
|
core.severe(request + " failed cause (" + connectionException + ")");
}else
core.debug(request + " failed cause (" + connectionException + ")");
} catch (Exception exception) {
core.severe(exception.getMessage(), exception);
}
return null;
}
protected Request.Builder defaultBuilder() {
return defaultBuilder(Config.getAPIKey());
}
protected Request.Builder defaultBuilder(String apiKey) {
return new Request.Builder()
.addHeader("accept", "*/*")
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json");
}
protected String getSubDirectory(RequestType type, Object... values) {
switch (type) {
case GET_ATTACKS: {
return new Formatter().format("/attacks", values).toString();
}
case GET_ATTACKS_GAMESHIELD: {
return new Formatter().format("/attacks/gameshield/%s", values).toString();
}
case GET_GAMESHIELD_BACKENDS: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_CREATE: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case DELETE_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case POST_GAMESHIELD_BACKEND_AVAILABLE: {
return new Formatter().format("/gameshield/backends/available", values).toString();
}
case GET_GAMESHIELD_DOMAINS: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_CREATE: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_AVAILABLE: {
return new Formatter().format("/gameshields/domains/available", values).toString();
}
case DELETE_GAMESHIELD_DOMAIN: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case GET_GAMESHIELD_FRONTENDS: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case POST_GAMESHIELD_FRONTEND_CREATE: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case GET_GAMESHIELDS: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_CREATE: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_UPDATE: {
return new Formatter().format("/gameshields/%s/settings", values).toString();
}
case POST_GAMESHIELD_UPDATE_REGION: {
return new Formatter().format("/gameshields/%s/region/%s", values).toString();
}
case GET_GAMESHIELD_PLAN: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_PLAN_UPGRADE: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_UPDATE_NAME: {
return new Formatter().format("/gameshields/%s/name", values).toString();
}
case POST_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case DELETE_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case POST_GAMESHIELD_UPDATE_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case DELETE_GAMESHIELD_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case POST_GAMESHIELD_AVAILABLE: {
return new Formatter().format("/gameshields/available", values).toString();
}
case GET_GAMESHIELD_INFO: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case DELETE_GAMESHIELD: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case GET_GAMESHIELD_LASTSTATS: {
return new Formatter().format("/gameshields/%s/lastStats", values).toString();
}
case GET_GAMESHIELD_ISUNDERATTACK: {
return new Formatter().format("/gameshields/%s/isUnderAttack", values).toString();
}
case GET_GAMESHIELD_BANDWIDTH: {
return new Formatter().format("/gameshields/%s/bandwidth", values).toString();
}
case GET_GAMESHIELD_ANALYTICS: {
return new Formatter().format("/gameshields/%s/analytics/%s", values).toString();
}
case GET_FIREWALLS: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case POST_FIREWALL_CREATE: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case DELETE_FIREWALL: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case GET_PLANS_AVAILABLE: {
return new Formatter().format("/plans/gameshield", values).toString();
}
case GET_PROFILE_TRANSACTIONS: {
return new Formatter().format("/profile/transactions", values).toString();
}
case GET_PROFILE_INFOS: {
return new Formatter().format("/profile/infos", values).toString();
}
case GET_PROFILE_GENERALINFORMATION: {
return new Formatter().format("/profile/generalInformation", values).toString();
}
case GET_NEO_SERVER_IPS: {
return new Formatter().format("/public/servers", values).toString();
}
case GET_NEO_SERVER_REGIONS: {
return new Formatter().format("/public/regions", values).toString();
}
case GET_VULNERABILITIES_GAMESHIELD: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case POST_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_VULNERABILITIES_ALL: {
return new Formatter().format("/vulnerabilities", values).toString();
}
case DELETE_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_WEBHOOKS: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_CREATE: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_TEST: {
return new Formatter().format("/webhooks/%s/%s/test", values).toString();
}
case DELETE_WEBHOOK: {
return new Formatter().format("/webhooks/%s/%s", values).toString();
}
default: {
return null;
}
}
}
public String getBaseURL() {
return baseURL;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/ResponseManager.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\nimport com.squareup.okhttp.Response;\nimport com.squareup.okhttp.ResponseBody;\nimport de.cubeattack.api.libraries.org.json.JSONArray;\nimport de.cubeattack.api.libraries.org.json.JSONException;\nimport de.cubeattack.api.libraries.org.json.JSONObject;\nimport java.io.IOException;\nimport java.net.SocketTimeoutException;\nimport java.util.Objects;\npublic class ResponseManager extends JSONObject {",
"score": 0.815727710723877
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/ResponseManager.java",
"retrieved_chunk": " private final String responseBody;\n private final Response response;\n private final int code;\n public ResponseManager(Response response) {\n this.responseBody = getBody(response);\n this.response = response;\n this.code = getCode();\n }\n private String getBody(Response response) {\n try (ResponseBody body = response.body()) {",
"score": 0.8073478937149048
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header(\"GameshieldID\", gameshieldID).header(\"BackendID\", backendID).post(requestBody).build())).checkCode(200);\n }\n private boolean updateBackend(RequestBody requestBody, String backendID) {\n return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);\n }\n public void setProxyProtocol(boolean setting) {\n rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"proxyProtocol\", String.valueOf(setting)).build().toString()), Config.getGameShieldID());\n }\n public JSONObject getAnalytics() {\n return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();",
"score": 0.800573468208313
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " public RestAPIRequests(Core core) {\n this.core = core;\n this.rest = new RestAPIManager(core);\n testCredentials();\n attackCheckSchedule();\n statsUpdateSchedule();\n versionCheckSchedule();\n neoServerIPsUpdateSchedule();\n if (Config.isUpdateIP()) {\n backendServerIPUpdater();",
"score": 0.792138397693634
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n public boolean isAPIInvalid(String apiKey) {\n return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);\n }\n public boolean isGameshieldInvalid(String gameshieldID) {\n return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);\n }\n public boolean isBackendInvalid(String backendID) {\n return getBackends().stream().noneMatch(e -> e.compareById(backendID));\n }",
"score": 0.7749543786048889
}
] |
java
|
.equals(core.getRestAPI().getStatsServer())) {
|
package de.cubeattack.neoprotect.core.request;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Formatter;
import java.util.concurrent.TimeUnit;
public class RestAPIManager {
private final OkHttpClient client = new OkHttpClient();
private final String baseURL = "https://api.neoprotect.net/v2";
private final Core core;
public RestAPIManager(Core core) {
this.core = core;
}
{
client.setConnectTimeout(4, TimeUnit.SECONDS);
}
protected ResponseManager request(RequestType type, RequestBody requestBody, Object... value) {
if (type.toString().startsWith("GET")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).build()));
} else if (type.toString().startsWith("POST")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).post(requestBody).build()));
} else {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).delete().build()));
}
}
protected Response callRequest(Request request) {
try {
return client.newCall(request).execute();
} catch (UnknownHostException | SocketTimeoutException | SocketException connectionException) {
if(!request.url().toString().equals(core.getRestAPI().getStatsServer())) {
core.severe(request + " failed cause (" + connectionException + ")");
}else
core.debug(request + " failed cause (" + connectionException + ")");
} catch (Exception exception) {
core.severe(exception.getMessage(), exception);
}
return null;
}
protected Request.Builder defaultBuilder() {
return defaultBuilder
|
(Config.getAPIKey());
|
}
protected Request.Builder defaultBuilder(String apiKey) {
return new Request.Builder()
.addHeader("accept", "*/*")
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json");
}
protected String getSubDirectory(RequestType type, Object... values) {
switch (type) {
case GET_ATTACKS: {
return new Formatter().format("/attacks", values).toString();
}
case GET_ATTACKS_GAMESHIELD: {
return new Formatter().format("/attacks/gameshield/%s", values).toString();
}
case GET_GAMESHIELD_BACKENDS: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_CREATE: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case DELETE_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case POST_GAMESHIELD_BACKEND_AVAILABLE: {
return new Formatter().format("/gameshield/backends/available", values).toString();
}
case GET_GAMESHIELD_DOMAINS: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_CREATE: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_AVAILABLE: {
return new Formatter().format("/gameshields/domains/available", values).toString();
}
case DELETE_GAMESHIELD_DOMAIN: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case GET_GAMESHIELD_FRONTENDS: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case POST_GAMESHIELD_FRONTEND_CREATE: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case GET_GAMESHIELDS: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_CREATE: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_UPDATE: {
return new Formatter().format("/gameshields/%s/settings", values).toString();
}
case POST_GAMESHIELD_UPDATE_REGION: {
return new Formatter().format("/gameshields/%s/region/%s", values).toString();
}
case GET_GAMESHIELD_PLAN: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_PLAN_UPGRADE: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_UPDATE_NAME: {
return new Formatter().format("/gameshields/%s/name", values).toString();
}
case POST_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case DELETE_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case POST_GAMESHIELD_UPDATE_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case DELETE_GAMESHIELD_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case POST_GAMESHIELD_AVAILABLE: {
return new Formatter().format("/gameshields/available", values).toString();
}
case GET_GAMESHIELD_INFO: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case DELETE_GAMESHIELD: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case GET_GAMESHIELD_LASTSTATS: {
return new Formatter().format("/gameshields/%s/lastStats", values).toString();
}
case GET_GAMESHIELD_ISUNDERATTACK: {
return new Formatter().format("/gameshields/%s/isUnderAttack", values).toString();
}
case GET_GAMESHIELD_BANDWIDTH: {
return new Formatter().format("/gameshields/%s/bandwidth", values).toString();
}
case GET_GAMESHIELD_ANALYTICS: {
return new Formatter().format("/gameshields/%s/analytics/%s", values).toString();
}
case GET_FIREWALLS: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case POST_FIREWALL_CREATE: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case DELETE_FIREWALL: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case GET_PLANS_AVAILABLE: {
return new Formatter().format("/plans/gameshield", values).toString();
}
case GET_PROFILE_TRANSACTIONS: {
return new Formatter().format("/profile/transactions", values).toString();
}
case GET_PROFILE_INFOS: {
return new Formatter().format("/profile/infos", values).toString();
}
case GET_PROFILE_GENERALINFORMATION: {
return new Formatter().format("/profile/generalInformation", values).toString();
}
case GET_NEO_SERVER_IPS: {
return new Formatter().format("/public/servers", values).toString();
}
case GET_NEO_SERVER_REGIONS: {
return new Formatter().format("/public/regions", values).toString();
}
case GET_VULNERABILITIES_GAMESHIELD: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case POST_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_VULNERABILITIES_ALL: {
return new Formatter().format("/vulnerabilities", values).toString();
}
case DELETE_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_WEBHOOKS: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_CREATE: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_TEST: {
return new Formatter().format("/webhooks/%s/%s/test", values).toString();
}
case DELETE_WEBHOOK: {
return new Formatter().format("/webhooks/%s/%s", values).toString();
}
default: {
return null;
}
}
}
public String getBaseURL() {
return baseURL;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\nimport com.google.gson.Gson;\nimport com.squareup.okhttp.MediaType;\nimport com.squareup.okhttp.Request;\nimport com.squareup.okhttp.RequestBody;\nimport de.cubeattack.api.libraries.org.json.JSONArray;\nimport de.cubeattack.api.libraries.org.json.JSONObject;\nimport de.cubeattack.api.util.versioning.VersionUtils;\nimport de.cubeattack.neoprotect.core.Config;\nimport de.cubeattack.neoprotect.core.Core;",
"score": 0.8040968179702759
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " public RestAPIRequests(Core core) {\n this.core = core;\n this.rest = new RestAPIManager(core);\n testCredentials();\n attackCheckSchedule();\n statsUpdateSchedule();\n versionCheckSchedule();\n neoServerIPsUpdateSchedule();\n if (Config.isUpdateIP()) {\n backendServerIPUpdater();",
"score": 0.7969405651092529
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " this.locale = executeBuilder.getLocal();\n this.args = executeBuilder.getArgs();\n this.msg = executeBuilder.getMsg();\n this.isViaConsole = executeBuilder.isViaConsole();\n }\n private void chatEvent(ExecutorBuilder executorBuilder) {\n initials(executorBuilder);\n if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {\n instance.sendMessage(sender, localization.get(locale, \"apikey.invalid\"));\n return;",
"score": 0.7928704023361206
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/ResponseManager.java",
"retrieved_chunk": " } catch (JSONException ignored) {}\n return new JSONArray();\n }\n @Override\n public String getString(String key) {\n return super.getString(key);\n }\n}",
"score": 0.7841038703918457
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/ResponseManager.java",
"retrieved_chunk": " }\n public int getCode() {\n try {\n return response.code();\n } catch (Exception ex) {\n return -1;\n }\n }\n public String getResponseBody() {\n return responseBody;",
"score": 0.7790143489837646
}
] |
java
|
(Config.getAPIKey());
|
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
|
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
|
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " channel.pipeline().addAfter(\"haproxy-decoder\", \"haproxy-handler\", new ChannelInboundHandlerAdapter() {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n if (msg instanceof HAProxyMessage) {\n HAProxyMessage message = (HAProxyMessage) msg;\n Reflection.FieldAccessor<SocketAddress> fieldAccessor = Reflection.getField(MinecraftConnection.class, SocketAddress.class, 0);\n inetAddress.set(new InetSocketAddress(message.sourceAddress(), message.sourcePort()));\n fieldAccessor.set(channel.pipeline().get(Connections.HANDLER), inetAddress.get());\n } else {\n super.channelRead(ctx, msg);",
"score": 0.9093367457389832
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " channel.pipeline().names().forEach((n) -> {\n if (n.equals(\"HAProxyMessageDecoder#0\"))\n channel.pipeline().remove(\"HAProxyMessageDecoder#0\");\n });\n channel.pipeline().addFirst(\"haproxy-decoder\", new HAProxyMessageDecoder());\n channel.pipeline().addAfter(\"haproxy-decoder\", \"haproxy-handler\", new ChannelInboundHandlerAdapter() {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n if (msg instanceof HAProxyMessage) {\n HAProxyMessage message = (HAProxyMessage) msg;",
"score": 0.8609341382980347
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import io.netty.channel.ChannelInitializer;\nimport io.netty.channel.epoll.EpollSocketChannel;\nimport io.netty.channel.epoll.EpollTcpInfo;\nimport io.netty.handler.codec.haproxy.HAProxyMessage;\nimport io.netty.handler.codec.haproxy.HAProxyMessageDecoder;\nimport net.md_5.bungee.BungeeCord;\nimport net.md_5.bungee.UserConnection;\nimport net.md_5.bungee.api.connection.ProxiedPlayer;\nimport net.md_5.bungee.netty.ChannelWrapper;\nimport net.md_5.bungee.netty.HandlerBoss;",
"score": 0.8422175049781799
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import io.netty.handler.codec.haproxy.HAProxyMessage;\nimport io.netty.handler.codec.haproxy.HAProxyMessageDecoder;\nimport java.lang.reflect.Field;\nimport java.net.InetSocketAddress;\nimport java.net.SocketAddress;\nimport java.util.ArrayList;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.logging.Level;\npublic class ProxyProtocol {",
"score": 0.8380606174468994
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n }\n public void addProxyProtocolHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress) {\n channel.pipeline().names().forEach((n) -> {\n if (n.equals(\"HAProxyMessageDecoder#0\"))\n channel.pipeline().remove(\"HAProxyMessageDecoder#0\");\n if (n.equals(\"ProxyProtocol$1#0\"))\n channel.pipeline().remove(\"ProxyProtocol$1#0\");\n });\n channel.pipeline().addFirst(\"haproxy-decoder\", new HAProxyMessageDecoder());",
"score": 0.8355485796928406
}
] |
java
|
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
|
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
|
instance.getCore().info("Proceeding with the server channel injection...");
|
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import java.util.logging.Level;\npublic class ProxyProtocol {\n private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, \"channel\", ChannelWrapper.class);\n private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;\n private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectBungee instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 0.880760669708252
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/Startup.java",
"retrieved_chunk": "public class Startup {\n public Startup(NeoProtectSpigot instance) {\n register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectSpigot instance) {\n PluginManager pm = Bukkit.getPluginManager();\n Objects.requireNonNull(instance.getCommand(\"neoprotect\")).setExecutor(new NeoProtectCommand(instance));\n Objects.requireNonNull(instance.getCommand(\"neoprotect\")).setTabCompleter(new NeoProtectTabCompleter(instance));\n pm.registerEvents(new ChatListener(instance), instance);",
"score": 0.866818904876709
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/Startup.java",
"retrieved_chunk": " register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectBungee instance) {\n PluginManager pm = ProxyServer.getInstance().getPluginManager();\n pm.registerCommand(instance, new NeoProtectCommand(instance, \"neoprotect\", \"neoprotect.admin\", \"np\"));\n pm.registerListener(instance, new ChatListener(instance));\n pm.registerListener(instance, new LoginListener(instance));\n pm.registerListener(instance, new DisconnectListener(instance));\n }",
"score": 0.8655825853347778
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(ChannelInitializer.class, \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectVelocity instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n VelocityServer velocityServer = (VelocityServer) instance.getProxy();\n Reflection.FieldAccessor<ConnectionManager> connectionManagerFieldAccessor = Reflection.getField(VelocityServer.class, ConnectionManager.class, 0);\n ConnectionManager connectionManager = connectionManagerFieldAccessor.get(velocityServer);\n ChannelInitializer<?> oldInitializer = connectionManager.getServerChannelInitializer().get();\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 0.860892653465271
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/Startup.java",
"retrieved_chunk": "public class Startup {\n public Startup(NeoProtectVelocity instance) {\n register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectVelocity instance) {\n EventManager em = instance.getProxy().getEventManager();\n CommandManager cm = instance.getProxy().getCommandManager();\n cm.register(cm.metaBuilder(\"neoprotect\").aliases(\"np\").build(), new NeoProtectCommand(instance));\n em.register(instance, new ChatListener(instance));",
"score": 0.8548482656478882
}
] |
java
|
instance.getCore().info("Proceeding with the server channel injection...");
|
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
|
instance.getCore().info("Late bind injection successful.");
|
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n };\n ServerChannelInitializerHolder newChannelHolder = (ServerChannelInitializerHolder) Reflection.getConstructor(ServerChannelInitializerHolder.class, ChannelInitializer.class).invoke(channelInitializer);\n Reflection.FieldAccessor<ServerChannelInitializerHolder> serverChannelInitializerHolderFieldAccessor = Reflection.getField(ConnectionManager.class, ServerChannelInitializerHolder.class, 0);\n Field channelInitializerHolderField = serverChannelInitializerHolderFieldAccessor.getField();\n channelInitializerHolderField.setAccessible(true);\n channelInitializerHolderField.set(connectionManager, newChannelHolder);\n instance.getLogger().info(\"Found the server channel and added the handler. Injection successfully!\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"An unknown error has occurred\", ex);",
"score": 0.8839460611343384
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import java.util.logging.Level;\npublic class ProxyProtocol {\n private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, \"channel\", ChannelWrapper.class);\n private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;\n private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectBungee instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 0.8663209080696106
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " addProxyProtocolHandler(channel, playerAddress);\n instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, velocityServer, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }",
"score": 0.8592947125434875
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }\n }",
"score": 0.8555625081062317
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(ChannelInitializer.class, \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectVelocity instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n VelocityServer velocityServer = (VelocityServer) instance.getProxy();\n Reflection.FieldAccessor<ConnectionManager> connectionManagerFieldAccessor = Reflection.getField(VelocityServer.class, ConnectionManager.class, 0);\n ConnectionManager connectionManager = connectionManagerFieldAccessor.get(velocityServer);\n ChannelInitializer<?> oldInitializer = connectionManager.getServerChannelInitializer().get();\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 0.8363115191459656
}
] |
java
|
instance.getCore().info("Late bind injection successful.");
|
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list =
|
Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
|
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n };\n ServerChannelInitializerHolder newChannelHolder = (ServerChannelInitializerHolder) Reflection.getConstructor(ServerChannelInitializerHolder.class, ChannelInitializer.class).invoke(channelInitializer);\n Reflection.FieldAccessor<ServerChannelInitializerHolder> serverChannelInitializerHolderFieldAccessor = Reflection.getField(ConnectionManager.class, ServerChannelInitializerHolder.class, 0);\n Field channelInitializerHolderField = serverChannelInitializerHolderFieldAccessor.getField();\n channelInitializerHolderField.setAccessible(true);\n channelInitializerHolderField.set(connectionManager, newChannelHolder);\n instance.getLogger().info(\"Found the server channel and added the handler. Injection successfully!\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"An unknown error has occurred\", ex);",
"score": 0.8352159857749939
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " };\n Field serverChild = PipelineUtils.class.getField(\"SERVER_CHILD\");\n serverChild.setAccessible(true);\n if (JavaUtils.javaVersionCheck() == 8) {\n Field modifiersField = Field.class.getDeclaredField(\"modifiers\");\n modifiersField.setAccessible(true);\n modifiersField.setInt(serverChild, serverChild.getModifiers() & ~Modifier.FINAL);\n serverChild.set(PipelineUtils.class, channelInitializer);\n } else {\n Field unsafeField = Unsafe.class.getDeclaredField(\"theUnsafe\");",
"score": 0.8108303546905518
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import java.util.logging.Level;\npublic class ProxyProtocol {\n private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, \"channel\", ChannelWrapper.class);\n private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;\n private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectBungee instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 0.8103657960891724
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(ChannelInitializer.class, \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectVelocity instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n VelocityServer velocityServer = (VelocityServer) instance.getProxy();\n Reflection.FieldAccessor<ConnectionManager> connectionManagerFieldAccessor = Reflection.getField(VelocityServer.class, ConnectionManager.class, 0);\n ConnectionManager connectionManager = connectionManagerFieldAccessor.get(velocityServer);\n ChannelInitializer<?> oldInitializer = connectionManager.getServerChannelInitializer().get();\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 0.8073569536209106
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.velocity.proxyprotocol;\nimport com.velocitypowered.api.proxy.Player;\nimport com.velocitypowered.proxy.VelocityServer;\nimport com.velocitypowered.proxy.connection.MinecraftConnection;\nimport com.velocitypowered.proxy.connection.client.ConnectedPlayer;\nimport com.velocitypowered.proxy.network.ConnectionManager;\nimport com.velocitypowered.proxy.network.Connections;\nimport com.velocitypowered.proxy.network.ServerChannelInitializerHolder;\nimport com.velocitypowered.proxy.protocol.packet.KeepAlive;\nimport de.cubeattack.neoprotect.core.Config;",
"score": 0.8065074682235718
}
] |
java
|
Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
|
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
|
instance.getCore().info("Delaying server channel injection due to late bind.");
|
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import java.util.logging.Level;\npublic class ProxyProtocol {\n private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, \"channel\", ChannelWrapper.class);\n private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;\n private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectBungee instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 0.906851053237915
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/Startup.java",
"retrieved_chunk": " register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectBungee instance) {\n PluginManager pm = ProxyServer.getInstance().getPluginManager();\n pm.registerCommand(instance, new NeoProtectCommand(instance, \"neoprotect\", \"neoprotect.admin\", \"np\"));\n pm.registerListener(instance, new ChatListener(instance));\n pm.registerListener(instance, new LoginListener(instance));\n pm.registerListener(instance, new DisconnectListener(instance));\n }",
"score": 0.8958815336227417
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/Startup.java",
"retrieved_chunk": "public class Startup {\n public Startup(NeoProtectSpigot instance) {\n register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectSpigot instance) {\n PluginManager pm = Bukkit.getPluginManager();\n Objects.requireNonNull(instance.getCommand(\"neoprotect\")).setExecutor(new NeoProtectCommand(instance));\n Objects.requireNonNull(instance.getCommand(\"neoprotect\")).setTabCompleter(new NeoProtectTabCompleter(instance));\n pm.registerEvents(new ChatListener(instance), instance);",
"score": 0.8930425643920898
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(ChannelInitializer.class, \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectVelocity instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n VelocityServer velocityServer = (VelocityServer) instance.getProxy();\n Reflection.FieldAccessor<ConnectionManager> connectionManagerFieldAccessor = Reflection.getField(VelocityServer.class, ConnectionManager.class, 0);\n ConnectionManager connectionManager = connectionManagerFieldAccessor.get(velocityServer);\n ChannelInitializer<?> oldInitializer = connectionManager.getServerChannelInitializer().get();\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 0.8866791725158691
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/Startup.java",
"retrieved_chunk": "public class Startup {\n public Startup(NeoProtectVelocity instance) {\n register(instance);\n new ProxyProtocol(instance);\n }\n private void register(NeoProtectVelocity instance) {\n EventManager em = instance.getProxy().getEventManager();\n CommandManager cm = instance.getProxy().getCommandManager();\n cm.register(cm.metaBuilder(\"neoprotect\").aliases(\"np\").build(), new NeoProtectCommand(instance));\n em.register(instance, new ChatListener(instance));",
"score": 0.8766191005706787
}
] |
java
|
instance.getCore().info("Delaying server channel injection due to late bind.");
|
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
|
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
|
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n };\n ServerChannelInitializerHolder newChannelHolder = (ServerChannelInitializerHolder) Reflection.getConstructor(ServerChannelInitializerHolder.class, ChannelInitializer.class).invoke(channelInitializer);\n Reflection.FieldAccessor<ServerChannelInitializerHolder> serverChannelInitializerHolderFieldAccessor = Reflection.getField(ConnectionManager.class, ServerChannelInitializerHolder.class, 0);\n Field channelInitializerHolderField = serverChannelInitializerHolderFieldAccessor.getField();\n channelInitializerHolderField.setAccessible(true);\n channelInitializerHolderField.set(connectionManager, newChannelHolder);\n instance.getLogger().info(\"Found the server channel and added the handler. Injection successfully!\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"An unknown error has occurred\", ex);",
"score": 0.8980603218078613
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " unsafeField.setAccessible(true);\n Unsafe unsafe = (Unsafe) unsafeField.get(null);\n unsafe.putObject(unsafe.staticFieldBase(serverChild), unsafe.staticFieldOffset(serverChild), channelInitializer);\n }\n instance.getLogger().info(\"Found the server channel and added the handler. Injection successfully!\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"An unknown error has occurred\", ex);\n }\n }\n public void addProxyProtocolHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress) {",
"score": 0.8492374420166016
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }\n }",
"score": 0.8404512405395508
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " addProxyProtocolHandler(channel, playerAddress);\n instance.getCore().debug(\"Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)\");\n }\n addKeepAlivePacketHandler(channel, playerAddress, velocityServer, instance);\n instance.getCore().debug(\"Added KeepAlivePacketHandler\");\n }\n instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getLogger().log(Level.SEVERE, \"Cannot inject incoming channel \" + channel, ex);\n }",
"score": 0.839411735534668
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import java.util.logging.Level;\npublic class ProxyProtocol {\n private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, \"channel\", ChannelWrapper.class);\n private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;\n private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectBungee instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 0.8325470685958862
}
] |
java
|
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
|
package de.cubeattack.neoprotect.spigot.listener;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.util.JavaUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Locale;
public class LoginListener implements Listener {
private final NeoProtectSpigot instance;
private final Localization localization;
public LoginListener(NeoProtectSpigot instance) {
this.instance = instance;
this.localization = instance.getCore().getLocalization();
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onLogin(PlayerJoinEvent event) {
Player player = event.getPlayer();
Locale locale = JavaUtils.javaVersionCheck() != 8 ? Locale.forLanguageTag(player.getLocale()) : Locale.ENGLISH;
if (!player.hasPermission("neoprotect.admin") && !instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode()))
return;
VersionUtils.Result result = instance.getCore().getVersionResult();
if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {
instance.sendMessage(player, localization.get(locale, "plugin.outdated.message", result.getCurrentVersion(), result.getLatestVersion()));
instance.sendMessage(player, MessageFormat.format("§7-> §b{0}",
result.getReleaseUrl().replace("/NeoPlugin", "").replace("/releases/tag", "")),
"OPEN_URL", result.getReleaseUrl(), null, null);
}
if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {
instance.sendMessage(player, localization.get(locale, "plugin.restart-required.message", result.getCurrentVersion(), result.getLatestVersion()));
}
if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {
instance.sendMessage(player, localization.get(locale, "setup.required.first"));
instance.sendMessage(player, localization.get(locale, "setup.required.second"));
}
|
if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {
|
Stats stats = instance.getStats();
String infos =
"§bOsName§7: " + System.getProperty("os.name") + " \n" +
"§bJavaVersion§7: " + System.getProperty("java.version") + " \n" +
"§bPluginVersion§7: " + stats.getPluginVersion() + " \n" +
"§bVersionStatus§7: " + instance.getCore().getVersionResult().getVersionStatus() + " \n" +
"§bUpdateSetting§7: " + Config.getAutoUpdaterSettings() + " \n" +
"§bProxyProtocol§7: " + Config.isProxyProtocol() + " \n" +
"§bNeoProtectPlan§7: " + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : "§cNOT CONNECTED") + " \n" +
"§bSpigotName§7: " + stats.getServerName() + " \n" +
"§bSpigotVersion§7: " + stats.getServerVersion() + " \n" +
"§bSpigotPlugins§7: " + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith("cmd_") && !p.equals("reconnect_yaml")).toArray());
instance.sendMessage(player, "§bHello " + player.getName() + " ;)", null, null, "SHOW_TEXT", infos);
instance.sendMessage(player, "§bThis server uses your NeoPlugin", null, null, "SHOW_TEXT", infos);
}
}
}
|
src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.914563775062561
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.9089265465736389
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.881803035736084
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8811981678009033
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() & !args[0].equals(\"setup\") & !args[0].equals(\"setgameshield\") & !args[0].equals(\"setbackend\")) {\n instance.sendMessage(sender, localization.get(locale, \"setup.command.required\"));\n return;\n }\n switch (args[0].toLowerCase()) {\n case \"setup\": {\n if (isViaConsole) {\n instance.sendMessage(sender, localization.get(Locale.getDefault(), \"console.command\"));\n } else {",
"score": 0.8376119136810303
}
] |
java
|
if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {
|
package de.cubeattack.neoprotect.velocity.listener;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.PostLoginEvent;
import com.velocitypowered.api.proxy.Player;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.velocity.NeoProtectVelocity;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
public class LoginListener {
private final NeoProtectVelocity instance;
private final Localization localization;
public LoginListener(NeoProtectVelocity instance) {
this.instance = instance;
this.localization = instance.getCore().getLocalization();
}
@Subscribe(order = PostOrder.LAST)
public void onPostLogin(PostLoginEvent event) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Player player = event.getPlayer();
Locale locale = (player.getEffectiveLocale() != null) ? player.getEffectiveLocale() : Locale.ENGLISH;
if (!player.hasPermission("neoprotect.admin") && !instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode()))
return;
VersionUtils.Result result = instance.getCore().getVersionResult();
if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {
instance.sendMessage(player, localization.get(locale, "plugin.outdated.message", result.getCurrentVersion(), result.getLatestVersion()));
instance.sendMessage(player, MessageFormat.format("§7-> §b{0}",
result.getReleaseUrl().replace("/NeoPlugin", "").replace("/releases/tag", "")),
"OPEN_URL", result.getReleaseUrl(), null, null);
}
if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {
instance.sendMessage(player, localization.get(locale, "plugin.restart-required.message", result.getCurrentVersion(), result.getLatestVersion()));
}
if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {
instance.sendMessage(player, localization.get(locale, "setup.required.first"));
instance.sendMessage(player, localization.get(locale, "setup.required.second"));
}
if (
|
instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {
|
Stats stats = instance.getStats();
String infos =
"§bOsName§7: " + System.getProperty("os.name") + " \n" +
"§bJavaVersion§7: " + System.getProperty("java.version") + " \n" +
"§bPluginVersion§7: " + stats.getPluginVersion() + " \n" +
"§bVersionStatus§7: " + instance.getCore().getVersionResult().getVersionStatus() + " \n" +
"§bUpdateSetting§7: " + Config.getAutoUpdaterSettings() + " \n" +
"§bProxyProtocol§7: " + Config.isProxyProtocol() + " \n" +
"§bNeoProtectPlan§7: " + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : "§cNOT CONNECTED") + " \n" +
"§bVelocityName§7: " + stats.getServerName() + " \n" +
"§bVelocityVersion§7: " + stats.getServerVersion() + " \n" +
"§bVelocityPlugins§7: " + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith("cmd_") && !p.equals("reconnect_yaml")).toArray());
instance.sendMessage(player, "§bHello " + player.getUsername() + " ;)", null, null, "SHOW_TEXT", infos);
instance.sendMessage(player, "§bThis server uses your NeoPlugin", null, null, "SHOW_TEXT", infos);
}
}
}, 500);
}
}
|
src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));",
"score": 0.9384607076644897
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 0.9208720922470093
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.9131094217300415
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.9123414754867554
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() & !args[0].equals(\"setup\") & !args[0].equals(\"setgameshield\") & !args[0].equals(\"setbackend\")) {\n instance.sendMessage(sender, localization.get(locale, \"setup.command.required\"));\n return;\n }\n switch (args[0].toLowerCase()) {\n case \"setup\": {\n if (isViaConsole) {\n instance.sendMessage(sender, localization.get(Locale.getDefault(), \"console.command\"));\n } else {",
"score": 0.8639585971832275
}
] |
java
|
instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {
|
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.logger.LogManager;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import de.cubeattack.neoprotect.core.request.RestAPIRequests;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
@SuppressWarnings("unused")
public class Core {
@SuppressWarnings("FieldCanBeLocal")
private final String prefix = "§8[§bNeo§3Protect§8] §7";
private final UUID maintainerOnlineUUID = UUID.fromString("201e5046-24df-4830-8b4a-82b635eb7cc7");
private final UUID maintainerOfflineeUUID = UUID.fromString("8c07bf89-9c8f-304c-9216-4666b670223b");
private final RestAPIRequests restAPIRequests;
private final NeoProtectPlugin plugin;
private final Localization localization;
private final List<Object> playerInSetup = new ArrayList<>();
private final List<String> directConnectWhitelist= new ArrayList<>();
private final ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, Timestamp> timestampsMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, ArrayList<DebugPingResponse>> debugPingResponses = new ConcurrentHashMap<>();
private VersionUtils.Result versionResult;
private boolean isDebugRunning = false;
public Core(NeoProtectPlugin plugin) {
LogManager.getLogger().setLogger(plugin.getLogger());
this.plugin = plugin;
this.versionResult = VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message();
FileUtils config = new FileUtils(Core.class.getResourceAsStream("/config.yml"), "plugins/NeoProtect", "config.yml", false);
FileUtils languageEN = new FileUtils(Core.class.getResourceAsStream("/language_en.properties"), "plugins/NeoProtect/languages", "language_en.properties", true);
FileUtils languageDE = new FileUtils(Core.class.getResourceAsStream("/language_de.properties"), "plugins/NeoProtect/languages", "language_de.properties", true);
FileUtils languageRU = new FileUtils(Core.class.getResourceAsStream("/language_ru.properties"), "plugins/NeoProtect/languages", "language_ru.properties", true);
FileUtils languageUA = new FileUtils(Core.class.getResourceAsStream("/language_ua.properties"), "plugins/NeoProtect/languages", "language_ua.properties", true);
Config.loadConfig(this, config);
this.localization = new Localization("language", Locale
|
.forLanguageTag(Config.getLanguage()), new File("plugins/NeoProtect/languages/"));
|
restAPIRequests = new RestAPIRequests(this);
}
public void debug(String output) {
if (Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output);
}
public void info(String output) {
LogManager.getLogger().info(output);
}
public void warn(String output) {
LogManager.getLogger().warn(output);
}
public void severe(String output) {
LogManager.getLogger().error(output);
}
public void severe(String output, Throwable t) {
LogManager.getLogger().error(output, t);
}
public String getPrefix() {
return prefix;
}
public boolean isDebugRunning() {
return isDebugRunning;
}
public void setDebugRunning(boolean debugRunning) {
isDebugRunning = debugRunning;
}
public NeoProtectPlugin getPlugin() {
return plugin;
}
public Localization getLocalization() {
return localization;
}
public RestAPIRequests getRestAPI() {
return restAPIRequests;
}
public boolean isSetup() {
return restAPIRequests.isSetup();
}
public List<Object> getPlayerInSetup() {
return playerInSetup;
}
public List<String> getDirectConnectWhitelist() {
return directConnectWhitelist;
}
public ConcurrentHashMap<KeepAliveResponseKey, Long> getPingMap() {
return pingMap;
}
public ConcurrentHashMap<Long, Timestamp> getTimestampsMap() {
return timestampsMap;
}
public ConcurrentHashMap<String, ArrayList<DebugPingResponse>> getDebugPingResponses() {
return debugPingResponses;
}
public VersionUtils.Result getVersionResult() {
return versionResult;
}
public void setVersionResult(VersionUtils.Result versionResult) {
this.versionResult = versionResult;
}
public boolean isPlayerMaintainer(UUID playerUUID, boolean onlineMode) {
return (onlineMode && playerUUID.equals(maintainerOnlineUUID)) || (!onlineMode && playerUUID.equals(maintainerOfflineeUUID));
}
}
|
src/main/java/de/cubeattack/neoprotect/core/Core.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java",
"retrieved_chunk": "public final class NeoProtectBungee extends Plugin implements NeoProtectPlugin {\n private static Core core;\n @Override\n public void onLoad() {\n Metrics metrics = new Metrics(this, 18726);\n metrics.addCustomChart(new SimplePie(\"language\", Config::getLanguage));\n }\n @Override\n public void onEnable() {\n core = new Core(this);",
"score": 0.8848492503166199
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.executor;\nimport de.cubeattack.api.API;\nimport de.cubeattack.api.language.Localization;\nimport de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;\nimport de.cubeattack.api.libraries.org.json.JSONObject;\nimport de.cubeattack.neoprotect.core.Config;\nimport de.cubeattack.neoprotect.core.NeoProtectPlugin;\nimport de.cubeattack.neoprotect.core.model.Backend;\nimport de.cubeattack.neoprotect.core.model.Gameshield;\nimport de.cubeattack.neoprotect.core.model.Stats;",
"score": 0.8590145707130432
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core;\nimport de.cubeattack.api.util.FileUtils;\nimport de.cubeattack.api.util.versioning.VersionUtils;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\n@SuppressWarnings(\"unused\")\npublic class Config {\n private static String APIKey;\n private static String language;",
"score": 0.8553784489631653
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": "import org.bstats.velocity.Metrics;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Objects;\nimport java.util.logging.Logger;\npublic class NeoProtectVelocity implements NeoProtectPlugin {\n private final Metrics.Factory metricsFactory;\n private final Logger logger;\n private final ProxyServer proxy;\n private Core core;",
"score": 0.8513754606246948
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/Startup.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.spigot;\nimport de.cubeattack.neoprotect.spigot.command.NeoProtectCommand;\nimport de.cubeattack.neoprotect.spigot.command.NeoProtectTabCompleter;\nimport de.cubeattack.neoprotect.spigot.listener.ChatListener;\nimport de.cubeattack.neoprotect.spigot.listener.DisconnectListener;\nimport de.cubeattack.neoprotect.spigot.listener.LoginListener;\nimport de.cubeattack.neoprotect.spigot.proxyprotocol.ProxyProtocol;\nimport org.bukkit.Bukkit;\nimport org.bukkit.plugin.PluginManager;\nimport java.util.Objects;",
"score": 0.8482242822647095
}
] |
java
|
.forLanguageTag(Config.getLanguage()), new File("plugins/NeoProtect/languages/"));
|
package de.cubeattack.neoprotect.velocity.listener;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.PostLoginEvent;
import com.velocitypowered.api.proxy.Player;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.velocity.NeoProtectVelocity;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
public class LoginListener {
private final NeoProtectVelocity instance;
private final Localization localization;
public LoginListener(NeoProtectVelocity instance) {
this.instance = instance;
this.localization = instance.getCore().getLocalization();
}
@Subscribe(order = PostOrder.LAST)
public void onPostLogin(PostLoginEvent event) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Player player = event.getPlayer();
Locale locale = (player.getEffectiveLocale() != null) ? player.getEffectiveLocale() : Locale.ENGLISH;
if (!player.hasPermission("neoprotect.admin") && !instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode()))
return;
VersionUtils.Result result = instance.getCore().getVersionResult();
if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {
instance.sendMessage(player, localization.get(locale, "plugin.outdated.message", result.getCurrentVersion(), result.getLatestVersion()));
instance.sendMessage(player, MessageFormat.format("§7-> §b{0}",
result.getReleaseUrl().replace("/NeoPlugin", "").replace("/releases/tag", "")),
"OPEN_URL", result.getReleaseUrl(), null, null);
}
if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {
instance.sendMessage(player, localization.get(locale, "plugin.restart-required.message", result.getCurrentVersion(), result.getLatestVersion()));
}
if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {
instance.sendMessage(player, localization.get(locale, "setup.required.first"));
instance.sendMessage(player, localization.get(locale, "setup.required.second"));
}
if (instance.getCore(
|
).isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {
|
Stats stats = instance.getStats();
String infos =
"§bOsName§7: " + System.getProperty("os.name") + " \n" +
"§bJavaVersion§7: " + System.getProperty("java.version") + " \n" +
"§bPluginVersion§7: " + stats.getPluginVersion() + " \n" +
"§bVersionStatus§7: " + instance.getCore().getVersionResult().getVersionStatus() + " \n" +
"§bUpdateSetting§7: " + Config.getAutoUpdaterSettings() + " \n" +
"§bProxyProtocol§7: " + Config.isProxyProtocol() + " \n" +
"§bNeoProtectPlan§7: " + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : "§cNOT CONNECTED") + " \n" +
"§bVelocityName§7: " + stats.getServerName() + " \n" +
"§bVelocityVersion§7: " + stats.getServerVersion() + " \n" +
"§bVelocityPlugins§7: " + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith("cmd_") && !p.equals("reconnect_yaml")).toArray());
instance.sendMessage(player, "§bHello " + player.getUsername() + " ;)", null, null, "SHOW_TEXT", infos);
instance.sendMessage(player, "§bThis server uses your NeoPlugin", null, null, "SHOW_TEXT", infos);
}
}
}, 500);
}
}
|
src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));",
"score": 0.9381241202354431
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 0.921433687210083
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.913442850112915
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.9107921719551086
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() & !args[0].equals(\"setup\") & !args[0].equals(\"setgameshield\") & !args[0].equals(\"setbackend\")) {\n instance.sendMessage(sender, localization.get(locale, \"setup.command.required\"));\n return;\n }\n switch (args[0].toLowerCase()) {\n case \"setup\": {\n if (isViaConsole) {\n instance.sendMessage(sender, localization.get(Locale.getDefault(), \"console.command\"));\n } else {",
"score": 0.8644077181816101
}
] |
java
|
).isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {
|
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.logger.LogManager;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import de.cubeattack.neoprotect.core.request.RestAPIRequests;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
@SuppressWarnings("unused")
public class Core {
@SuppressWarnings("FieldCanBeLocal")
private final String prefix = "§8[§bNeo§3Protect§8] §7";
private final UUID maintainerOnlineUUID = UUID.fromString("201e5046-24df-4830-8b4a-82b635eb7cc7");
private final UUID maintainerOfflineeUUID = UUID.fromString("8c07bf89-9c8f-304c-9216-4666b670223b");
private final RestAPIRequests restAPIRequests;
private final NeoProtectPlugin plugin;
private final Localization localization;
private final List<Object> playerInSetup = new ArrayList<>();
private final List<String> directConnectWhitelist= new ArrayList<>();
private final ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, Timestamp> timestampsMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, ArrayList<DebugPingResponse>> debugPingResponses = new ConcurrentHashMap<>();
private VersionUtils.Result versionResult;
private boolean isDebugRunning = false;
public Core(NeoProtectPlugin plugin) {
LogManager.getLogger().setLogger(plugin.getLogger());
this.plugin = plugin;
this.versionResult = VersionUtils.checkVersion(
|
"NeoProtect", "NeoPlugin", "v" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message();
|
FileUtils config = new FileUtils(Core.class.getResourceAsStream("/config.yml"), "plugins/NeoProtect", "config.yml", false);
FileUtils languageEN = new FileUtils(Core.class.getResourceAsStream("/language_en.properties"), "plugins/NeoProtect/languages", "language_en.properties", true);
FileUtils languageDE = new FileUtils(Core.class.getResourceAsStream("/language_de.properties"), "plugins/NeoProtect/languages", "language_de.properties", true);
FileUtils languageRU = new FileUtils(Core.class.getResourceAsStream("/language_ru.properties"), "plugins/NeoProtect/languages", "language_ru.properties", true);
FileUtils languageUA = new FileUtils(Core.class.getResourceAsStream("/language_ua.properties"), "plugins/NeoProtect/languages", "language_ua.properties", true);
Config.loadConfig(this, config);
this.localization = new Localization("language", Locale.forLanguageTag(Config.getLanguage()), new File("plugins/NeoProtect/languages/"));
restAPIRequests = new RestAPIRequests(this);
}
public void debug(String output) {
if (Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output);
}
public void info(String output) {
LogManager.getLogger().info(output);
}
public void warn(String output) {
LogManager.getLogger().warn(output);
}
public void severe(String output) {
LogManager.getLogger().error(output);
}
public void severe(String output, Throwable t) {
LogManager.getLogger().error(output, t);
}
public String getPrefix() {
return prefix;
}
public boolean isDebugRunning() {
return isDebugRunning;
}
public void setDebugRunning(boolean debugRunning) {
isDebugRunning = debugRunning;
}
public NeoProtectPlugin getPlugin() {
return plugin;
}
public Localization getLocalization() {
return localization;
}
public RestAPIRequests getRestAPI() {
return restAPIRequests;
}
public boolean isSetup() {
return restAPIRequests.isSetup();
}
public List<Object> getPlayerInSetup() {
return playerInSetup;
}
public List<String> getDirectConnectWhitelist() {
return directConnectWhitelist;
}
public ConcurrentHashMap<KeepAliveResponseKey, Long> getPingMap() {
return pingMap;
}
public ConcurrentHashMap<Long, Timestamp> getTimestampsMap() {
return timestampsMap;
}
public ConcurrentHashMap<String, ArrayList<DebugPingResponse>> getDebugPingResponses() {
return debugPingResponses;
}
public VersionUtils.Result getVersionResult() {
return versionResult;
}
public void setVersionResult(VersionUtils.Result versionResult) {
this.versionResult = versionResult;
}
public boolean isPlayerMaintainer(UUID playerUUID, boolean onlineMode) {
return (onlineMode && playerUUID.equals(maintainerOnlineUUID)) || (!onlineMode && playerUUID.equals(maintainerOfflineeUUID));
}
}
|
src/main/java/de/cubeattack/neoprotect/core/Core.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": "import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;\nimport java.io.File;\nimport java.nio.file.Files;\nimport java.sql.Timestamp;\nimport java.text.DecimalFormat;\nimport java.util.*;\nimport java.util.concurrent.atomic.AtomicReference;\npublic class NeoProtectExecutor {\n private static Timer debugTimer = new Timer();\n private NeoProtectPlugin instance;",
"score": 0.8706983327865601
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import de.cubeattack.neoprotect.core.NeoProtectPlugin;\nimport de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;\nimport de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;\nimport de.cubeattack.neoprotect.velocity.NeoProtectVelocity;\nimport io.netty.channel.Channel;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.channel.ChannelInboundHandlerAdapter;\nimport io.netty.channel.ChannelInitializer;\nimport io.netty.channel.epoll.EpollSocketChannel;\nimport io.netty.channel.epoll.EpollTcpInfo;",
"score": 0.8593974113464355
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": "import org.bstats.velocity.Metrics;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Objects;\nimport java.util.logging.Logger;\npublic class NeoProtectVelocity implements NeoProtectPlugin {\n private final Metrics.Factory metricsFactory;\n private final Logger logger;\n private final ProxyServer proxy;\n private Core core;",
"score": 0.8583030700683594
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.bungee.proxyprotocol;\nimport de.cubeattack.api.util.JavaUtils;\nimport de.cubeattack.neoprotect.bungee.NeoProtectBungee;\nimport de.cubeattack.neoprotect.core.Config;\nimport de.cubeattack.neoprotect.core.NeoProtectPlugin;\nimport de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;\nimport de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;\nimport io.netty.channel.Channel;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.channel.ChannelInboundHandlerAdapter;",
"score": 0.8506620526313782
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": "import de.cubeattack.neoprotect.core.Core;\nimport de.cubeattack.neoprotect.core.NeoProtectPlugin;\nimport de.cubeattack.neoprotect.core.Permission;\nimport de.cubeattack.neoprotect.core.model.Stats;\nimport de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;\nimport net.kyori.adventure.text.Component;\nimport net.kyori.adventure.text.TextComponent;\nimport net.kyori.adventure.text.event.ClickEvent;\nimport net.kyori.adventure.text.event.HoverEvent;\nimport org.bstats.charts.SimplePie;",
"score": 0.8501132726669312
}
] |
java
|
"NeoProtect", "NeoPlugin", "v" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message();
|
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.logger.LogManager;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import de.cubeattack.neoprotect.core.request.RestAPIRequests;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
@SuppressWarnings("unused")
public class Core {
@SuppressWarnings("FieldCanBeLocal")
private final String prefix = "§8[§bNeo§3Protect§8] §7";
private final UUID maintainerOnlineUUID = UUID.fromString("201e5046-24df-4830-8b4a-82b635eb7cc7");
private final UUID maintainerOfflineeUUID = UUID.fromString("8c07bf89-9c8f-304c-9216-4666b670223b");
private final RestAPIRequests restAPIRequests;
private final NeoProtectPlugin plugin;
private final Localization localization;
private final List<Object> playerInSetup = new ArrayList<>();
private final List<String> directConnectWhitelist= new ArrayList<>();
private final ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, Timestamp> timestampsMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, ArrayList<DebugPingResponse>> debugPingResponses = new ConcurrentHashMap<>();
private VersionUtils.Result versionResult;
private boolean isDebugRunning = false;
public Core(NeoProtectPlugin plugin) {
LogManager.getLogger().setLogger(plugin.getLogger());
this.plugin = plugin;
this.versionResult = VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message();
FileUtils config = new FileUtils(Core.class.getResourceAsStream("/config.yml"), "plugins/NeoProtect", "config.yml", false);
FileUtils languageEN = new FileUtils(Core.class.getResourceAsStream("/language_en.properties"), "plugins/NeoProtect/languages", "language_en.properties", true);
FileUtils languageDE = new FileUtils(Core.class.getResourceAsStream("/language_de.properties"), "plugins/NeoProtect/languages", "language_de.properties", true);
FileUtils languageRU = new FileUtils(Core.class.getResourceAsStream("/language_ru.properties"), "plugins/NeoProtect/languages", "language_ru.properties", true);
FileUtils languageUA = new FileUtils(Core.class.getResourceAsStream("/language_ua.properties"), "plugins/NeoProtect/languages", "language_ua.properties", true);
Config.loadConfig(this, config);
this.localization = new Localization("language", Locale.forLanguageTag(Config.getLanguage()), new File("plugins/NeoProtect/languages/"));
restAPIRequests = new RestAPIRequests(this);
}
public void debug(String output) {
if (Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output);
}
public void info(String output) {
LogManager.getLogger().info(output);
}
public void warn(String output) {
LogManager.getLogger().warn(output);
}
public void severe(String output) {
LogManager.getLogger().error(output);
}
public void severe(String output, Throwable t) {
LogManager.getLogger().error(output, t);
}
public String getPrefix() {
return prefix;
}
public boolean isDebugRunning() {
return isDebugRunning;
}
public void setDebugRunning(boolean debugRunning) {
isDebugRunning = debugRunning;
}
public NeoProtectPlugin getPlugin() {
return plugin;
}
public Localization getLocalization() {
return localization;
}
public RestAPIRequests getRestAPI() {
return restAPIRequests;
}
public boolean isSetup() {
|
return restAPIRequests.isSetup();
|
}
public List<Object> getPlayerInSetup() {
return playerInSetup;
}
public List<String> getDirectConnectWhitelist() {
return directConnectWhitelist;
}
public ConcurrentHashMap<KeepAliveResponseKey, Long> getPingMap() {
return pingMap;
}
public ConcurrentHashMap<Long, Timestamp> getTimestampsMap() {
return timestampsMap;
}
public ConcurrentHashMap<String, ArrayList<DebugPingResponse>> getDebugPingResponses() {
return debugPingResponses;
}
public VersionUtils.Result getVersionResult() {
return versionResult;
}
public void setVersionResult(VersionUtils.Result versionResult) {
this.versionResult = versionResult;
}
public boolean isPlayerMaintainer(UUID playerUUID, boolean onlineMode) {
return (onlineMode && playerUUID.equals(maintainerOnlineUUID)) || (!onlineMode && playerUUID.equals(maintainerOfflineeUUID));
}
}
|
src/main/java/de/cubeattack/neoprotect/core/Core.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n public boolean isSetup() {\n return setup;\n }\n}",
"score": 0.8434098362922668
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Stats.java",
"retrieved_chunk": " }\n public String getPluginVersion() {\n return pluginVersion;\n }\n public String getVersionStatus() {\n return versionStatus;\n }\n public String getUpdateSetting() {\n return updateSetting;\n }",
"score": 0.8303576707839966
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/NeoProtectPlugin.java",
"retrieved_chunk": " Core getCore();\n Stats getStats();\n Logger getLogger();\n ArrayList<String> getPlugins();\n PluginType getPluginType();\n String getPluginVersion();\n enum PluginType {\n SPIGOT,\n VELOCITY,\n BUNGEECORD,",
"score": 0.8072084784507751
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " @SuppressWarnings(\"FieldCanBeLocal\")\n private final String ipGetter = \"https://api4.my-ip.io/ip.json\";\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final String pasteServer = \"https://paste.neoprotect.net/documents\";\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final String statsServer = \"https://metrics.einfachesache.de/api/stats/plugin\";\n private JSONArray neoServerIPs = null;\n private boolean setup = false;\n private final Core core;\n private final RestAPIManager rest;",
"score": 0.8006619215011597
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java",
"retrieved_chunk": " new Startup(this);\n }\n public Core getCore() {\n return core;\n }\n @Override\n public Stats getStats() {\n return new Stats(\n getPluginType(),\n getProxy().getVersion(),",
"score": 0.796883225440979
}
] |
java
|
return restAPIRequests.isSetup();
|
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.logger.LogManager;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import de.cubeattack.neoprotect.core.request.RestAPIRequests;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
@SuppressWarnings("unused")
public class Core {
@SuppressWarnings("FieldCanBeLocal")
private final String prefix = "§8[§bNeo§3Protect§8] §7";
private final UUID maintainerOnlineUUID = UUID.fromString("201e5046-24df-4830-8b4a-82b635eb7cc7");
private final UUID maintainerOfflineeUUID = UUID.fromString("8c07bf89-9c8f-304c-9216-4666b670223b");
private final RestAPIRequests restAPIRequests;
private final NeoProtectPlugin plugin;
private final Localization localization;
private final List<Object> playerInSetup = new ArrayList<>();
private final List<String> directConnectWhitelist= new ArrayList<>();
private final ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, Timestamp> timestampsMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, ArrayList<DebugPingResponse>> debugPingResponses = new ConcurrentHashMap<>();
private VersionUtils.Result versionResult;
private boolean isDebugRunning = false;
public Core(NeoProtectPlugin plugin) {
LogManager.getLogger().setLogger(plugin.getLogger());
this.plugin = plugin;
this.versionResult = VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message();
FileUtils config = new FileUtils(Core.class.getResourceAsStream("/config.yml"), "plugins/NeoProtect", "config.yml", false);
FileUtils languageEN = new FileUtils(Core.class.getResourceAsStream("/language_en.properties"), "plugins/NeoProtect/languages", "language_en.properties", true);
FileUtils languageDE = new FileUtils(Core.class.getResourceAsStream("/language_de.properties"), "plugins/NeoProtect/languages", "language_de.properties", true);
FileUtils languageRU = new FileUtils(Core.class.getResourceAsStream("/language_ru.properties"), "plugins/NeoProtect/languages", "language_ru.properties", true);
FileUtils languageUA = new FileUtils(Core.class.getResourceAsStream("/language_ua.properties"), "plugins/NeoProtect/languages", "language_ua.properties", true);
Config.loadConfig(this, config);
this.localization = new Localization("language", Locale.forLanguageTag(Config.getLanguage()), new File("plugins/NeoProtect/languages/"));
restAPIRequests = new RestAPIRequests(this);
}
public void debug(String output) {
if
|
(Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output);
|
}
public void info(String output) {
LogManager.getLogger().info(output);
}
public void warn(String output) {
LogManager.getLogger().warn(output);
}
public void severe(String output) {
LogManager.getLogger().error(output);
}
public void severe(String output, Throwable t) {
LogManager.getLogger().error(output, t);
}
public String getPrefix() {
return prefix;
}
public boolean isDebugRunning() {
return isDebugRunning;
}
public void setDebugRunning(boolean debugRunning) {
isDebugRunning = debugRunning;
}
public NeoProtectPlugin getPlugin() {
return plugin;
}
public Localization getLocalization() {
return localization;
}
public RestAPIRequests getRestAPI() {
return restAPIRequests;
}
public boolean isSetup() {
return restAPIRequests.isSetup();
}
public List<Object> getPlayerInSetup() {
return playerInSetup;
}
public List<String> getDirectConnectWhitelist() {
return directConnectWhitelist;
}
public ConcurrentHashMap<KeepAliveResponseKey, Long> getPingMap() {
return pingMap;
}
public ConcurrentHashMap<Long, Timestamp> getTimestampsMap() {
return timestampsMap;
}
public ConcurrentHashMap<String, ArrayList<DebugPingResponse>> getDebugPingResponses() {
return debugPingResponses;
}
public VersionUtils.Result getVersionResult() {
return versionResult;
}
public void setVersionResult(VersionUtils.Result versionResult) {
this.versionResult = versionResult;
}
public boolean isPlayerMaintainer(UUID playerUUID, boolean onlineMode) {
return (onlineMode && playerUUID.equals(maintainerOnlineUUID)) || (!onlineMode && playerUUID.equals(maintainerOfflineeUUID));
}
}
|
src/main/java/de/cubeattack/neoprotect/core/Core.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core;\nimport de.cubeattack.api.util.FileUtils;\nimport de.cubeattack.api.util.versioning.VersionUtils;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\n@SuppressWarnings(\"unused\")\npublic class Config {\n private static String APIKey;\n private static String language;",
"score": 0.8591064214706421
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " public static void loadConfig(Core core, FileUtils config) {\n Config.core = core;\n fileUtils = config;\n APIKey = config.getString(\"APIKey\", \"\");\n language = config.getString(\"defaultLanguage\", Locale.ENGLISH.toLanguageTag());\n proxyProtocol = config.getBoolean(\"ProxyProtocol\", true);\n gameShieldID = config.getString(\"gameshield.serverId\", \"\");\n backendID = config.getString(\"gameshield.backendId\", \"\");\n geyserBackendID = config.getString(\"gameshield.geyserBackendId\", \"\");\n updateIP = config.getBoolean(\"gameshield.autoUpdateIP\", false);",
"score": 0.8383334875106812
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.executor;\nimport de.cubeattack.api.API;\nimport de.cubeattack.api.language.Localization;\nimport de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;\nimport de.cubeattack.api.libraries.org.json.JSONObject;\nimport de.cubeattack.neoprotect.core.Config;\nimport de.cubeattack.neoprotect.core.NeoProtectPlugin;\nimport de.cubeattack.neoprotect.core.model.Backend;\nimport de.cubeattack.neoprotect.core.model.Gameshield;\nimport de.cubeattack.neoprotect.core.model.Stats;",
"score": 0.8166884779930115
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " debugMode = config.getBoolean(\"DebugMode\", false);\n geyserServerIP = config.getString(\"geyserServerIP\", \"127.0.0.1\");\n if (APIKey.length() != 64) {\n core.severe(\"Failed to load API-Key. Key is null or not valid\");\n return;\n }\n if (gameShieldID.isEmpty()) {\n core.severe(\"Failed to load GameshieldID. ID is null\");\n return;\n }",
"score": 0.8118089437484741
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java",
"retrieved_chunk": "public final class NeoProtectBungee extends Plugin implements NeoProtectPlugin {\n private static Core core;\n @Override\n public void onLoad() {\n Metrics metrics = new Metrics(this, 18726);\n metrics.addCustomChart(new SimplePie(\"language\", Config::getLanguage));\n }\n @Override\n public void onEnable() {\n core = new Core(this);",
"score": 0.8081375956535339
}
] |
java
|
(Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output);
|
package de.cubeattack.neoprotect.bungee.proxyprotocol;
import de.cubeattack.api.util.JavaUtils;
import de.cubeattack.neoprotect.bungee.NeoProtectBungee;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.epoll.EpollTcpInfo;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.UserConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.HandlerBoss;
import net.md_5.bungee.netty.PipelineUtils;
import net.md_5.bungee.protocol.PacketWrapper;
import net.md_5.bungee.protocol.packet.KeepAlive;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
public class ProxyProtocol {
private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, "channel", ChannelWrapper.class);
private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;
private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), "initChannel", Channel.class);
public ProxyProtocol(NeoProtectBungee instance) {
instance.getLogger().info("Proceeding with the server channel injection...");
try {
ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
try {
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
initChannelMethod.invoke(bungeeChannelInitializer, channel);
AtomicReference<InetSocketAddress> playerAddress = new AtomicReference<>();
String sourceAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
if (channel.localAddress().toString().startsWith("local:") || sourceAddress.equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {
channel.close();
instance.getCore().debug("Close connection IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (close / return)");
return;
}
instance.getCore().debug("Adding handler...");
if (instance.getCore().isSetup() && Config.isProxyProtocol()) {
addProxyProtocolHandler(channel, playerAddress);
instance.getCore().debug("Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)");
}
addKeepAlivePacketHandler(channel, playerAddress, instance);
instance.getCore().debug("Added KeepAlivePacketHandler");
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getLogger().log(Level.SEVERE, "Cannot inject incoming channel " + channel, ex);
}
}
};
Field serverChild = PipelineUtils.class.getField("SERVER_CHILD");
serverChild.setAccessible(true);
if (JavaUtils.javaVersionCheck() == 8) {
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(serverChild, serverChild.getModifiers() & ~Modifier.FINAL);
serverChild.set(PipelineUtils.class, channelInitializer);
} else {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Unsafe unsafe = (Unsafe) unsafeField.get(null);
unsafe.putObject(unsafe.staticFieldBase(serverChild), unsafe.staticFieldOffset(serverChild), channelInitializer);
}
instance.getLogger().info("Found the server channel and added the handler. Injection successfully!");
} catch (Exception ex) {
instance.getLogger().log(Level.SEVERE, "An unknown error has occurred", ex);
}
}
public void addProxyProtocolHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress) {
channel.pipeline().names().forEach((n) -> {
if (n.equals("HAProxyMessageDecoder#0"))
channel.pipeline().remove("HAProxyMessageDecoder#0");
});
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HAProxyMessage) {
HAProxyMessage message = (HAProxyMessage) msg;
inetAddress.set(new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
channelWrapperAccessor.get(channel.pipeline().get(HandlerBoss.class)).setRemoteAddress(inetAddress.get());
} else {
super.channelRead(ctx, msg);
}
}
});
}
public void addKeepAlivePacketHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress, NeoProtectPlugin instance) {
channel.pipeline().addAfter(PipelineUtils.PACKET_DECODER, "neo-keep-alive-handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
super.channelRead(ctx, msg);
if (!(msg instanceof PacketWrapper)) {
return;
}
if (!(((PacketWrapper) msg).packet instanceof KeepAlive)) {
return;
}
KeepAlive keepAlive = (KeepAlive) ((PacketWrapper) msg).packet;
ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = instance.getCore().getPingMap();
instance.getCore().debug("Received KeepAlivePackets (" + keepAlive.getRandomId() + ")");
for (KeepAliveResponseKey keepAliveResponseKey : pingMap.keySet()) {
if (!keepAliveResponseKey.getAddress().equals(inetAddress.get()) || !(keepAliveResponseKey.getId() == keepAlive.getRandomId())) {
continue;
}
instance.getCore().debug("KeepAlivePackets matched to DebugKeepAlivePacket");
for (ProxiedPlayer player : BungeeCord.getInstance().getPlayers()) {
if (!(player).getPendingConnection().getSocketAddress().equals(inetAddress.get())) {
continue;
}
instance.getCore().debug("Player matched to DebugKeepAlivePacket (loading data...)");
EpollTcpInfo tcpInfo = ((EpollSocketChannel) channel).tcpInfo();
EpollTcpInfo tcpInfoBackend = ((EpollSocketChannel) ((UserConnection) player).getServer().getCh().getHandle()).tcpInfo();
long ping = System.currentTimeMillis() - pingMap.get(keepAliveResponseKey);
long neoRTT = 0;
long backendRTT = 0;
if (tcpInfo != null) {
neoRTT = tcpInfo.rtt() / 1000;
}
if (tcpInfoBackend != null) {
backendRTT = tcpInfoBackend.rtt() / 1000;
}
ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();
if (!map.containsKey(player.getName())) {
|
instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>());
|
}
map.get(player.getName()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));
instance.getCore().debug("Loading completed");
instance.getCore().debug(" ");
}
instance.getCore().getPingMap().remove(keepAliveResponseKey);
}
}
});
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if (!ipRange.contains("/")) {
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (tcpInfo != null) {\n neoRTT = tcpInfo.rtt() / 1000;\n }\n if (tcpInfoBackend != null) {\n backendRTT = tcpInfoBackend.rtt() / 1000;\n }\n ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();\n if (!map.containsKey(player.getUsername())) {\n instance.getCore().getDebugPingResponses().put(player.getUsername(), new ArrayList<>());\n }",
"score": 0.9852547645568848
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " for (Player player : velocityServer.getAllPlayers()) {\n if (!(player).getRemoteAddress().equals(inetAddress.get())) {\n continue;\n }\n instance.getCore().debug(\"Player matched to DebugKeepAlivePacket (loading data...)\");\n EpollTcpInfo tcpInfo = ((EpollSocketChannel) channel).tcpInfo();\n EpollTcpInfo tcpInfoBackend = ((EpollSocketChannel) ((ConnectedPlayer) player).getConnection().getChannel()).tcpInfo();\n long ping = System.currentTimeMillis() - pingMap.get(keepAliveResponseKey);\n long neoRTT = 0;\n long backendRTT = 0;",
"score": 0.8936641216278076
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " long minPlayerToNeoLatenz = Long.MAX_VALUE;\n configuration.set(\"players.\" + playerName + \".playerAddress\", list.get(0).getPlayerAddress());\n configuration.set(\"players.\" + playerName + \".neoAddress\", list.get(0).getNeoAddress());\n for (DebugPingResponse response : list) {\n if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())\n maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();\n if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())\n maxNeoToProxyLatenz = response.getNeoToProxyLatenz();\n if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())\n maxProxyToBackendLatenz = response.getProxyToBackendLatenz();",
"score": 0.8426623344421387
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/debugtool/DebugPingResponse.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.model.debugtool;\nimport java.net.SocketAddress;\n@SuppressWarnings(\"unused\")\npublic class DebugPingResponse {\n private final long proxyToBackendLatenz;\n private final long playerToProxyLatenz;\n private final long neoToProxyLatenz;\n private final SocketAddress playerAddress;\n private final SocketAddress neoAddress;\n public DebugPingResponse(long playerToProxyLatenz, long neoToProxyLatenz, long proxyToBackendLatenz, SocketAddress playerAddress, SocketAddress neoAddress) {",
"score": 0.8406797051429749
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " return;\n }\n KeepAlive keepAlive = (KeepAlive) msg;\n ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = instance.getCore().getPingMap();\n instance.getCore().debug(\"Received KeepAlivePackets (\" + keepAlive.getRandomId() + \")\");\n for (KeepAliveResponseKey keepAliveResponseKey : pingMap.keySet()) {\n if (!keepAliveResponseKey.getAddress().equals(inetAddress.get()) || !(keepAliveResponseKey.getId() == keepAlive.getRandomId())) {\n continue;\n }\n instance.getCore().debug(\"KeepAlivePackets matched to DebugKeepAlivePacket\");",
"score": 0.8395751714706421
}
] |
java
|
instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>());
|
package de.cubeattack.neoprotect.bungee.proxyprotocol;
import de.cubeattack.api.util.JavaUtils;
import de.cubeattack.neoprotect.bungee.NeoProtectBungee;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.epoll.EpollTcpInfo;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.UserConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.HandlerBoss;
import net.md_5.bungee.netty.PipelineUtils;
import net.md_5.bungee.protocol.PacketWrapper;
import net.md_5.bungee.protocol.packet.KeepAlive;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
public class ProxyProtocol {
private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, "channel", ChannelWrapper.class);
private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;
private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), "initChannel", Channel.class);
public ProxyProtocol(NeoProtectBungee instance) {
instance.getLogger().info("Proceeding with the server channel injection...");
try {
ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
try {
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
initChannelMethod.invoke(bungeeChannelInitializer, channel);
AtomicReference<InetSocketAddress> playerAddress = new AtomicReference<>();
String sourceAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
if (channel.localAddress().toString().startsWith("local:") || sourceAddress.equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {
channel.close();
instance.getCore().debug("Close connection IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (close / return)");
return;
}
instance.getCore().debug("Adding handler...");
if (instance.getCore().isSetup() && Config.isProxyProtocol()) {
addProxyProtocolHandler(channel, playerAddress);
instance.getCore().debug("Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)");
}
addKeepAlivePacketHandler(channel, playerAddress, instance);
instance.getCore().debug("Added KeepAlivePacketHandler");
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getLogger().log(Level.SEVERE, "Cannot inject incoming channel " + channel, ex);
}
}
};
Field serverChild = PipelineUtils.class.getField("SERVER_CHILD");
serverChild.setAccessible(true);
if (JavaUtils.javaVersionCheck() == 8) {
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(serverChild, serverChild.getModifiers() & ~Modifier.FINAL);
serverChild.set(PipelineUtils.class, channelInitializer);
} else {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Unsafe unsafe = (Unsafe) unsafeField.get(null);
unsafe.putObject(unsafe.staticFieldBase(serverChild), unsafe.staticFieldOffset(serverChild), channelInitializer);
}
instance.getLogger().info("Found the server channel and added the handler. Injection successfully!");
} catch (Exception ex) {
instance.getLogger().log(Level.SEVERE, "An unknown error has occurred", ex);
}
}
public void addProxyProtocolHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress) {
channel.pipeline().names().forEach((n) -> {
if (n.equals("HAProxyMessageDecoder#0"))
channel.pipeline().remove("HAProxyMessageDecoder#0");
});
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HAProxyMessage) {
HAProxyMessage message = (HAProxyMessage) msg;
inetAddress.set(new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
channelWrapperAccessor.get(channel.pipeline().get(HandlerBoss.class)).setRemoteAddress(inetAddress.get());
} else {
super.channelRead(ctx, msg);
}
}
});
}
public void addKeepAlivePacketHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress, NeoProtectPlugin instance) {
channel.pipeline().addAfter(PipelineUtils.PACKET_DECODER, "neo-keep-alive-handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
super.channelRead(ctx, msg);
if (!(msg instanceof PacketWrapper)) {
return;
}
if (!(((PacketWrapper) msg).packet instanceof KeepAlive)) {
return;
}
KeepAlive keepAlive = (KeepAlive) ((PacketWrapper) msg).packet;
ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = instance.getCore().getPingMap();
instance.getCore().debug("Received KeepAlivePackets (" + keepAlive.getRandomId() + ")");
for (KeepAliveResponseKey keepAliveResponseKey : pingMap.keySet()) {
if (!keepAliveResponseKey.getAddress().equals(inetAddress.get()) || !(keepAliveResponseKey.getId() == keepAlive.getRandomId())) {
continue;
}
instance.getCore().debug("KeepAlivePackets matched to DebugKeepAlivePacket");
for (ProxiedPlayer player : BungeeCord.getInstance().getPlayers()) {
if (!(player).getPendingConnection().getSocketAddress().equals(inetAddress.get())) {
continue;
}
instance.getCore().debug("Player matched to DebugKeepAlivePacket (loading data...)");
EpollTcpInfo tcpInfo = ((EpollSocketChannel) channel).tcpInfo();
EpollTcpInfo tcpInfoBackend = ((EpollSocketChannel) ((UserConnection) player).getServer().getCh().getHandle()).tcpInfo();
long ping = System.currentTimeMillis() - pingMap.get(keepAliveResponseKey);
long neoRTT = 0;
long backendRTT = 0;
if (tcpInfo != null) {
neoRTT = tcpInfo.rtt() / 1000;
}
if (tcpInfoBackend != null) {
backendRTT = tcpInfoBackend.rtt() / 1000;
}
ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();
if (!map.containsKey(player.getName())) {
instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>());
}
map.get(player.getName()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));
instance.getCore().debug("Loading completed");
instance.getCore().debug(" ");
}
|
instance.getCore().getPingMap().remove(keepAliveResponseKey);
|
}
}
});
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if (!ipRange.contains("/")) {
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
|
src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (tcpInfo != null) {\n neoRTT = tcpInfo.rtt() / 1000;\n }\n if (tcpInfoBackend != null) {\n backendRTT = tcpInfoBackend.rtt() / 1000;\n }\n ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();\n if (!map.containsKey(player.getUsername())) {\n instance.getCore().getDebugPingResponses().put(player.getUsername(), new ArrayList<>());\n }",
"score": 0.924902081489563
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " for (Player player : velocityServer.getAllPlayers()) {\n if (!(player).getRemoteAddress().equals(inetAddress.get())) {\n continue;\n }\n instance.getCore().debug(\"Player matched to DebugKeepAlivePacket (loading data...)\");\n EpollTcpInfo tcpInfo = ((EpollSocketChannel) channel).tcpInfo();\n EpollTcpInfo tcpInfoBackend = ((EpollSocketChannel) ((ConnectedPlayer) player).getConnection().getChannel()).tcpInfo();\n long ping = System.currentTimeMillis() - pingMap.get(keepAliveResponseKey);\n long neoRTT = 0;\n long backendRTT = 0;",
"score": 0.9058562517166138
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " return;\n }\n KeepAlive keepAlive = (KeepAlive) msg;\n ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = instance.getCore().getPingMap();\n instance.getCore().debug(\"Received KeepAlivePackets (\" + keepAlive.getRandomId() + \")\");\n for (KeepAliveResponseKey keepAliveResponseKey : pingMap.keySet()) {\n if (!keepAliveResponseKey.getAddress().equals(inetAddress.get()) || !(keepAliveResponseKey.getId() == keepAlive.getRandomId())) {\n continue;\n }\n instance.getCore().debug(\"KeepAlivePackets matched to DebugKeepAlivePacket\");",
"score": 0.8681379556655884
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " map.get(player.getUsername()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));\n instance.getCore().debug(\"Loading completed\");\n instance.getCore().debug(\" \");\n }\n pingMap.remove(keepAliveResponseKey);\n }\n }\n });\n }\n public static boolean isIPInRange(String ipRange, String ipAddress) {",
"score": 0.8556123375892639
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " configuration.load(file);\n configuration.set(\"general.osName\", System.getProperty(\"os.name\"));\n configuration.set(\"general.javaVersion\", System.getProperty(\"java.version\"));\n configuration.set(\"general.pluginVersion\", stats.getPluginVersion());\n configuration.set(\"general.ProxyName\", stats.getServerName());\n configuration.set(\"general.ProxyVersion\", stats.getServerVersion());\n configuration.set(\"general.ProxyPlugins\", instance.getPlugins());\n instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {\n List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);\n long maxPlayerToProxyLatenz = 0;",
"score": 0.8323075771331787
}
] |
java
|
instance.getCore().getPingMap().remove(keepAliveResponseKey);
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest
|
.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
|
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " private static boolean proxyProtocol;\n private static String gameShieldID;\n private static String backendID;\n private static String geyserBackendID;\n private static boolean updateIP;\n private static boolean debugMode;\n private static String geyserServerIP;\n private static String updateSetting;\n private static Core core;\n private static FileUtils fileUtils;",
"score": 0.8320251703262329
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Stats.java",
"retrieved_chunk": " private final boolean proxyProtocol;\n public Stats(NeoProtectPlugin.PluginType serverType, String serverVersion, String serverName, String javaVersion, String osName, String osArch, String osVersion, String pluginVersion, String versionStatus, String updateSetting, String neoProtectPlan, String serverPlugins, int playerAmount, int managedServers, int coreCount, boolean onlineMode, boolean proxyProtocol) {\n this.serverType = serverType.name().toLowerCase();\n this.serverVersion = serverVersion;\n this.serverName = serverName;\n this.javaVersion = javaVersion;\n this.osName = osName;\n this.osArch = osArch;\n this.osVersion = osVersion;\n this.pluginVersion = pluginVersion;",
"score": 0.8178958892822266
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {\n if (ak.equals(\"bandwidth\")) {\n return;\n }\n if (ak.equals(\"traffic\")) {\n instance.sendMessage(sender, ak.replace(\"traffic\", \"bandwidth\") + \": \" +\n new DecimalFormat(\"#.####\").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + \" mbit/s\");\n JSONObject traffic = instance.getCore().getRestAPI().getTraffic();\n AtomicReference<String> trafficUsed = new AtomicReference<>();\n AtomicReference<String> trafficAvailable = new AtomicReference<>();",
"score": 0.8135769367218018
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RequestType.java",
"retrieved_chunk": " GET_GAMESHIELD_LASTSTATS,\n GET_GAMESHIELD_ISUNDERATTACK,\n GET_GAMESHIELD_BANDWIDTH,\n GET_GAMESHIELD_ANALYTICS,\n GET_FIREWALLS,\n POST_FIREWALL_CREATE,\n DELETE_FIREWALL,\n GET_PLANS_AVAILABLE,\n GET_PROFILE_TRANSACTIONS,\n GET_PROFILE_INFOS,",
"score": 0.813520610332489
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " return restAPIRequests.isSetup();\n }\n public List<Object> getPlayerInSetup() {\n return playerInSetup;\n }\n public List<String> getDirectConnectWhitelist() {\n return directConnectWhitelist;\n }\n public ConcurrentHashMap<KeepAliveResponseKey, Long> getPingMap() {\n return pingMap;",
"score": 0.8075317144393921
}
] |
java
|
.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.
|
POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
|
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n APIKey = key;\n }\n public static void setGameShieldID(String id) {\n fileUtils.set(\"gameshield.serverId\", id);\n fileUtils.save();\n gameShieldID = id;\n }\n public static void setBackendID(String id) {\n fileUtils.set(\"gameshield.backendId\", id);",
"score": 0.8324684500694275
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.81769859790802
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n backendID = id;\n }\n public static void setGeyserBackendID(String id) {\n fileUtils.set(\"gameshield.geyserBackendId\", id);\n fileUtils.save();\n geyserBackendID = id;\n }\n public static void addAutoUpdater(boolean basicPlan) {\n if (basicPlan) {",
"score": 0.8174680471420288
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RequestType.java",
"retrieved_chunk": " GET_GAMESHIELD_PLAN,\n POST_GAMESHIELD_PLAN_UPGRADE,\n POST_GAMESHIELD_UPDATE_NAME,\n POST_GAMESHIELD_UPDATE_ICON,\n DELETE_GAMESHIELD_UPDATE_ICON,\n POST_GAMESHIELD_UPDATE_BANNER,\n DELETE_GAMESHIELD_BANNER,\n POST_GAMESHIELD_AVAILABLE,\n GET_GAMESHIELD_INFO,\n DELETE_GAMESHIELD,",
"score": 0.8174582123756409
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " }\n public static String getLanguage() {\n return language;\n }\n public static String getGameShieldID() {\n return gameShieldID;\n }\n public static String getBackendID() {\n return backendID;\n }",
"score": 0.8168765306472778
}
] |
java
|
POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if
|
(isAPIInvalid(Config.getAPIKey())) {
|
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {\n if (ak.equals(\"bandwidth\")) {\n return;\n }\n if (ak.equals(\"traffic\")) {\n instance.sendMessage(sender, ak.replace(\"traffic\", \"bandwidth\") + \": \" +\n new DecimalFormat(\"#.####\").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + \" mbit/s\");\n JSONObject traffic = instance.getCore().getRestAPI().getTraffic();\n AtomicReference<String> trafficUsed = new AtomicReference<>();\n AtomicReference<String> trafficAvailable = new AtomicReference<>();",
"score": 0.8232494592666626
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " return restAPIRequests.isSetup();\n }\n public List<Object> getPlayerInSetup() {\n return playerInSetup;\n }\n public List<String> getDirectConnectWhitelist() {\n return directConnectWhitelist;\n }\n public ConcurrentHashMap<KeepAliveResponseKey, Long> getPingMap() {\n return pingMap;",
"score": 0.8171846866607666
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " if (backendID.isEmpty()) {\n core.severe(\"Failed to load BackendID. ID is null\");\n return;\n }\n core.info(\"API-Key loaded successful '\" + \"******************************\" + APIKey.substring(32) + \"'\");\n core.info(\"GameshieldID loaded successful '\" + gameShieldID + \"'\");\n core.info(\"BackendID loaded successful '\" + backendID + \"'\");\n }\n public static String getAPIKey() {\n return APIKey;",
"score": 0.815363883972168
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/ResponseManager.java",
"retrieved_chunk": " }\n public JSONObject getResponseBodyObject() {\n try {\n return new JSONObject(responseBody);\n } catch (JSONException ignored) {}\n return new JSONObject();\n }\n public JSONArray getResponseBodyArray() {\n try {\n return new JSONArray(responseBody);",
"score": 0.8093017339706421
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RequestType.java",
"retrieved_chunk": " GET_GAMESHIELD_LASTSTATS,\n GET_GAMESHIELD_ISUNDERATTACK,\n GET_GAMESHIELD_BANDWIDTH,\n GET_GAMESHIELD_ANALYTICS,\n GET_FIREWALLS,\n POST_FIREWALL_CREATE,\n DELETE_FIREWALL,\n GET_PLANS_AVAILABLE,\n GET_PROFILE_TRANSACTIONS,\n GET_PROFILE_INFOS,",
"score": 0.808262825012207
}
] |
java
|
(isAPIInvalid(Config.getAPIKey())) {
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest
|
.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
|
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RequestType.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\n@SuppressWarnings(\"unused\")\npublic enum RequestType {\n GET_ATTACKS,\n GET_ATTACKS_GAMESHIELD,\n GET_GAMESHIELD_BACKENDS,\n POST_GAMESHIELD_BACKEND_CREATE,\n POST_GAMESHIELD_BACKEND_UPDATE,\n DELETE_GAMESHIELD_BACKEND_UPDATE,\n POST_GAMESHIELD_BACKEND_AVAILABLE,",
"score": 0.8185216784477234
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Gameshield.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Gameshield {\n private final String id;\n private final String name;\n public Gameshield(String id, String name) {\n this.id = id;\n this.name = name;\n }\n public String getId() {\n return id;",
"score": 0.8178528547286987
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n APIKey = key;\n }\n public static void setGameShieldID(String id) {\n fileUtils.set(\"gameshield.serverId\", id);\n fileUtils.save();\n gameShieldID = id;\n }\n public static void setBackendID(String id) {\n fileUtils.set(\"gameshield.backendId\", id);",
"score": 0.8093571066856384
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.8075937032699585
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " case GET_GAMESHIELD_INFO: {\n return new Formatter().format(\"/gameshields/%s\", values).toString();\n }\n case DELETE_GAMESHIELD: {\n return new Formatter().format(\"/gameshields/%s\", values).toString();\n }\n case GET_GAMESHIELD_LASTSTATS: {\n return new Formatter().format(\"/gameshields/%s/lastStats\", values).toString();\n }\n case GET_GAMESHIELD_ISUNDERATTACK: {",
"score": 0.8073467016220093
}
] |
java
|
.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()),
|
Config.getGameShieldID());
|
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " private static boolean proxyProtocol;\n private static String gameShieldID;\n private static String backendID;\n private static String geyserBackendID;\n private static boolean updateIP;\n private static boolean debugMode;\n private static String geyserServerIP;\n private static String updateSetting;\n private static Core core;\n private static FileUtils fileUtils;",
"score": 0.8504676222801208
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n APIKey = key;\n }\n public static void setGameShieldID(String id) {\n fileUtils.set(\"gameshield.serverId\", id);\n fileUtils.save();\n gameShieldID = id;\n }\n public static void setBackendID(String id) {\n fileUtils.set(\"gameshield.backendId\", id);",
"score": 0.8465850353240967
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.8229029178619385
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n backendID = id;\n }\n public static void setGeyserBackendID(String id) {\n fileUtils.set(\"gameshield.geyserBackendId\", id);\n fileUtils.save();\n geyserBackendID = id;\n }\n public static void addAutoUpdater(boolean basicPlan) {\n if (basicPlan) {",
"score": 0.8165391683578491
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " if (args.length == 1 && !isViaConsole) {\n gameshieldSelector();\n } else if (args.length == 2) {\n setGameshield(args);\n } else {\n instance.sendMessage(sender, localization.get(locale, \"usage.setgameshield\"));\n }\n break;\n }\n case \"setbackend\": {",
"score": 0.8092473745346069
}
] |
java
|
Config.getGameShieldID());
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
|
if (Config.isUpdateIP()) {
|
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": "import java.util.Formatter;\nimport java.util.concurrent.TimeUnit;\npublic class RestAPIManager {\n private final OkHttpClient client = new OkHttpClient();\n private final String baseURL = \"https://api.neoprotect.net/v2\";\n private final Core core;\n public RestAPIManager(Core core) {\n this.core = core;\n }\n {",
"score": 0.8827670812606812
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " private final ConcurrentHashMap<String, ArrayList<DebugPingResponse>> debugPingResponses = new ConcurrentHashMap<>();\n private VersionUtils.Result versionResult;\n private boolean isDebugRunning = false;\n public Core(NeoProtectPlugin plugin) {\n LogManager.getLogger().setLogger(plugin.getLogger());\n this.plugin = plugin;\n this.versionResult = VersionUtils.checkVersion(\"NeoProtect\", \"NeoPlugin\", \"v\" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message();\n FileUtils config = new FileUtils(Core.class.getResourceAsStream(\"/config.yml\"), \"plugins/NeoProtect\", \"config.yml\", false);\n FileUtils languageEN = new FileUtils(Core.class.getResourceAsStream(\"/language_en.properties\"), \"plugins/NeoProtect/languages\", \"language_en.properties\", true);\n FileUtils languageDE = new FileUtils(Core.class.getResourceAsStream(\"/language_de.properties\"), \"plugins/NeoProtect/languages\", \"language_de.properties\", true);",
"score": 0.8288364410400391
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core;\nimport de.cubeattack.api.language.Localization;\nimport de.cubeattack.api.logger.LogManager;\nimport de.cubeattack.api.util.FileUtils;\nimport de.cubeattack.api.util.versioning.VersionUtils;\nimport de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;\nimport de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;\nimport de.cubeattack.neoprotect.core.request.RestAPIRequests;\nimport java.io.File;\nimport java.sql.Timestamp;",
"score": 0.8231447339057922
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\nimport com.squareup.okhttp.OkHttpClient;\nimport com.squareup.okhttp.Request;\nimport com.squareup.okhttp.RequestBody;\nimport com.squareup.okhttp.Response;\nimport de.cubeattack.neoprotect.core.Config;\nimport de.cubeattack.neoprotect.core.Core;\nimport java.net.SocketException;\nimport java.net.SocketTimeoutException;\nimport java.net.UnknownHostException;",
"score": 0.8127018213272095
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " private final String prefix = \"§8[§bNeo§3Protect§8] §7\";\n private final UUID maintainerOnlineUUID = UUID.fromString(\"201e5046-24df-4830-8b4a-82b635eb7cc7\");\n private final UUID maintainerOfflineeUUID = UUID.fromString(\"8c07bf89-9c8f-304c-9216-4666b670223b\");\n private final RestAPIRequests restAPIRequests;\n private final NeoProtectPlugin plugin;\n private final Localization localization;\n private final List<Object> playerInSetup = new ArrayList<>();\n private final List<String> directConnectWhitelist= new ArrayList<>();\n private final ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = new ConcurrentHashMap<>();\n private final ConcurrentHashMap<Long, Timestamp> timestampsMap = new ConcurrentHashMap<>();",
"score": 0.8111262321472168
}
] |
java
|
if (Config.isUpdateIP()) {
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
|
setProxyProtocol(Config.isProxyProtocol());
|
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " private static boolean proxyProtocol;\n private static String gameShieldID;\n private static String backendID;\n private static String geyserBackendID;\n private static boolean updateIP;\n private static boolean debugMode;\n private static String geyserServerIP;\n private static String updateSetting;\n private static Core core;\n private static FileUtils fileUtils;",
"score": 0.868979275226593
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.8525516986846924
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " debugMode = config.getBoolean(\"DebugMode\", false);\n geyserServerIP = config.getString(\"geyserServerIP\", \"127.0.0.1\");\n if (APIKey.length() != 64) {\n core.severe(\"Failed to load API-Key. Key is null or not valid\");\n return;\n }\n if (gameShieldID.isEmpty()) {\n core.severe(\"Failed to load GameshieldID. ID is null\");\n return;\n }",
"score": 0.8501283526420593
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " public static void loadConfig(Core core, FileUtils config) {\n Config.core = core;\n fileUtils = config;\n APIKey = config.getString(\"APIKey\", \"\");\n language = config.getString(\"defaultLanguage\", Locale.ENGLISH.toLanguageTag());\n proxyProtocol = config.getBoolean(\"ProxyProtocol\", true);\n gameShieldID = config.getString(\"gameshield.serverId\", \"\");\n backendID = config.getString(\"gameshield.backendId\", \"\");\n geyserBackendID = config.getString(\"gameshield.geyserBackendId\", \"\");\n updateIP = config.getBoolean(\"gameshield.autoUpdateIP\", false);",
"score": 0.8489707112312317
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " if (args.length == 1 && !isViaConsole) {\n gameshieldSelector();\n } else if (args.length == 2) {\n setGameshield(args);\n } else {\n instance.sendMessage(sender, localization.get(locale, \"usage.setgameshield\"));\n }\n break;\n }\n case \"setbackend\": {",
"score": 0.8484852313995361
}
] |
java
|
setProxyProtocol(Config.isProxyProtocol());
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
|
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
|
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n backendID = id;\n }\n public static void setGeyserBackendID(String id) {\n fileUtils.set(\"gameshield.geyserBackendId\", id);\n fileUtils.save();\n geyserBackendID = id;\n }\n public static void addAutoUpdater(boolean basicPlan) {\n if (basicPlan) {",
"score": 0.8487714529037476
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " private static boolean proxyProtocol;\n private static String gameShieldID;\n private static String backendID;\n private static String geyserBackendID;\n private static boolean updateIP;\n private static boolean debugMode;\n private static String geyserServerIP;\n private static String updateSetting;\n private static Core core;\n private static FileUtils fileUtils;",
"score": 0.8425911664962769
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " public static void loadConfig(Core core, FileUtils config) {\n Config.core = core;\n fileUtils = config;\n APIKey = config.getString(\"APIKey\", \"\");\n language = config.getString(\"defaultLanguage\", Locale.ENGLISH.toLanguageTag());\n proxyProtocol = config.getBoolean(\"ProxyProtocol\", true);\n gameShieldID = config.getString(\"gameshield.serverId\", \"\");\n backendID = config.getString(\"gameshield.backendId\", \"\");\n geyserBackendID = config.getString(\"gameshield.geyserBackendId\", \"\");\n updateIP = config.getBoolean(\"gameshield.autoUpdateIP\", false);",
"score": 0.8286408185958862
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": " getProxy().getVersion().getVersion(),\n getProxy().getVersion().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),\n System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getPluginVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",",
"score": 0.8238456845283508
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.8221645355224609
}
] |
java
|
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
|
Config.getGameShieldID()).getCode();
|
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " int response = instance.getCore().getRestAPI().toggle(args[1]);\n if (response == 403) {\n instance.sendMessage(sender, localization.get(locale, \"err.upgrade-plan\"));\n return;\n }\n if (response == 429) {\n instance.sendMessage(sender, localization.get(locale, \"err.rate-limit\"));\n return;\n }\n if (response == -1) {",
"score": 0.8021502494812012
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.8013924360275269
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n APIKey = key;\n }\n public static void setGameShieldID(String id) {\n fileUtils.set(\"gameshield.serverId\", id);\n fileUtils.save();\n gameShieldID = id;\n }\n public static void setBackendID(String id) {\n fileUtils.set(\"gameshield.backendId\", id);",
"score": 0.7940934300422668
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " if (args.length == 1 && !isViaConsole) {\n gameshieldSelector();\n } else if (args.length == 2) {\n setGameshield(args);\n } else {\n instance.sendMessage(sender, localization.get(locale, \"usage.setgameshield\"));\n }\n break;\n }\n case \"setbackend\": {",
"score": 0.7822075486183167
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " case \"whitelist\":\n case \"blacklist\": {\n firewall(args);\n break;\n }\n case \"debugtool\": {\n debugTool(args);\n break;\n }\n case \"setgameshield\": {",
"score": 0.779808521270752
}
] |
java
|
Config.getGameShieldID()).getCode();
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
|
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
|
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {\n if (ak.equals(\"bandwidth\")) {\n return;\n }\n if (ak.equals(\"traffic\")) {\n instance.sendMessage(sender, ak.replace(\"traffic\", \"bandwidth\") + \": \" +\n new DecimalFormat(\"#.####\").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + \" mbit/s\");\n JSONObject traffic = instance.getCore().getRestAPI().getTraffic();\n AtomicReference<String> trafficUsed = new AtomicReference<>();\n AtomicReference<String> trafficAvailable = new AtomicReference<>();",
"score": 0.8231820464134216
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " return restAPIRequests.isSetup();\n }\n public List<Object> getPlayerInSetup() {\n return playerInSetup;\n }\n public List<String> getDirectConnectWhitelist() {\n return directConnectWhitelist;\n }\n public ConcurrentHashMap<KeepAliveResponseKey, Long> getPingMap() {\n return pingMap;",
"score": 0.8189288377761841
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " if (backendID.isEmpty()) {\n core.severe(\"Failed to load BackendID. ID is null\");\n return;\n }\n core.info(\"API-Key loaded successful '\" + \"******************************\" + APIKey.substring(32) + \"'\");\n core.info(\"GameshieldID loaded successful '\" + gameShieldID + \"'\");\n core.info(\"BackendID loaded successful '\" + backendID + \"'\");\n }\n public static String getAPIKey() {\n return APIKey;",
"score": 0.8132457733154297
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " debugMode = config.getBoolean(\"DebugMode\", false);\n geyserServerIP = config.getString(\"geyserServerIP\", \"127.0.0.1\");\n if (APIKey.length() != 64) {\n core.severe(\"Failed to load API-Key. Key is null or not valid\");\n return;\n }\n if (gameShieldID.isEmpty()) {\n core.severe(\"Failed to load GameshieldID. ID is null\");\n return;\n }",
"score": 0.8081124424934387
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": "import java.util.Formatter;\nimport java.util.concurrent.TimeUnit;\npublic class RestAPIManager {\n private final OkHttpClient client = new OkHttpClient();\n private final String baseURL = \"https://api.neoprotect.net/v2\";\n private final Core core;\n public RestAPIManager(Core core) {\n this.core = core;\n }\n {",
"score": 0.8063879013061523
}
] |
java
|
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
|
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
|
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " if (backendID.isEmpty()) {\n core.severe(\"Failed to load BackendID. ID is null\");\n return;\n }\n core.info(\"API-Key loaded successful '\" + \"******************************\" + APIKey.substring(32) + \"'\");\n core.info(\"GameshieldID loaded successful '\" + gameShieldID + \"'\");\n core.info(\"BackendID loaded successful '\" + backendID + \"'\");\n }\n public static String getAPIKey() {\n return APIKey;",
"score": 0.8249858021736145
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {\n if (ak.equals(\"bandwidth\")) {\n return;\n }\n if (ak.equals(\"traffic\")) {\n instance.sendMessage(sender, ak.replace(\"traffic\", \"bandwidth\") + \": \" +\n new DecimalFormat(\"#.####\").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + \" mbit/s\");\n JSONObject traffic = instance.getCore().getRestAPI().getTraffic();\n AtomicReference<String> trafficUsed = new AtomicReference<>();\n AtomicReference<String> trafficAvailable = new AtomicReference<>();",
"score": 0.8246381878852844
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " debugMode = config.getBoolean(\"DebugMode\", false);\n geyserServerIP = config.getString(\"geyserServerIP\", \"127.0.0.1\");\n if (APIKey.length() != 64) {\n core.severe(\"Failed to load API-Key. Key is null or not valid\");\n return;\n }\n if (gameShieldID.isEmpty()) {\n core.severe(\"Failed to load GameshieldID. ID is null\");\n return;\n }",
"score": 0.8203942775726318
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " return restAPIRequests.isSetup();\n }\n public List<Object> getPlayerInSetup() {\n return playerInSetup;\n }\n public List<String> getDirectConnectWhitelist() {\n return directConnectWhitelist;\n }\n public ConcurrentHashMap<KeepAliveResponseKey, Long> getPingMap() {\n return pingMap;",
"score": 0.8191867470741272
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": "import java.util.Formatter;\nimport java.util.concurrent.TimeUnit;\npublic class RestAPIManager {\n private final OkHttpClient client = new OkHttpClient();\n private final String baseURL = \"https://api.neoprotect.net/v2\";\n private final Core core;\n public RestAPIManager(Core core) {\n this.core = core;\n }\n {",
"score": 0.814691424369812
}
] |
java
|
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS,
|
null, Config.getGameShieldID()).getResponseBodyArray();
|
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Gameshield.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Gameshield {\n private final String id;\n private final String name;\n public Gameshield(String id, String name) {\n this.id = id;\n this.name = name;\n }\n public String getId() {\n return id;",
"score": 0.8008809685707092
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGameShieldID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.gameshield\", args[1]));\n javaBackendSelector();\n }\n private void javaBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"java\"));\n for (Backend backend : backendList) {\n if(backend.isGeyser())continue;",
"score": 0.7938323020935059
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " }\n case GET_GAMESHIELD_BACKENDS: {\n return new Formatter().format(\"/gameshields/%s/backends\", values).toString();\n }\n case POST_GAMESHIELD_BACKEND_CREATE: {\n return new Formatter().format(\"/gameshields/%s/backends\", values).toString();\n }\n case POST_GAMESHIELD_BACKEND_UPDATE: {\n return new Formatter().format(\"/gameshields/%s/backends/%s\", values).toString();\n }",
"score": 0.791433572769165
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RequestType.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\n@SuppressWarnings(\"unused\")\npublic enum RequestType {\n GET_ATTACKS,\n GET_ATTACKS_GAMESHIELD,\n GET_GAMESHIELD_BACKENDS,\n POST_GAMESHIELD_BACKEND_CREATE,\n POST_GAMESHIELD_BACKEND_UPDATE,\n DELETE_GAMESHIELD_BACKEND_UPDATE,\n POST_GAMESHIELD_BACKEND_AVAILABLE,",
"score": 0.7881016135215759
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n APIKey = key;\n }\n public static void setGameShieldID(String id) {\n fileUtils.set(\"gameshield.serverId\", id);\n fileUtils.save();\n gameShieldID = id;\n }\n public static void setBackendID(String id) {\n fileUtils.set(\"gameshield.backendId\", id);",
"score": 0.7848287224769592
}
] |
java
|
null, Config.getGameShieldID()).getResponseBodyArray();
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
|
Config.setGeyserBackendID(args[1]);
|
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n if (geyserBackend != null) {\n if (!ip.equals(geyserBackend.getIp())) {\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"ipv4\", ip).build().toString());\n if (!updateBackend(requestBody, Config.getGeyserBackendID())) {\n core.warn(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' failed\");\n } else {\n core.info(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' success\");\n geyserBackend.setIp(ip);\n }",
"score": 0.8168699145317078
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");",
"score": 0.800643265247345
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Backend.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Backend {\n private final String id;\n private String ip;\n private final String port;\n private final boolean geyser;\n public Backend(String id, String ip, String port, boolean geyser) {\n this.id = id;\n this.ip = ip;\n this.port = port;",
"score": 0.7999208569526672
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " .local((sender instanceof ProxiedPlayer) ? ((ProxiedPlayer) sender).getLocale() : Locale.ENGLISH)\n .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n }\n @Override\n public Iterable<String> onTabComplete(CommandSender commandSender, String[] args) {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();",
"score": 0.7987018823623657
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());",
"score": 0.7950643301010132
}
] |
java
|
Config.setGeyserBackendID(args[1]);
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
|
Config.setBackendID(args[1]);
|
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " if (javaBackend != null) {\n if (!ip.equals(javaBackend.getIp())) {\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"ipv4\", ip).build().toString());\n if (!updateBackend(requestBody, Config.getBackendID())) {\n core.warn(\"Update java backendserver ID '\" + Config.getBackendID() + \"' to IP '\" + ip + \"' failed\");\n } else {\n core.info(\"Update java backendserver ID '\" + Config.getBackendID() + \"' to IP '\" + ip + \"' success\");\n javaBackend.setIp(ip);\n }\n }",
"score": 0.8245519399642944
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");",
"score": 0.8040303587913513
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n if (geyserBackend != null) {\n if (!ip.equals(geyserBackend.getIp())) {\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"ipv4\", ip).build().toString());\n if (!updateBackend(requestBody, Config.getGeyserBackendID())) {\n core.warn(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' failed\");\n } else {\n core.info(\"Update geyser backendserver ID '\" + Config.getGeyserBackendID() + \"' to IP '\" + ip + \"' success\");\n geyserBackend.setIp(ip);\n }",
"score": 0.8002968430519104
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " .local((sender instanceof ProxiedPlayer) ? ((ProxiedPlayer) sender).getLocale() : Locale.ENGLISH)\n .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n }\n @Override\n public Iterable<String> onTabComplete(CommandSender commandSender, String[] args) {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();",
"score": 0.7945126295089722
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " private void backendServerIPUpdater() {\n core.info(\"BackendServerIPUpdate scheduler started\");\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n if (!setup) return;\n Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);\n Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);\n String ip = getIpv4();\n if (ip == null) return;",
"score": 0.7907217144966125
}
] |
java
|
Config.setBackendID(args[1]);
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
|
int response = instance.getCore().getRestAPI().toggle(args[1]);
|
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");\n }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");",
"score": 0.8648152947425842
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " if (args.length == 2) {\n if (args[0].equalsIgnoreCase(\"debugtool\")) {\n for (int i = 10; i <= 100; i = i + 10) {\n list.add(String.valueOf(i));\n }\n list.add(\"cancel\");\n }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");",
"score": 0.8545642495155334
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");\n list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");",
"score": 0.8435933589935303
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");",
"score": 0.8315247297286987
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");\n }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");",
"score": 0.8231830596923828
}
] |
java
|
int response = instance.getCore().getRestAPI().toggle(args[1]);
|
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return
|
getBackends().stream().noneMatch(e -> e.compareById(backendID));
|
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
|
src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " if (backendID.isEmpty()) {\n core.severe(\"Failed to load BackendID. ID is null\");\n return;\n }\n core.info(\"API-Key loaded successful '\" + \"******************************\" + APIKey.substring(32) + \"'\");\n core.info(\"GameshieldID loaded successful '\" + gameShieldID + \"'\");\n core.info(\"BackendID loaded successful '\" + backendID + \"'\");\n }\n public static String getAPIKey() {\n return APIKey;",
"score": 0.8141140341758728
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n APIKey = key;\n }\n public static void setGameShieldID(String id) {\n fileUtils.set(\"gameshield.serverId\", id);\n fileUtils.save();\n gameShieldID = id;\n }\n public static void setBackendID(String id) {\n fileUtils.set(\"gameshield.backendId\", id);",
"score": 0.7900552749633789
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RequestType.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\n@SuppressWarnings(\"unused\")\npublic enum RequestType {\n GET_ATTACKS,\n GET_ATTACKS_GAMESHIELD,\n GET_GAMESHIELD_BACKENDS,\n POST_GAMESHIELD_BACKEND_CREATE,\n POST_GAMESHIELD_BACKEND_UPDATE,\n DELETE_GAMESHIELD_BACKEND_UPDATE,\n POST_GAMESHIELD_BACKEND_AVAILABLE,",
"score": 0.7879233956336975
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Backend.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Backend {\n private final String id;\n private String ip;\n private final String port;\n private final boolean geyser;\n public Backend(String id, String ip, String port, boolean geyser) {\n this.id = id;\n this.ip = ip;\n this.port = port;",
"score": 0.7827990055084229
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " debugMode = config.getBoolean(\"DebugMode\", false);\n geyserServerIP = config.getString(\"geyserServerIP\", \"127.0.0.1\");\n if (APIKey.length() != 64) {\n core.severe(\"Failed to load API-Key. Key is null or not valid\");\n return;\n }\n if (gameShieldID.isEmpty()) {\n core.severe(\"Failed to load GameshieldID. ID is null\");\n return;\n }",
"score": 0.7814040184020996
}
] |
java
|
getBackends().stream().noneMatch(e -> e.compareById(backendID));
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic
|
= instance.getCore().getRestAPI().getTraffic();
|
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (tcpInfo != null) {\n neoRTT = tcpInfo.rtt() / 1000;\n }\n if (tcpInfoBackend != null) {\n backendRTT = tcpInfoBackend.rtt() / 1000;\n }\n ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();\n if (!map.containsKey(player.getUsername())) {\n instance.getCore().getDebugPingResponses().put(player.getUsername(), new ArrayList<>());\n }",
"score": 0.83151775598526
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (tcpInfoBackend != null) {\n backendRTT = tcpInfoBackend.rtt() / 1000;\n }\n ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();\n if (!map.containsKey(player.getName())) {\n instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>());\n }\n map.get(player.getName()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));\n instance.getCore().debug(\"Loading completed\");\n instance.getCore().debug(\" \");",
"score": 0.8274658918380737
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bVelocityName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bVelocityVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bVelocityPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getUsername() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);",
"score": 0.8238074779510498
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n public JSONObject getTraffic() {\n return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();\n }\n public void testCredentials() {\n if (isAPIInvalid(Config.getAPIKey())) {\n core.severe(\"API is not valid! Please run /neoprotect setup to set the API Key\");\n setup = false;\n return;\n } else if (isGameshieldInvalid(Config.getGameShieldID())) {",
"score": 0.820443868637085
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bBungeecordName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bBungeecordVersion§7: \" + stats.getServerVersion()+ \" \\n\" +\n \"§bBungeecordPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);",
"score": 0.8204044699668884
}
] |
java
|
= instance.getCore().getRestAPI().getTraffic();
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
|
Config.setGameShieldID(args[1]);
|
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " core.severe(\"Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield\");\n setup = false;\n return;\n } else if (isBackendInvalid(Config.getBackendID())) {\n core.severe(\"Backend is not valid! Please run /neoprotect setbackend to set the backend\");\n setup = false;\n return;\n }\n this.setup = true;\n setProxyProtocol(Config.isProxyProtocol());",
"score": 0.8240998983383179
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " return;\n }\n if (!attackRunning[0]) {\n core.warn(\"Gameshield ID '\" + Config.getGameShieldID() + \"' is under attack\");\n core.getPlugin().sendAdminMessage(Permission.NOTIFY, \"Gameshield ID '\" + Config.getGameShieldID() + \"' is under attack\", null, null, null, null);\n attackRunning[0] = true;\n }\n }\n }, 1000 * 5, 1000 * 10);\n }",
"score": 0.8239623308181763
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");",
"score": 0.8188695907592773
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Gameshield.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Gameshield {\n private final String id;\n private final String name;\n public Gameshield(String id, String name) {\n this.id = id;\n this.name = name;\n }\n public String getId() {\n return id;",
"score": 0.8172256946563721
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.save();\n APIKey = key;\n }\n public static void setGameShieldID(String id) {\n fileUtils.set(\"gameshield.serverId\", id);\n fileUtils.save();\n gameShieldID = id;\n }\n public static void setBackendID(String id) {\n fileUtils.set(\"gameshield.backendId\", id);",
"score": 0.8025616407394409
}
] |
java
|
Config.setGameShieldID(args[1]);
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
|
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
|
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");\n }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");",
"score": 0.824667751789093
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}",
"score": 0.8233294486999512
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");\n list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");",
"score": 0.8180890083312988
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8156785368919373
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bBungeecordName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bBungeecordVersion§7: \" + stats.getServerVersion()+ \" \\n\" +\n \"§bBungeecordPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);",
"score": 0.8142400979995728
}
] |
java
|
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
|
Config.setAPIKey(msg);
|
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/ChatListener.java",
"retrieved_chunk": " new NeoProtectExecutor.ExecutorBuilder()\n .local(JavaUtils.javaVersionCheck() != 8 ? Locale.forLanguageTag(player.getLocale()) : Locale.ENGLISH)\n .neoProtectPlugin(instance)\n .sender(event.getPlayer())\n .msg(event.getMessage())\n .executeChatEvent();\n }\n}",
"score": 0.8432027697563171
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/ChatListener.java",
"retrieved_chunk": " public ChatListener(NeoProtectBungee instance) {\n this.instance = instance;\n }\n @EventHandler\n public void onChat(ChatEvent event) {\n CommandSender sender = (CommandSender) event.getSender();\n if (!sender.hasPermission(\"neoprotect.admin\") || !instance.getCore().getPlayerInSetup().contains(sender) || event.isCommand())\n return;\n event.setCancelled(true);\n new NeoProtectExecutor.ExecutorBuilder()",
"score": 0.8334559798240662
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/ChatListener.java",
"retrieved_chunk": " }\n @Subscribe\n public void onChat(PlayerChatEvent event) {\n Player player = event.getPlayer();\n if (!player.hasPermission(\"neoprotect.admin\") || !instance.getCore().getPlayerInSetup().contains(player))\n return;\n event.setResult(PlayerChatEvent.ChatResult.denied());\n new NeoProtectExecutor.ExecutorBuilder()\n .local(player.getEffectiveLocale())\n .neoProtectPlugin(instance)",
"score": 0.8316417932510376
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/ChatListener.java",
"retrieved_chunk": " .local(((ProxiedPlayer) sender).getLocale())\n .neoProtectPlugin(instance)\n .sender(event.getSender())\n .msg(event.getMessage())\n .executeChatEvent();\n }\n}",
"score": 0.8307245969772339
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/ChatListener.java",
"retrieved_chunk": " .sender(event.getPlayer())\n .msg(event.getMessage())\n .executeChatEvent();\n }\n}",
"score": 0.8304135799407959
}
] |
java
|
Config.setAPIKey(msg);
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if
|
(instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
|
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " if (args.length == 2) {\n if (args[0].equalsIgnoreCase(\"debugtool\")) {\n for (int i = 10; i <= 100; i = i + 10) {\n list.add(String.valueOf(i));\n }\n list.add(\"cancel\");\n }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");",
"score": 0.8551615476608276
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");\n }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");",
"score": 0.8401613831520081
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");\n list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");",
"score": 0.8337006568908691
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");",
"score": 0.8278065323829651
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectCommand.java",
"retrieved_chunk": "public class NeoProtectCommand implements CommandExecutor {\n private final NeoProtectSpigot instance;\n public NeoProtectCommand(NeoProtectSpigot instance) {\n this.instance = instance;\n }\n @Override\n public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {\n new NeoProtectExecutor.ExecutorBuilder()\n .viaConsole(!(sender instanceof Player))\n .local(JavaUtils.javaVersionCheck() != 8 ? ((sender instanceof Player) ? Locale.forLanguageTag(((Player) sender).getLocale()) : Locale.ENGLISH) : Locale.ENGLISH)",
"score": 0.8242765069007874
}
] |
java
|
(instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
|
instance.getCore().severe(ex.getMessage(), ex);
|
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));",
"score": 0.8326566219329834
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.82249915599823
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 0.8182536959648132
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.8177608251571655
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8158979415893555
}
] |
java
|
instance.getCore().severe(ex.getMessage(), ex);
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int
|
response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
|
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();\n for (Object object : firewalls) {\n JSONObject firewallJSON = (JSONObject) object;\n list.add(new Firewall(firewallJSON.getString(\"ip\"), firewallJSON.get(\"id\").toString()));\n }\n return list;\n }\n public int updateFirewall(String ip, String action, String mode) {\n if(action.equalsIgnoreCase(\"REMOVE\")){\n Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);",
"score": 0.8724257349967957
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " if(firewall == null){\n return 0;\n }\n return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();\n }else if(action.equalsIgnoreCase(\"ADD\")){\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new JsonBuilder().appendField(\"entry\", ip).build().toString());\n return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();\n }\n return -1;\n }",
"score": 0.8619927167892456
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");\n }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");",
"score": 0.8405600786209106
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " if (args.length == 2) {\n if (args[0].equalsIgnoreCase(\"debugtool\")) {\n for (int i = 10; i <= 100; i = i + 10) {\n list.add(String.valueOf(i));\n }\n list.add(\"cancel\");\n }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");",
"score": 0.833747148513794
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");\n list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");",
"score": 0.823376476764679
}
] |
java
|
response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
|
instance.getCore().getDirectConnectWhitelist().add(args[1]);
|
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");\n }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");",
"score": 0.8673039078712463
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " if (args.length == 2) {\n if (args[0].equalsIgnoreCase(\"debugtool\")) {\n for (int i = 10; i <= 100; i = i + 10) {\n list.add(String.valueOf(i));\n }\n list.add(\"cancel\");\n }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");",
"score": 0.8626168966293335
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");\n }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");",
"score": 0.8439195156097412
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");\n list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");",
"score": 0.8438313603401184
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");",
"score": 0.8375093340873718
}
] |
java
|
instance.getCore().getDirectConnectWhitelist().add(args[1]);
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set
|
("general.ProxyPlugins", instance.getPlugins());
|
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bVelocityName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bVelocityVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bVelocityPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getUsername() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);",
"score": 0.8189960718154907
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bBungeecordName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bBungeecordVersion§7: \" + stats.getServerVersion()+ \" \\n\" +\n \"§bBungeecordPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);",
"score": 0.8153514862060547
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java",
"retrieved_chunk": " System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getPluginVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",\n Arrays.toString(getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray()),\n getServer().getOnlinePlayers().size(),\n 0,\n Runtime.getRuntime().availableProcessors(),",
"score": 0.8131908178329468
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " public static void loadConfig(Core core, FileUtils config) {\n Config.core = core;\n fileUtils = config;\n APIKey = config.getString(\"APIKey\", \"\");\n language = config.getString(\"defaultLanguage\", Locale.ENGLISH.toLanguageTag());\n proxyProtocol = config.getBoolean(\"ProxyProtocol\", true);\n gameShieldID = config.getString(\"gameshield.serverId\", \"\");\n backendID = config.getString(\"gameshield.backendId\", \"\");\n geyserBackendID = config.getString(\"gameshield.geyserBackendId\", \"\");\n updateIP = config.getBoolean(\"gameshield.autoUpdateIP\", false);",
"score": 0.8131420612335205
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": " getProxy().getVersion().getVersion(),\n getProxy().getVersion().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),\n System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getPluginVersion(),\n getCore().getVersionResult().getVersionStatus().toString(),\n Config.getAutoUpdaterSettings().toString(),\n getCore().isSetup() ? getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\",",
"score": 0.8130843639373779
}
] |
java
|
("general.ProxyPlugins", instance.getPlugins());
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
|
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
|
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/ChatListener.java",
"retrieved_chunk": " new NeoProtectExecutor.ExecutorBuilder()\n .local(JavaUtils.javaVersionCheck() != 8 ? Locale.forLanguageTag(player.getLocale()) : Locale.ENGLISH)\n .neoProtectPlugin(instance)\n .sender(event.getPlayer())\n .msg(event.getMessage())\n .executeChatEvent();\n }\n}",
"score": 0.8453423976898193
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/ChatListener.java",
"retrieved_chunk": " .local(((ProxiedPlayer) sender).getLocale())\n .neoProtectPlugin(instance)\n .sender(event.getSender())\n .msg(event.getMessage())\n .executeChatEvent();\n }\n}",
"score": 0.8323559165000916
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/ChatListener.java",
"retrieved_chunk": " public ChatListener(NeoProtectBungee instance) {\n this.instance = instance;\n }\n @EventHandler\n public void onChat(ChatEvent event) {\n CommandSender sender = (CommandSender) event.getSender();\n if (!sender.hasPermission(\"neoprotect.admin\") || !instance.getCore().getPlayerInSetup().contains(sender) || event.isCommand())\n return;\n event.setCancelled(true);\n new NeoProtectExecutor.ExecutorBuilder()",
"score": 0.8253671526908875
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " this.localization = instance.getCore().getLocalization();\n }\n @EventHandler(priority = EventPriority.HIGHEST)\n public void onLogin(PlayerJoinEvent event) {\n Player player = event.getPlayer();\n Locale locale = JavaUtils.javaVersionCheck() != 8 ? Locale.forLanguageTag(player.getLocale()) : Locale.ENGLISH;\n if (!player.hasPermission(\"neoprotect.admin\") && !instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode()))\n return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {",
"score": 0.8207024335861206
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " this.localization = instance.getCore().getLocalization();\n }\n @Subscribe(order = PostOrder.LAST)\n public void onPostLogin(PostLoginEvent event) {\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n Player player = event.getPlayer();\n Locale locale = (player.getEffectiveLocale() != null) ? player.getEffectiveLocale() : Locale.ENGLISH;\n if (!player.hasPermission(\"neoprotect.admin\") && !instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode()))",
"score": 0.8188979625701904
}
] |
java
|
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
|
instance.getCore().setDebugRunning(false);
|
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " if (args.length == 2) {\n if (args[0].equalsIgnoreCase(\"debugtool\")) {\n for (int i = 10; i <= 100; i = i + 10) {\n list.add(String.valueOf(i));\n }\n list.add(\"cancel\");\n }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");",
"score": 0.8517006635665894
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " .local((sender instanceof ProxiedPlayer) ? ((ProxiedPlayer) sender).getLocale() : Locale.ENGLISH)\n .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n }\n @Override\n public Iterable<String> onTabComplete(CommandSender commandSender, String[] args) {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();",
"score": 0.8272226452827454
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectCommand.java",
"retrieved_chunk": "public class NeoProtectCommand implements CommandExecutor {\n private final NeoProtectSpigot instance;\n public NeoProtectCommand(NeoProtectSpigot instance) {\n this.instance = instance;\n }\n @Override\n public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {\n new NeoProtectExecutor.ExecutorBuilder()\n .viaConsole(!(sender instanceof Player))\n .local(JavaUtils.javaVersionCheck() != 8 ? ((sender instanceof Player) ? Locale.forLanguageTag(((Player) sender).getLocale()) : Locale.ENGLISH) : Locale.ENGLISH)",
"score": 0.8223364353179932
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");",
"score": 0.8208166360855103
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}",
"score": 0.8206957578659058
}
] |
java
|
instance.getCore().setDebugRunning(false);
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (
|
instance.getCore().isDebugRunning()) {
|
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.8337065577507019
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.831675112247467
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8314658999443054
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8310710191726685
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " if (args.length == 2) {\n if (args[0].equalsIgnoreCase(\"debugtool\")) {\n for (int i = 10; i <= 100; i = i + 10) {\n list.add(String.valueOf(i));\n }\n list.add(\"cancel\");\n }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");",
"score": 0.8306472301483154
}
] |
java
|
instance.getCore().isDebugRunning()) {
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
|
instance.getCore().getPlayerInSetup().add(sender);
|
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.849074125289917
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.847434937953949
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 0.8406792879104614
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n }\n if (args.length <= 1) {\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");\n list.add(\"analytics\");\n list.add(\"debugTool\");",
"score": 0.8168166279792786
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/DisconnectListener.java",
"retrieved_chunk": " @EventHandler\n public void onDisconnect(PlayerDisconnectEvent event) {\n instance.getCore().getPlayerInSetup().remove(event.getPlayer());\n }\n}",
"score": 0.8161984086036682
}
] |
java
|
instance.getCore().getPlayerInSetup().add(sender);
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale
|
, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
|
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " .local((sender instanceof ProxiedPlayer) ? ((ProxiedPlayer) sender).getLocale() : Locale.ENGLISH)\n .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n }\n @Override\n public Iterable<String> onTabComplete(CommandSender commandSender, String[] args) {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();",
"score": 0.8148840665817261
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");\n list.add(\"ipWhitelist\");\n list.add(\"ipBlacklist\");\n list.add(\"secureProfiles\");\n list.add(\"advancedAntiBot\");",
"score": 0.8079370856285095
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " Config.addAutoUpdater(getPlan().equalsIgnoreCase(\"Basic\"));\n }\n public String paste(String content) {\n try {\n return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)\n .post(RequestBody.create(MediaType.parse(\"text/plain\"), content)).build())).getResponseBodyObject().getString(\"key\");\n } catch (Exception ignore) {}\n return null;\n }\n public boolean togglePanicMode() {",
"score": 0.8024078011512756
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " if (args.length == 2) {\n if (args[0].equalsIgnoreCase(\"debugtool\")) {\n for (int i = 10; i <= 100; i = i + 10) {\n list.add(String.valueOf(i));\n }\n list.add(\"cancel\");\n }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");",
"score": 0.8017218112945557
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");\n }\n if (args[0].equalsIgnoreCase(\"toggle\")) {\n list.add(\"antiVPN\");\n list.add(\"anycast\");\n list.add(\"motdCache\");\n list.add(\"blockForge\");",
"score": 0.8013585805892944
}
] |
java
|
, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
|
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
|
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 0.8434146642684937
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8292176723480225
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8289000988006592
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}",
"score": 0.8262393474578857
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +\n \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bBungeecordName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bBungeecordVersion§7: \" + stats.getServerVersion()+ \" \\n\" +\n \"§bBungeecordPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);",
"score": 0.8261193037033081
}
] |
java
|
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
|
instance.getCore().getDebugPingResponses().clear();
|
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (tcpInfoBackend != null) {\n backendRTT = tcpInfoBackend.rtt() / 1000;\n }\n ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();\n if (!map.containsKey(player.getName())) {\n instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>());\n }\n map.get(player.getName()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));\n instance.getCore().debug(\"Loading completed\");\n instance.getCore().debug(\" \");",
"score": 0.8438757061958313
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (tcpInfo != null) {\n neoRTT = tcpInfo.rtt() / 1000;\n }\n if (tcpInfoBackend != null) {\n backendRTT = tcpInfoBackend.rtt() / 1000;\n }\n ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();\n if (!map.containsKey(player.getUsername())) {\n instance.getCore().getDebugPingResponses().put(player.getUsername(), new ArrayList<>());\n }",
"score": 0.8414859175682068
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/debugtool/DebugPingResponse.java",
"retrieved_chunk": " this.proxyToBackendLatenz = proxyToBackendLatenz;\n this.playerToProxyLatenz = playerToProxyLatenz;\n this.neoToProxyLatenz = neoToProxyLatenz;\n this.playerAddress = playerAddress;\n this.neoAddress = neoAddress;\n }\n public long getPlayerToProxyLatenz() {\n return playerToProxyLatenz;\n }\n public long getNeoToProxyLatenz() {",
"score": 0.8157035112380981
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/debugtool/DebugPingResponse.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.model.debugtool;\nimport java.net.SocketAddress;\n@SuppressWarnings(\"unused\")\npublic class DebugPingResponse {\n private final long proxyToBackendLatenz;\n private final long playerToProxyLatenz;\n private final long neoToProxyLatenz;\n private final SocketAddress playerAddress;\n private final SocketAddress neoAddress;\n public DebugPingResponse(long playerToProxyLatenz, long neoToProxyLatenz, long proxyToBackendLatenz, SocketAddress playerAddress, SocketAddress neoAddress) {",
"score": 0.811457633972168
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n instance.getCore().debug(\"Player matched to DebugKeepAlivePacket (loading data...)\");\n EpollTcpInfo tcpInfo = ((EpollSocketChannel) channel).tcpInfo();\n EpollTcpInfo tcpInfoBackend = ((EpollSocketChannel) ((UserConnection) player).getServer().getCh().getHandle()).tcpInfo();\n long ping = System.currentTimeMillis() - pingMap.get(keepAliveResponseKey);\n long neoRTT = 0;\n long backendRTT = 0;\n if (tcpInfo != null) {\n neoRTT = tcpInfo.rtt() / 1000;\n }",
"score": 0.8098641037940979
}
] |
java
|
instance.getCore().getDebugPingResponses().clear();
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
|
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
|
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));",
"score": 0.8374151587486267
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.8322598338127136
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.8306005597114563
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 0.8211649656295776
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8147923350334167
}
] |
java
|
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
|
instance.getCore().setDebugRunning(true);
|
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 0.8404664397239685
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8381212949752808
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8378592133522034
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.8271321058273315
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 0.824855387210846
}
] |
java
|
instance.getCore().setDebugRunning(true);
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
|
instance.sendMessage(sender, " - /np analytics");
|
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 0.8622114658355713
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));",
"score": 0.8487783670425415
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8454120755195618
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));\n instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +",
"score": 0.8447951078414917
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " \"§bProxyProtocol§7: \" + Config.isProxyProtocol() + \" \\n\" +\n \"§bNeoProtectPlan§7: \" + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : \"§cNOT CONNECTED\") + \" \\n\" +\n \"§bSpigotName§7: \" + stats.getServerName() + \" \\n\" +\n \"§bSpigotVersion§7: \" + stats.getServerVersion() + \" \\n\" +\n \"§bSpigotPlugins§7: \" + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray());\n instance.sendMessage(player, \"§bHello \" + player.getName() + \" ;)\", null, null, \"SHOW_TEXT\", infos);\n instance.sendMessage(player, \"§bThis server uses your NeoPlugin\", null, null, \"SHOW_TEXT\", infos);\n }\n }\n}",
"score": 0.8282785415649414
}
] |
java
|
instance.sendMessage(sender, " - /np analytics");
|
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
|
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
|
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java
|
NeoProtect-NeoPlugin-a71f673
|
[
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " return;\n }\n if (!attackRunning[0]) {\n core.warn(\"Gameshield ID '\" + Config.getGameShieldID() + \"' is under attack\");\n core.getPlugin().sendAdminMessage(Permission.NOTIFY, \"Gameshield ID '\" + Config.getGameShieldID() + \"' is under attack\", null, null, null, null);\n attackRunning[0] = true;\n }\n }\n }, 1000 * 5, 1000 * 10);\n }",
"score": 0.8535043001174927
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " public List<Gameshield> getGameshields() {\n List<Gameshield> list = new ArrayList<>();\n JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();\n for (Object object : gameshields) {\n JSONObject jsonObject = (JSONObject) object;\n list.add(new Gameshield(jsonObject.getString(\"id\"), jsonObject.getString(\"name\")));\n }\n return list;\n }\n public List<Backend> getBackends() {",
"score": 0.8031762838363647
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldSettings\");\n String mitigationSensitivity = settings.getString(\"mitigationSensitivity\");\n if (mitigationSensitivity.equals(\"UNDER_ATTACK\")) {\n rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(\"mitigationSensitivity\", \"MEDIUM\").toString()),\n Config.getGameShieldID());\n return false;\n } else {\n rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(\"mitigationSensitivity\", \"UNDER_ATTACK\").toString()),",
"score": 0.7949648499488831
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " private void statsUpdateSchedule() {\n core.info(\"StatsUpdate scheduler started\");\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n if (!setup) return;\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), new Gson().toJson(core.getPlugin().getStats()));\n if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))\n core.debug(\"Request to Update stats failed\");\n }",
"score": 0.7905207872390747
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Gameshield.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.model;\npublic class Gameshield {\n private final String id;\n private final String name;\n public Gameshield(String id, String name) {\n this.id = id;\n this.name = name;\n }\n public String getId() {\n return id;",
"score": 0.7893408536911011
}
] |
java
|
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.