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/action/BasePilotPluginAction.java",
"retrieved_chunk": " doCommand(statement, editor, project);\n }\n private void doCommand(String statement, Editor editor, Project project) {\n AppSettings settings = AppSettingsStorage.getInstance().getState();\n if(settings == null){\n NotifyUtils.notifyMessage(project,\"gpt-copilot settings is null, please check!\", NotificationType.ERROR);\n return;\n }\n List<CompletionChoice> choices = GPTClient.callChatGPT(statement, settings);\n String optimizedCode;",
"score": 0.8446062803268433
},
{
"filename": "src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java",
"retrieved_chunk": " if(GPTClient.isSuccessful(choices)){\n optimizedCode = GPTClient.toString(choices);\n } else {\n NotifyUtils.notifyMessage(project,\"gpt-copilot connection failed, please check!\", NotificationType.ERROR);\n return;\n }\n //处理readable操作\n ApplicationManager.getApplication().runWriteAction(() -> {\n CommandProcessor.getInstance().executeCommand(\n project,",
"score": 0.8091809749603271
},
{
"filename": "src/main/java/com/minivv/pilot/utils/GPTClient.java",
"retrieved_chunk": " } catch (Exception e) {\n return new ArrayList<>();\n }\n }\n public static boolean isSuccessful(List<CompletionChoice> choices) {\n return CollectionUtils.isNotEmpty(choices) && !choices.get(0).getText().isBlank();\n }\n public static String toString(List<CompletionChoice> choices) {\n if (CollectionUtils.isEmpty(choices)) {\n return \"ChatGPT response is empty,please check your network or config!\";",
"score": 0.7712360620498657
},
{
"filename": "src/main/java/com/minivv/pilot/utils/GPTClient.java",
"retrieved_chunk": " return service.createCompletion(completionRequest).getChoices();\n } else {\n OpenAiService service = new OpenAiService(settings.gptKey);\n CompletionRequest completionRequest = CompletionRequest.builder()\n .prompt(code)\n .model(settings.gptModel)\n .echo(true)\n .build();\n return service.createCompletion(completionRequest).getChoices();\n }",
"score": 0.7639279365539551
},
{
"filename": "src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java",
"retrieved_chunk": " public void update(@NotNull AnActionEvent e) {\n super.update(e);\n // 只有当编辑器中有选中的代码片段时才显示 GptCopilotAction 菜单选项\n Editor editor = e.getData(CommonDataKeys.EDITOR);\n if (editor == null) {\n e.getPresentation().setEnabled(false);\n return;\n }\n String code = editor.getSelectionModel().getSelectedText();\n e.getPresentation().setEnabled(code != null && !code.isEmpty());",
"score": 0.7232857346534729
}
] | java | notifyMessage(AppSettings.getProject(), "Test connection successfully!ChatGPT answer:" + GPTClient.toString(choices), NotificationType.INFORMATION); |
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.7848190665245056
},
{
"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.7532427310943604
},
{
"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,\"[email protected]\",\"4321\",\"Christopher\",\"Lee\",\"767676767676\",1932));\n userManager.getUsers().stream().forEach(System.out::println);\n System.out.println(\"***************************************************\");",
"score": 0.723274827003479
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " if(campaign.getGames().contains(game) ){\n game.setCost(game.getCost()-(game.getCost()*campaign.getDiscountAmount()/100));\n game.setCountOwner(game.getCountOwner()+1);\n System.out.println(\"New Cost \"+ game.getName()+\" is \"+game.getCost());\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName());\n customer.addGame(game);\n }\n }\n if(!(customer.getGames().contains(game))){\n game.setCountOwner(game.getCountOwner() + 1);",
"score": 0.7081640362739563
},
{
"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.704686164855957
}
] | java | setBirthYear(customer.getBirthYear()); |
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.9036383032798767
},
{
"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.8585610389709473
},
{
"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.8571445941925049
},
{
"filename": "src/com/xxf/i18n/plugin/action/AndroidDirAction.java",
"retrieved_chunk": " 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);\n }",
"score": 0.8540960550308228
},
{
"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.8314179182052612
}
] | java | append("\n <string name=\"" + singleStrings.getId() + "\">" + singleStrings.getValue() + "</string>"); |
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/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.795926570892334
},
{
"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.7944808006286621
},
{
"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.7766395807266235
},
{
"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.7728357911109924
},
{
"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.7497583627700806
}
] | 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/service/concretes/SellingManager.java",
"retrieved_chunk": " public SellingManager(CampaignService campaignService,UserService userService) {\n this.campaignService = campaignService;\n this.userService = userService;\n }\n public void sell(Customer customer, Game game) {\n if(customer.getGames().contains(game)){\n System.out.println(\"bu oyuna zaten sahipsin\");\n return;\n }\n for(Campaign campaign:campaignService.getCampaigns()){",
"score": 0.829674482345581
},
{
"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.779227614402771
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/UserManager.java",
"retrieved_chunk": " } else {\n customers.add(customer);\n System.out.println(\"User is added.\");\n }\n }\n public Customer getCustomer(int id ){\n for (Customer customer : customers) {\n if(customer.getId() == id){\n return customer;\n }",
"score": 0.7777976989746094
},
{
"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.7680526971817017
},
{
"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.7662304639816284
}
] | java | if(campaign1.getId()==id){ |
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/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.9098713994026184
},
{
"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.8812166452407837
},
{
"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.8686033487319946
},
{
"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.8425560593605042
},
{
"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.8391039371490479
}
] | java | "\"=\"" + string.getValue() + "\"; |
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.8392841219902039
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/UserManager.java",
"retrieved_chunk": " } else {\n customers.add(customer);\n System.out.println(\"User is added.\");\n }\n }\n public Customer getCustomer(int id ){\n for (Customer customer : customers) {\n if(customer.getId() == id){\n return customer;\n }",
"score": 0.8080282807350159
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " public SellingManager(CampaignService campaignService,UserService userService) {\n this.campaignService = campaignService;\n this.userService = userService;\n }\n public void sell(Customer customer, Game game) {\n if(customer.getGames().contains(game)){\n System.out.println(\"bu oyuna zaten sahipsin\");\n return;\n }\n for(Campaign campaign:campaignService.getCampaigns()){",
"score": 0.8076784610748291
},
{
"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.803877055644989
},
{
"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.7837963700294495
}
] | 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.7670612931251526
},
{
"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.7503852844238281
},
{
"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.7471123933792114
},
{
"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.72565758228302
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/UserManager.java",
"retrieved_chunk": " System.out.println(user2.getName() +\" is updated to \" + customer.getName());\n userToUpdate = user2;\n userToUpdate.setId(customer.getId());\n userToUpdate.setPassword(customer.getPassword());\n userToUpdate.setEmail(customer.getEmail());\n userToUpdate.setName(customer.getName());\n userToUpdate.setSurName(customer.getSurName());\n userToUpdate.setBirthYear(customer.getBirthYear());\n userToUpdate.setTc(customer.getTc());\n }",
"score": 0.6779557466506958
}
] | java | !(customer.getGames().contains(game))){ |
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/composite/Playlist.java",
"retrieved_chunk": "\t\tthis.items = new ArrayList<>();\n\t}\n\tpublic void insert(PlaylistItem item) {\n\t\tthis.items.add(item);\n\t}\n\tpublic void remove(PlaylistItem item) {\n\t\tthis.items.remove(item);\n\t}\n\tpublic List<PlaylistItem> getChildren() {\n\t\treturn this.items;",
"score": 0.823272168636322
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerMode.java",
"retrieved_chunk": "\t\t@Override\n\t\tpublic PlaylistIterator createIterator(List<PlaylistItem> items) {\n\t\t\treturn new RepeatAllIterator(items);\n\t\t}\n\t}, RandomMode {\n\t\t@Override\n\t\tpublic PlaylistIterator createIterator(List<PlaylistItem> items) {\n\t\t\treturn new RandomModeIterator(items);\n\t\t}\n\t};",
"score": 0.7090961337089539
},
{
"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.699594259262085
},
{
"filename": "br/edu/ifba/inf011/model/iterator/RandomModeIterator.java",
"retrieved_chunk": "\t\tPlaylistItem playlistItem = items.get(nextRandom());\n\t\tif (playlistItem instanceof Playlist) {\n\t\t\treturn ((Playlist) playlistItem).randomize();\n\t\t}\n\t\treturn playlistItem;\n\t}\n\tprivate int nextRandom() {\n\t\treturn random.nextInt(this.items.size());\n\t}\n}",
"score": 0.6979979276657104
},
{
"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.6908136606216431
}
] | 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/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.7879726886749268
},
{
"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.7736784815788269
},
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "\t\tthis.items = new ArrayList<>();\n\t}\n\tpublic void insert(PlaylistItem item) {\n\t\tthis.items.add(item);\n\t}\n\tpublic void remove(PlaylistItem item) {\n\t\tthis.items.remove(item);\n\t}\n\tpublic List<PlaylistItem> getChildren() {\n\t\treturn this.items;",
"score": 0.687222957611084
},
{
"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.6675339937210083
},
{
"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.660142719745636
}
] | java | while (iterator.temProximo()) { |
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\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.8171470165252686
},
{
"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.8106676340103149
},
{
"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.6923111081123352
},
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "\t\tthis.items = new ArrayList<>();\n\t}\n\tpublic void insert(PlaylistItem item) {\n\t\tthis.items.add(item);\n\t}\n\tpublic void remove(PlaylistItem item) {\n\t\tthis.items.remove(item);\n\t}\n\tpublic List<PlaylistItem> getChildren() {\n\t\treturn this.items;",
"score": 0.6486577987670898
},
{
"filename": "br/edu/ifba/inf011/model/decorator/MusicaLetraOriginal.java",
"retrieved_chunk": "\t\tthis.setLetraOriginal();\n\t}\n\tpublic void setLetraOriginal() throws IOException {\n\t\tthis.letraOriginal = resourceLoader.loadLetra(getNome());\n\t}\n\tpublic Boolean finish() {\n\t\treturn this.linha >= this.letraOriginal.size();\n\t}\n\tpublic String play() {\n\t\treturn this.component.play() + \"\\n\" + this.letraOriginal.get(this.linha++);",
"score": 0.6299791932106018
}
] | java | .println(playlist1.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.8728897571563721
},
{
"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.8218035697937012
},
{
"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.7107143402099609
},
{
"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.6351394653320312
},
{
"filename": "br/edu/ifba/inf011/model/decorator/MusicaLetraOriginal.java",
"retrieved_chunk": "\t\tthis.setLetraOriginal();\n\t}\n\tpublic void setLetraOriginal() throws IOException {\n\t\tthis.letraOriginal = resourceLoader.loadLetra(getNome());\n\t}\n\tpublic Boolean finish() {\n\t\treturn this.linha >= this.letraOriginal.size();\n\t}\n\tpublic String play() {\n\t\treturn this.component.play() + \"\\n\" + this.letraOriginal.get(this.linha++);",
"score": 0.6124515533447266
}
] | 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/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.7393797636032104
},
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "\t\tthis.items = new ArrayList<>();\n\t}\n\tpublic void insert(PlaylistItem item) {\n\t\tthis.items.add(item);\n\t}\n\tpublic void remove(PlaylistItem item) {\n\t\tthis.items.remove(item);\n\t}\n\tpublic List<PlaylistItem> getChildren() {\n\t\treturn this.items;",
"score": 0.7189262509346008
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "\t@Override\n\tpublic void removeItem(PlaylistItem item) {\n\t\tthis.items.remove(item);\n\t}\n\t@Override\n\tpublic PlaylistIterator createIterator() {\n\t\treturn this.mode.createIterator(items);\n\t}\n\tpublic void setMode(PlayerMode mode) {\n\t\tthis.mode = mode;",
"score": 0.6984636783599854
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerMode.java",
"retrieved_chunk": "\t\t@Override\n\t\tpublic PlaylistIterator createIterator(List<PlaylistItem> items) {\n\t\t\treturn new RepeatAllIterator(items);\n\t\t}\n\t}, RandomMode {\n\t\t@Override\n\t\tpublic PlaylistIterator createIterator(List<PlaylistItem> items) {\n\t\t\treturn new RandomModeIterator(items);\n\t\t}\n\t};",
"score": 0.6962978839874268
},
{
"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.6921713352203369
}
] | 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\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.7690507173538208
},
{
"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.7299487590789795
},
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "\t\tthis.items = new ArrayList<>();\n\t}\n\tpublic void insert(PlaylistItem item) {\n\t\tthis.items.add(item);\n\t}\n\tpublic void remove(PlaylistItem item) {\n\t\tthis.items.remove(item);\n\t}\n\tpublic List<PlaylistItem> getChildren() {\n\t\treturn this.items;",
"score": 0.7132542133331299
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "\t@Override\n\tpublic void removeItem(PlaylistItem item) {\n\t\tthis.items.remove(item);\n\t}\n\t@Override\n\tpublic PlaylistIterator createIterator() {\n\t\treturn this.mode.createIterator(items);\n\t}\n\tpublic void setMode(PlayerMode mode) {\n\t\tthis.mode = mode;",
"score": 0.6818991899490356
},
{
"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.6731967926025391
}
] | 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/PlayerMode.java",
"retrieved_chunk": "\t\t@Override\n\t\tpublic PlaylistIterator createIterator(List<PlaylistItem> items) {\n\t\t\treturn new RepeatAllIterator(items);\n\t\t}\n\t}, RandomMode {\n\t\t@Override\n\t\tpublic PlaylistIterator createIterator(List<PlaylistItem> items) {\n\t\t\treturn new RandomModeIterator(items);\n\t\t}\n\t};",
"score": 0.7331622838973999
},
{
"filename": "br/edu/ifba/inf011/model/iterator/RepeatAllIterator.java",
"retrieved_chunk": "\t\tthis.reset();\n\t}\n\t@Override\n\tpublic boolean temProximo() {\n\t\treturn true;\n\t}\n\t@Override\n\tpublic PlaylistItem proximo() {\n\t\tif (index >= items.size()) this.reset();\n\t\treturn items.get(index++);",
"score": 0.7245045900344849
},
{
"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.7217612266540527
},
{
"filename": "br/edu/ifba/inf011/model/iterator/RandomModeIterator.java",
"retrieved_chunk": "\t\tPlaylistItem playlistItem = items.get(nextRandom());\n\t\tif (playlistItem instanceof Playlist) {\n\t\t\treturn ((Playlist) playlistItem).randomize();\n\t\t}\n\t\treturn playlistItem;\n\t}\n\tprivate int nextRandom() {\n\t\treturn random.nextInt(this.items.size());\n\t}\n}",
"score": 0.7204585075378418
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "\t@Override\n\tpublic void removeItem(PlaylistItem item) {\n\t\tthis.items.remove(item);\n\t}\n\t@Override\n\tpublic PlaylistIterator createIterator() {\n\t\treturn this.mode.createIterator(items);\n\t}\n\tpublic void setMode(PlayerMode mode) {\n\t\tthis.mode = mode;",
"score": 0.7053786516189575
}
] | 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/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.7692249417304993
},
{
"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.7437724471092224
},
{
"filename": "br/edu/ifba/inf011/model/decorator/MusicaBase.java",
"retrieved_chunk": "\t\t\tbuilder.append(play());\n\t\t}\n\t\treturn builder.toString();\n\t}\n\t@Override\n\tpublic void reset() {\n\t\tthis.linha = 0;\n\t\tcomponent.reset();\n\t}\n}",
"score": 0.7344105243682861
},
{
"filename": "br/edu/ifba/inf011/model/decorator/MusicaNotas.java",
"retrieved_chunk": "\t\tthis.setNotas();\n\t}\n\tpublic void setNotas() throws IOException {\n\t\tthis.notas = resourceLoader.loadNotas(getNome());\n\t}\n\tpublic Boolean finish() {\n\t\treturn this.linha >= this.notas.size();\n\t}\n\tpublic String play() {\n\t\treturn component.play() + \"\\n\" + this.notas.get(this.linha++);",
"score": 0.7152103185653687
},
{
"filename": "br/edu/ifba/inf011/model/iterator/RepeatAllIterator.java",
"retrieved_chunk": "\t\tthis.reset();\n\t}\n\t@Override\n\tpublic boolean temProximo() {\n\t\treturn true;\n\t}\n\t@Override\n\tpublic PlaylistItem proximo() {\n\t\tif (index >= items.size()) this.reset();\n\t\treturn items.get(index++);",
"score": 0.7061713337898254
}
] | 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/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.7753940224647522
},
{
"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.7609566450119019
},
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "\t\tthis.items = new ArrayList<>();\n\t}\n\tpublic void insert(PlaylistItem item) {\n\t\tthis.items.add(item);\n\t}\n\tpublic void remove(PlaylistItem item) {\n\t\tthis.items.remove(item);\n\t}\n\tpublic List<PlaylistItem> getChildren() {\n\t\treturn this.items;",
"score": 0.6844216585159302
},
{
"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.6671222448348999
},
{
"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.661971390247345
}
] | 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/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.8437656760215759
},
{
"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.7797185182571411
},
{
"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.7739569544792175
},
{
"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.7690567374229431
},
{
"filename": "src/com/xxf/i18n/plugin/action/ToStringXml.java",
"retrieved_chunk": "public class ToStringXml extends AnAction {\n @Override\n public void actionPerformed(AnActionEvent e) {\n VirtualFile file = e.getData(PlatformDataKeys.VIRTUAL_FILE);\n if (file == null) {\n showHint(\"找不到目标文件\");\n return;\n }\n String extension = file.getExtension();\n if (extension != null && extension.equalsIgnoreCase(\"xml\")) {",
"score": 0.748458743095398
}
] | 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/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.8477474451065063
},
{
"filename": "Compiler/src/core/Trees.java",
"retrieved_chunk": " protected static List<Statement> typeTree(Iterator<Lexer.Token> tokens) {\n return typeTree(tokens, tokens.next());\n }\n // Constuructor of a type Tree that takes a stream of tokens, Starting from the given token (currentToken)\n protected static List<Statement> typeTree(Iterator<Lexer.Token> tokens, Lexer.Token currentToken) {\n List<Statement> statements = new LinkedList<>();\n Lexer.Token token = currentToken;\n statements.add(new Type(token.value()));\n // Checks the type of token \n token = tokens.next();",
"score": 0.8283511996269226
},
{
"filename": "Compiler/src/core/Trees.java",
"retrieved_chunk": " }\n // Constructor for equals tree from a stream of tokens\n private static List<Statement> equalsTree(Iterator<Lexer.Token> tokens) {\n return equalsTree(tokens, true);\n }\n // Constructor for equals tree from a stream of tokens, optionally starting with a new value\n private static List<Statement> equalsTree(Iterator<Lexer.Token> tokens, boolean newValue) {\n List<Statement> statements = new LinkedList<>();\n if (newValue)\n statements.add(new Setter(\"0\"));",
"score": 0.8211647272109985
},
{
"filename": "Compiler/src/core/Trees.java",
"retrieved_chunk": " //Checks for Jump statements\n if (jump) statements.add(new Jump(\"NONE\"));\n statements.add(new End());\n return statements;\n }\n // Identifier for type of token ofr the correct tree construction\n private static List<Statement> identifyToken(Iterator<Lexer.Token> tokens) {\n List<Statement> statements = new LinkedList<>();\n Lexer.Token token;\n // Iterates through tokens until there are no more",
"score": 0.812462329864502
},
{
"filename": "Compiler/src/core/Trees.java",
"retrieved_chunk": " protected static List<Statement> identifierTree(Iterator<Lexer.Token> tokens) {\n return identifierTree(tokens, tokens.next());\n }\n // Constructor for identifier tree from a stream of tokens, starting from a given token (currentToken)\n protected static List<Statement> identifierTree(Iterator<Lexer.Token> tokens, Lexer.Token currentToken) {\n List<Statement> statements = new LinkedList<>();\n Lexer.Token token = currentToken;\n statements.add(new Variable(token.value()));\n statements.add(new Load(token.value()));\n token = tokens.next();",
"score": 0.8102316856384277
}
] | 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/util/HtmlReportUtil.java",
"retrieved_chunk": " public List<Collision> parse(Document doc, String filename, Project project) {\n String regexDisciplines = \"^(\\\\p{L}+)-(\\\\p{L}+)\\\\.html$\";\n Date currDate = new Date();\n List<Collision> collisionList = new ArrayList<>();\n Pattern pattern = Pattern.compile(regexDisciplines);\n Matcher matcher = pattern.matcher(filename);\n String id1 = null;\n String id2 = null;\n String discipline1 = null;\n String discipline2 = null;",
"score": 0.7783360481262207
},
{
"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.7708740234375
},
{
"filename": "src/main/java/ru/jbimer/core/dao/CollisionDAO.java",
"retrieved_chunk": " @Autowired\n public CollisionDAO(EntityManager entityManager) {\n this.entityManager = entityManager;\n }\n public void saveAll(List<Collision> collisions) {\n entityManager.getTransaction().begin();\n System.out.println(\"here1\");\n for (Collision collision :\n collisions) {\n System.out.println(\"here2\");",
"score": 0.7530086040496826
},
{
"filename": "src/main/java/ru/jbimer/core/models/HtmlReportData.java",
"retrieved_chunk": " private Project project;\n public String getDateForProjectShowPage() {\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");\n return dateFormat.format(this.uploadedAt);\n }\n}",
"score": 0.7432026863098145
},
{
"filename": "src/main/java/ru/jbimer/core/models/Project.java",
"retrieved_chunk": " private List<Engineer> engineersOnProject;\n public int getDoneCollisionsRatio() {\n if (collisionsOnProject != null && collisionsOnProject.size() > 0) {\n int doneCollisions = (int) collisionsOnProject.stream()\n .filter(collision -> collision.getStatus().equals(\"Done\"))\n .count();\n return (doneCollisions * 100) / collisionsOnProject.size();\n }\n return 0;\n }",
"score": 0.7418428659439087
}
] | 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/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.8608547449111938
},
{
"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.8536569476127625
},
{
"filename": "src/main/java/ru/jbimer/core/services/ProjectService.java",
"retrieved_chunk": " return projectRepository.findAll();\n }\n public Project findOne(int id) {\n Optional<Project> foundProject = projectRepository.findById(id);\n return foundProject.orElse(null);\n }\n @Transactional\n public void save(Project project) {\n projectRepository.save(project);\n }",
"score": 0.846326470375061
},
{
"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.8348243236541748
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " @RequestParam(defaultValue = \"1\") Integer page,\n @RequestParam(defaultValue = \"10\") Integer size) {\n try {\n List<Collision> collisions;\n Pageable paging = PageRequest.of(page - 1, size, Sort.by(\"id\"));\n Page<Collision> collisionPage;\n if (keyword == null) {\n collisionPage = collisionsService.findAllWithPagination(project_id, paging);\n } else {\n collisionPage = collisionsService.searchByDiscipline(keyword, project_id, paging);",
"score": 0.8220683336257935
}
] | 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.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/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.8667095303535461
},
{
"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.8497774600982666
},
{
"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.8287758231163025
},
{
"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.8089486956596375
},
{
"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.8077677488327026
}
] | java | "engineers", engineersService.findAll()); |
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.9046981930732727
},
{
"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.8915190696716309
},
{
"filename": "src/main/java/ru/jbimer/core/services/EngineersService.java",
"retrieved_chunk": " return engineer.get().getCollisions();\n }\n else {\n return Collections.emptyList();\n }\n }\n @Transactional\n public void save(Engineer engineer) {\n engineersRepository.save(engineer);\n }",
"score": 0.8126959800720215
},
{
"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.8061705827713013
},
{
"filename": "src/main/java/ru/jbimer/core/services/EngineersService.java",
"retrieved_chunk": " this.engineersRepository = engineersRepository;\n this.engineerDAO = engineerDAO;\n this.passwordEncoder = passwordEncoder;\n }\n public Optional<Engineer> findByUsername(String username) {\n return engineersRepository.findByUsername(username);\n }\n public List<Engineer> findAll() {\n return engineersRepository.findAll();\n }",
"score": 0.7860382199287415
}
] | java | Optional<Collision> optionalCollision = collisionsRepository.findByIdFetchEngineer(id); |
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.860278844833374
},
{
"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.8319048881530762
},
{
"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.8279452323913574
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " return \"engineers/edit\";\n }\n @PatchMapping(\"/{id}\")\n public String update(@ModelAttribute(\"engineer\") @Valid Engineer updatedEngineer,\n BindingResult bindingResult,\n @PathVariable(\"id\") int id) {\n if (bindingResult.hasErrors()) return \"engineers/edit\";\n Engineer originalEngineer = engineersService.findOne(id);\n engineersService.update(id, updatedEngineer, originalEngineer);\n return \"redirect:/engineers\";",
"score": 0.824671745300293
},
{
"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.8222741484642029
}
] | java | .findByIdFetchCollisions(engineerDetails.getEngineer().getId()); |
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/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.8710013628005981
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " @ModelAttribute(\"project\") Project project) {\n model.addAttribute(\"engineers\", engineersService.findAll());\n return \"projects/new\";\n }\n @PostMapping\n public String create(@ModelAttribute(\"project\") @Valid Project project,\n BindingResult bindingResult, Model model) {\n model.addAttribute(\"engineers\", engineersService.findAll());\n if (bindingResult.hasErrors()) return \"projects/new\";\n projectService.save(project);",
"score": 0.8668579459190369
},
{
"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.8102664351463318
},
{
"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.8084291219711304
},
{
"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.8073988556861877
}
] | 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.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/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.8878400921821594
},
{
"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.8760300278663635
},
{
"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.8441847562789917
},
{
"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.843889594078064
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " @ModelAttribute(\"project\") Project project) {\n model.addAttribute(\"engineers\", engineersService.findAll());\n return \"projects/new\";\n }\n @PostMapping\n public String create(@ModelAttribute(\"project\") @Valid Project project,\n BindingResult bindingResult, Model model) {\n model.addAttribute(\"engineers\", engineersService.findAll());\n if (bindingResult.hasErrors()) return \"projects/new\";\n projectService.save(project);",
"score": 0.8404558300971985
}
] | 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/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.9088934659957886
},
{
"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.8794389963150024
},
{
"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.8756780624389648
},
{
"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.8673930168151855
},
{
"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.8409873247146606
}
] | 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/services/ProjectService.java",
"retrieved_chunk": " @Transactional\n public void update(int id, Project updatedProject) {\n updatedProject.setId(id);\n projectRepository.save(updatedProject);\n }\n @Transactional\n public void delete(int id) {\n projectRepository.deleteById(id);\n }\n}",
"score": 0.8436527252197266
},
{
"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.8425432443618774
},
{
"filename": "src/main/java/ru/jbimer/core/services/EngineersService.java",
"retrieved_chunk": " return engineer.get().getCollisions();\n }\n else {\n return Collections.emptyList();\n }\n }\n @Transactional\n public void save(Engineer engineer) {\n engineersRepository.save(engineer);\n }",
"score": 0.8158643245697021
},
{
"filename": "src/main/java/ru/jbimer/core/services/ProjectService.java",
"retrieved_chunk": " return projectRepository.findAll();\n }\n public Project findOne(int id) {\n Optional<Project> foundProject = projectRepository.findById(id);\n return foundProject.orElse(null);\n }\n @Transactional\n public void save(Project project) {\n projectRepository.save(project);\n }",
"score": 0.814760684967041
},
{
"filename": "src/main/java/ru/jbimer/core/dao/CollisionDAO.java",
"retrieved_chunk": " @Autowired\n public CollisionDAO(EntityManager entityManager) {\n this.entityManager = entityManager;\n }\n public void saveAll(List<Collision> collisions) {\n entityManager.getTransaction().begin();\n System.out.println(\"here1\");\n for (Collision collision :\n collisions) {\n System.out.println(\"here2\");",
"score": 0.8049865961074829
}
] | 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": " }\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.8425580263137817
},
{
"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.8249149322509766
},
{
"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.8116366863250732
},
{
"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.7967106699943542
},
{
"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.7963398098945618
}
] | 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/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.8119305372238159
},
{
"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.803277313709259
},
{
"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.7933700084686279
},
{
"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.7908452749252319
},
{
"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.7841951251029968
}
] | 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/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.8197658061981201
},
{
"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.8124569058418274
},
{
"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.8041706085205078
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ProjectController.java",
"retrieved_chunk": " @ModelAttribute(\"project\") Project project) {\n model.addAttribute(\"engineers\", engineersService.findAll());\n return \"projects/new\";\n }\n @PostMapping\n public String create(@ModelAttribute(\"project\") @Valid Project project,\n BindingResult bindingResult, Model model) {\n model.addAttribute(\"engineers\", engineersService.findAll());\n if (bindingResult.hasErrors()) return \"projects/new\";\n projectService.save(project);",
"score": 0.7896235585212708
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/EngineersController.java",
"retrieved_chunk": " return \"engineers/edit\";\n }\n @PatchMapping(\"/{id}\")\n public String update(@ModelAttribute(\"engineer\") @Valid Engineer updatedEngineer,\n BindingResult bindingResult,\n @PathVariable(\"id\") int id) {\n if (bindingResult.hasErrors()) return \"engineers/edit\";\n Engineer originalEngineer = engineersService.findOne(id);\n engineersService.update(id, updatedEngineer, originalEngineer);\n return \"redirect:/engineers\";",
"score": 0.7869394421577454
}
] | 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/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.8070063591003418
},
{
"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.8058261871337891
},
{
"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.7828986644744873
},
{
"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.7815672159194946
},
{
"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.7783358097076416
}
] | java | (id, engineerDetails.getEngineer(), comment); |
/*
* 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/Platform.java",
"retrieved_chunk": " }\n public static MemorySegment allocate(MemoryLayout layout, long count, SegmentScope scope){\n return MemorySegment.allocateNative(layout.byteSize() * count, scope);\n }\n public static long offsetOf(MemoryLayout structLayout, String field){\n return structLayout.byteOffset(MemoryLayout.PathElement.groupElement(field));\n }\n public static OperatingSystemFamily detectOS(){\n var os = System.getProperty(\"os.name\").toLowerCase();\n if(os.contains(\"win\")){",
"score": 0.8177056312561035
},
{
"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.805211067199707
},
{
"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.791523814201355
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " if(type.equals(void.class)){\n return 0;\n }\n return layoutFor(type).byteSize();\n }\n public MemorySegment allocate(Class<?> type, SegmentScope scope){\n return Platform.allocate(getLayout(type), scope);\n }\n public <T> Array<T> arrayOf(MemorySegment array, Class<T> type, long length, SegmentScope scope){\n return arrayOf(array, type, false, length, scope);",
"score": 0.7785662412643433
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " public MemoryLayout getLayout(FieldDef field){\n var layout = getLayout(field.isPointer() ? MemorySegment.class : field.type());\n return field.isArray() ? getArrayLayout(layout, field.array()) : layout;\n }\n public MemoryLayout getLayout(Class<?> targetType){\n var layout = layouts.get(targetType);\n if(layout == null){\n var structAnnotation = getStructAnnotation(targetType);\n var structDef = structs.get(structAnnotation.name());\n if(structDef == null){",
"score": 0.7737423181533813
}
] | java | mapper.getLayout(target.getClass()).byteOffset(MemoryLayout.PathElement.groupElement(model.name())); |
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": " 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.8858075737953186
},
{
"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.8657374978065491
},
{
"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.8203462362289429
},
{
"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.8103643655776978
},
{
"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.8097974061965942
}
] | 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/NativeMapper.java",
"retrieved_chunk": " public MemoryLayout getLayout(FieldDef field){\n var layout = getLayout(field.isPointer() ? MemorySegment.class : field.type());\n return field.isArray() ? getArrayLayout(layout, field.array()) : layout;\n }\n public MemoryLayout getLayout(Class<?> targetType){\n var layout = layouts.get(targetType);\n if(layout == null){\n var structAnnotation = getStructAnnotation(targetType);\n var structDef = structs.get(structAnnotation.name());\n if(structDef == null){",
"score": 0.8078212738037109
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " return structs.containsKey(name);\n }\n public StructDef getOrDefineStruct(Class<?> type){\n var struct = getStructAnnotation(type);\n return structs.computeIfAbsent(struct.name(), (t) -> {\n var builder = StructDef.create(struct.name(), struct.packed());\n for (int i = 0; i < struct.fields().length; i++) {\n var field = struct.fields()[i];\n builder.with(new FieldDef(i, field.name(), field.type(), field.pointer(), field.array()));\n }",
"score": 0.7855814695358276
},
{
"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.784640908241272
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " return null; // Struct has no elements yet, so we don't need padding\n }\n var remainder = structSize % element.bitAlignment();\n return remainder != 0 ? MemoryLayout.paddingLayout(element.bitAlignment() - remainder) : null;\n }\n public <T> NativeMapper register(Class<T> targetType){\n return register(targetType, false);\n }\n public <T> NativeMapper register(Class<T> targetType, boolean registerSupers){\n StructDef structDef = null;",
"score": 0.7660371661186218
},
{
"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.7636560201644897
}
] | java | var structDef = mapper.getOrDefineStruct(fieldType); |
/*
* 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/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.8106269240379333
},
{
"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.7896018028259277
},
{
"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.7878631353378296
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/FunctionHandler.java",
"retrieved_chunk": " @Override\n public void fill(NativeMapper mapper, T target) throws IllegalAccessException {\n if(Util.skipField(field, target)){\n return;\n }\n if(handle == null){\n handle = mapper.getOrDefineFunction(name, descriptor);\n }\n field.set(target, handle);\n }",
"score": 0.7787210941314697
},
{
"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.7777820825576782
}
] | java | handle = getHandle(mapper.getLayout(target.getClass())); |
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.8376089930534363
},
{
"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.8300173282623291
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " this.localization = instance.getCore().getLocalization();\n }\n @EventHandler(priority = 6)\n public void onLogin(PostLoginEvent event) {\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n ProxiedPlayer player = event.getPlayer();\n Locale locale = (player.getLocale() != null) ? player.getLocale() : Locale.ENGLISH;\n if (!player.hasPermission(\"neoprotect.admin\") && !instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfig().isOnlineMode()))",
"score": 0.8264498710632324
},
{
"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.8256878852844238
},
{
"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.8188523054122925
}
] | 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.9553133249282837
},
{
"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.9412158727645874
},
{
"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.8409054279327393
},
{
"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.8331196904182434
},
{
"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.7831746935844421
}
] | 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": " private final NeoProtectSpigot instance;\n public ChatListener(NeoProtectSpigot instance) {\n this.instance = instance;\n }\n @EventHandler\n public void onChat(AsyncPlayerChatEvent event) {\n Player player = event.getPlayer();\n if (!player.hasPermission(\"neoprotect.admin\") || !instance.getCore().getPlayerInSetup().contains(player))\n return;\n event.setCancelled(true);",
"score": 0.8235824108123779
},
{
"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.8116172552108765
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/messageunsign/SessionChatListener.java",
"retrieved_chunk": " if (!checkConnection(player)) return;\n event.setResult(ResultedEvent.GenericResult.denied());\n player.getChatQueue().queuePacket(\n plugin.getProxy().getEventManager().fire(new PlayerChatEvent(player, chatMessage))\n .thenApply(PlayerChatEvent::getResult)\n .thenApply(result -> {\n if (!result.isAllowed()) {\n return null;\n }\n final boolean isModified = result",
"score": 0.8057225942611694
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java",
"retrieved_chunk": " ((ProxiedPlayer) receiver).unsafe().sendPacket(new KeepAlive(id));\n getCore().getPingMap().put(new KeepAliveResponseKey(((ProxiedPlayer) receiver).getSocketAddress(), id), System.currentTimeMillis());\n }\n }\n @Override\n public long sendKeepAliveMessage(long id) {\n for (ProxiedPlayer player : this.getProxy().getPlayers()) {\n sendKeepAliveMessage(player, id);\n }\n return id;",
"score": 0.8047287464141846
},
{
"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.8019940853118896
}
] | java | .getEventManager(), neoProtectVelocity.getLogger())); |
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.9506310224533081
},
{
"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.939774215221405
},
{
"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.842461109161377
},
{
"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.8353532552719116
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": " Arrays.toString(getPlugins().stream().filter(p -> !p.startsWith(\"cmd_\") && !p.equals(\"reconnect_yaml\")).toArray()),\n getProxy().getPlayerCount(),\n getProxy().getAllServers().size(),\n Runtime.getRuntime().availableProcessors(),\n getProxy().getConfiguration().isOnlineMode(),\n Config.isProxyProtocol()\n );\n }\n public ProxyServer getProxy() {\n return proxy;",
"score": 0.7959996461868286
}
] | 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": " }\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.7788940668106079
},
{
"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.7523208856582642
},
{
"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.7402621507644653
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " if(!backend.isGeyser())continue;\n instance.sendMessage(sender, \"§5\" + backend.getIp() + \":\" + backend.getPort() + localization.get(locale, \"utils.click\"),\n \"RUN_COMMAND\", \"/np setgeyserbackend \" + backend.getId(),\n \"SHOW_TEXT\", localization.get(locale, \"hover.backend\", backend.getIp(), backend.getPort(), backend.getId()));\n }\n }\n private void setBedrockBackend(String[] args) {\n if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {\n instance.sendMessage(sender, localization.get(locale, \"invalid.backend\", \"geyser\", args[1]));\n return;",
"score": 0.7357789278030396
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " FileUtils languageRU = new FileUtils(Core.class.getResourceAsStream(\"/language_ru.properties\"), \"plugins/NeoProtect/languages\", \"language_ru.properties\", true);\n FileUtils languageUA = new FileUtils(Core.class.getResourceAsStream(\"/language_ua.properties\"), \"plugins/NeoProtect/languages\", \"language_ua.properties\", true);\n Config.loadConfig(this, config);\n this.localization = new Localization(\"language\", Locale.forLanguageTag(Config.getLanguage()), new File(\"plugins/NeoProtect/languages/\"));\n restAPIRequests = new RestAPIRequests(this);\n }\n public void debug(String output) {\n if (Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output);\n }\n public void info(String output) {",
"score": 0.7346864342689514
}
] | java | core.severe("Failed to load API-Key. Key is null or not valid"); |
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": " 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.723448634147644
},
{
"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.7103756666183472
},
{
"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.6979761719703674
},
{
"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.6966054439544678
},
{
"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.6886664032936096
}
] | java | core.severe(exception.getMessage(), exception); |
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.8134950995445251
},
{
"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.8102708458900452
},
{
"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.8040657639503479
},
{
"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.7496364116668701
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .addHeader(\"Content-Type\", \"application/json\");\n }\n protected String getSubDirectory(RequestType type, Object... values) {\n switch (type) {\n case GET_ATTACKS: {\n return new Formatter().format(\"/attacks\", values).toString();\n }\n case GET_ATTACKS_GAMESHIELD: {\n return new Formatter().format(\"/attacks/gameshield/%s\", values).toString();",
"score": 0.7466062903404236
}
] | java | core.info("BackendID loaded successful '" + backendID + "'"); |
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.8173109292984009
},
{
"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.8161944150924683
},
{
"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.8130922317504883
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " inetAddress.set(new InetSocketAddress(message.sourceAddress(), message.sourcePort()));\n channelWrapperAccessor.get(channel.pipeline().get(HandlerBoss.class)).setRemoteAddress(inetAddress.get());\n } else {\n super.channelRead(ctx, msg);\n }\n }\n });\n }\n public void addKeepAlivePacketHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress, NeoProtectPlugin instance) {\n channel.pipeline().addAfter(PipelineUtils.PACKET_DECODER, \"neo-keep-alive-handler\", new ChannelInboundHandlerAdapter() {",
"score": 0.7757539749145508
},
{
"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.7757142782211304
}
] | 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.8257167339324951
},
{
"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.8111239075660706
},
{
"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.7874867916107178
},
{
"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.7477425336837769
},
{
"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.7320479154586792
}
] | 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": " }\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.8249871730804443
},
{
"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.8210046291351318
},
{
"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.8135056495666504
},
{
"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.7480031251907349
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .addHeader(\"Content-Type\", \"application/json\");\n }\n protected String getSubDirectory(RequestType type, Object... values) {\n switch (type) {\n case GET_ATTACKS: {\n return new Formatter().format(\"/attacks\", values).toString();\n }\n case GET_ATTACKS_GAMESHIELD: {\n return new Formatter().format(\"/attacks/gameshield/%s\", values).toString();",
"score": 0.7456907033920288
}
] | java | core.info("GameshieldID loaded successful '" + gameShieldID + "'"); |
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": " }\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.8223416805267334
},
{
"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.8065497875213623
},
{
"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.786791205406189
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, false).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 0 : code;\n } else {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, true).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 1 : code;\n }\n }",
"score": 0.7461079359054565
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " Config.getGameShieldID());\n return true;\n }\n }\n public int toggle(String mode) {\n JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldSettings\");\n if(!settings.has(mode)) return -1;\n boolean mitigationSensitivity = settings.getBoolean(mode);\n if (mitigationSensitivity) {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,",
"score": 0.737930417060852
}
] | java | core.severe("Failed to load GameshieldID. ID is null"); |
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": " }\n }\n private String getIpv4() {\n try {\n return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString(\"ip\");\n }catch (Exception ignore){}\n return null;\n }\n private JSONArray getNeoIPs() {\n return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();",
"score": 0.8104000091552734
},
{
"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.806638240814209
},
{
"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.7543007135391235
},
{
"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.7451220750808716
},
{
"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.7401808500289917
}
] | 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/spigot/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " instance.getCore().debug(\"Connecting finished\");\n } catch (Exception ex) {\n instance.getCore().severe(\"Cannot inject incoming channel \" + channel, ex);\n }\n }\n };\n // This is executed before Minecraft's channel handler\n beginInitProtocol = new ChannelInitializer<Channel>() {\n @Override\n protected void initChannel(Channel channel) {",
"score": 0.8533794283866882
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/ResponseManager.java",
"retrieved_chunk": " return body.string();\n } catch (NullPointerException | SocketTimeoutException ignored) {\n return \"{}\";\n } catch (IOException ex) {\n ex.printStackTrace();\n return null;\n }\n }\n public boolean checkCode(int code) {\n return Objects.equals(this.code, code);",
"score": 0.8272768259048462
},
{
"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.8153649568557739
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/Reflection.java",
"retrieved_chunk": " @Override\n public Object invoke(Object... arguments) {\n try {\n return constructor.newInstance(arguments);\n } catch (Exception e) {\n throw new RuntimeException(\"Cannot invoke constructor \" + constructor, e);\n }\n }\n };\n }",
"score": 0.814569354057312
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/Reflection.java",
"retrieved_chunk": " @Override\n public Object invoke(Object... arguments) {\n try {\n return constructor.newInstance(arguments);\n } catch (Exception e) {\n throw new RuntimeException(\"Cannot invoke constructor \" + constructor, e);\n }\n }\n };\n }",
"score": 0.814505398273468
}
] | 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.8313747644424438
},
{
"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.8184760212898254
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n }\n });\n }\n public void addKeepAlivePacketHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress, VelocityServer velocityServer, NeoProtectPlugin instance) {\n channel.pipeline().addAfter(\"minecraft-decoder\", \"neo-keep-alive-handler\", new ChannelInboundHandlerAdapter() {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n super.channelRead(ctx, msg);\n if (!(msg instanceof KeepAlive)) {",
"score": 0.7981722354888916
},
{
"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.7980418801307678
},
{
"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.7974457144737244
}
] | 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/velocity/proxyprotocol/Reflection.java",
"retrieved_chunk": "public final class Reflection {\n /**\n * An interface for invoking a specific constructor.\n */\n public interface ConstructorInvoker {\n /**\n * Invoke a constructor for a specific class.\n *\n * @param arguments - the arguments to pass to the constructor.\n * @return The constructed object.",
"score": 0.837282121181488
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/Reflection.java",
"retrieved_chunk": "public final class Reflection {\n /**\n * An interface for invoking a specific constructor.\n */\n public interface ConstructorInvoker {\n /**\n * Invoke a constructor for a specific class.\n *\n * @param arguments - the arguments to pass to the constructor.\n * @return The constructed object.",
"score": 0.8372048139572144
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/Reflection.java",
"retrieved_chunk": " */\n Object invoke(Object... arguments);\n }\n /**\n * An interface for invoking a specific method.\n */\n public interface MethodInvoker {\n /**\n * Invoke a method on a specific target object.\n *",
"score": 0.8362247943878174
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/Reflection.java",
"retrieved_chunk": " */\n Object invoke(Object... arguments);\n }\n /**\n * An interface for invoking a specific method.\n */\n public interface MethodInvoker {\n /**\n * Invoke a method on a specific target object.\n *",
"score": 0.8361943960189819
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/Reflection.java",
"retrieved_chunk": " *\n * @param arguments - the arguments to pass to the constructor.\n * @return The constructed object.\n */\n Object invoke(Object... arguments);\n }\n /**\n * An interface for invoking a specific method.\n */\n public interface MethodInvoker {",
"score": 0.8355025053024292
}
] | 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/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n private void attackCheckSchedule() {\n core.info(\"AttackCheck scheduler started\");\n final Boolean[] attackRunning = {false};\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n if (!setup) return;\n if (!isAttack()) {\n attackRunning[0] = false;",
"score": 0.8249354362487793
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }, 0, 1000 * 60);\n }\n private void versionCheckSchedule() {\n core.info(\"VersionCheck scheduler started\");\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n core.setVersionResult(VersionUtils.checkVersion(\"NeoProtect\", \"NeoPlugin\", \"v\" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));\n }\n }, 1000 * 10, 1000 * 60 * 5);",
"score": 0.8028849363327026
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " public void run() {\n counter++;\n instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));\n instance.sendMessage(sender, localization.get(locale, \"debug.sendingPackets\") + \" (\" + counter + \"/\" + amount + \")\");\n if (counter >= amount) this.cancel();\n }\n }, 500, 2000);\n debugTimer.schedule(new TimerTask() {\n @Override\n public void run() {",
"score": 0.7848395705223083
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }, 1000, 1000 * 5);\n }\n private void neoServerIPsUpdateSchedule() {\n core.info(\"NeoServerIPsUpdate scheduler started\");\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n JSONArray IPs = getNeoIPs();\n neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;\n }",
"score": 0.782832682132721
},
{
"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.782699465751648
}
] | 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/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.8180621862411499
},
{
"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.8145595192909241
},
{
"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.8099357485771179
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": " @Inject\n public NeoProtectVelocity(ProxyServer proxy, Logger logger, Metrics.Factory metricsFactory) {\n this.proxy = proxy;\n this.logger = logger;\n this.metricsFactory = metricsFactory;\n }\n @Subscribe\n public void onProxyInitialize(ProxyInitializeEvent event) {\n Metrics metrics = metricsFactory.make(this, 18727);\n metrics.addCustomChart(new SimplePie(\"language\", Config::getLanguage));",
"score": 0.8060084581375122
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }, 0, 1000 * 60);\n }\n private void versionCheckSchedule() {\n core.info(\"VersionCheck scheduler started\");\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n core.setVersionResult(VersionUtils.checkVersion(\"NeoProtect\", \"NeoPlugin\", \"v\" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));\n }\n }, 1000 * 10, 1000 * 60 * 5);",
"score": 0.8030457496643066
}
] | 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.8320698738098145
},
{
"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.8291260004043579
},
{
"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.8004604578018188
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java",
"retrieved_chunk": " getProxy().getOnlineCount(),\n getProxy().getServers().size(),\n Runtime.getRuntime().availableProcessors(),\n getProxy().getConfig().isOnlineMode(),\n Config.isProxyProtocol()\n );\n }\n @Override\n public void sendMessage(Object receiver, String text) {\n sendMessage(receiver, text, null, null, null, null);",
"score": 0.7697526216506958
},
{
"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.766336977481842
}
] | java | Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection); |
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/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.884292483329773
},
{
"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.8836261034011841
},
{
"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.8702118396759033
},
{
"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.8694495558738708
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n Config.setGeyserBackendID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.backend\",\"geyser\", args[1]));\n if (instance.getCore().getPlayerInSetup().remove(sender)) {\n instance.sendMessage(sender, localization.get(locale, \"setup.finished\"));\n }\n }\n private void showHelp() {\n instance.sendMessage(sender, localization.get(locale, \"available.commands\"));\n instance.sendMessage(sender, \" - /np setup\");",
"score": 0.7827454805374146
}
] | java | if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) { |
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.8315078020095825
},
{
"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.8260184526443481
},
{
"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.8231768608093262
},
{
"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.8018746376037598
},
{
"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.7942121624946594
}
] | java | this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!"); |
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": " 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.6937311291694641
},
{
"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.6574028730392456
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " final String pasteKey = instance.getCore().getRestAPI().paste(content);\n instance.getCore().getDebugPingResponses().clear();\n instance.sendMessage(sender, localization.get(locale, \"debug.finished.first\") + \" (took \" + (System.currentTimeMillis() - startTime) + \"ms)\");\n if(pasteKey != null) {\n final String url = \"https://paste.neoprotect.net/\" + pasteKey + \".yml\";\n instance.sendMessage(sender, localization.get(locale, \"debug.finished.url\") + url + localization.get(locale, \"utils.open\"), \"OPEN_URL\", url, null, null);\n } else {\n instance.sendMessage(sender, localization.get(locale, \"debug.finished.file\") + file.getAbsolutePath() + localization.get(locale, \"utils.copy\"), \"COPY_TO_CLIPBOARD\", file.getAbsolutePath(), null, null);\n }\n instance.getCore().setDebugRunning(false);",
"score": 0.6547106504440308
},
{
"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.6545283794403076
},
{
"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.6495237350463867
}
] | 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.9233849048614502
},
{
"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.8778140544891357
},
{
"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.8728916645050049
},
{
"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.7978548407554626
},
{
"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.7772692441940308
}
] | java | instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) { |
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.923186719417572
},
{
"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.8805341124534607
},
{
"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.8715053796768188
},
{
"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.8015153408050537
},
{
"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.7801399230957031
}
] | 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/request/RestAPIRequests.java",
"retrieved_chunk": " }, 0, 1000 * 60);\n }\n private void versionCheckSchedule() {\n core.info(\"VersionCheck scheduler started\");\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n core.setVersionResult(VersionUtils.checkVersion(\"NeoProtect\", \"NeoPlugin\", \"v\" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));\n }\n }, 1000 * 10, 1000 * 60 * 5);",
"score": 0.7898611426353455
},
{
"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.788771390914917
},
{
"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.7859365940093994
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " return debugMode;\n }\n public static String getGeyserServerIP() {\n return geyserServerIP;\n }\n public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {\n return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);\n }\n public static void setAPIKey(String key) {\n fileUtils.set(\"APIKey\", key);",
"score": 0.7744373679161072
},
{
"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.7696742415428162
}
] | 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/model/Stats.java",
"retrieved_chunk": " return managedServers;\n }\n public int getCoreCount() {\n return coreCount;\n }\n public boolean isOnlineMode() {\n return onlineMode;\n }\n public boolean isProxyProtocol() {\n return proxyProtocol;",
"score": 0.8854771852493286
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " public static String getGeyserBackendID() {\n return geyserBackendID;\n }\n public static boolean isProxyProtocol() {\n return proxyProtocol;\n }\n public static boolean isUpdateIP() {\n return updateIP;\n }\n public static boolean isDebugMode() {",
"score": 0.8709297180175781
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n public Object getSender() {\n return sender;\n }\n public String[] getArgs() {\n return args;\n }\n public Locale getLocal() {\n return local;\n }",
"score": 0.859735369682312
},
{
"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.8582979440689087
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Stats.java",
"retrieved_chunk": " public String getServerType() {\n return serverType;\n }\n public String getServerVersion() {\n return serverVersion;\n }\n public String getServerName() {\n return serverName;\n }\n public String getJavaVersion() {",
"score": 0.8469981551170349
}
] | 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": " 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.7309788465499878
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " final String pasteKey = instance.getCore().getRestAPI().paste(content);\n instance.getCore().getDebugPingResponses().clear();\n instance.sendMessage(sender, localization.get(locale, \"debug.finished.first\") + \" (took \" + (System.currentTimeMillis() - startTime) + \"ms)\");\n if(pasteKey != null) {\n final String url = \"https://paste.neoprotect.net/\" + pasteKey + \".yml\";\n instance.sendMessage(sender, localization.get(locale, \"debug.finished.url\") + url + localization.get(locale, \"utils.open\"), \"OPEN_URL\", url, null, null);\n } else {\n instance.sendMessage(sender, localization.get(locale, \"debug.finished.file\") + file.getAbsolutePath() + localization.get(locale, \"utils.copy\"), \"COPY_TO_CLIPBOARD\", file.getAbsolutePath(), null, null);\n }\n instance.getCore().setDebugRunning(false);",
"score": 0.7018170356750488
},
{
"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.699254035949707
},
{
"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.6971180438995361
},
{
"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.6949865818023682
}
] | java | (Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output); |
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": " .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .addHeader(\"Content-Type\", \"application/json\");\n }\n protected String getSubDirectory(RequestType type, Object... values) {\n switch (type) {\n case GET_ATTACKS: {\n return new Formatter().format(\"/attacks\", values).toString();\n }\n case GET_ATTACKS_GAMESHIELD: {\n return new Formatter().format(\"/attacks/gameshield/%s\", values).toString();",
"score": 0.7561925649642944
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " return new Formatter().format(\"/gameshields/%s/isUnderAttack\", values).toString();\n }\n case GET_GAMESHIELD_BANDWIDTH: {\n return new Formatter().format(\"/gameshields/%s/bandwidth\", values).toString();\n }\n case GET_GAMESHIELD_ANALYTICS: {\n return new Formatter().format(\"/gameshields/%s/analytics/%s\", values).toString();\n }\n case GET_FIREWALLS: {\n return new Formatter().format(\"/firewall/gameshield/%s/%s\", values).toString();",
"score": 0.7533437013626099
},
{
"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.7505317330360413
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " case POST_GAMESHIELD_UPDATE: {\n return new Formatter().format(\"/gameshields/%s/settings\", values).toString();\n }\n case POST_GAMESHIELD_UPDATE_REGION: {\n return new Formatter().format(\"/gameshields/%s/region/%s\", values).toString();\n }\n case GET_GAMESHIELD_PLAN: {\n return new Formatter().format(\"/gameshields/%s/plan\", values).toString();\n }\n case POST_GAMESHIELD_PLAN_UPGRADE: {",
"score": 0.7489873170852661
},
{
"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.7409403324127197
}
] | java | .request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject(); |
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.8798436522483826
},
{
"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.8139868378639221
},
{
"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.8100286722183228
},
{
"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.8025683164596558
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java",
"retrieved_chunk": " ((ProxiedPlayer) receiver).unsafe().sendPacket(new KeepAlive(id));\n getCore().getPingMap().put(new KeepAliveResponseKey(((ProxiedPlayer) receiver).getSocketAddress(), id), System.currentTimeMillis());\n }\n }\n @Override\n public long sendKeepAliveMessage(long id) {\n for (ProxiedPlayer player : this.getProxy().getPlayers()) {\n sendKeepAliveMessage(player, id);\n }\n return id;",
"score": 0.778338611125946
}
] | java | instance.getCore().getPingMap().remove(keepAliveResponseKey); |
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.9825050830841064
},
{
"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.8558181524276733
},
{
"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.7839851379394531
},
{
"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.7527226805686951
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java",
"retrieved_chunk": " ((ProxiedPlayer) receiver).unsafe().sendPacket(new KeepAlive(id));\n getCore().getPingMap().put(new KeepAliveResponseKey(((ProxiedPlayer) receiver).getSocketAddress(), id), System.currentTimeMillis());\n }\n }\n @Override\n public long sendKeepAliveMessage(long id) {\n for (ProxiedPlayer player : this.getProxy().getPlayers()) {\n sendKeepAliveMessage(player, id);\n }\n return id;",
"score": 0.7363098859786987
}
] | java | instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>()); |
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": " }\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.7644320130348206
},
{
"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.7605385184288025
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " for (Gameshield gameshield : gameshieldList) {\n instance.sendMessage(sender, \"§5\" + gameshield.getName() + localization.get(locale, \"utils.click\"),\n \"RUN_COMMAND\", \"/np setgameshield \" + gameshield.getId(),\n \"SHOW_TEXT\", localization.get(locale, \"hover.gameshield\", gameshield.getName(), gameshield.getId()));\n }\n }\n private void setGameshield(String[] args) {\n if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {\n instance.sendMessage(sender, localization.get(locale, \"invalid.gameshield\", args[1]));\n return;",
"score": 0.7528345584869385
},
{
"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.739403486251831
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " } catch (Exception ex) {\n instance.getCore().severe(ex.getMessage(), ex);\n }\n });\n }\n }, 2000L * amount + 500);\n }\n private void gameshieldSelector() {\n instance.sendMessage(sender, localization.get(locale, \"select.gameshield\"));\n List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();",
"score": 0.7330464124679565
}
] | 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/request/RestAPIManager.java",
"retrieved_chunk": " .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .addHeader(\"Content-Type\", \"application/json\");\n }\n protected String getSubDirectory(RequestType type, Object... values) {\n switch (type) {\n case GET_ATTACKS: {\n return new Formatter().format(\"/attacks\", values).toString();\n }\n case GET_ATTACKS_GAMESHIELD: {\n return new Formatter().format(\"/attacks/gameshield/%s\", values).toString();",
"score": 0.7742807865142822
},
{
"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.7677865624427795
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " return debugMode;\n }\n public static String getGeyserServerIP() {\n return geyserServerIP;\n }\n public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {\n return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);\n }\n public static void setAPIKey(String key) {\n fileUtils.set(\"APIKey\", key);",
"score": 0.7584022879600525
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " core.severe(exception.getMessage(), exception);\n }\n return null;\n }\n protected Request.Builder defaultBuilder() {\n return defaultBuilder(Config.getAPIKey());\n }\n protected Request.Builder defaultBuilder(String apiKey) {\n return new Request.Builder()\n .addHeader(\"accept\", \"*/*\")",
"score": 0.7402846813201904
},
{
"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.7393954992294312
}
] | 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/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.7551413774490356
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " for (Gameshield gameshield : gameshieldList) {\n instance.sendMessage(sender, \"§5\" + gameshield.getName() + localization.get(locale, \"utils.click\"),\n \"RUN_COMMAND\", \"/np setgameshield \" + gameshield.getId(),\n \"SHOW_TEXT\", localization.get(locale, \"hover.gameshield\", gameshield.getName(), gameshield.getId()));\n }\n }\n private void setGameshield(String[] args) {\n if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {\n instance.sendMessage(sender, localization.get(locale, \"invalid.gameshield\", args[1]));\n return;",
"score": 0.743165135383606
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .addHeader(\"Content-Type\", \"application/json\");\n }\n protected String getSubDirectory(RequestType type, Object... values) {\n switch (type) {\n case GET_ATTACKS: {\n return new Formatter().format(\"/attacks\", values).toString();\n }\n case GET_ATTACKS_GAMESHIELD: {\n return new Formatter().format(\"/attacks/gameshield/%s\", values).toString();",
"score": 0.7318581342697144
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " client.setConnectTimeout(4, TimeUnit.SECONDS);\n }\n protected ResponseManager request(RequestType type, RequestBody requestBody, Object... value) {\n if (type.toString().startsWith(\"GET\")) {\n return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).build()));\n } else if (type.toString().startsWith(\"POST\")) {\n return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).post(requestBody).build()));\n } else {\n return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).delete().build()));\n }",
"score": 0.7170733213424683
},
{
"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.7149250507354736
}
] | 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/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.7553830146789551
},
{
"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.753675103187561
},
{
"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.7479473352432251
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " client.setConnectTimeout(4, TimeUnit.SECONDS);\n }\n protected ResponseManager request(RequestType type, RequestBody requestBody, Object... value) {\n if (type.toString().startsWith(\"GET\")) {\n return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).build()));\n } else if (type.toString().startsWith(\"POST\")) {\n return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).post(requestBody).build()));\n } else {\n return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).delete().build()));\n }",
"score": 0.741287887096405
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " for (Gameshield gameshield : gameshieldList) {\n instance.sendMessage(sender, \"§5\" + gameshield.getName() + localization.get(locale, \"utils.click\"),\n \"RUN_COMMAND\", \"/np setgameshield \" + gameshield.getId(),\n \"SHOW_TEXT\", localization.get(locale, \"hover.gameshield\", gameshield.getName(), gameshield.getId()));\n }\n }\n private void setGameshield(String[] args) {\n if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {\n instance.sendMessage(sender, localization.get(locale, \"invalid.gameshield\", args[1]));\n return;",
"score": 0.7410954236984253
}
] | 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/Config.java",
"retrieved_chunk": " return debugMode;\n }\n public static String getGeyserServerIP() {\n return geyserServerIP;\n }\n public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {\n return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);\n }\n public static void setAPIKey(String key) {\n fileUtils.set(\"APIKey\", key);",
"score": 0.78001469373703
},
{
"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.7743968963623047
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": " @Inject\n public NeoProtectVelocity(ProxyServer proxy, Logger logger, Metrics.Factory metricsFactory) {\n this.proxy = proxy;\n this.logger = logger;\n this.metricsFactory = metricsFactory;\n }\n @Subscribe\n public void onProxyInitialize(ProxyInitializeEvent event) {\n Metrics metrics = metricsFactory.make(this, 18727);\n metrics.addCustomChart(new SimplePie(\"language\", Config::getLanguage));",
"score": 0.7737199068069458
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Stats.java",
"retrieved_chunk": " this.versionStatus = versionStatus;\n this.updateSetting = updateSetting;\n this.neoProtectPlan = neoProtectPlan;\n this.serverPlugins = serverPlugins;\n this.playerAmount = playerAmount;\n this.managedServers = managedServers;\n this.coreCount = coreCount;\n this.onlineMode = onlineMode;\n this.proxyProtocol = proxyProtocol;\n }",
"score": 0.7539867162704468
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " return this;\n }\n public void executeChatEvent() {\n API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));\n }\n public void executeCommand() {\n API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));\n }\n public NeoProtectPlugin getInstance() {\n return instance;",
"score": 0.7452789545059204
}
] | 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": " 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.7350629568099976
},
{
"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.7317686080932617
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " fileUtils.remove(\"AutoUpdater\");\n } else if (!fileUtils.getConfig().isSet(\"AutoUpdater\")) {\n fileUtils.getConfig().set(\"AutoUpdater\", \"ENABLED\");\n }\n List<String> description = new ArrayList<>();\n description.add(\"This setting is only for paid costumer and allow you to disable the AutoUpdater\");\n description.add(\"'ENABLED' (Recommended/Default) Update/Downgrade plugin to the current version \");\n description.add(\"'DISABLED' AutoUpdater just disabled\");\n description.add(\"'DEV' Only update to the latest version (Please never use this)\");\n fileUtils.getConfig().setComments(\"AutoUpdater\", description);",
"score": 0.7309814095497131
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectTabCompleter.java",
"retrieved_chunk": " completorList.add(\"remove\");\n }\n if (args.length != 1) {\n return completorList;\n }\n list.add(\"setup\");\n if (instance.getCore().isSetup()) {\n list.add(\"directConnectWhitelist\");\n list.add(\"setgameshield\");\n list.add(\"setbackend\");",
"score": 0.7298827171325684
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " instance.sendMessage(sender, \"§5\" + backend.getIp() + \":\" + backend.getPort() + localization.get(locale, \"utils.click\"),\n \"RUN_COMMAND\", \"/np setbackend \" + backend.getId(),\n \"SHOW_TEXT\", localization.get(locale, \"hover.backend\", backend.getIp(), backend.getPort(), backend.getId()));\n }\n }\n private void setJavaBackend(String[] args) {\n if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {\n instance.sendMessage(sender, localization.get(locale, \"invalid.backend\", \"java\", args[1]));\n return;\n }",
"score": 0.7252107262611389
}
] | 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": " for (Gameshield gameshield : gameshieldList) {\n instance.sendMessage(sender, \"§5\" + gameshield.getName() + localization.get(locale, \"utils.click\"),\n \"RUN_COMMAND\", \"/np setgameshield \" + gameshield.getId(),\n \"SHOW_TEXT\", localization.get(locale, \"hover.gameshield\", gameshield.getName(), gameshield.getId()));\n }\n }\n private void setGameshield(String[] args) {\n if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {\n instance.sendMessage(sender, localization.get(locale, \"invalid.gameshield\", args[1]));\n return;",
"score": 0.7625449299812317
},
{
"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.7437052726745605
},
{
"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.7424784898757935
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " } catch (Exception ex) {\n instance.getCore().severe(ex.getMessage(), ex);\n }\n });\n }\n }, 2000L * amount + 500);\n }\n private void gameshieldSelector() {\n instance.sendMessage(sender, localization.get(locale, \"select.gameshield\"));\n List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();",
"score": 0.7204639911651611
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .addHeader(\"Content-Type\", \"application/json\");\n }\n protected String getSubDirectory(RequestType type, Object... values) {\n switch (type) {\n case GET_ATTACKS: {\n return new Formatter().format(\"/attacks\", values).toString();\n }\n case GET_ATTACKS_GAMESHIELD: {\n return new Formatter().format(\"/attacks/gameshield/%s\", values).toString();",
"score": 0.7069834470748901
}
] | 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/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.7989096641540527
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .addHeader(\"Content-Type\", \"application/json\");\n }\n protected String getSubDirectory(RequestType type, Object... values) {\n switch (type) {\n case GET_ATTACKS: {\n return new Formatter().format(\"/attacks\", values).toString();\n }\n case GET_ATTACKS_GAMESHIELD: {\n return new Formatter().format(\"/attacks/gameshield/%s\", values).toString();",
"score": 0.7948176264762878
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " return debugMode;\n }\n public static String getGeyserServerIP() {\n return geyserServerIP;\n }\n public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {\n return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);\n }\n public static void setAPIKey(String key) {\n fileUtils.set(\"APIKey\", key);",
"score": 0.7849637269973755
},
{
"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.7819697260856628
},
{
"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.7807328104972839
}
] | 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/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.8493283987045288
},
{
"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.8366844654083252
},
{
"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.7980402708053589
},
{
"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.7776886820793152
},
{
"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.7711142301559448
}
] | 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": " 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.769349217414856
},
{
"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.7562289237976074
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .addHeader(\"Content-Type\", \"application/json\");\n }\n protected String getSubDirectory(RequestType type, Object... values) {\n switch (type) {\n case GET_ATTACKS: {\n return new Formatter().format(\"/attacks\", values).toString();\n }\n case GET_ATTACKS_GAMESHIELD: {\n return new Formatter().format(\"/attacks/gameshield/%s\", values).toString();",
"score": 0.7461196184158325
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " } catch (Exception ex) {\n instance.getCore().severe(ex.getMessage(), ex);\n }\n });\n }\n }, 2000L * amount + 500);\n }\n private void gameshieldSelector() {\n instance.sendMessage(sender, localization.get(locale, \"select.gameshield\"));\n List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();",
"score": 0.7399312257766724
},
{
"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.7332890629768372
}
] | java | null, Config.getGameShieldID()).getResponseBodyArray(); |
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": " 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.8229835033416748
},
{
"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.79083251953125
},
{
"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.7882107496261597
},
{
"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.7784939408302307
},
{
"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.7684193253517151
}
] | java | setProxyProtocol(Config.isProxyProtocol()); |
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.7963770031929016
},
{
"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.7406104803085327
},
{
"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.7313416600227356
},
{
"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.7102816104888916
},
{
"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.7082710266113281
}
] | 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/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.7879209518432617
},
{
"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.76031494140625
},
{
"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.7281783223152161
},
{
"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.7246087789535522
},
{
"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.7147102355957031
}
] | 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": " RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, false).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 0 : code;\n } else {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, true).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 1 : code;\n }\n }",
"score": 0.6731482744216919
},
{
"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.6568589806556702
},
{
"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.6566430330276489
},
{
"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.6557013392448425
},
{
"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.6497723460197449
}
] | 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/request/RestAPIManager.java",
"retrieved_chunk": " client.setConnectTimeout(4, TimeUnit.SECONDS);\n }\n protected ResponseManager request(RequestType type, RequestBody requestBody, Object... value) {\n if (type.toString().startsWith(\"GET\")) {\n return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).build()));\n } else if (type.toString().startsWith(\"POST\")) {\n return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).post(requestBody).build()));\n } else {\n return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).delete().build()));\n }",
"score": 0.7526493668556213
},
{
"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.7214330434799194
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " for (Gameshield gameshield : gameshieldList) {\n instance.sendMessage(sender, \"§5\" + gameshield.getName() + localization.get(locale, \"utils.click\"),\n \"RUN_COMMAND\", \"/np setgameshield \" + gameshield.getId(),\n \"SHOW_TEXT\", localization.get(locale, \"hover.gameshield\", gameshield.getName(), gameshield.getId()));\n }\n }\n private void setGameshield(String[] args) {\n if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {\n instance.sendMessage(sender, localization.get(locale, \"invalid.gameshield\", args[1]));\n return;",
"score": 0.7146116495132446
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " Config.setBackendID(args[1]);\n instance.sendMessage(sender, localization.get(locale, \"set.backend\", \"java\", args[1]));\n instance.getCore().getRestAPI().testCredentials();\n bedrockBackendSelector();\n }\n private void bedrockBackendSelector() {\n List<Backend> backendList = instance.getCore().getRestAPI().getBackends();\n if(backendList.stream().noneMatch(Backend::isGeyser))return;\n instance.sendMessage(sender, localization.get(locale, \"select.backend\", \"geyser\"));\n for (Backend backend : backendList) {",
"score": 0.713970422744751
},
{
"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.7106305956840515
}
] | 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/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.6715662479400635
},
{
"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.6707605719566345
},
{
"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.6693084239959717
},
{
"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.6686763763427734
},
{
"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.6640552282333374
}
] | 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/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.756581723690033
},
{
"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.7551626563072205
},
{
"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.752228856086731
},
{
"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.7488013505935669
},
{
"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.7458707094192505
}
] | 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/core/request/RestAPIRequests.java",
"retrieved_chunk": " Config.getGameShieldID());\n return true;\n }\n }\n public int toggle(String mode) {\n JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldSettings\");\n if(!settings.has(mode)) return -1;\n boolean mitigationSensitivity = settings.getBoolean(mode);\n if (mitigationSensitivity) {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,",
"score": 0.7661991119384766
},
{
"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.758693277835846
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " private boolean isAttack() {\n return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals(\"true\");\n }\n public String getPlan() {\n try {\n return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldPlan\").getJSONObject(\"options\").getString(\"name\");\n }catch (Exception ignore){}\n return null;\n }\n private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {",
"score": 0.7571447491645813
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, false).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 0 : code;\n } else {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, true).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 1 : code;\n }\n }",
"score": 0.7508087158203125
},
{
"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.746666431427002
}
] | 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/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.7356759905815125
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " FileUtils languageRU = new FileUtils(Core.class.getResourceAsStream(\"/language_ru.properties\"), \"plugins/NeoProtect/languages\", \"language_ru.properties\", true);\n FileUtils languageUA = new FileUtils(Core.class.getResourceAsStream(\"/language_ua.properties\"), \"plugins/NeoProtect/languages\", \"language_ua.properties\", true);\n Config.loadConfig(this, config);\n this.localization = new Localization(\"language\", Locale.forLanguageTag(Config.getLanguage()), new File(\"plugins/NeoProtect/languages/\"));\n restAPIRequests = new RestAPIRequests(this);\n }\n public void debug(String output) {\n if (Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output);\n }\n public void info(String output) {",
"score": 0.7345871925354004
},
{
"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.7339730858802795
},
{
"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.733913779258728
},
{
"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.7309437990188599
}
] | 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/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.7868748903274536
},
{
"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.7571700811386108
},
{
"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.7569671869277954
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/messageunsign/SessionChatListener.java",
"retrieved_chunk": " if (!checkConnection(player)) return;\n event.setResult(ResultedEvent.GenericResult.denied());\n player.getChatQueue().queuePacket(\n plugin.getProxy().getEventManager().fire(new PlayerChatEvent(player, chatMessage))\n .thenApply(PlayerChatEvent::getResult)\n .thenApply(result -> {\n if (!result.isAllowed()) {\n return null;\n }\n final boolean isModified = result",
"score": 0.7545191645622253
},
{
"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.7460575103759766
}
] | 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/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.7911517024040222
},
{
"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.7762041091918945
},
{
"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.7498453855514526
},
{
"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.7414077520370483
},
{
"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.7373227477073669
}
] | 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/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.7721508741378784
},
{
"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.7572067975997925
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " List<Backend> list = new ArrayList<>();\n JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();\n for (Object object : backends) {\n JSONObject jsonObject = (JSONObject) object;\n list.add(new Backend(jsonObject.getString(\"id\"), jsonObject.getString(\"ipv4\"), String.valueOf(jsonObject.getInt(\"port\")), jsonObject.getBoolean(\"geyser\")));\n }\n return list;\n }\n public List<Firewall> getFirewall(String mode) {\n List<Firewall> list = new ArrayList<>();",
"score": 0.7569917440414429
},
{
"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.7469606399536133
},
{
"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.7398245334625244
}
] | 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/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.7409970760345459
},
{
"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.7408080101013184
},
{
"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.7405086755752563
},
{
"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.7347056865692139
},
{
"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.7336698770523071
}
] | 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/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.8031487464904785
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java",
"retrieved_chunk": " getProxy().getName(),\n System.getProperty(\"java.version\"),\n System.getProperty(\"os.name\"),\n System.getProperty(\"os.arch\"),\n System.getProperty(\"os.version\"),\n getDescription().getVersion(),\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()),",
"score": 0.7981681823730469
},
{
"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.7749958634376526
},
{
"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.771321177482605
},
{
"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.7341758012771606
}
] | 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.764201283454895
},
{
"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.7370578050613403
},
{
"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.729393482208252
},
{
"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.7220617532730103
},
{
"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.7136449813842773
}
] | 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/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.7821605205535889
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }, 0, 1000 * 60);\n }\n private void versionCheckSchedule() {\n core.info(\"VersionCheck scheduler started\");\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n core.setVersionResult(VersionUtils.checkVersion(\"NeoProtect\", \"NeoPlugin\", \"v\" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));\n }\n }, 1000 * 10, 1000 * 60 * 5);",
"score": 0.7804093956947327
},
{
"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.7778834104537964
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectTabCompleter.java",
"retrieved_chunk": " public NeoProtectTabCompleter(NeoProtectPlugin instance) {\n this.instance = instance;\n }\n @Override\n public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();\n if (args.length == 2 && args[0].equalsIgnoreCase(\"toggle\")) {\n completorList.add(\"antiVPN\");\n completorList.add(\"anycast\");",
"score": 0.7747902274131775
},
{
"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.7699404954910278
}
] | 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/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.6790504455566406
},
{
"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.6773519515991211
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/command/NeoProtectCommand.java",
"retrieved_chunk": " .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n return false;\n }\n}",
"score": 0.6707273721694946
},
{
"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.6652498245239258
},
{
"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.6578474640846252
}
] | 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/spigot/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " public void run() {\n registerChannelHandler();\n instance.getCore().info(\"Late bind injection successful.\");\n }\n }.runTask(instance);\n }\n }\n private void createServerChannelHandler() {\n // Handle connected channels\n endInitProtocol = new ChannelInitializer<Channel>() {",
"score": 0.8140955567359924
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/messageunsign/SessionChatListener.java",
"retrieved_chunk": " return chatPacket;\n }),\n chatPacket.getTimestamp()\n );\n }\n public boolean checkConnection(final ConnectedPlayer player) {\n try {\n player.ensureAndGetCurrentServer().ensureConnected();\n return true;\n } catch (final IllegalStateException e) {",
"score": 0.8082900047302246
},
{
"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.7908412218093872
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " return null;\n }\n }\n }\n public String getBaseURL() {\n return baseURL;\n }\n}",
"score": 0.7822723388671875
},
{
"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.7678157091140747
}
] | 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/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.7315236926078796
},
{
"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.7026966214179993
},
{
"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.7023476958274841
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " 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\");\n for (ProxiedPlayer player : BungeeCord.getInstance().getPlayers()) {\n if (!(player).getPendingConnection().getSocketAddress().equals(inetAddress.get())) {\n continue;",
"score": 0.6918050050735474
},
{
"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.6906222105026245
}
] | 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.7385069727897644
},
{
"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.7289745807647705
},
{
"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.7288187742233276
},
{
"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.7212713956832886
},
{
"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.7188807725906372
}
] | 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": " \"§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.7314908504486084
},
{
"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.7277563810348511
},
{
"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.7234638929367065
},
{
"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.7219152450561523
},
{
"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.70115727186203
}
] | 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/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.6770099401473999
},
{
"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.6760063171386719
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, false).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 0 : code;\n } else {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, true).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 1 : code;\n }\n }",
"score": 0.6701644659042358
},
{
"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.6501994132995605
},
{
"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.6425755620002747
}
] | 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, \"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.7036775946617126
},
{
"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.6830674409866333
},
{
"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.6815989017486572
},
{
"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.6781678795814514
},
{
"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.6641197204589844
}
] | 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/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.7489677667617798
},
{
"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.7483823299407959
},
{
"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.7475987076759338
},
{
"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.7103082537651062
},
{
"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.7082611322402954
}
] | 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.7267192602157593
},
{
"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.7263821363449097
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, false).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 0 : code;\n } else {\n int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(mode, true).toString()),\n Config.getGameShieldID()).getCode();\n return code == 200 ? 1 : code;\n }\n }",
"score": 0.7214723825454712
},
{
"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.7195896506309509
},
{
"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.7171945571899414
}
] | 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.