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 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/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": 23.87767886658887
},
{
"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": 15.021121665254087
},
{
"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": 14.96582976000182
},
{
"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": 11.889697333989007
},
{
"filename": "src/main/java/org/example/hmwk1/entity/Campaign.java",
"retrieved_chunk": "package org.example.hmwk1.entity;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class Campaign {\n private int id;\n private int discountAmount=0;\n private int dayTime = 15;\n private List<Game> games = new ArrayList<>();\n public Campaign(int id, int discountAmount, int dayTime, Game games) {\n this.id=id;",
"score": 11.239319052152108
}
] | java | campaign.getGames().get(id)); |
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": 44.975244941724064
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " customer.addGame(game);\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName()+\" cost: \"+game.getCost());\n }\n }\n}",
"score": 41.83637173272481
},
{
"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": 38.97230613484121
},
{
"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": 22.988873919788077
},
{
"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": 19.051717946718583
}
] | 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": 46.72291845431019
},
{
"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": 41.47325815755478
},
{
"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": 38.64703998719022
},
{
"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": 35.173193531342704
},
{
"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": 33.88820381613977
}
] | 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/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": 28.039032318061736
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " customer.addGame(game);\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName()+\" cost: \"+game.getCost());\n }\n }\n}",
"score": 26.218674752126343
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/CampaignManager.java",
"retrieved_chunk": " System.out.println(\"Campaign is not found and also not updated\");\n }\n }\n }\n @Override\n public List<Campaign> getCampaigns() {\n return campaigns;\n }\n}",
"score": 25.5203967917285
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/GameManager.java",
"retrieved_chunk": " updateToGame.setCountOwner(game.getCountOwner());\n }else{\n System.out.println(\"Game is not found and also not updated\");\n }\n }\n }\n @Override\n public List<Game> getGames() {\n return games;\n }",
"score": 23.6571435674067
},
{
"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": 22.364947900946063
}
] | 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/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": 26.11877286909681
},
{
"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": 20.658972686130788
},
{
"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": 20.361962020743526
},
{
"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": 18.816403385966456
},
{
"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": 17.789201831697945
}
] | java | if(campaign1.getId()==id){ |
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/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": 34.63166823612234
},
{
"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": 23.21226264186874
},
{
"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": 22.936510435912048
},
{
"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": 21.75812494692246
},
{
"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": 20.65691743498007
}
] | java | (campaign.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": 52.52149654159764
},
{
"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": 41.50325600843277
},
{
"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": 39.41002859496713
},
{
"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": 37.761587334225766
},
{
"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": 34.42919877109528
}
] | java | "\"=\"" + string.getValue() + "\"; |
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/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": 41.98153745088132
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/GameManager.java",
"retrieved_chunk": " updateToGame.setCountOwner(game.getCountOwner());\n }else{\n System.out.println(\"Game is not found and also not updated\");\n }\n }\n }\n @Override\n public List<Game> getGames() {\n return games;\n }",
"score": 33.78737431834162
},
{
"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": 33.064475129328784
},
{
"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": 28.51175338352827
},
{
"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": 28.26369633746711
}
] | java | !(customer.getGames().contains(game))){ |
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
System.out.println(playlist1.execute());
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator = player.createIterator();
| while (iterator.temProximo()) { |
PlaylistItem playlistItem = iterator.proximo();
String content = playlistItem.execute();
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
iterator = player.createIterator();
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
}
}
| br/edu/ifba/inf011/Aplicacao.java | nando-cezar-design-patterns-music-19ebdb3 | [
{
"filename": "br/edu/ifba/inf011/model/iterator/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": 17.946209655820848
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "\tprivate PlayerMode mode;\n\tpublic Player() {\n\t\tthis.items = new ArrayList<>();\n\t\tthis.listeners = new ArrayList<>();\n\t\tthis.mode = PlayerMode.PlayerAll;\n\t}\n\t@Override\n\tpublic void addItem(PlaylistItem item) {\n\t\tthis.items.add(item);\n\t}",
"score": 13.545858468264315
},
{
"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": 11.412341842831408
},
{
"filename": "br/edu/ifba/inf011/model/iterator/RandomModeIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport java.util.Random;\nimport br.edu.ifba.inf011.model.composite.Playlist;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.iterator.PlaylistIterator;\n/* Concrete Iterator: Iterator pattern */\npublic class RandomModeIterator implements PlaylistIterator {\n\tprivate final Random random;\n\tprivate final List<PlaylistItem> items;",
"score": 8.38989248302336
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlaylistIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Iterator: Iterator pattern */\npublic interface PlaylistIterator {\n boolean temProximo();\n PlaylistItem proximo();\n}",
"score": 7.497454859066709
}
] | 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": 18.297996785734593
},
{
"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": 15.902922673652775
},
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "\t}\n\t@Override\n\tpublic String getNome() {\n\t\treturn this.nome;\n\t}\n\tpublic PlaylistItem randomize() {\n\t\tint random = new Random().nextInt(items.size());\n\t\tPlaylistItem playlistItem = items.get(random);\n\t\tif (playlistItem instanceof Playlist) {\n\t\t\treturn ((Playlist) playlistItem).randomize();",
"score": 14.850503242924642
},
{
"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": 13.70432438436607
},
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.composite;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\n/* Composite: Composite pattern */\npublic class Playlist implements PlaylistItem {\n\tprivate final String nome;\n\tprivate final List<PlaylistItem> items;\n\tpublic Playlist(String nome) {\n\t\tthis.nome = nome;",
"score": 11.252414555924727
}
] | java | .println(playlist1.execute()); |
package br.edu.ifba.inf011.model.iterator;
import java.util.ArrayList;
import java.util.List;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.observer.PlayerListener;
/* Concrete Aggregate: Iterator pattern */
/* Subject: Observer pattern */
public class Player implements PlayerIterable {
private final List<PlaylistItem> items;
private final List<PlayerListener> listeners;
private PlayerMode mode;
public Player() {
this.items = new ArrayList<>();
this.listeners = new ArrayList<>();
this.mode = PlayerMode.PlayerAll;
}
@Override
public void addItem(PlaylistItem item) {
this.items.add(item);
}
@Override
public void removeItem(PlaylistItem item) {
this.items.remove(item);
}
@Override
public PlaylistIterator createIterator() {
return this.mode.createIterator(items);
}
public void setMode(PlayerMode mode) {
this.mode = mode;
notificar();
}
public PlayerMode getMode(){
return this.mode;
}
public void addListeners(PlayerListener listener) {
this.listeners.add(listener);
}
public void removeListener(PlayerListener listener) {
this.listeners.remove(listener);
}
public void notificar() {
for (PlayerListener listener : listeners) {
| listener.onChangeMode(); |
}
}
}
| br/edu/ifba/inf011/model/iterator/Player.java | nando-cezar-design-patterns-music-19ebdb3 | [
{
"filename": "br/edu/ifba/inf011/model/observer/PlayerListener.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.observer;\n/* Observer: Observer pattern */\n@FunctionalInterface\npublic interface PlayerListener {\n void onChangeMode();\n}",
"score": 19.181941811006062
},
{
"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": 17.05133152957975
},
{
"filename": "br/edu/ifba/inf011/Aplicacao.java",
"retrieved_chunk": "import br.edu.ifba.inf011.model.resources.ResourceLoader;\n/* Concrete Observer: Observer pattern */\npublic class Aplicacao implements PlayerListener {\n\tprivate final Player player;\n\tpublic Aplicacao() {\n\t\tthis.player = new Player();\n\t\tthis.player.addListeners(this);\n\t}\n\tpublic static void main(String[] args) throws IOException, InterruptedException {\n\t\tAplicacao app = new Aplicacao();",
"score": 16.20186056604554
},
{
"filename": "br/edu/ifba/inf011/Aplicacao.java",
"retrieved_chunk": "\tpublic void onChangeMode() {\n\t\tSystem.out.printf(\"\\n::::::::::::\\nModo: %s, está ativado!\\n\", player.getMode());\n\t}\n}",
"score": 9.573409202312515
},
{
"filename": "br/edu/ifba/inf011/model/iterator/RepeatAllIterator.java",
"retrieved_chunk": " }\n public void reset() {\n this.index = 0;\n }\n}",
"score": 8.596161408810838
}
] | 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/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": 19.86329084451104
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "\tprivate PlayerMode mode;\n\tpublic Player() {\n\t\tthis.items = new ArrayList<>();\n\t\tthis.listeners = new ArrayList<>();\n\t\tthis.mode = PlayerMode.PlayerAll;\n\t}\n\t@Override\n\tpublic void addItem(PlaylistItem item) {\n\t\tthis.items.add(item);\n\t}",
"score": 12.226838700663981
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlaylistIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Iterator: Iterator pattern */\npublic interface PlaylistIterator {\n boolean temProximo();\n PlaylistItem proximo();\n}",
"score": 11.974710835262192
},
{
"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": 9.738283568172374
},
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "\t\t}\n\t\treturn playlistItem;\n\t}\n\t@Override\n\tpublic String execute() {\n\t\tStringBuffer str = new StringBuffer();\n\t\tfor (PlaylistItem item : items) {\n\t\t\tstr.append(item.execute());\n\t\t}\n\t\treturn str.toString();",
"score": 9.40960100124069
}
] | 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": 26.155533690281757
},
{
"filename": "br/edu/ifba/inf011/model/resources/ResourceLoader.java",
"retrieved_chunk": "\t\treturn this.loadResource(nome, extensao);\n\t}\n\tpublic List<String> loadResource(String nome, String extensao) throws IOException {\n\t\tList<String> resource = new ArrayList<>();\n\t\tPath path = Paths.get(ResourceLoader.DIR_NAME + nome + \".\" + extensao);\n\t\tFiles\n\t\t\t\t.lines(path, StandardCharsets.ISO_8859_1)\n\t\t\t\t.forEach(resource::add);\n\t\treturn resource;\n\t}",
"score": 17.79547426917672
},
{
"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": 16.160520060914195
},
{
"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": 15.902922673652775
},
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "\t}\n\t@Override\n\tpublic String getNome() {\n\t\treturn this.nome;\n\t}\n\tpublic PlaylistItem randomize() {\n\t\tint random = new Random().nextInt(items.size());\n\t\tPlaylistItem playlistItem = items.get(random);\n\t\tif (playlistItem instanceof Playlist) {\n\t\t\treturn ((Playlist) playlistItem).randomize();",
"score": 14.850503242924642
}
] | 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/composite/Playlist.java",
"retrieved_chunk": "\t}\n\t@Override\n\tpublic String getNome() {\n\t\treturn this.nome;\n\t}\n\tpublic PlaylistItem randomize() {\n\t\tint random = new Random().nextInt(items.size());\n\t\tPlaylistItem playlistItem = items.get(random);\n\t\tif (playlistItem instanceof Playlist) {\n\t\t\treturn ((Playlist) playlistItem).randomize();",
"score": 19.28853910324031
},
{
"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": 17.675065213587203
},
{
"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": 17.63910662817081
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlaylistIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Iterator: Iterator pattern */\npublic interface PlaylistIterator {\n boolean temProximo();\n PlaylistItem proximo();\n}",
"score": 13.76923141880484
},
{
"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": 13.495726411119481
}
] | java | iterator = player.createIterator(); |
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
System.out.println(playlist1.execute());
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator = player.createIterator();
while (iterator.temProximo()) {
PlaylistItem | playlistItem = iterator.proximo(); |
String content = playlistItem.execute();
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
iterator = player.createIterator();
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
}
}
| br/edu/ifba/inf011/Aplicacao.java | nando-cezar-design-patterns-music-19ebdb3 | [
{
"filename": "br/edu/ifba/inf011/model/iterator/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": 19.86329084451104
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "\tprivate PlayerMode mode;\n\tpublic Player() {\n\t\tthis.items = new ArrayList<>();\n\t\tthis.listeners = new ArrayList<>();\n\t\tthis.mode = PlayerMode.PlayerAll;\n\t}\n\t@Override\n\tpublic void addItem(PlaylistItem item) {\n\t\tthis.items.add(item);\n\t}",
"score": 12.226838700663981
},
{
"filename": "br/edu/ifba/inf011/model/iterator/PlaylistIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Iterator: Iterator pattern */\npublic interface PlaylistIterator {\n boolean temProximo();\n PlaylistItem proximo();\n}",
"score": 11.974710835262192
},
{
"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": 8.016556508805335
},
{
"filename": "br/edu/ifba/inf011/model/iterator/RepeatAllIterator.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport java.util.List;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\nimport br.edu.ifba.inf011.model.iterator.PlaylistIterator;\n/* Concrete Iterator: Iterator pattern */\npublic class RepeatAllIterator implements PlaylistIterator {\n\tprivate final List<PlaylistItem> items;\n\tprivate Integer index;\n\tpublic RepeatAllIterator(List<PlaylistItem> items) {\n\t\tthis.items = items;",
"score": 7.582326767008809
}
] | 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/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": 12.787642238802446
},
{
"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": 12.140909873772712
},
{
"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": 9.081995253385823
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "\t\tnotificar();\n\t}\n\tpublic PlayerMode getMode(){\n\t\treturn this.mode;\n\t}\n\tpublic void addListeners(PlayerListener listener) {\n\t\tthis.listeners.add(listener);\n\t}\n\tpublic void removeListener(PlayerListener listener) {\n\t\tthis.listeners.remove(listener);",
"score": 8.202833028710005
},
{
"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": 7.054959600682832
}
] | java | ("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode()); |
package br.edu.ifba.inf011;
import java.io.IOException;
import java.util.Random;
import br.edu.ifba.inf011.model.iterator.Player;
import br.edu.ifba.inf011.model.iterator.PlayerMode;
import br.edu.ifba.inf011.model.composite.Playlist;
import br.edu.ifba.inf011.model.composite.PlaylistItem;
import br.edu.ifba.inf011.model.iterator.PlaylistIterator;
import br.edu.ifba.inf011.model.decorator.MusicaBase;
import br.edu.ifba.inf011.model.observer.PlayerListener;
import br.edu.ifba.inf011.model.resources.ResourceLoader;
/* Concrete Observer: Observer pattern */
public class Aplicacao implements PlayerListener {
private final Player player;
public Aplicacao() {
this.player = new Player();
this.player.addListeners(this);
}
public static void main(String[] args) throws IOException, InterruptedException {
Aplicacao app = new Aplicacao();
// app.musica();
app.player();
}
private void musica() throws IOException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
System.out.println(playlist1.execute());
}
private void player() throws IOException, InterruptedException {
var resource = ResourceLoader.instance();
MusicaBase musicaComNotaLetraOriginal = resource.createMusicaComNotaLetra("AndreaDorea");
MusicaBase musicaComNotaLetraOriginalTraduzida = resource.createMusicaComNotaLetraOriginalTraduzida(
"GodSaveTheQueen", "pt");
MusicaBase musicaSomenteComNota = resource.createMusicaSomenteComNota("GodSaveTheQueen");
Playlist playlist1 = new Playlist("Minha playlist 1");
playlist1.insert(musicaSomenteComNota);
playlist1.insert(musicaComNotaLetraOriginalTraduzida);
Playlist playlist2 = new Playlist("Minha playlist 2");
playlist2.insert(musicaComNotaLetraOriginal);
playlist1.insert(playlist2);
player.addItem(playlist1);
player.addItem(playlist2);
player.addItem(musicaSomenteComNota);
player.addItem(musicaComNotaLetraOriginal);
PlaylistIterator iterator = | player.createIterator(); |
while (iterator.temProximo()) {
PlaylistItem playlistItem = iterator.proximo();
String content = playlistItem.execute();
System.out.println(content);
Thread.sleep(1000);
int numero = new Random().nextInt(2,8);
if (numero % 5 == 0){
player.setMode(PlayerMode.RepeatAll);
iterator = player.createIterator();
}else if (numero % 7 == 0){
player.setMode(PlayerMode.RandomMode);
iterator = player.createIterator();
}
}
}
@Override
public void onChangeMode() {
System.out.printf("\n::::::::::::\nModo: %s, está ativado!\n", player.getMode());
}
}
| br/edu/ifba/inf011/Aplicacao.java | nando-cezar-design-patterns-music-19ebdb3 | [
{
"filename": "br/edu/ifba/inf011/model/iterator/PlayerIterable.java",
"retrieved_chunk": "package br.edu.ifba.inf011.model.iterator;\nimport br.edu.ifba.inf011.model.composite.PlaylistItem;\n/* Aggregate: Iterator pattern */\npublic interface PlayerIterable {\n\tvoid addItem(PlaylistItem item);\n\tvoid removeItem(PlaylistItem item);\n\tPlaylistIterator createIterator();\n}",
"score": 16.310996785709456
},
{
"filename": "br/edu/ifba/inf011/model/iterator/Player.java",
"retrieved_chunk": "\tprivate PlayerMode mode;\n\tpublic Player() {\n\t\tthis.items = new ArrayList<>();\n\t\tthis.listeners = new ArrayList<>();\n\t\tthis.mode = PlayerMode.PlayerAll;\n\t}\n\t@Override\n\tpublic void addItem(PlaylistItem item) {\n\t\tthis.items.add(item);\n\t}",
"score": 13.545858468264315
},
{
"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": 11.412341842831408
},
{
"filename": "br/edu/ifba/inf011/model/composite/Playlist.java",
"retrieved_chunk": "\t}\n\t@Override\n\tpublic String getNome() {\n\t\treturn this.nome;\n\t}\n\tpublic PlaylistItem randomize() {\n\t\tint random = new Random().nextInt(items.size());\n\t\tPlaylistItem playlistItem = items.get(random);\n\t\tif (playlistItem instanceof Playlist) {\n\t\t\treturn ((Playlist) playlistItem).randomize();",
"score": 7.425251621462321
},
{
"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": 6.852162192183035
}
] | java | player.createIterator(); |
package com.xxf.i18n.plugin.action;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.StandardFileSystems;
import com.xxf.i18n.plugin.bean.StringEntity;
import com.xxf.i18n.plugin.utils.AndroidStringFileUtils;
import com.xxf.i18n.plugin.utils.FileUtils;
import com.google.common.collect.Lists;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.vfs.VirtualFile;
import com.xxf.i18n.plugin.utils.MessageUtils;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* layout或者java(仅支持kt)文件夹转成strings
* Created by xyw on 2023/5/21.
*/
public class AndroidDirAction extends AnAction {
/**
*解析的属性名
*/
private List<String> textAttributeNamesList = Arrays.asList("android:text","android:hint","app:leftText","app:rightText","app:titleText");
private int index = 0;
//避免重复 key 中文字符串 value 为已经生成的id
Map<String,String> valueKeyMap = new HashMap();
@Override
public void actionPerformed(AnActionEvent e) {
Project currentProject = e.getProject();
//检查项目的配置
String path= FileUtils.getConfigPathValue(currentProject);
if(path==null||path.length()<=0){
MessageUtils.showAlert(e,String.format("请在%s\n目录下面创建%s文件,且设置有效的生成文件路径(string.xml)",
FileUtils.getConfigPathDir(currentProject).getPath(),
FileUtils.getConfigPathFileName()));
return;
}
VirtualFile targetStringFile = StandardFileSystems.local().findFileByPath(path);
if (targetStringFile == null||!targetStringFile.exists()) {
MessageUtils.showAlert(e,String.format("请在%s\n目录下面创建%s文件,且设置有效的生成文件路径(string.xml)",
FileUtils.getConfigPathDir(currentProject).getPath(),
FileUtils.getConfigPathFileName()));
return;
}
String extension = targetStringFile.getExtension();
if (extension == null || !extension.equalsIgnoreCase("xml")) {
MessageUtils.showAlert(e,"生成的文件类型必须是string.xml");
return;
}
VirtualFile eventFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
if (eventFile == null) {
MessageUtils.showAlert(e,"找不到目标文件");
return;
}
valueKeyMap.clear();
//读取已经存在的 复用,这里建议都是按中文来
readFileToDict(targetStringFile);
int resultStart= valueKeyMap.size();
StringBuilder sb = new StringBuilder();
//layout 目录 可能是pad layout_s600dp等等
if(eventFile.isDirectory() && eventFile.getName().startsWith("layout")) {
//遍历所有layout文件,然后获取其中的字串写到stringbuilder里面去
VirtualFile[] children = eventFile.getChildren();
for (VirtualFile child : children) {
layoutChild(child, sb);
}
}else if(eventFile.getExtension()!=null && eventFile.getExtension().equalsIgnoreCase("xml")){
//可能是layout布局文件
layoutChild(eventFile, sb);
}else{
//遍历所有 kt文件,然后获取其中的字串写到stringbuilder里面去
classChild(eventFile, sb);
}
int resultCount= valueKeyMap.size()-resultStart;
try {
if(!sb.isEmpty()) {
String content = new String(targetStringFile.contentsToByteArray(), "utf-8"); //源文件内容
String result = content.replace("</resources>", sb.toString() + "\n</resources>"); //在最下方加上新的字串
FileUtils.replaceContentToFile(targetStringFile.getPath(), result);//替换文件
}
Map<String, List<String>> repeatRecords = AndroidStringFileUtils.getRepeatRecords(targetStringFile);
StringBuilder repeatStringBuilder=new StringBuilder("重复条数:"+repeatRecords.size());
if(repeatRecords.size()>0){
repeatStringBuilder.append("\n请确认是否xxf_i18n_plugin_path.txt是中文清单,否则去重没有意义");
repeatStringBuilder.append("\n请确认是否xxf_i18n_plugin_path.txt是中文清单,否则去重没有意义");
}
for(Map.Entry<String,List<String>> entry : repeatRecords.entrySet()){
repeatStringBuilder.append("\nvalue:"+entry.getKey());
repeatStringBuilder.append("\nkeys:");
for (String key:entry.getValue()) {
repeatStringBuilder.append("\n");
repeatStringBuilder.append(key);
}
repeatStringBuilder.append("\n\n");
}
MessageUtils.showAlert(e,String.format("国际化执行完成,新生成(%d)条结果,%s", resultCount,repeatStringBuilder.toString()));
} catch (IOException ex) {
ex.printStackTrace();
MessageUtils.showAlert(e,ex.getMessage());
}
e.getActionManager().getAction(IdeActions.ACTION_SYNCHRONIZE).actionPerformed(e);
}
/**
* 将已经存在字符串读取到字典里面 避免重复
* @param file
*/
private void readFileToDict(VirtualFile file){
InputStream is = null;
try {
is = file.getInputStream();
// String str="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
// "<resources>\n" +
// " <string name=\"flowus_app_name\">FlowUs 息流</string>\n" +
// " <string name=\"app_name\">FlowUs 息流</string>\n" +
// " <string name=\"ok\">确定</string>\n" +
// "</resources>";
// is =new ByteArrayInputStream(str.getBytes());
Node node=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
this.findStringNode(node);
} catch (Throwable ex) {
ex.printStackTrace();
} finally {
FileUtils.closeQuietly(is);
}
}
private void findStringNode(Node node){
if (node.getNodeType() == Node.ELEMENT_NODE
&&"string".equals(node.getNodeName())) {
Node key = node.getAttributes().getNamedItem("name");
if(key!=null) {
String valueKey=node.getTextContent();
if(!this.valueKeyMap.containsKey(valueKey)){
this.valueKeyMap.put(valueKey,key.getNodeValue());
}
}
}
NodeList children = node.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
findStringNode(children.item(j));
}
}
/**
* 执行 java 文件和kt文件
* @param file
* @param sb
*/
private void classChild(VirtualFile file, StringBuilder sb){
index = 0;
if(file.isDirectory()){
VirtualFile[] children = file.getChildren();
for (VirtualFile child : children) {
classChild(child,sb);
}
}else{
String extension = file.getExtension();
if (extension != null && extension.equalsIgnoreCase("kt")) {
List<StringEntity> strings;
StringBuilder oldContent = new StringBuilder();
try {
oldContent.append(new String(file.contentsToByteArray(), "utf-8"));
} catch (IOException e1) {
e1.printStackTrace();
}
InputStream is = null;
try {
is = file.getInputStream();
strings = extraClassEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent, valueKeyMap);
if (strings != null) {
for (StringEntity string : strings) {
sb.append("\n <string name=\"" + string.getId() + "\">" + string.getValue() + "</string>");
}
FileUtils.replaceContentToFile(file.getPath(), oldContent.toString());
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
FileUtils.closeQuietly(is);
}
}
}
}
private List<StringEntity> extraClassEntity(InputStream is, String fileName, StringBuilder oldContent,Map<String,String> strDistinctMap) {
List<StringEntity> strings = Lists.newArrayList();
String resultText=replaceUsingSB(fileName,oldContent.toString(),strings,strDistinctMap);
oldContent = oldContent.replace(0, oldContent.length(), resultText);
return strings;
}
public String replaceUsingSB(String fileName, String str, List<StringEntity> strings,Map<String,String> strDistinctMap) {
StringBuilder sb = new StringBuilder(str.length());
Pattern p = Pattern.compile("(?=\".{1,60}\")\"[^$+,\\n\"{}]*[\\u4E00-\\u9FFF]+[^$+,\\n\"{}]*\"");
Matcher m = p.matcher(str);
int lastIndex = 0;
while (m.find()) {
sb.append(str, lastIndex, m.start());
String value=m.group();
//去除前后的双引号
if(value.startsWith("\"")&&value.endsWith("\"")){
value=value.substring(1,value.length()-1);
}
//复用已经存在的
String id=strDistinctMap.get(value);
if(id==null||id.length()<=0){
//生成新的id
id = currentIdString(fileName);
strDistinctMap.put(value,id);
strings.add(new StringEntity(id, value));
}
sb.append("com.xxf.application.applicationContext.getString(com.next.space.cflow.resources.R.string."+id+")");
lastIndex = m.end();
}
sb.append(str.substring(lastIndex));
return sb.toString();
}
/**
* 递归执行layout xml
* @param file
* @param sb
*/
private void layoutChild(VirtualFile file, StringBuilder sb) {
index = 0;
String extension = file.getExtension();
if (extension != null && extension.equalsIgnoreCase("xml")) {
if (!file.getParent().getName().startsWith("layout")) {
| MessageUtils.showNotify("请选择布局文件"); |
return;
}
}
List<StringEntity> strings;
StringBuilder oldContent = new StringBuilder();
try {
oldContent.append(new String(file.contentsToByteArray(), "utf-8"));
} catch (IOException e1) {
e1.printStackTrace();
}
InputStream is = null;
try {
is = file.getInputStream();
strings = extraStringEntity(is, file.getNameWithoutExtension().toLowerCase(), oldContent);
if (strings != null) {
for (StringEntity string : strings) {
sb.append("\n <string name=\"" + string.getId() + "\">" + string.getValue() + "</string>");
}
FileUtils.replaceContentToFile(file.getPath(), oldContent.toString());
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
FileUtils.closeQuietly(is);
}
}
private List<StringEntity> extraStringEntity(InputStream is, String fileName, StringBuilder oldContent) {
List<StringEntity> strings = Lists.newArrayList();
try {
return generateStrings(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is), strings, fileName, oldContent);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
private String currentIdString(String fileName){
//需要加时间 多次生成的key避免错位和冲突,key 一样 内容不一样 合并风险太高
final String id = fileName +"_"+ System.currentTimeMillis() +"_" + (index++);
return id;
}
private List<StringEntity> generateStrings(Node node, List<StringEntity> strings, String fileName, StringBuilder oldContent) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
NamedNodeMap attributes = node.getAttributes();
for (int i = 0; i <attributes.getLength() ; i++) {
Node item = attributes.item(i);
if(textAttributeNamesList.contains(item.getNodeName())){
String value = item.getNodeValue();
if (value!=null && !value.contains("@string")) {
//复用已经存在的
String id= valueKeyMap.get(value);
if(id==null||id.length()<=0){
//生成新的id
id = currentIdString(fileName);
valueKeyMap.put(value,id);
strings.add(new StringEntity(id, value));
}
String newContent = oldContent.toString().replaceFirst("\"" + value + "\"", "\"@string/" + id + "\"");
oldContent = oldContent.replace(0, oldContent.length(), newContent);
}
}
}
}
NodeList children = node.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
generateStrings(children.item(j), strings, fileName, oldContent);
}
return strings;
}
}
| src/com/xxf/i18n/plugin/action/AndroidDirAction.java | NBXXF-XXFi18nPlugin-065127d | [
{
"filename": "src/com/xxf/i18n/plugin/action/ToStringXml.java",
"retrieved_chunk": " if (extension != null && extension.equalsIgnoreCase(\"xml\")) {\n if (!file.getParent().getName().startsWith(\"layout\")) {\n showError(\"请选择布局文件\");\n return;\n }\n }\n List<StringEntity> strings;\n StringBuilder oldContent = new StringBuilder(); //整个file字串\n try {\n oldContent.append(new String(file.contentsToByteArray(), \"utf-8\")); //源文件整体字符串",
"score": 48.31171858625748
},
{
"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": 44.78070630744864
},
{
"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": 38.533212980605846
},
{
"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": 36.585840679097835
},
{
"filename": "src/com/xxf/i18n/plugin/action/IosDirAction.java",
"retrieved_chunk": " classChild(child,sb,strDistinctMap);\n }\n }else{\n String extension = file.getExtension();\n if (extension != null && extension.equalsIgnoreCase(\"m\")) {\n List<StringEntity> strings;\n StringBuilder oldContent = new StringBuilder();\n try {\n oldContent.append(new String(file.contentsToByteArray(), \"utf-8\"));\n } catch (IOException e1) {",
"score": 34.61014301616418
}
] | 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/Parser.java",
"retrieved_chunk": " private Queue<Statement> statements = new LinkedList<>();\n // Current index of the given tokens\n private int index = 0;\n protected Parser(List<Lexer.Token> tokens) {\n this.tokens = tokens;\n }\n /**\n * @return a new Queue of generated bytecode statements based on the tokens given to the Parser object\n */\n protected Queue<Statement> getStatements() {",
"score": 26.426845208035786
},
{
"filename": "Compiler/src/core/Lexer.java",
"retrieved_chunk": " int i = 0;\n while (i < s.length()) {\n char c = s.charAt(i);\n if (Character.isWhitespace(c)) {\n i++;\n continue;\n }\n if (Character.isDigit(c) || c == '.') {\n StringBuilder numberBuilder = new StringBuilder();\n while (i < s.length() && Character.isDigit(s.charAt(i)) || s.charAt(i) == '.') {",
"score": 21.71727289496677
},
{
"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": 20.533443944039014
},
{
"filename": "Compiler/src/core/Lexer.java",
"retrieved_chunk": "package core;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class Lexer {\n public enum TokenType {\n TYPE, IDENTIFIER, EQUALS, NUMBER, BINARY_OPERATOR, OPEN_PAREN, CLOSE_PAREN, OPEN_HEAD, CLOSE_HEAD, END,\n KEYWORD, FUNCTION, CONDITION\n }\n protected static List<Token> tokenize(String s) {\n List<Token> tokenList = new ArrayList<>();",
"score": 20.410917642214606
},
{
"filename": "Compiler/src/core/Lexer.java",
"retrieved_chunk": " numberBuilder.append(s.charAt(i));\n i++;\n }\n tokenList.add(new Token(numberBuilder.toString(), TokenType.NUMBER));\n continue;\n }\n if (Character.isLetter(c)) {\n StringBuilder identifierBuilder = new StringBuilder();\n while (i < s.length() && Character.isLetterOrDigit(s.charAt(i))) {\n identifierBuilder.append(s.charAt(i));",
"score": 20.212991346769105
}
] | 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/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": 67.68964484566945
},
{
"filename": "src/main/java/ru/jbimer/core/models/Collision.java",
"retrieved_chunk": " @Column(name = \"created_at\")\n @Temporal(TemporalType.TIMESTAMP)\n private Date createdAt;\n @Column(name = \"fake\")\n private boolean fake;\n public List<String> getComments() {\n if (comment == null) return null;\n else return List.of(comment.split(\"#@\"));\n }\n public String getFullInfoString() {",
"score": 28.41996432290466
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " }\n @GetMapping(\"/{id}/not-fake\")\n public String markAsNotFake(@PathVariable(\"id\") int id, @PathVariable(\"project_id\") int project_id) {\n collisionsService.markAsNotFake(id);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }\n @PostMapping(\"/{id}/add-comment\")\n public String addComment(@PathVariable(\"id\") int id,\n @RequestParam(\"comment\") String comment,\n @PathVariable(\"project_id\") int project_id) {",
"score": 28.12010604891742
},
{
"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": 27.63281756660679
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n String authority = authentication.getAuthorities().stream().findFirst().orElse(null).getAuthority();\n Collision collision = collisionsService.findOneAndEngineer(id);\n Engineer collisionOwner = collision.getEngineer();\n model.addAttribute(\"collision\", collision);\n model.addAttribute(\"comments\", collision.getComments());\n model.addAttribute(\"role\", authority);\n if (collisionOwner != null){\n model.addAttribute(\"owner\", collisionOwner);\n }",
"score": 25.36593647304235
}
] | java | + ": "+ selectedEngineer.getFullNameWithDiscipline() + ": " + comment + "#@"; |
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": 64.86136262850329
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " verify(engineersService).findOne(id);\n }\n @Test\n public void testUpdate() throws Exception {\n int id = 1;\n Engineer updatedEngineer = new Engineer();\n updatedEngineer.setId(id);\n BindingResult bindingResult = mock(BindingResult.class);\n when(bindingResult.hasErrors()).thenReturn(false);\n Engineer originalEngineer = mock(Engineer.class);",
"score": 50.44798546242789
},
{
"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": 49.90399520438138
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " when(engineersService.findOne(id)).thenReturn(originalEngineer);\n String viewName = engineersController.update(updatedEngineer, bindingResult, id);\n assertEquals(\"redirect:/engineers\", viewName);\n verify(engineersService).update(id, updatedEngineer, originalEngineer);\n }\n @Test\n public void testDelete() throws Exception {\n int id = 1;\n Authentication authentication = mock(Authentication.class);\n SecurityContextHolder.getContext().setAuthentication(authentication);",
"score": 48.463118720763866
},
{
"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": 46.41894114529416
}
] | java | originalEngineer = 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": " 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": 44.91796443953519
},
{
"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": 43.67358771344105
},
{
"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": 36.837948582524255
},
{
"filename": "src/main/java/ru/jbimer/core/repositories/CollisionsRepository.java",
"retrieved_chunk": " @Param(\"project\") Project project,\n Pageable pageable);\n @Query(\"SELECT c FROM Collision c LEFT JOIN FETCH c.engineer WHERE c.id = :id\")\n Optional<Collision> findByIdFetchEngineer(@Param(\"id\") int id);\n @Query(\"SELECT c FROM Collision c LEFT JOIN FETCH c.engineer ORDER BY c.id\")\n List<Collision> findAllFetchEngineers();\n List<Collision> findByEngineer(Engineer engineer);\n @Query(\"SELECT c FROM Collision c LEFT JOIN FETCH c.projectBase WHERE c.projectBase = :project and \" +\n \"(c.elementId1 =: elemId1 and c.elementId2 = :elemId2\" +\n \" or c.elementId1 = :elemId2 and c.elementId2 = :elemId1)\")",
"score": 35.78168032271696
},
{
"filename": "src/main/java/ru/jbimer/core/repositories/CollisionsRepository.java",
"retrieved_chunk": " @Param(\"project\") Project project);\n Page<Collision> findByProjectBase(Project project, Pageable pageable);\n List<Collision> findAllByProjectBase(Project project);\n}",
"score": 30.74176017046968
}
] | java | > foundCollision = 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/CollisionsController.java",
"retrieved_chunk": " Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n EngineerDetails engineerDetails = (EngineerDetails) authentication.getPrincipal();\n collisionsService.addComment(id, engineerDetails.getEngineer(), comment);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }\n}",
"score": 58.58270228310406
},
{
"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": 40.65003891922212
},
{
"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": 40.58250101495985
},
{
"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": 32.50665974518407
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n String authority = authentication.getAuthorities().stream().findFirst().orElse(null).getAuthority();\n Collision collision = collisionsService.findOneAndEngineer(id);\n Engineer collisionOwner = collision.getEngineer();\n model.addAttribute(\"collision\", collision);\n model.addAttribute(\"comments\", collision.getComments());\n model.addAttribute(\"role\", authority);\n if (collisionOwner != null){\n model.addAttribute(\"owner\", collisionOwner);\n }",
"score": 27.12763849057948
}
] | 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.models.Engineer;
import ru.jbimer.core.models.Project;
import ru.jbimer.core.services.CollisionsService;
import ru.jbimer.core.services.EngineersService;
import ru.jbimer.core.services.HtmlReportService;
import ru.jbimer.core.services.ProjectService;
import java.util.List;
@Controller
@RequestMapping("/projects")
public class ProjectController {
private final ProjectService projectService;
private final EngineersService engineersService;
private final HtmlReportService htmlReportService;
private final CollisionsService collisionsService;
@Autowired
public ProjectController(ProjectService projectService, EngineersService engineersService, HtmlReportService htmlReportService, CollisionsService collisionsService) {
this.projectService = projectService;
this.engineersService = engineersService;
this.htmlReportService = htmlReportService;
this.collisionsService = collisionsService;
}
@GetMapping()
public String index(Model model) {
List<Project> projects = projectService.findAll();
model.addAttribute("projects", projects);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String authority = authentication.getAuthorities().stream().findFirst().orElse(null).getAuthority();
model.addAttribute("role", authority);
return "projects/index";
}
@GetMapping("/{id}")
public String show(@PathVariable("id") int project_id, Model model) {
Project project = projectService.findOne(project_id);
List<Engineer> engineers = project.getEngineersOnProject();
model.addAttribute("project", project);
model.addAttribute("engineers", engineers);
model.addAttribute("reports", htmlReportService.findAllByProject(project));
return "projects/show";
}
@GetMapping("/new")
public String newProject(Model model,
@ModelAttribute("project") Project project) {
model.addAttribute( | "engineers", engineersService.findAll()); |
return "projects/new";
}
@PostMapping
public String create(@ModelAttribute("project") @Valid Project project,
BindingResult bindingResult, Model model) {
model.addAttribute("engineers", engineersService.findAll());
if (bindingResult.hasErrors()) return "projects/new";
projectService.save(project);
return "redirect:/projects";
}
@GetMapping("/{id}/edit")
public String edit(Model model, @PathVariable("id") int id) {
model.addAttribute("project", projectService.findOne(id));
model.addAttribute("engineers", engineersService.findAll());
return "projects/edit";
}
@PatchMapping("/{id}")
public String update(@ModelAttribute("project") @Valid Project project,
BindingResult bindingResult,
@PathVariable("id") int id) {
if (bindingResult.hasErrors()) return "projects/edit";
projectService.save(project);
return "redirect:/projects/" + id;
}
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") int id){
projectService.delete(id);
return "redirect:/projects";
}
}
| src/main/java/ru/jbimer/core/controllers/ProjectController.java | mitrofmep-JBimer-fd7a0ba | [
{
"filename": "src/test/java/ru/jbimer/core/controllers/ProjectControllerTest.java",
"retrieved_chunk": " public void testNewProject() {\n Model model = Mockito.mock(Model.class);\n Project project = new Project();\n List<Engineer> engineers = Arrays.asList(new Engineer(), new Engineer(), new Engineer());\n Mockito.when(engineersService.findAll()).thenReturn(engineers);\n String viewName = projectController.newProject(model, project);\n assertEquals(\"projects/new\", viewName);\n Mockito.verify(model).addAttribute(\"project\", project);\n Mockito.verify(model).addAttribute(\"engineers\", engineers);\n }",
"score": 69.58117608159023
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/ProjectControllerTest.java",
"retrieved_chunk": " List<Engineer> engineers = Arrays.asList(new Engineer(), new Engineer(), new Engineer());\n project.setEngineersOnProject(engineers);\n int projectId = 1;\n Mockito.when(projectService.findOne(projectId)).thenReturn(project);\n String viewName = projectController.show(projectId, model);\n assertEquals(\"projects/show\", viewName);\n Mockito.verify(model).addAttribute(\"project\", project);\n Mockito.verify(model).addAttribute(\"engineers\", engineers);\n }\n @Test",
"score": 61.04590690414124
},
{
"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": 58.2830361350825
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/ProjectControllerTest.java",
"retrieved_chunk": " Mockito.verify(model).addAttribute(\"project\", project);\n Mockito.verify(model).addAttribute(\"engineers\", engineers);\n }\n @Test\n public void testUpdate() {\n Project project = new Project();\n BindingResult bindingResult = Mockito.mock(BindingResult.class);\n int projectId = 1;\n Mockito.when(bindingResult.hasErrors()).thenReturn(false);\n String viewName = projectController.update(project, bindingResult, projectId);",
"score": 53.5512489284341
},
{
"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": 52.80406091189046
}
] | 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/controllers/CollisionsController.java",
"retrieved_chunk": " }\n @GetMapping(\"/{id}/not-fake\")\n public String markAsNotFake(@PathVariable(\"id\") int id, @PathVariable(\"project_id\") int project_id) {\n collisionsService.markAsNotFake(id);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }\n @PostMapping(\"/{id}/add-comment\")\n public String addComment(@PathVariable(\"id\") int id,\n @RequestParam(\"comment\") String comment,\n @PathVariable(\"project_id\") int project_id) {",
"score": 29.10333837447675
},
{
"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": 28.153445723624852
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " @PatchMapping(\"/{id}/assign\")\n public String assign(@PathVariable(\"id\") int id, @ModelAttribute(\"engineer\")Engineer engineer,\n @PathVariable(\"project_id\") int project_id) {\n collisionsService.assign(id, engineer);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }\n @GetMapping(\"/{id}/fake\")\n public String markAsFake(@PathVariable(\"id\") int id, @PathVariable(\"project_id\") int project_id) {\n collisionsService.markAsFake(id);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;",
"score": 27.303246767552736
},
{
"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": 26.91296707314513
},
{
"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": 25.129860171868
}
] | java | Optional<Collision> optionalCollision = collisionsRepository.findByIdFetchEngineer(id); |
package ru.jbimer.core.controllers;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.jbimer.core.security.EngineerDetails;
import ru.jbimer.core.util.EngineerValidator;
import ru.jbimer.core.models.Engineer;
import ru.jbimer.core.services.EngineersService;
import java.util.*;
@Controller
@RequestMapping("/engineers")
public class EngineersController {
private final EngineerValidator engineerValidator;
private final EngineersService engineersService;
@Autowired
public EngineersController(EngineerValidator engineerValidator, EngineersService engineersService) {
this.engineerValidator = engineerValidator;
this.engineersService = engineersService;
}
@GetMapping()
public String index(Model model) {
List<Engineer> engineers = engineersService.findAllSortedByCollisionsSize();
model.addAttribute("engineers", engineers);
return "engineers/index";
}
@GetMapping("/{id}")
public String show(@PathVariable("id") int id, Model model) {
Engineer engineer | = engineersService.findByIdFetchCollisions(id); |
model.addAttribute("engineer", engineer);
model.addAttribute("collisions", engineer.getCollisions());
return "engineers/show";
}
@GetMapping("/{id}/edit")
public String edit(Model model, @PathVariable("id") int id) {
model.addAttribute("engineer", engineersService.findOne(id));
return "engineers/edit";
}
@PatchMapping("/{id}")
public String update(@ModelAttribute("engineer") @Valid Engineer updatedEngineer,
BindingResult bindingResult,
@PathVariable("id") int id) {
if (bindingResult.hasErrors()) return "engineers/edit";
Engineer originalEngineer = engineersService.findOne(id);
engineersService.update(id, updatedEngineer, originalEngineer);
return "redirect:/engineers";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") int id) {
engineersService.delete(id);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(null);
}
return "redirect:/logout";
}
}
| src/main/java/ru/jbimer/core/controllers/EngineersController.java | mitrofmep-JBimer-fd7a0ba | [
{
"filename": "src/main/java/ru/jbimer/core/controllers/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": 57.68460436528059
},
{
"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": 52.78369889611853
},
{
"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": 52.33072893484115
},
{
"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": 51.47923115659107
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " @MockBean\n private EngineersController engineersController;\n @Test\n public void testIndex() throws Exception {\n List<Engineer> engineers = new ArrayList<>();\n engineers.add(new Engineer());\n when(engineersService.findAllSortedByCollisionsSize()).thenReturn(engineers);\n Model model = new ExtendedModelMap();\n String viewName = engineersController.index(model);\n assertEquals(\"engineers/index\", viewName);",
"score": 48.51644303904563
}
] | java | = engineersService.findByIdFetchCollisions(id); |
package ru.jbimer.core.controllers;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.jbimer.core.security.EngineerDetails;
import ru.jbimer.core.util.EngineerValidator;
import ru.jbimer.core.models.Engineer;
import ru.jbimer.core.services.EngineersService;
import java.util.*;
@Controller
@RequestMapping("/engineers")
public class EngineersController {
private final EngineerValidator engineerValidator;
private final EngineersService engineersService;
@Autowired
public EngineersController(EngineerValidator engineerValidator, EngineersService engineersService) {
this.engineerValidator = engineerValidator;
this.engineersService = engineersService;
}
@GetMapping()
public String index(Model model) {
List<Engineer> engineers = engineersService.findAllSortedByCollisionsSize();
model.addAttribute("engineers", engineers);
return "engineers/index";
}
@GetMapping("/{id}")
public String show(@PathVariable("id") int id, Model model) {
Engineer engineer = engineersService.findByIdFetchCollisions(id);
model.addAttribute("engineer", engineer);
model.addAttribute("collisions", engineer.getCollisions());
return "engineers/show";
}
@GetMapping("/{id}/edit")
public String edit(Model model, @PathVariable("id") int id) {
model.addAttribute( | "engineer", engineersService.findOne(id)); |
return "engineers/edit";
}
@PatchMapping("/{id}")
public String update(@ModelAttribute("engineer") @Valid Engineer updatedEngineer,
BindingResult bindingResult,
@PathVariable("id") int id) {
if (bindingResult.hasErrors()) return "engineers/edit";
Engineer originalEngineer = engineersService.findOne(id);
engineersService.update(id, updatedEngineer, originalEngineer);
return "redirect:/engineers";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") int id) {
engineersService.delete(id);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(null);
}
return "redirect:/logout";
}
}
| src/main/java/ru/jbimer/core/controllers/EngineersController.java | mitrofmep-JBimer-fd7a0ba | [
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " } catch (Exception e) {\n model.addAttribute(\"message\", e.getMessage());\n }\n return \"collisions/index\";\n }\n @GetMapping(\"/{id}\")\n public String show(@PathVariable(\"id\") int id,\n @PathVariable(\"project_id\") int project_id,\n Model model,\n @ModelAttribute(\"engineer\") Engineer engineer) {",
"score": 81.72852495317233
},
{
"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": 80.062592463291
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " when(engineersService.findByIdFetchCollisions(id)).thenReturn(engineer);\n Model model = new ExtendedModelMap();\n String viewName = engineersController.show(id, model);\n assertEquals(\"engineers/show\", viewName);\n assertTrue(model.containsAttribute(\"engineer\"));\n assertSame(engineer, model.getAttribute(\"engineer\"));\n assertTrue(model.containsAttribute(\"collisions\"));\n assertSame(collisions, model.getAttribute(\"collisions\"));\n verify(engineersService).findByIdFetchCollisions(id);\n }",
"score": 72.86429892838339
},
{
"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": 72.12156067537377
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " @Test\n public void testEdit() throws Exception {\n int id = 1;\n Engineer engineer = new Engineer();\n when(engineersService.findOne(id)).thenReturn(engineer);\n Model model = new ExtendedModelMap();\n String viewName = engineersController.edit(model, id);\n assertEquals(\"engineers/edit\", viewName);\n assertTrue(model.containsAttribute(\"engineer\"));\n assertSame(engineer, model.getAttribute(\"engineer\"));",
"score": 71.36877771195975
}
] | 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": 39.178157870457895
},
{
"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": 32.67041371254906
},
{
"filename": "src/main/java/ru/jbimer/core/services/ProjectService.java",
"retrieved_chunk": "@Transactional(readOnly = true)\npublic class ProjectService {\n private final ProjectRepository projectRepository;\n private final CollisionsRepository collisionsRepository;\n @Autowired\n public ProjectService(ProjectRepository projectRepository, CollisionsRepository collisionsRepository) {\n this.projectRepository = projectRepository;\n this.collisionsRepository = collisionsRepository;\n }\n public List<Project> findAll() {",
"score": 30.009456591852267
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/CollisionsController.java",
"retrieved_chunk": " public String delete(@PathVariable(\"id\") int id, @PathVariable(\"project_id\") int project_id) {\n collisionsService.delete(id);\n return \"redirect:/projects/\" + project_id + \"/collisions\";\n }\n @PatchMapping(\"/{id}/release\")\n public String release(@PathVariable(\"id\") int id,\n @PathVariable(\"project_id\") int project_id) {\n collisionsService.release(id);\n return \"redirect:/projects/\" + project_id + \"/collisions/\" + id;\n }",
"score": 29.130618386487985
},
{
"filename": "src/main/java/ru/jbimer/core/repositories/CollisionsRepository.java",
"retrieved_chunk": " Optional<Collision> findByIdsForValidation(@Param(\"elemId1\") String elemId1,\n @Param(\"elemId2\") String elemId2,\n @Param(\"project\") Project project);\n @Modifying\n @Query(\"update Collision c set c.status = 'Done' where c.projectBase = :project \" +\n \"and c.createdAt < :currDate and (c.discipline1 = :disc1 and c.discipline2 = :disc2 \" +\n \"or c.discipline1 = :disc2 and c.discipline2 = :disc1)\")\n void updateStatus(@Param(\"currDate\") Date date,\n @Param(\"disc1\") String disc1,\n @Param(\"disc2\") String disc2,",
"score": 27.112359588366807
}
] | 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/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " @MockBean\n private EngineersController engineersController;\n @Test\n public void testIndex() throws Exception {\n List<Engineer> engineers = new ArrayList<>();\n engineers.add(new Engineer());\n when(engineersService.findAllSortedByCollisionsSize()).thenReturn(engineers);\n Model model = new ExtendedModelMap();\n String viewName = engineersController.index(model);\n assertEquals(\"engineers/index\", viewName);",
"score": 29.39115084649203
},
{
"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": 27.221547376100386
},
{
"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": 25.70555457344273
},
{
"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": 24.00895117373968
},
{
"filename": "src/test/java/ru/jbimer/core/controllers/EngineersControllerTest.java",
"retrieved_chunk": " assertTrue(model.containsAttribute(\"engineers\"));\n assertSame(engineers, model.getAttribute(\"engineers\"));\n verify(engineersService).findAllSortedByCollisionsSize();\n }\n @Test\n public void testShow() throws Exception {\n int id = 1;\n Engineer engineer = new Engineer();\n Set<Collision> collisions = new HashSet<>();\n engineer.setCollisions((List<Collision>) collisions);",
"score": 23.132053216397594
}
] | 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/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": 73.23433084510938
},
{
"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": 54.77203623213727
},
{
"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": 50.15494952320976
},
{
"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": 48.10512730620118
},
{
"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": 40.55235950768393
}
] | 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": 65.71006285337405
},
{
"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": 52.834200279662234
},
{
"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": 46.47743819365725
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/HomeController.java",
"retrieved_chunk": " this.collisionsService = collisionsService;\n this.projectService = projectService;\n }\n @GetMapping\n public String index() {\n return \"index_main\";\n }\n @GetMapping(\"/account\")\n public String showUserAccount(Model model) {\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();",
"score": 38.020316765741995
},
{
"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": 36.90069200822776
}
] | 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": " }\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": 56.46274802642745
},
{
"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": 52.33712711864022
},
{
"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": 45.51309788463107
},
{
"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": 42.26445724037185
},
{
"filename": "src/main/java/ru/jbimer/core/controllers/ReportUploadController.java",
"retrieved_chunk": " @Autowired\n public ReportUploadController(HtmlReportService htmlReportService, ProjectService projectService) {\n this.htmlReportService = htmlReportService;\n this.projectService = projectService;\n }\n @PostMapping()\n public String upload(@RequestParam(\"file\") MultipartFile file,\n Model model,\n @RequestParam(\"projectId\") int project_id) throws IOException {\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();",
"score": 41.66250902730586
}
] | java | (id, engineerDetails.getEngineer(), comment); |
package ru.jbimer.core.services;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.jbimer.core.dao.EngineerDAO;
import ru.jbimer.core.models.Collision;
import ru.jbimer.core.repositories.EngineersRepository;
import ru.jbimer.core.models.Engineer;
import java.util.*;
@Service
@Transactional(readOnly = true)
public class EngineersService{
private final EngineersRepository engineersRepository;
private final EngineerDAO engineerDAO;
private final PasswordEncoder passwordEncoder;
@Autowired
public EngineersService(EngineersRepository engineersRepository, EngineerDAO engineerDAO, PasswordEncoder passwordEncoder) {
this.engineersRepository = engineersRepository;
this.engineerDAO = engineerDAO;
this.passwordEncoder = passwordEncoder;
}
public Optional<Engineer> findByUsername(String username) {
return engineersRepository.findByUsername(username);
}
public List<Engineer> findAll() {
return engineersRepository.findAll();
}
public List<Engineer> findAllOnProject(int project_id) {
return engineersRepository.findAllOnProject(project_id);
}
public List<Engineer> findAllSortedByCollisionsSize() {
List<Engineer> engineers = new ArrayList<>(engineerDAO.index());
engineers.sort((e1, e2) -> {
int collisionsComparison = Integer.compare(e2.getCollisions().size(), e1.getCollisions().size());
if (collisionsComparison != 0) {
return collisionsComparison;
} else {
return Integer.compare(e1.getId(), e2.getId());
}
});
return engineers;
}
public Optional<Engineer> findByTelegramUsername(String telegramUsername) {
return engineersRepository.findByTelegramUsername(telegramUsername);
}
public Optional<Engineer> findByEmail(String email) {
return engineersRepository.findByEmail(email);
}
public Engineer findOne(int id) {
Optional<Engineer> foundEngineer = engineersRepository.findById(id);
return foundEngineer.orElse(null);
}
public Engineer findByIdFetchCollisions(int id) {
Optional< | Engineer> foundEngineer = engineersRepository.findByIdFetchCollisions(id); |
return foundEngineer.orElse(null);
}
@Transactional
public void register(Engineer engineer) {
engineer.setPassword(passwordEncoder.encode(engineer.getPassword()));
engineer.setRole("ROLE_USER");
engineersRepository.save(engineer);
}
@Transactional
public void update(int id, Engineer updatedEngineer, Engineer originalEngineer) {
originalEngineer.setDiscipline(updatedEngineer.getDiscipline());
originalEngineer.setFirstName(updatedEngineer.getFirstName());
originalEngineer.setLastName(updatedEngineer.getLastName());
engineersRepository.save(originalEngineer);
}
@Transactional
public void delete(int id) {
engineersRepository.deleteById(id);
}
public List<Collision> getCollisionsByEngineerId(int id) {
Optional<Engineer> engineer = engineersRepository.findById(id);
if (engineer.isPresent()) {
Hibernate.initialize(engineer.get().getCollisions());
return engineer.get().getCollisions();
}
else {
return Collections.emptyList();
}
}
@Transactional
public void save(Engineer engineer) {
engineersRepository.save(engineer);
}
}
| src/main/java/ru/jbimer/core/services/EngineersService.java | mitrofmep-JBimer-fd7a0ba | [
{
"filename": "src/main/java/ru/jbimer/core/repositories/EngineersRepository.java",
"retrieved_chunk": " Optional<Engineer> findByTelegramUsername(String telegramUsername);\n Optional<Engineer> findByEmail(String email);\n Optional<Engineer> findByUsername(String username);\n @Query(\"SELECT e FROM Engineer e LEFT JOIN FETCH e.collisions WHERE e.id = :id\")\n Optional<Engineer> findByIdFetchCollisions(@Param(\"id\") int id);\n @Query(\"SELECT e FROM Engineer e LEFT JOIN FETCH e.projects p where p.id = :project_id\")\n List<Engineer> findAllOnProject(@Param(\"project_id\") int id);\n}",
"score": 49.37564917770029
},
{
"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": 41.13050922168155
},
{
"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": 38.359499831845305
},
{
"filename": "src/main/java/ru/jbimer/core/services/EngineerDetailsService.java",
"retrieved_chunk": "import java.util.Optional;\n@Service\npublic class EngineerDetailsService implements UserDetailsService {\n private final EngineersRepository engineersRepository;\n @Autowired\n public EngineerDetailsService(EngineersRepository engineersRepository) {\n this.engineersRepository = engineersRepository;\n }\n @Override\n public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {",
"score": 37.267380176242014
},
{
"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": 32.2350998610977
}
] | java | Engineer> foundEngineer = engineersRepository.findByIdFetchCollisions(id); |
/*
* Copyright (c) 2023. MyWorld, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.myworldvw.buoy.mapping;
import com.myworldvw.buoy.Array;
import com.myworldvw.buoy.FieldDef;
import com.myworldvw.buoy.NativeMapper;
import com.myworldvw.buoy.Pointer;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;
public class FieldHandler<T> implements StructMappingHandler<T> {
protected final FieldDef model;
protected final Field field;
protected volatile VarHandle handle;
public FieldHandler(FieldDef model, Field field){
this.model = model;
this.field = field;
}
public VarHandle getHandle(MemoryLayout layout){
return layout.varHandle(MemoryLayout.PathElement.groupElement(model.name()));
}
public MethodHandle getAccessor(MemoryLayout layout, VarHandle.AccessMode mode){
return getHandle(layout).toMethodHandle(mode);
}
public MethodHandle getGetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.GET);
}
public MethodHandle getGetter(MemorySegment ptr, MemoryLayout layout){
return getGetter(layout).bindTo(ptr);
}
public MethodHandle getSetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.SET);
}
public MethodHandle getSetter(MemorySegment ptr, MemoryLayout layout){
return getSetter(layout).bindTo(ptr);
}
@Override
public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {
// Given the field type:
// If it's a VarHandle, we get a handle to the field in the struct
// If it's a MemorySegment, we calculate the field offset and assign it
// If it's an Array, we bind it to the segment
// If it's an object, we determine if it's a nested struct or a pointer to a struct,
// and we populate it with the offset of the field (nested) *or* the memory address
// contained in the field (pointer) as the object's self-pointer segment
if(Util.skipField(field, target)){
return;
}
var fieldType = field.getType();
if(fieldType.equals(VarHandle.class)){
if(handle == null){
| handle = getHandle(mapper.getLayout(target.getClass())); |
}
field.set(target, handle);
}else if(fieldType.equals(MemorySegment.class)){
field.set(target, segmentForField(mapper, target, segment));
}else if(fieldType.equals(Array.class)){
field.set(target, new Array<>(
arraySegmentForField(mapper, target, segment),
mapper.getLayout(model.type()),
model.type(),
model.isPointer()
));
} else{
var structDef = mapper.getOrDefineStruct(fieldType);
if(structDef == null){
throw new IllegalArgumentException("Not a mappable type for a field handle: " + fieldType);
}
var structSegment = segmentForField(mapper, target, segment);
if(model.isPointer()){
// If this is a pointer type, we have to construct a new segment starting at the address
// contained in this segment, with the length of the field type.
structSegment = MemorySegment.ofAddress(
Pointer.getAddress(structSegment),
mapper.sizeOf(model.type()),
structSegment.scope());
}
var nestedTarget = field.get(target);
if(nestedTarget != null){
mapper.populate(nestedTarget, structSegment);
}
}
}
protected MemorySegment arraySegmentForField(NativeMapper mapper, Object target, MemorySegment segment){
// 1. If model is a pointer (*type[length]), dereference to get the address of the array.
// 2. Create a segment appropriate to the array type * length
var fieldSegment = segmentForField(mapper, target, segment);
var address = fieldSegment.address();
if(model.isPointer()){
address = Pointer.getAddress(fieldSegment);
}
var elementType = mapper.getLayout(model.type());
return MemorySegment.ofAddress(address, elementType.byteSize() * model.array(), segment.scope());
}
protected MemorySegment segmentForField(NativeMapper mapper, Object target, MemorySegment segment){
var offset = mapper.getLayout(target.getClass()).byteOffset(MemoryLayout.PathElement.groupElement(model.name()));
return model.isPointer()
? segment.asSlice(offset, ValueLayout.ADDRESS.byteSize())
: segment.asSlice(offset, mapper.sizeOf(model));
}
}
| lib/src/main/java/com/myworldvw/buoy/mapping/FieldHandler.java | MyWorldLLC-Buoy-c7d77a1 | [
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/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": 67.90481984846163
},
{
"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": 61.859700869928716
},
{
"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": 59.835091796563624
},
{
"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": 50.458280996506026
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " var layouts = new ArrayList<>();\n for(int i = 0; i < def.fields().length; i++){\n var field = def.fields()[i];\n var layout = getLayout(field).withName(field.name());\n // Track largest element so that we can set\n // end padding of the struct accordingly\n if(largestElement == null || largestElement.bitSize() < layout.bitSize()){\n largestElement = layout;\n }\n if(!def.isPacked()){",
"score": 49.24408017266731
}
] | java | handle = getHandle(mapper.getLayout(target.getClass())); |
/*
* Copyright (c) 2023. MyWorld, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.myworldvw.buoy.mapping;
import com.myworldvw.buoy.Array;
import com.myworldvw.buoy.FieldDef;
import com.myworldvw.buoy.NativeMapper;
import com.myworldvw.buoy.Pointer;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;
public class FieldHandler<T> implements StructMappingHandler<T> {
protected final FieldDef model;
protected final Field field;
protected volatile VarHandle handle;
public FieldHandler(FieldDef model, Field field){
this.model = model;
this.field = field;
}
public VarHandle getHandle(MemoryLayout layout){
return layout.varHandle(MemoryLayout.PathElement.groupElement(model.name()));
}
public MethodHandle getAccessor(MemoryLayout layout, VarHandle.AccessMode mode){
return getHandle(layout).toMethodHandle(mode);
}
public MethodHandle getGetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.GET);
}
public MethodHandle getGetter(MemorySegment ptr, MemoryLayout layout){
return getGetter(layout).bindTo(ptr);
}
public MethodHandle getSetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.SET);
}
public MethodHandle getSetter(MemorySegment ptr, MemoryLayout layout){
return getSetter(layout).bindTo(ptr);
}
@Override
public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {
// Given the field type:
// If it's a VarHandle, we get a handle to the field in the struct
// If it's a MemorySegment, we calculate the field offset and assign it
// If it's an Array, we bind it to the segment
// If it's an object, we determine if it's a nested struct or a pointer to a struct,
// and we populate it with the offset of the field (nested) *or* the memory address
// contained in the field (pointer) as the object's self-pointer segment
if(Util.skipField(field, target)){
return;
}
var fieldType = field.getType();
if(fieldType.equals(VarHandle.class)){
if(handle == null){
handle = getHandle(mapper.getLayout(target.getClass()));
}
field.set(target, handle);
}else if(fieldType.equals(MemorySegment.class)){
field.set(target, segmentForField(mapper, target, segment));
}else if(fieldType.equals(Array.class)){
field.set(target, new Array<>(
arraySegmentForField(mapper, target, segment),
mapper.getLayout(model.type()),
model.type(),
model.isPointer()
));
} else{
var structDef = mapper.getOrDefineStruct(fieldType);
if(structDef == null){
throw new IllegalArgumentException("Not a mappable type for a field handle: " + fieldType);
}
var structSegment = segmentForField(mapper, target, segment);
if(model.isPointer()){
// If this is a pointer type, we have to construct a new segment starting at the address
// contained in this segment, with the length of the field type.
structSegment = MemorySegment.ofAddress(
Pointer.getAddress(structSegment),
mapper.sizeOf(model.type()),
structSegment.scope());
}
var nestedTarget = field.get(target);
if(nestedTarget != null){
mapper.populate(nestedTarget, structSegment);
}
}
}
protected MemorySegment arraySegmentForField(NativeMapper mapper, Object target, MemorySegment segment){
// 1. If model is a pointer (*type[length]), dereference to get the address of the array.
// 2. Create a segment appropriate to the array type * length
var fieldSegment = segmentForField(mapper, target, segment);
var address = fieldSegment.address();
if(model.isPointer()){
address = Pointer.getAddress(fieldSegment);
}
var elementType = mapper.getLayout(model.type());
return MemorySegment.ofAddress(address, elementType.byteSize() * model.array(), segment.scope());
}
protected MemorySegment segmentForField(NativeMapper mapper, Object target, MemorySegment segment){
var offset = | mapper.getLayout(target.getClass()).byteOffset(MemoryLayout.PathElement.groupElement(model.name())); |
return model.isPointer()
? segment.asSlice(offset, ValueLayout.ADDRESS.byteSize())
: segment.asSlice(offset, mapper.sizeOf(model));
}
}
| lib/src/main/java/com/myworldvw/buoy/mapping/FieldHandler.java | MyWorldLLC-Buoy-c7d77a1 | [
{
"filename": "lib/src/main/java/com/myworldvw/buoy/Pointer.java",
"retrieved_chunk": " return MemorySegment.ofAddress(p.address(), targetType.byteSize(), p.scope());\n }\n public static MemorySegment cast(MemorySegment p, MemoryLayout targetType, SegmentScope scope){\n return MemorySegment.ofAddress(p.address(), targetType.byteSize(), scope);\n }\n public static long getAddress(MemorySegment p){\n return p.get(ValueLayout.ADDRESS, 0).address();\n }\n public static void setAddress(MemorySegment p, long a){\n p.set(ValueLayout.ADDRESS, 0, MemorySegment.ofAddress(a));",
"score": 49.42502807983432
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " }\n public SymbolLookup getLookup(){\n return lookup;\n }\n public void defineStruct(StructDef model){\n if(structs.containsKey(model.name())){\n throw new IllegalStateException(\"Struct %s is already defined\".formatted(model.name()));\n }\n structs.put(model.name(), model);\n }",
"score": 43.78692972079472
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/NativeMapper.java",
"retrieved_chunk": " }\n public <T> Array<T> arrayOf(MemorySegment array, Class<T> type, boolean isPointer, long length, SegmentScope scope){\n var segment = Array.cast(array, getLayout(type), length, scope);\n return arrayOf(segment, type, isPointer);\n }\n public <T> Array<T> arrayOf(MemorySegment array, Class<T> type){\n return arrayOf(array, type, false);\n }\n public <T> Array<T> arrayOf(MemorySegment array, Class<T> type, boolean isPointer){\n return new Array<>(array, getLayout(type), type, isPointer);",
"score": 38.887815963272395
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/StructMappingHandler.java",
"retrieved_chunk": " default T handle(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException{\n fill(mapper, segment, target);\n return target;\n }\n}",
"score": 38.22431123049114
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/GlobalHandler.java",
"retrieved_chunk": " if(symbolPtr == null){\n symbolPtr = mapper.getLookup().find(name)\n .map(symbol -> Pointer.cast(symbol, mapper.getLayout(pointer ? MemorySegment.class : type)))\n .orElseThrow(() -> new IllegalArgumentException(\"Symbol \" + name + \" not found\"));\n }\n field.set(target, symbolPtr);\n }\n}",
"score": 35.81886180184672
}
] | java | mapper.getLayout(target.getClass()).byteOffset(MemoryLayout.PathElement.groupElement(model.name())); |
/*
* Copyright (c) 2023. MyWorld, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.myworldvw.buoy.mapping;
import com.myworldvw.buoy.Array;
import com.myworldvw.buoy.FieldDef;
import com.myworldvw.buoy.NativeMapper;
import com.myworldvw.buoy.Pointer;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;
public class FieldHandler<T> implements StructMappingHandler<T> {
protected final FieldDef model;
protected final Field field;
protected volatile VarHandle handle;
public FieldHandler(FieldDef model, Field field){
this.model = model;
this.field = field;
}
public VarHandle getHandle(MemoryLayout layout){
return layout.varHandle(MemoryLayout.PathElement.groupElement(model.name()));
}
public MethodHandle getAccessor(MemoryLayout layout, VarHandle.AccessMode mode){
return getHandle(layout).toMethodHandle(mode);
}
public MethodHandle getGetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.GET);
}
public MethodHandle getGetter(MemorySegment ptr, MemoryLayout layout){
return getGetter(layout).bindTo(ptr);
}
public MethodHandle getSetter(MemoryLayout layout){
return getAccessor(layout, VarHandle.AccessMode.SET);
}
public MethodHandle getSetter(MemorySegment ptr, MemoryLayout layout){
return getSetter(layout).bindTo(ptr);
}
@Override
public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {
// Given the field type:
// If it's a VarHandle, we get a handle to the field in the struct
// If it's a MemorySegment, we calculate the field offset and assign it
// If it's an Array, we bind it to the segment
// If it's an object, we determine if it's a nested struct or a pointer to a struct,
// and we populate it with the offset of the field (nested) *or* the memory address
// contained in the field (pointer) as the object's self-pointer segment
if(Util.skipField(field, target)){
return;
}
var fieldType = field.getType();
if(fieldType.equals(VarHandle.class)){
if(handle == null){
handle = getHandle(mapper.getLayout(target.getClass()));
}
field.set(target, handle);
}else if(fieldType.equals(MemorySegment.class)){
field.set(target, segmentForField(mapper, target, segment));
}else if(fieldType.equals(Array.class)){
field.set(target, new Array<>(
arraySegmentForField(mapper, target, segment),
mapper.getLayout(model.type()),
model.type(),
model.isPointer()
));
} else{
| var structDef = mapper.getOrDefineStruct(fieldType); |
if(structDef == null){
throw new IllegalArgumentException("Not a mappable type for a field handle: " + fieldType);
}
var structSegment = segmentForField(mapper, target, segment);
if(model.isPointer()){
// If this is a pointer type, we have to construct a new segment starting at the address
// contained in this segment, with the length of the field type.
structSegment = MemorySegment.ofAddress(
Pointer.getAddress(structSegment),
mapper.sizeOf(model.type()),
structSegment.scope());
}
var nestedTarget = field.get(target);
if(nestedTarget != null){
mapper.populate(nestedTarget, structSegment);
}
}
}
protected MemorySegment arraySegmentForField(NativeMapper mapper, Object target, MemorySegment segment){
// 1. If model is a pointer (*type[length]), dereference to get the address of the array.
// 2. Create a segment appropriate to the array type * length
var fieldSegment = segmentForField(mapper, target, segment);
var address = fieldSegment.address();
if(model.isPointer()){
address = Pointer.getAddress(fieldSegment);
}
var elementType = mapper.getLayout(model.type());
return MemorySegment.ofAddress(address, elementType.byteSize() * model.array(), segment.scope());
}
protected MemorySegment segmentForField(NativeMapper mapper, Object target, MemorySegment segment){
var offset = mapper.getLayout(target.getClass()).byteOffset(MemoryLayout.PathElement.groupElement(model.name()));
return model.isPointer()
? segment.asSlice(offset, ValueLayout.ADDRESS.byteSize())
: segment.asSlice(offset, mapper.sizeOf(model));
}
}
| lib/src/main/java/com/myworldvw/buoy/mapping/FieldHandler.java | MyWorldLLC-Buoy-c7d77a1 | [
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/SelfPointerHandler.java",
"retrieved_chunk": " protected final Field field;\n public SelfPointerHandler(Field field){\n this.field = field;\n }\n @Override\n public void fill(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException {\n if(!Util.skipField(field, target)){\n field.set(target, segment);\n }\n }",
"score": 51.058758047431
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/GlobalHandler.java",
"retrieved_chunk": " if(symbolPtr == null){\n symbolPtr = mapper.getLookup().find(name)\n .map(symbol -> Pointer.cast(symbol, mapper.getLayout(pointer ? MemorySegment.class : type)))\n .orElseThrow(() -> new IllegalArgumentException(\"Symbol \" + name + \" not found\"));\n }\n field.set(target, symbolPtr);\n }\n}",
"score": 46.330669001115695
},
{
"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": 44.84117452424317
},
{
"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": 44.349398459110326
},
{
"filename": "lib/src/main/java/com/myworldvw/buoy/mapping/StructMappingHandler.java",
"retrieved_chunk": " default T handle(NativeMapper mapper, MemorySegment segment, T target) throws IllegalAccessException{\n fill(mapper, segment, target);\n return target;\n }\n}",
"score": 43.987210026007006
}
] | java | var structDef = mapper.getOrDefineStruct(fieldType); |
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
| instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)"); |
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
| src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " 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": 68.19797164712975
},
{
"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": 66.03849770782715
},
{
"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": 62.49934366735487
},
{
"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": 61.47285876334492
},
{
"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": 50.92861883032498
}
] | 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/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": 143.03978752281415
},
{
"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": 142.09316479310343
},
{
"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": 74.13465890078827
},
{
"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": 72.05014771101249
},
{
"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": 62.893125767415256
}
] | 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/velocity/messageunsign/SessionChatListener.java",
"retrieved_chunk": " this.plugin = plugin;\n }\n @Subscribe\n public void onChat(PacketReceiveEvent event) {\n if (!(event.getPacket() instanceof SessionPlayerChat)) {\n return;\n }\n SessionPlayerChat chatPacket = (SessionPlayerChat) event.getPacket();\n ConnectedPlayer player = (ConnectedPlayer) event.getPlayer();\n String chatMessage = chatPacket.getMessage();",
"score": 33.540357313937584
},
{
"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": 31.745344090944418
},
{
"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": 29.428020203782825
},
{
"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": 28.68229791124415
},
{
"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": 28.601565018006777
}
] | java | .getEventManager(), neoProtectVelocity.getLogger())); |
package de.cubeattack.neoprotect.core.request;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Formatter;
import java.util.concurrent.TimeUnit;
public class RestAPIManager {
private final OkHttpClient client = new OkHttpClient();
private final String baseURL = "https://api.neoprotect.net/v2";
private final Core core;
public RestAPIManager(Core core) {
this.core = core;
}
{
client.setConnectTimeout(4, TimeUnit.SECONDS);
}
protected ResponseManager request(RequestType type, RequestBody requestBody, Object... value) {
if (type.toString().startsWith("GET")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).build()));
} else if (type.toString().startsWith("POST")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).post(requestBody).build()));
} else {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).delete().build()));
}
}
protected Response callRequest(Request request) {
try {
return client.newCall(request).execute();
} catch (UnknownHostException | SocketTimeoutException | SocketException connectionException) {
if(!request.url().toString().equals(core.getRestAPI().getStatsServer())) {
core.severe(request + " failed cause (" + connectionException + ")");
}else
core.debug(request + " failed cause (" + connectionException + ")");
} catch (Exception exception) {
| core.severe(exception.getMessage(), exception); |
}
return null;
}
protected Request.Builder defaultBuilder() {
return defaultBuilder(Config.getAPIKey());
}
protected Request.Builder defaultBuilder(String apiKey) {
return new Request.Builder()
.addHeader("accept", "*/*")
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json");
}
protected String getSubDirectory(RequestType type, Object... values) {
switch (type) {
case GET_ATTACKS: {
return new Formatter().format("/attacks", values).toString();
}
case GET_ATTACKS_GAMESHIELD: {
return new Formatter().format("/attacks/gameshield/%s", values).toString();
}
case GET_GAMESHIELD_BACKENDS: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_CREATE: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case DELETE_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case POST_GAMESHIELD_BACKEND_AVAILABLE: {
return new Formatter().format("/gameshield/backends/available", values).toString();
}
case GET_GAMESHIELD_DOMAINS: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_CREATE: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_AVAILABLE: {
return new Formatter().format("/gameshields/domains/available", values).toString();
}
case DELETE_GAMESHIELD_DOMAIN: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case GET_GAMESHIELD_FRONTENDS: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case POST_GAMESHIELD_FRONTEND_CREATE: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case GET_GAMESHIELDS: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_CREATE: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_UPDATE: {
return new Formatter().format("/gameshields/%s/settings", values).toString();
}
case POST_GAMESHIELD_UPDATE_REGION: {
return new Formatter().format("/gameshields/%s/region/%s", values).toString();
}
case GET_GAMESHIELD_PLAN: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_PLAN_UPGRADE: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_UPDATE_NAME: {
return new Formatter().format("/gameshields/%s/name", values).toString();
}
case POST_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case DELETE_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case POST_GAMESHIELD_UPDATE_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case DELETE_GAMESHIELD_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case POST_GAMESHIELD_AVAILABLE: {
return new Formatter().format("/gameshields/available", values).toString();
}
case GET_GAMESHIELD_INFO: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case DELETE_GAMESHIELD: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case GET_GAMESHIELD_LASTSTATS: {
return new Formatter().format("/gameshields/%s/lastStats", values).toString();
}
case GET_GAMESHIELD_ISUNDERATTACK: {
return new Formatter().format("/gameshields/%s/isUnderAttack", values).toString();
}
case GET_GAMESHIELD_BANDWIDTH: {
return new Formatter().format("/gameshields/%s/bandwidth", values).toString();
}
case GET_GAMESHIELD_ANALYTICS: {
return new Formatter().format("/gameshields/%s/analytics/%s", values).toString();
}
case GET_FIREWALLS: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case POST_FIREWALL_CREATE: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case DELETE_FIREWALL: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case GET_PLANS_AVAILABLE: {
return new Formatter().format("/plans/gameshield", values).toString();
}
case GET_PROFILE_TRANSACTIONS: {
return new Formatter().format("/profile/transactions", values).toString();
}
case GET_PROFILE_INFOS: {
return new Formatter().format("/profile/infos", values).toString();
}
case GET_PROFILE_GENERALINFORMATION: {
return new Formatter().format("/profile/generalInformation", values).toString();
}
case GET_NEO_SERVER_IPS: {
return new Formatter().format("/public/servers", values).toString();
}
case GET_NEO_SERVER_REGIONS: {
return new Formatter().format("/public/regions", values).toString();
}
case GET_VULNERABILITIES_GAMESHIELD: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case POST_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_VULNERABILITIES_ALL: {
return new Formatter().format("/vulnerabilities", values).toString();
}
case DELETE_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_WEBHOOKS: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_CREATE: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_TEST: {
return new Formatter().format("/webhooks/%s/%s/test", values).toString();
}
case DELETE_WEBHOOK: {
return new Formatter().format("/webhooks/%s/%s", values).toString();
}
default: {
return null;
}
}
}
public String getBaseURL() {
return baseURL;
}
}
| src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\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": 36.12053416225561
},
{
"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": 35.73471818698667
},
{
"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": 35.35683457526509
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject(\"gameShieldSettings\");\n String mitigationSensitivity = settings.getString(\"mitigationSensitivity\");\n if (mitigationSensitivity.equals(\"UNDER_ATTACK\")) {\n rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(\"mitigationSensitivity\", \"MEDIUM\").toString()),\n Config.getGameShieldID());\n return false;\n } else {\n rest.request(RequestType.POST_GAMESHIELD_UPDATE,\n RequestBody.create(MediaType.parse(\"application/json\"), settings.put(\"mitigationSensitivity\", \"UNDER_ATTACK\").toString()),",
"score": 34.58008431618528
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " } catch (Exception exception) {\n // Closing the channel because we do not want people on the server with a proxy ip\n ctx.channel().close();\n // Logging for the lovely server admins :)\n instance.getCore().severe(\"Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.\", exception);\n }\n }\n }\n @ChannelHandler.Sharable\n class ServerChannelInitializer extends ChannelInboundHandlerAdapter {",
"score": 32.38882623699909
}
] | java | core.severe(exception.getMessage(), exception); |
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
| instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)"); |
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
| src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/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": 176.37164585754954
},
{
"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": 176.17904117471105
},
{
"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": 124.12277002271269
},
{
"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": 120.49614590133973
},
{
"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": 99.08938859176821
}
] | 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/Core.java",
"retrieved_chunk": " private final ConcurrentHashMap<String, ArrayList<DebugPingResponse>> debugPingResponses = new ConcurrentHashMap<>();\n private VersionUtils.Result versionResult;\n private boolean isDebugRunning = false;\n public Core(NeoProtectPlugin plugin) {\n LogManager.getLogger().setLogger(plugin.getLogger());\n this.plugin = plugin;\n this.versionResult = VersionUtils.checkVersion(\"NeoProtect\", \"NeoPlugin\", \"v\" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message();\n FileUtils config = new FileUtils(Core.class.getResourceAsStream(\"/config.yml\"), \"plugins/NeoProtect\", \"config.yml\", false);\n FileUtils languageEN = new FileUtils(Core.class.getResourceAsStream(\"/language_en.properties\"), \"plugins/NeoProtect/languages\", \"language_en.properties\", true);\n FileUtils languageDE = new FileUtils(Core.class.getResourceAsStream(\"/language_de.properties\"), \"plugins/NeoProtect/languages\", \"language_de.properties\", true);",
"score": 62.72226662248097
},
{
"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": 51.21800804200468
},
{
"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": 43.625097260008445
},
{
"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": 39.68034572358133
},
{
"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": 38.23490085789717
}
] | java | core.severe("Failed to load API-Key. Key is null or not valid"); |
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
| instance.getCore().severe("Cannot inject incoming channel " + channel, ex); |
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
| src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " 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": 115.89370544334311
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n }\n public void addProxyProtocolHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress) {\n channel.pipeline().names().forEach((n) -> {\n if (n.equals(\"HAProxyMessageDecoder#0\"))\n channel.pipeline().remove(\"HAProxyMessageDecoder#0\");\n if (n.equals(\"ProxyProtocol$1#0\"))\n channel.pipeline().remove(\"ProxyProtocol$1#0\");\n });\n channel.pipeline().addFirst(\"haproxy-decoder\", new HAProxyMessageDecoder());",
"score": 89.89278136222296
},
{
"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": 83.79981318546342
},
{
"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": 82.87710941897517
},
{
"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": 79.24430427422409
}
] | 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": 58.598802963419914
},
{
"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": 58.40496958097937
},
{
"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": 36.388959482490634
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " private final ConcurrentHashMap<String, ArrayList<DebugPingResponse>> debugPingResponses = new ConcurrentHashMap<>();\n private VersionUtils.Result versionResult;\n private boolean isDebugRunning = false;\n public Core(NeoProtectPlugin plugin) {\n LogManager.getLogger().setLogger(plugin.getLogger());\n this.plugin = plugin;\n this.versionResult = VersionUtils.checkVersion(\"NeoProtect\", \"NeoPlugin\", \"v\" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message();\n FileUtils config = new FileUtils(Core.class.getResourceAsStream(\"/config.yml\"), \"plugins/NeoProtect\", \"config.yml\", false);\n FileUtils languageEN = new FileUtils(Core.class.getResourceAsStream(\"/language_en.properties\"), \"plugins/NeoProtect/languages\", \"language_en.properties\", true);\n FileUtils languageDE = new FileUtils(Core.class.getResourceAsStream(\"/language_de.properties\"), \"plugins/NeoProtect/languages\", \"language_de.properties\", true);",
"score": 33.42452926464085
},
{
"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": 22.562390147519874
}
] | java | core.severe("Failed to load GameshieldID. ID is null"); |
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@SuppressWarnings("unused")
public class Config {
private static String APIKey;
private static String language;
private static boolean proxyProtocol;
private static String gameShieldID;
private static String backendID;
private static String geyserBackendID;
private static boolean updateIP;
private static boolean debugMode;
private static String geyserServerIP;
private static String updateSetting;
private static Core core;
private static FileUtils fileUtils;
public static void loadConfig(Core core, FileUtils config) {
Config.core = core;
fileUtils = config;
APIKey = config.getString("APIKey", "");
language = config.getString("defaultLanguage", Locale.ENGLISH.toLanguageTag());
proxyProtocol = config.getBoolean("ProxyProtocol", true);
gameShieldID = config.getString("gameshield.serverId", "");
backendID = config.getString("gameshield.backendId", "");
geyserBackendID = config.getString("gameshield.geyserBackendId", "");
updateIP = config.getBoolean("gameshield.autoUpdateIP", false);
debugMode = config.getBoolean("DebugMode", false);
geyserServerIP = config.getString("geyserServerIP", "127.0.0.1");
if (APIKey.length() != 64) {
core.severe("Failed to load API-Key. Key is null or not valid");
return;
}
if (gameShieldID.isEmpty()) {
core.severe("Failed to load GameshieldID. ID is null");
return;
}
if (backendID.isEmpty()) {
core.severe("Failed to load BackendID. ID is null");
return;
}
core.info("API-Key loaded successful '" + "******************************" + APIKey.substring(32) + "'");
core.info("GameshieldID loaded successful '" + gameShieldID + "'");
| core.info("BackendID loaded successful '" + backendID + "'"); |
}
public static String getAPIKey() {
return APIKey;
}
public static String getLanguage() {
return language;
}
public static String getGameShieldID() {
return gameShieldID;
}
public static String getBackendID() {
return backendID;
}
public static String getGeyserBackendID() {
return geyserBackendID;
}
public static boolean isProxyProtocol() {
return proxyProtocol;
}
public static boolean isUpdateIP() {
return updateIP;
}
public static boolean isDebugMode() {
return debugMode;
}
public static String getGeyserServerIP() {
return geyserServerIP;
}
public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {
return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);
}
public static void setAPIKey(String key) {
fileUtils.set("APIKey", key);
fileUtils.save();
APIKey = key;
}
public static void setGameShieldID(String id) {
fileUtils.set("gameshield.serverId", id);
fileUtils.save();
gameShieldID = id;
}
public static void setBackendID(String id) {
fileUtils.set("gameshield.backendId", id);
fileUtils.save();
backendID = id;
}
public static void setGeyserBackendID(String id) {
fileUtils.set("gameshield.geyserBackendId", id);
fileUtils.save();
geyserBackendID = id;
}
public static void addAutoUpdater(boolean basicPlan) {
if (basicPlan) {
fileUtils.remove("AutoUpdater");
} else if (!fileUtils.getConfig().isSet("AutoUpdater")) {
fileUtils.getConfig().set("AutoUpdater", "ENABLED");
}
List<String> description = new ArrayList<>();
description.add("This setting is only for paid costumer and allow you to disable the AutoUpdater");
description.add("'ENABLED' (Recommended/Default) Update/Downgrade plugin to the current version ");
description.add("'DISABLED' AutoUpdater just disabled");
description.add("'DEV' Only update to the latest version (Please never use this)");
fileUtils.getConfig().setComments("AutoUpdater", description);
fileUtils.save();
updateSetting = fileUtils.getString("AutoUpdater", "ENABLED");
}
}
| src/main/java/de/cubeattack/neoprotect/core/Config.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " 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": 45.92504983490754
},
{
"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": 45.83044140938724
},
{
"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": 41.30667563958468
},
{
"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": 39.32631271833415
},
{
"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": 39.32631271833415
}
] | java | core.info("BackendID loaded successful '" + backendID + "'"); |
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@SuppressWarnings("unused")
public class Config {
private static String APIKey;
private static String language;
private static boolean proxyProtocol;
private static String gameShieldID;
private static String backendID;
private static String geyserBackendID;
private static boolean updateIP;
private static boolean debugMode;
private static String geyserServerIP;
private static String updateSetting;
private static Core core;
private static FileUtils fileUtils;
public static void loadConfig(Core core, FileUtils config) {
Config.core = core;
fileUtils = config;
APIKey = config.getString("APIKey", "");
language = config.getString("defaultLanguage", Locale.ENGLISH.toLanguageTag());
proxyProtocol = config.getBoolean("ProxyProtocol", true);
gameShieldID = config.getString("gameshield.serverId", "");
backendID = config.getString("gameshield.backendId", "");
geyserBackendID = config.getString("gameshield.geyserBackendId", "");
updateIP = config.getBoolean("gameshield.autoUpdateIP", false);
debugMode = config.getBoolean("DebugMode", false);
geyserServerIP = config.getString("geyserServerIP", "127.0.0.1");
if (APIKey.length() != 64) {
core.severe("Failed to load API-Key. Key is null or not valid");
return;
}
if (gameShieldID.isEmpty()) {
core.severe("Failed to load GameshieldID. ID is null");
return;
}
if (backendID.isEmpty()) {
core.severe("Failed to load BackendID. ID is null");
return;
}
| core.info("API-Key loaded successful '" + "******************************" + APIKey.substring(32) + "'"); |
core.info("GameshieldID loaded successful '" + gameShieldID + "'");
core.info("BackendID loaded successful '" + backendID + "'");
}
public static String getAPIKey() {
return APIKey;
}
public static String getLanguage() {
return language;
}
public static String getGameShieldID() {
return gameShieldID;
}
public static String getBackendID() {
return backendID;
}
public static String getGeyserBackendID() {
return geyserBackendID;
}
public static boolean isProxyProtocol() {
return proxyProtocol;
}
public static boolean isUpdateIP() {
return updateIP;
}
public static boolean isDebugMode() {
return debugMode;
}
public static String getGeyserServerIP() {
return geyserServerIP;
}
public static VersionUtils.UpdateSetting getAutoUpdaterSettings() {
return VersionUtils.UpdateSetting.getByNameOrDefault(updateSetting);
}
public static void setAPIKey(String key) {
fileUtils.set("APIKey", key);
fileUtils.save();
APIKey = key;
}
public static void setGameShieldID(String id) {
fileUtils.set("gameshield.serverId", id);
fileUtils.save();
gameShieldID = id;
}
public static void setBackendID(String id) {
fileUtils.set("gameshield.backendId", id);
fileUtils.save();
backendID = id;
}
public static void setGeyserBackendID(String id) {
fileUtils.set("gameshield.geyserBackendId", id);
fileUtils.save();
geyserBackendID = id;
}
public static void addAutoUpdater(boolean basicPlan) {
if (basicPlan) {
fileUtils.remove("AutoUpdater");
} else if (!fileUtils.getConfig().isSet("AutoUpdater")) {
fileUtils.getConfig().set("AutoUpdater", "ENABLED");
}
List<String> description = new ArrayList<>();
description.add("This setting is only for paid costumer and allow you to disable the AutoUpdater");
description.add("'ENABLED' (Recommended/Default) Update/Downgrade plugin to the current version ");
description.add("'DISABLED' AutoUpdater just disabled");
description.add("'DEV' Only update to the latest version (Please never use this)");
fileUtils.getConfig().setComments("AutoUpdater", description);
fileUtils.save();
updateSetting = fileUtils.getString("AutoUpdater", "ENABLED");
}
}
| src/main/java/de/cubeattack/neoprotect/core/Config.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\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": 43.245873671148075
},
{
"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": 41.27375847861944
},
{
"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": 36.962026196659274
},
{
"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": 30.315313390800156
},
{
"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": 30.315313390800156
}
] | 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": 45.02249369419372
},
{
"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": 43.95976576905663
},
{
"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": 39.45997668369752
},
{
"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": 35.342836791376065
},
{
"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": 35.342836791376065
}
] | java | core.info("GameshieldID loaded successful '" + gameShieldID + "'"); |
package de.cubeattack.neoprotect.core.request;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Formatter;
import java.util.concurrent.TimeUnit;
public class RestAPIManager {
private final OkHttpClient client = new OkHttpClient();
private final String baseURL = "https://api.neoprotect.net/v2";
private final Core core;
public RestAPIManager(Core core) {
this.core = core;
}
{
client.setConnectTimeout(4, TimeUnit.SECONDS);
}
protected ResponseManager request(RequestType type, RequestBody requestBody, Object... value) {
if (type.toString().startsWith("GET")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).build()));
} else if (type.toString().startsWith("POST")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).post(requestBody).build()));
} else {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).delete().build()));
}
}
protected Response callRequest(Request request) {
try {
return client.newCall(request).execute();
} catch (UnknownHostException | SocketTimeoutException | SocketException connectionException) {
if(!request.url().toString() | .equals(core.getRestAPI().getStatsServer())) { |
core.severe(request + " failed cause (" + connectionException + ")");
}else
core.debug(request + " failed cause (" + connectionException + ")");
} catch (Exception exception) {
core.severe(exception.getMessage(), exception);
}
return null;
}
protected Request.Builder defaultBuilder() {
return defaultBuilder(Config.getAPIKey());
}
protected Request.Builder defaultBuilder(String apiKey) {
return new Request.Builder()
.addHeader("accept", "*/*")
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json");
}
protected String getSubDirectory(RequestType type, Object... values) {
switch (type) {
case GET_ATTACKS: {
return new Formatter().format("/attacks", values).toString();
}
case GET_ATTACKS_GAMESHIELD: {
return new Formatter().format("/attacks/gameshield/%s", values).toString();
}
case GET_GAMESHIELD_BACKENDS: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_CREATE: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case DELETE_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case POST_GAMESHIELD_BACKEND_AVAILABLE: {
return new Formatter().format("/gameshield/backends/available", values).toString();
}
case GET_GAMESHIELD_DOMAINS: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_CREATE: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_AVAILABLE: {
return new Formatter().format("/gameshields/domains/available", values).toString();
}
case DELETE_GAMESHIELD_DOMAIN: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case GET_GAMESHIELD_FRONTENDS: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case POST_GAMESHIELD_FRONTEND_CREATE: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case GET_GAMESHIELDS: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_CREATE: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_UPDATE: {
return new Formatter().format("/gameshields/%s/settings", values).toString();
}
case POST_GAMESHIELD_UPDATE_REGION: {
return new Formatter().format("/gameshields/%s/region/%s", values).toString();
}
case GET_GAMESHIELD_PLAN: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_PLAN_UPGRADE: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_UPDATE_NAME: {
return new Formatter().format("/gameshields/%s/name", values).toString();
}
case POST_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case DELETE_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case POST_GAMESHIELD_UPDATE_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case DELETE_GAMESHIELD_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case POST_GAMESHIELD_AVAILABLE: {
return new Formatter().format("/gameshields/available", values).toString();
}
case GET_GAMESHIELD_INFO: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case DELETE_GAMESHIELD: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case GET_GAMESHIELD_LASTSTATS: {
return new Formatter().format("/gameshields/%s/lastStats", values).toString();
}
case GET_GAMESHIELD_ISUNDERATTACK: {
return new Formatter().format("/gameshields/%s/isUnderAttack", values).toString();
}
case GET_GAMESHIELD_BANDWIDTH: {
return new Formatter().format("/gameshields/%s/bandwidth", values).toString();
}
case GET_GAMESHIELD_ANALYTICS: {
return new Formatter().format("/gameshields/%s/analytics/%s", values).toString();
}
case GET_FIREWALLS: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case POST_FIREWALL_CREATE: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case DELETE_FIREWALL: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case GET_PLANS_AVAILABLE: {
return new Formatter().format("/plans/gameshield", values).toString();
}
case GET_PROFILE_TRANSACTIONS: {
return new Formatter().format("/profile/transactions", values).toString();
}
case GET_PROFILE_INFOS: {
return new Formatter().format("/profile/infos", values).toString();
}
case GET_PROFILE_GENERALINFORMATION: {
return new Formatter().format("/profile/generalInformation", values).toString();
}
case GET_NEO_SERVER_IPS: {
return new Formatter().format("/public/servers", values).toString();
}
case GET_NEO_SERVER_REGIONS: {
return new Formatter().format("/public/regions", values).toString();
}
case GET_VULNERABILITIES_GAMESHIELD: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case POST_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_VULNERABILITIES_ALL: {
return new Formatter().format("/vulnerabilities", values).toString();
}
case DELETE_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_WEBHOOKS: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_CREATE: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_TEST: {
return new Formatter().format("/webhooks/%s/%s/test", values).toString();
}
case DELETE_WEBHOOK: {
return new Formatter().format("/webhooks/%s/%s", values).toString();
}
default: {
return null;
}
}
}
public String getBaseURL() {
return baseURL;
}
}
| src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/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": 60.1358351344635
},
{
"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": 48.910749235736006
},
{
"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": 42.3369961177373
},
{
"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": 38.789173871270265
},
{
"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": 27.674385043932865
}
] | java | .equals(core.getRestAPI().getStatsServer())) { |
package de.cubeattack.neoprotect.core.request;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Formatter;
import java.util.concurrent.TimeUnit;
public class RestAPIManager {
private final OkHttpClient client = new OkHttpClient();
private final String baseURL = "https://api.neoprotect.net/v2";
private final Core core;
public RestAPIManager(Core core) {
this.core = core;
}
{
client.setConnectTimeout(4, TimeUnit.SECONDS);
}
protected ResponseManager request(RequestType type, RequestBody requestBody, Object... value) {
if (type.toString().startsWith("GET")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).build()));
} else if (type.toString().startsWith("POST")) {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).post(requestBody).build()));
} else {
return new ResponseManager(callRequest(defaultBuilder().url(baseURL + getSubDirectory(type, value)).delete().build()));
}
}
protected Response callRequest(Request request) {
try {
return client.newCall(request).execute();
} catch (UnknownHostException | SocketTimeoutException | SocketException connectionException) {
if(!request.url().toString().equals(core.getRestAPI().getStatsServer())) {
core.severe(request + " failed cause (" + connectionException + ")");
}else
core.debug(request + " failed cause (" + connectionException + ")");
} catch (Exception exception) {
core.severe(exception.getMessage(), exception);
}
return null;
}
protected Request.Builder defaultBuilder() {
return defaultBuilder | (Config.getAPIKey()); |
}
protected Request.Builder defaultBuilder(String apiKey) {
return new Request.Builder()
.addHeader("accept", "*/*")
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json");
}
protected String getSubDirectory(RequestType type, Object... values) {
switch (type) {
case GET_ATTACKS: {
return new Formatter().format("/attacks", values).toString();
}
case GET_ATTACKS_GAMESHIELD: {
return new Formatter().format("/attacks/gameshield/%s", values).toString();
}
case GET_GAMESHIELD_BACKENDS: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_CREATE: {
return new Formatter().format("/gameshields/%s/backends", values).toString();
}
case POST_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case DELETE_GAMESHIELD_BACKEND_UPDATE: {
return new Formatter().format("/gameshields/%s/backends/%s", values).toString();
}
case POST_GAMESHIELD_BACKEND_AVAILABLE: {
return new Formatter().format("/gameshield/backends/available", values).toString();
}
case GET_GAMESHIELD_DOMAINS: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_CREATE: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case POST_GAMESHIELD_DOMAIN_AVAILABLE: {
return new Formatter().format("/gameshields/domains/available", values).toString();
}
case DELETE_GAMESHIELD_DOMAIN: {
return new Formatter().format("/gameshields/domains/%s", values).toString();
}
case GET_GAMESHIELD_FRONTENDS: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case POST_GAMESHIELD_FRONTEND_CREATE: {
return new Formatter().format("/gameshields/%s/frontends", values).toString();
}
case GET_GAMESHIELDS: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_CREATE: {
return new Formatter().format("/gameshields", values).toString();
}
case POST_GAMESHIELD_UPDATE: {
return new Formatter().format("/gameshields/%s/settings", values).toString();
}
case POST_GAMESHIELD_UPDATE_REGION: {
return new Formatter().format("/gameshields/%s/region/%s", values).toString();
}
case GET_GAMESHIELD_PLAN: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_PLAN_UPGRADE: {
return new Formatter().format("/gameshields/%s/plan", values).toString();
}
case POST_GAMESHIELD_UPDATE_NAME: {
return new Formatter().format("/gameshields/%s/name", values).toString();
}
case POST_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case DELETE_GAMESHIELD_UPDATE_ICON: {
return new Formatter().format("/gameshields/%s/icon", values).toString();
}
case POST_GAMESHIELD_UPDATE_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case DELETE_GAMESHIELD_BANNER: {
return new Formatter().format("/gameshields/%s/banner", values).toString();
}
case POST_GAMESHIELD_AVAILABLE: {
return new Formatter().format("/gameshields/available", values).toString();
}
case GET_GAMESHIELD_INFO: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case DELETE_GAMESHIELD: {
return new Formatter().format("/gameshields/%s", values).toString();
}
case GET_GAMESHIELD_LASTSTATS: {
return new Formatter().format("/gameshields/%s/lastStats", values).toString();
}
case GET_GAMESHIELD_ISUNDERATTACK: {
return new Formatter().format("/gameshields/%s/isUnderAttack", values).toString();
}
case GET_GAMESHIELD_BANDWIDTH: {
return new Formatter().format("/gameshields/%s/bandwidth", values).toString();
}
case GET_GAMESHIELD_ANALYTICS: {
return new Formatter().format("/gameshields/%s/analytics/%s", values).toString();
}
case GET_FIREWALLS: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case POST_FIREWALL_CREATE: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case DELETE_FIREWALL: {
return new Formatter().format("/firewall/gameshield/%s/%s", values).toString();
}
case GET_PLANS_AVAILABLE: {
return new Formatter().format("/plans/gameshield", values).toString();
}
case GET_PROFILE_TRANSACTIONS: {
return new Formatter().format("/profile/transactions", values).toString();
}
case GET_PROFILE_INFOS: {
return new Formatter().format("/profile/infos", values).toString();
}
case GET_PROFILE_GENERALINFORMATION: {
return new Formatter().format("/profile/generalInformation", values).toString();
}
case GET_NEO_SERVER_IPS: {
return new Formatter().format("/public/servers", values).toString();
}
case GET_NEO_SERVER_REGIONS: {
return new Formatter().format("/public/regions", values).toString();
}
case GET_VULNERABILITIES_GAMESHIELD: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case POST_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_VULNERABILITIES_ALL: {
return new Formatter().format("/vulnerabilities", values).toString();
}
case DELETE_VULNERABILITIES: {
return new Formatter().format("/vulnerabilities/%s", values).toString();
}
case GET_WEBHOOKS: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_CREATE: {
return new Formatter().format("/webhooks/%s", values).toString();
}
case POST_WEBHOOK_TEST: {
return new Formatter().format("/webhooks/%s/%s/test", values).toString();
}
case DELETE_WEBHOOK: {
return new Formatter().format("/webhooks/%s/%s", values).toString();
}
default: {
return null;
}
}
}
public String getBaseURL() {
return baseURL;
}
}
| src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\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": 29.28002892998967
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " } catch (Exception exception) {\n // Closing the channel because we do not want people on the server with a proxy ip\n ctx.channel().close();\n // Logging for the lovely server admins :)\n instance.getCore().severe(\"Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.\", exception);\n }\n }\n }\n @ChannelHandler.Sharable\n class ServerChannelInitializer extends ChannelInboundHandlerAdapter {",
"score": 27.1051175547549
},
{
"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": 26.1663043849719
},
{
"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": 21.202527776284047
},
{
"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": 20.793533032072
}
] | 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": 101.49914981586078
},
{
"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": 77.65010163967695
},
{
"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": 76.8894111457342
},
{
"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": 55.60891684404162
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/Reflection.java",
"retrieved_chunk": " * @return The value of the field.\n */\n T get(Object target);\n /**\n * Set the content of a field.\n *\n * @param target - the target object, or NULL for a static field.\n * @param value - the new value of the field.\n */\n void set(Object target, Object value);",
"score": 54.371158813361276
}
] | java | instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception); |
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
| instance.getCore().info("Proceeding with the server channel injection..."); |
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
| src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import java.util.logging.Level;\npublic class ProxyProtocol {\n private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, \"channel\", ChannelWrapper.class);\n private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;\n private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectBungee instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 38.546981044198006
},
{
"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": 37.93334935525482
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/Reflection.java",
"retrieved_chunk": " return getConstructor(getClass(className), params);\n }\n /**\n * Search for the first publically and privately defined constructor of the given name and parameter count.\n *\n * @param clazz - a class to start with.\n * @param params - the expected parameters.\n * @return An object that invokes this constructor.\n * @throws IllegalStateException If we cannot find this method.\n */",
"score": 29.85922171762418
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/Reflection.java",
"retrieved_chunk": " }\n /**\n * Search for the first publicly and privately defined method of the given name and parameter count.\n *\n * @param clazz - a class to start with.\n * @param methodName - the method name, or NULL to skip.\n * @param params - the expected parameters.\n * @return An object that invokes this specific method.\n * @throws IllegalStateException If we cannot find this method.\n */",
"score": 29.62078049093629
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/Reflection.java",
"retrieved_chunk": " }\n /**\n * Search for the first publicly and privately defined method of the given name and parameter count.\n *\n * @param clazz - a class to start with.\n * @param methodName - the method name, or NULL to skip.\n * @param returnType - the expected return type, or NULL to ignore.\n * @param params - the expected parameters.\n * @return An object that invokes this specific method.\n * @throws IllegalStateException If we cannot find this method.",
"score": 28.187590818234586
}
] | java | instance.getCore().info("Proceeding with the server channel injection..."); |
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
instance.getCore().info("Late bind injection successful.");
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = | Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection); |
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
| src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " return CompletableFuture.supplyAsync(() -> {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();\n String[] args = invocation.arguments();\n 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\");",
"score": 56.82422226626183
},
{
"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": 47.42093614568265
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " public List<Gameshield> getGameshields() {\n List<Gameshield> list = new ArrayList<>();\n JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();\n for (Object object : gameshields) {\n JSONObject jsonObject = (JSONObject) object;\n list.add(new Gameshield(jsonObject.getString(\"id\"), jsonObject.getString(\"name\")));\n }\n return list;\n }\n public List<Backend> getBackends() {",
"score": 40.13155731294122
},
{
"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": 38.036444797230416
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n long decimal = 0;\n for (int i = 0; i < 4; i++) {\n int octet = Integer.parseInt(parts[i]);\n if (octet < 0 || octet > 255) {\n return -1;\n }\n decimal += (long) (octet * Math.pow(256, 3 - i));\n }\n return decimal;",
"score": 33.824263819645644
}
] | java | Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection); |
package de.cubeattack.neoprotect.spigot.proxyprotocol;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import io.netty.channel.*;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
/**
* Represents a very tiny alternative to ProtocolLib.
* <p>
* It now supports intercepting packets during login and status ping (such as OUT_SERVER_PING)!
*
* @author Kristian // Love ya <3 ~ytendx
*/
public class ProxyProtocol {
// Looking up ServerConnection
private final Class<Object> minecraftServerClass = Reflection.getUntypedClass("{nms}.MinecraftServer");
private final Class<Object> serverConnectionClass = Reflection.getUntypedClass("{nms}" + (Reflection.isNewerPackage() ? ".network" : "") + ".ServerConnection");
private final Reflection.FieldAccessor<Object> getMinecraftServer = Reflection.getField("{obc}.CraftServer", minecraftServerClass, 0);
private final Reflection.FieldAccessor<Object> getServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0);
private final Reflection.MethodInvoker getNetworkMarkers = !Reflection.isNewerPackage() && !Reflection.VERSION.contains("16") ? Reflection.getTypedMethod(serverConnectionClass, null, List.class, serverConnectionClass) : null;
private final Reflection.FieldAccessor<List> networkManagersFieldAccessor = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? Reflection.getField(serverConnectionClass, List.class, 0) : null;
private final Class<Object> networkManager = Reflection.getUntypedClass(Reflection.isNewerPackage() ? "net.minecraft.network.NetworkManager" : "{nms}.NetworkManager");
private final Reflection.FieldAccessor<SocketAddress> socketAddressFieldAccessor = Reflection.getField(networkManager, SocketAddress.class, 0);
private List<Object> networkManagers;
private ServerChannelInitializer serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
protected NeoProtectSpigot instance;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
* <p>
* You can construct multiple instances per plugin.
*
* @param instance - the plugin.
*/
public ProxyProtocol(NeoProtectSpigot instance) {
this.instance = instance;
try {
instance.getCore().info("Proceeding with the server channel injection...");
registerChannelHandler();
} catch (IllegalArgumentException ex) {
// Damn you, late bind
instance.getCore().info("Delaying server channel injection due to late bind.");
new BukkitRunnable() {
@Override
public void run() {
registerChannelHandler();
| instance.getCore().info("Late bind injection successful."); |
}
}.runTask(instance);
}
}
private void createServerChannelHandler() {
// Handle connected channels
endInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {
instance.getCore().debug("Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)");
return;
}
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {
channel.close();
instance.getCore().debug("Player connected over IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (warning)");
return;
}
try {
instance.getCore().debug("Adding Handler...");
synchronized (networkManagers) {
// Adding the decoder to the pipeline
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
// Adding the proxy message handler to the pipeline too
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", HAPROXY_MESSAGE_HANDLER);
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getCore().severe("Cannot inject incoming channel " + channel, ex);
}
}
};
// This is executed before Minecraft's channel handler
beginInitProtocol = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(endInitProtocol);
}
};
serverChannelHandler = new ServerChannelInitializer();
}
@SuppressWarnings("unchecked")
private void registerChannelHandler() {
Object mcServer = getMinecraftServer.get(Bukkit.getServer());
Object serverConnection = getServerConnection.get(mcServer);
boolean looking = true;
// We need to synchronize against this list
networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains("16") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);
createServerChannelHandler();
// Find the correct list, or implicitly throw an exception
for (int i = 0; looking; i++) {
List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);
for (Object item : list) {
if (!(item instanceof ChannelFuture))
break;
// Channel future that contains the server connection
Channel serverChannel = ((ChannelFuture) item).channel();
serverChannel.pipeline().addFirst(serverChannelHandler);
looking = false;
this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!");
}
}
}
private final HAProxyMessageHandler HAPROXY_MESSAGE_HANDLER = new HAProxyMessageHandler();
@ChannelHandler.Sharable
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage)) {
super.channelRead(ctx, msg);
return;
}
try {
final HAProxyMessage message = (HAProxyMessage) msg;
// Set the SocketAddress field of the NetworkManager ("packet_handler" handler) to the client address
socketAddressFieldAccessor.set(ctx.channel().pipeline().get("packet_handler"), new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
} catch (Exception exception) {
// Closing the channel because we do not want people on the server with a proxy ip
ctx.channel().close();
// Logging for the lovely server admins :)
instance.getCore().severe("Error: The server was unable to set the IP address from the 'HAProxyMessage'. Therefore we closed the channel.", exception);
}
}
}
@ChannelHandler.Sharable
class ServerChannelInitializer extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel channel = (Channel) msg;
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
if (channel.localAddress().toString().startsWith("local:") || ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress().equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
// Prepare to initialize ths channel
channel.pipeline().addFirst(beginInitProtocol);
ctx.fireChannelRead(msg);
}
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if(!ipRange.contains("/")){
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
| src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": "import java.util.logging.Level;\npublic class ProxyProtocol {\n private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, \"channel\", ChannelWrapper.class);\n private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;\n private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), \"initChannel\", Channel.class);\n public ProxyProtocol(NeoProtectBungee instance) {\n instance.getLogger().info(\"Proceeding with the server channel injection...\");\n try {\n ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {\n @Override",
"score": 47.726137867110566
},
{
"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": 46.68995942701858
},
{
"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": 37.458459179141165
},
{
"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": 32.32837440502225
},
{
"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": 32.29490006598059
}
] | 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": "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": 50.76857928066697
},
{
"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": 49.223808567032286
},
{
"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": 40.0360662198707
},
{
"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": 39.727891330238066
},
{
"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": 39.564313549152715
}
] | 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/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": 54.06770072075035
},
{
"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": 52.602062337651525
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " return CompletableFuture.supplyAsync(() -> {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();\n String[] args = invocation.arguments();\n 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\");",
"score": 50.11297331633956
},
{
"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": 44.62244222618389
},
{
"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": 42.435071027211855
}
] | java | this.instance.getCore().info("Found the server channel and added the handler. Injection successfully!"); |
package de.cubeattack.neoprotect.spigot.listener;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.util.JavaUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.spigot.NeoProtectSpigot;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Locale;
public class LoginListener implements Listener {
private final NeoProtectSpigot instance;
private final Localization localization;
public LoginListener(NeoProtectSpigot instance) {
this.instance = instance;
this.localization = instance.getCore().getLocalization();
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onLogin(PlayerJoinEvent event) {
Player player = event.getPlayer();
Locale locale = JavaUtils.javaVersionCheck() != 8 ? Locale.forLanguageTag(player.getLocale()) : Locale.ENGLISH;
if (!player.hasPermission("neoprotect.admin") && !instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode()))
return;
VersionUtils.Result result = instance.getCore().getVersionResult();
if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {
instance.sendMessage(player, localization.get(locale, "plugin.outdated.message", result.getCurrentVersion(), result.getLatestVersion()));
instance.sendMessage(player, MessageFormat.format("§7-> §b{0}",
result.getReleaseUrl().replace("/NeoPlugin", "").replace("/releases/tag", "")),
"OPEN_URL", result.getReleaseUrl(), null, null);
}
if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {
instance.sendMessage(player, localization.get(locale, "plugin.restart-required.message", result.getCurrentVersion(), result.getLatestVersion()));
}
if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {
instance.sendMessage(player, localization.get(locale, "setup.required.first"));
instance.sendMessage(player, localization.get(locale, "setup.required.second"));
}
| if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) { |
Stats stats = instance.getStats();
String infos =
"§bOsName§7: " + System.getProperty("os.name") + " \n" +
"§bJavaVersion§7: " + System.getProperty("java.version") + " \n" +
"§bPluginVersion§7: " + stats.getPluginVersion() + " \n" +
"§bVersionStatus§7: " + instance.getCore().getVersionResult().getVersionStatus() + " \n" +
"§bUpdateSetting§7: " + Config.getAutoUpdaterSettings() + " \n" +
"§bProxyProtocol§7: " + Config.isProxyProtocol() + " \n" +
"§bNeoProtectPlan§7: " + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : "§cNOT CONNECTED") + " \n" +
"§bSpigotName§7: " + stats.getServerName() + " \n" +
"§bSpigotVersion§7: " + stats.getServerVersion() + " \n" +
"§bSpigotPlugins§7: " + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith("cmd_") && !p.equals("reconnect_yaml")).toArray());
instance.sendMessage(player, "§bHello " + player.getName() + " ;)", null, null, "SHOW_TEXT", infos);
instance.sendMessage(player, "§bThis server uses your NeoPlugin", null, null, "SHOW_TEXT", infos);
}
}
}
| src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/LoginListener.java",
"retrieved_chunk": " return;\n VersionUtils.Result result = instance.getCore().getVersionResult();\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {\n instance.sendMessage(player, localization.get(locale, result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));",
"score": 167.24312639534222
},
{
"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": 167.11783868260173
},
{
"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": 121.83588530034605
},
{
"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": 121.83588530034605
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() & !args[0].equals(\"setup\") & !args[0].equals(\"setgameshield\") & !args[0].equals(\"setbackend\")) {\n instance.sendMessage(sender, localization.get(locale, \"setup.command.required\"));\n return;\n }\n switch (args[0].toLowerCase()) {\n case \"setup\": {\n if (isViaConsole) {\n instance.sendMessage(sender, localization.get(Locale.getDefault(), \"console.command\"));\n } else {",
"score": 83.42625035995289
}
] | java | if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) { |
package de.cubeattack.neoprotect.velocity.listener;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.PostLoginEvent;
import com.velocitypowered.api.proxy.Player;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.velocity.NeoProtectVelocity;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
public class LoginListener {
private final NeoProtectVelocity instance;
private final Localization localization;
public LoginListener(NeoProtectVelocity instance) {
this.instance = instance;
this.localization = instance.getCore().getLocalization();
}
@Subscribe(order = PostOrder.LAST)
public void onPostLogin(PostLoginEvent event) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Player player = event.getPlayer();
Locale locale = (player.getEffectiveLocale() != null) ? player.getEffectiveLocale() : Locale.ENGLISH;
if (!player.hasPermission("neoprotect.admin") && !instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode()))
return;
VersionUtils.Result result = instance.getCore().getVersionResult();
if (result.getVersionStatus().equals(VersionUtils.VersionStatus.OUTDATED)) {
instance.sendMessage(player, localization.get(locale, "plugin.outdated.message", result.getCurrentVersion(), result.getLatestVersion()));
instance.sendMessage(player, MessageFormat.format("§7-> §b{0}",
result.getReleaseUrl().replace("/NeoPlugin", "").replace("/releases/tag", "")),
"OPEN_URL", result.getReleaseUrl(), null, null);
}
if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {
instance.sendMessage(player, localization.get(locale, "plugin.restart-required.message", result.getCurrentVersion(), result.getLatestVersion()));
}
if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {
instance.sendMessage(player, localization.get(locale, "setup.required.first"));
instance.sendMessage(player, localization.get(locale, "setup.required.second"));
}
if ( | instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) { |
Stats stats = instance.getStats();
String infos =
"§bOsName§7: " + System.getProperty("os.name") + " \n" +
"§bJavaVersion§7: " + System.getProperty("java.version") + " \n" +
"§bPluginVersion§7: " + stats.getPluginVersion() + " \n" +
"§bVersionStatus§7: " + instance.getCore().getVersionResult().getVersionStatus() + " \n" +
"§bUpdateSetting§7: " + Config.getAutoUpdaterSettings() + " \n" +
"§bProxyProtocol§7: " + Config.isProxyProtocol() + " \n" +
"§bNeoProtectPlan§7: " + (instance.getCore().isSetup() ? instance.getCore().getRestAPI().getPlan() : "§cNOT CONNECTED") + " \n" +
"§bVelocityName§7: " + stats.getServerName() + " \n" +
"§bVelocityVersion§7: " + stats.getServerVersion() + " \n" +
"§bVelocityPlugins§7: " + Arrays.toString(instance.getPlugins().stream().filter(p -> !p.startsWith("cmd_") && !p.equals("reconnect_yaml")).toArray());
instance.sendMessage(player, "§bHello " + player.getUsername() + " ;)", null, null, "SHOW_TEXT", infos);
instance.sendMessage(player, "§bThis server uses your NeoPlugin", null, null, "SHOW_TEXT", infos);
}
}
}, 500);
}
}
| src/main/java/de/cubeattack/neoprotect/velocity/listener/LoginListener.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));",
"score": 165.30027613507096
},
{
"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": 143.70844117103545
},
{
"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": 127.85969014869187
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 88.55704857495596
},
{
"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": 87.9811762702606
}
] | java | instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getProxy().getConfiguration().isOnlineMode())) { |
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.logger.LogManager;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import de.cubeattack.neoprotect.core.request.RestAPIRequests;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
@SuppressWarnings("unused")
public class Core {
@SuppressWarnings("FieldCanBeLocal")
private final String prefix = "§8[§bNeo§3Protect§8] §7";
private final UUID maintainerOnlineUUID = UUID.fromString("201e5046-24df-4830-8b4a-82b635eb7cc7");
private final UUID maintainerOfflineeUUID = UUID.fromString("8c07bf89-9c8f-304c-9216-4666b670223b");
private final RestAPIRequests restAPIRequests;
private final NeoProtectPlugin plugin;
private final Localization localization;
private final List<Object> playerInSetup = new ArrayList<>();
private final List<String> directConnectWhitelist= new ArrayList<>();
private final ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, Timestamp> timestampsMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, ArrayList<DebugPingResponse>> debugPingResponses = new ConcurrentHashMap<>();
private VersionUtils.Result versionResult;
private boolean isDebugRunning = false;
public Core(NeoProtectPlugin plugin) {
LogManager.getLogger().setLogger(plugin.getLogger());
this.plugin = plugin;
this.versionResult = VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message();
FileUtils config = new FileUtils(Core.class.getResourceAsStream("/config.yml"), "plugins/NeoProtect", "config.yml", false);
FileUtils languageEN = new FileUtils(Core.class.getResourceAsStream("/language_en.properties"), "plugins/NeoProtect/languages", "language_en.properties", true);
FileUtils languageDE = new FileUtils(Core.class.getResourceAsStream("/language_de.properties"), "plugins/NeoProtect/languages", "language_de.properties", true);
FileUtils languageRU = new FileUtils(Core.class.getResourceAsStream("/language_ru.properties"), "plugins/NeoProtect/languages", "language_ru.properties", true);
FileUtils languageUA = new FileUtils(Core.class.getResourceAsStream("/language_ua.properties"), "plugins/NeoProtect/languages", "language_ua.properties", true);
Config.loadConfig(this, config);
this.localization = new Localization("language", Locale | .forLanguageTag(Config.getLanguage()), new File("plugins/NeoProtect/languages/")); |
restAPIRequests = new RestAPIRequests(this);
}
public void debug(String output) {
if (Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output);
}
public void info(String output) {
LogManager.getLogger().info(output);
}
public void warn(String output) {
LogManager.getLogger().warn(output);
}
public void severe(String output) {
LogManager.getLogger().error(output);
}
public void severe(String output, Throwable t) {
LogManager.getLogger().error(output, t);
}
public String getPrefix() {
return prefix;
}
public boolean isDebugRunning() {
return isDebugRunning;
}
public void setDebugRunning(boolean debugRunning) {
isDebugRunning = debugRunning;
}
public NeoProtectPlugin getPlugin() {
return plugin;
}
public Localization getLocalization() {
return localization;
}
public RestAPIRequests getRestAPI() {
return restAPIRequests;
}
public boolean isSetup() {
return restAPIRequests.isSetup();
}
public List<Object> getPlayerInSetup() {
return playerInSetup;
}
public List<String> getDirectConnectWhitelist() {
return directConnectWhitelist;
}
public ConcurrentHashMap<KeepAliveResponseKey, Long> getPingMap() {
return pingMap;
}
public ConcurrentHashMap<Long, Timestamp> getTimestampsMap() {
return timestampsMap;
}
public ConcurrentHashMap<String, ArrayList<DebugPingResponse>> getDebugPingResponses() {
return debugPingResponses;
}
public VersionUtils.Result getVersionResult() {
return versionResult;
}
public void setVersionResult(VersionUtils.Result versionResult) {
this.versionResult = versionResult;
}
public boolean isPlayerMaintainer(UUID playerUUID, boolean onlineMode) {
return (onlineMode && playerUUID.equals(maintainerOnlineUUID)) || (!onlineMode && playerUUID.equals(maintainerOfflineeUUID));
}
}
| src/main/java/de/cubeattack/neoprotect/core/Core.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/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": 126.89132731984549
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " API.getExecutorService().submit(() -> {\n try {\n long startTime = System.currentTimeMillis();\n Stats stats = instance.getStats();\n File file = new File(\"plugins/NeoProtect/debug\" + \"/\" + new Timestamp(System.currentTimeMillis()) + \".yml\");\n YamlConfiguration configuration = new YamlConfiguration();\n if (!file.exists()) {\n file.getParentFile().mkdirs();\n file.createNewFile();\n }",
"score": 91.6156730733511
},
{
"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": 74.05923116039553
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core;\nimport de.cubeattack.api.util.FileUtils;\nimport de.cubeattack.api.util.versioning.VersionUtils;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\n@SuppressWarnings(\"unused\")\npublic class Config {\n private static String APIKey;\n private static String language;",
"score": 69.45329614813521
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " private static boolean proxyProtocol;\n private static String gameShieldID;\n private static String backendID;\n private static String geyserBackendID;\n private static boolean updateIP;\n private static boolean debugMode;\n private static String geyserServerIP;\n private static String updateSetting;\n private static Core core;\n private static FileUtils fileUtils;",
"score": 63.62032354168828
}
] | 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": 165.30027613507096
},
{
"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": 143.70844117103545
},
{
"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": 127.85969014869187
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 88.55704857495596
},
{
"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": 87.9811762702606
}
] | 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": 46.55758846686571
},
{
"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": 46.359912445513736
},
{
"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": 44.76026465317627
},
{
"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": 44.716012035054234
},
{
"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": 40.926688202425446
}
] | java | "NeoProtect", "NeoPlugin", "v" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message(); |
package de.cubeattack.neoprotect.core;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.logger.LogManager;
import de.cubeattack.api.util.FileUtils;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import de.cubeattack.neoprotect.core.request.RestAPIRequests;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
@SuppressWarnings("unused")
public class Core {
@SuppressWarnings("FieldCanBeLocal")
private final String prefix = "§8[§bNeo§3Protect§8] §7";
private final UUID maintainerOnlineUUID = UUID.fromString("201e5046-24df-4830-8b4a-82b635eb7cc7");
private final UUID maintainerOfflineeUUID = UUID.fromString("8c07bf89-9c8f-304c-9216-4666b670223b");
private final RestAPIRequests restAPIRequests;
private final NeoProtectPlugin plugin;
private final Localization localization;
private final List<Object> playerInSetup = new ArrayList<>();
private final List<String> directConnectWhitelist= new ArrayList<>();
private final ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, Timestamp> timestampsMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, ArrayList<DebugPingResponse>> debugPingResponses = new ConcurrentHashMap<>();
private VersionUtils.Result versionResult;
private boolean isDebugRunning = false;
public Core(NeoProtectPlugin plugin) {
LogManager.getLogger().setLogger(plugin.getLogger());
this.plugin = plugin;
this.versionResult = VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + plugin.getPluginVersion(), VersionUtils.UpdateSetting.DISABLED).message();
FileUtils config = new FileUtils(Core.class.getResourceAsStream("/config.yml"), "plugins/NeoProtect", "config.yml", false);
FileUtils languageEN = new FileUtils(Core.class.getResourceAsStream("/language_en.properties"), "plugins/NeoProtect/languages", "language_en.properties", true);
FileUtils languageDE = new FileUtils(Core.class.getResourceAsStream("/language_de.properties"), "plugins/NeoProtect/languages", "language_de.properties", true);
FileUtils languageRU = new FileUtils(Core.class.getResourceAsStream("/language_ru.properties"), "plugins/NeoProtect/languages", "language_ru.properties", true);
FileUtils languageUA = new FileUtils(Core.class.getResourceAsStream("/language_ua.properties"), "plugins/NeoProtect/languages", "language_ua.properties", true);
Config.loadConfig(this, config);
this.localization = new Localization("language", Locale.forLanguageTag(Config.getLanguage()), new File("plugins/NeoProtect/languages/"));
restAPIRequests = new RestAPIRequests(this);
}
public void debug(String output) {
if (Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output);
}
public void info(String output) {
LogManager.getLogger().info(output);
}
public void warn(String output) {
LogManager.getLogger().warn(output);
}
public void severe(String output) {
LogManager.getLogger().error(output);
}
public void severe(String output, Throwable t) {
LogManager.getLogger().error(output, t);
}
public String getPrefix() {
return prefix;
}
public boolean isDebugRunning() {
return isDebugRunning;
}
public void setDebugRunning(boolean debugRunning) {
isDebugRunning = debugRunning;
}
public NeoProtectPlugin getPlugin() {
return plugin;
}
public Localization getLocalization() {
return localization;
}
public RestAPIRequests getRestAPI() {
return restAPIRequests;
}
public boolean isSetup() {
| return restAPIRequests.isSetup(); |
}
public List<Object> getPlayerInSetup() {
return playerInSetup;
}
public List<String> getDirectConnectWhitelist() {
return directConnectWhitelist;
}
public ConcurrentHashMap<KeepAliveResponseKey, Long> getPingMap() {
return pingMap;
}
public ConcurrentHashMap<Long, Timestamp> getTimestampsMap() {
return timestampsMap;
}
public ConcurrentHashMap<String, ArrayList<DebugPingResponse>> getDebugPingResponses() {
return debugPingResponses;
}
public VersionUtils.Result getVersionResult() {
return versionResult;
}
public void setVersionResult(VersionUtils.Result versionResult) {
this.versionResult = versionResult;
}
public boolean isPlayerMaintainer(UUID playerUUID, boolean onlineMode) {
return (onlineMode && playerUUID.equals(maintainerOnlineUUID)) || (!onlineMode && playerUUID.equals(maintainerOfflineeUUID));
}
}
| src/main/java/de/cubeattack/neoprotect/core/Core.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " }\n public boolean isSetup() {\n return setup;\n }\n}",
"score": 27.62468654508688
},
{
"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": 20.32797207859418
},
{
"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": 19.95385569777767
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " public String getMsg() {\n return msg;\n }\n public boolean isViaConsole() {\n return viaConsole;\n }\n }\n public static boolean isInteger(String input) {\n try {\n Integer.parseInt(input);",
"score": 18.389312022950257
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Backend.java",
"retrieved_chunk": " this.geyser = geyser;\n }\n public boolean compareById(String otherId) {\n return id.equals(otherId);\n }\n public String getId() {\n return id;\n }\n public String getIp() {\n return ip;",
"score": 18.08994915981644
}
] | 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": 70.48328435793485
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " API.getExecutorService().submit(() -> {\n try {\n long startTime = System.currentTimeMillis();\n Stats stats = instance.getStats();\n File file = new File(\"plugins/NeoProtect/debug\" + \"/\" + new Timestamp(System.currentTimeMillis()) + \".yml\");\n YamlConfiguration configuration = new YamlConfiguration();\n if (!file.exists()) {\n file.getParentFile().mkdirs();\n file.createNewFile();\n }",
"score": 58.12574234715455
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": " public Logger getLogger() {\n return logger;\n }\n @Override\n public ArrayList<String> getPlugins() {\n ArrayList<String> plugins = new ArrayList<>();\n getProxy().getPluginManager().getPlugins().forEach(p -> plugins.add(p.getDescription().getName().orElseThrow(null)));\n return plugins;\n }\n @Override",
"score": 52.009297261139764
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java",
"retrieved_chunk": " public void onLoad() {\n Metrics metrics = new Metrics(this, 18725);\n metrics.addCustomChart(new SimplePie(\"language\", Config::getLanguage));\n }\n @Override\n public void onEnable() {\n core = new Core(this);\n new Startup(this);\n }\n public Core getCore() {",
"score": 50.83070154371862
},
{
"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": 50.06227916544455
}
] | java | (Config.isDebugMode()) ((Logger) LogManager.getLogger().logger).log(Level.SEVERE, output); |
package de.cubeattack.neoprotect.bungee.proxyprotocol;
import de.cubeattack.api.util.JavaUtils;
import de.cubeattack.neoprotect.bungee.NeoProtectBungee;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.epoll.EpollTcpInfo;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.UserConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.HandlerBoss;
import net.md_5.bungee.netty.PipelineUtils;
import net.md_5.bungee.protocol.PacketWrapper;
import net.md_5.bungee.protocol.packet.KeepAlive;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
public class ProxyProtocol {
private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, "channel", ChannelWrapper.class);
private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;
private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), "initChannel", Channel.class);
public ProxyProtocol(NeoProtectBungee instance) {
instance.getLogger().info("Proceeding with the server channel injection...");
try {
ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
try {
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
initChannelMethod.invoke(bungeeChannelInitializer, channel);
AtomicReference<InetSocketAddress> playerAddress = new AtomicReference<>();
String sourceAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
if (channel.localAddress().toString().startsWith("local:") || sourceAddress.equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {
channel.close();
instance.getCore().debug("Close connection IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (close / return)");
return;
}
instance.getCore().debug("Adding handler...");
if (instance.getCore().isSetup() && Config.isProxyProtocol()) {
addProxyProtocolHandler(channel, playerAddress);
instance.getCore().debug("Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)");
}
addKeepAlivePacketHandler(channel, playerAddress, instance);
instance.getCore().debug("Added KeepAlivePacketHandler");
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getLogger().log(Level.SEVERE, "Cannot inject incoming channel " + channel, ex);
}
}
};
Field serverChild = PipelineUtils.class.getField("SERVER_CHILD");
serverChild.setAccessible(true);
if (JavaUtils.javaVersionCheck() == 8) {
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(serverChild, serverChild.getModifiers() & ~Modifier.FINAL);
serverChild.set(PipelineUtils.class, channelInitializer);
} else {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Unsafe unsafe = (Unsafe) unsafeField.get(null);
unsafe.putObject(unsafe.staticFieldBase(serverChild), unsafe.staticFieldOffset(serverChild), channelInitializer);
}
instance.getLogger().info("Found the server channel and added the handler. Injection successfully!");
} catch (Exception ex) {
instance.getLogger().log(Level.SEVERE, "An unknown error has occurred", ex);
}
}
public void addProxyProtocolHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress) {
channel.pipeline().names().forEach((n) -> {
if (n.equals("HAProxyMessageDecoder#0"))
channel.pipeline().remove("HAProxyMessageDecoder#0");
});
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HAProxyMessage) {
HAProxyMessage message = (HAProxyMessage) msg;
inetAddress.set(new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
channelWrapperAccessor.get(channel.pipeline().get(HandlerBoss.class)).setRemoteAddress(inetAddress.get());
} else {
super.channelRead(ctx, msg);
}
}
});
}
public void addKeepAlivePacketHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress, NeoProtectPlugin instance) {
channel.pipeline().addAfter(PipelineUtils.PACKET_DECODER, "neo-keep-alive-handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
super.channelRead(ctx, msg);
if (!(msg instanceof PacketWrapper)) {
return;
}
if (!(((PacketWrapper) msg).packet instanceof KeepAlive)) {
return;
}
KeepAlive keepAlive = (KeepAlive) ((PacketWrapper) msg).packet;
ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = instance.getCore().getPingMap();
instance.getCore().debug("Received KeepAlivePackets (" + keepAlive.getRandomId() + ")");
for (KeepAliveResponseKey keepAliveResponseKey : pingMap.keySet()) {
if (!keepAliveResponseKey.getAddress().equals(inetAddress.get()) || !(keepAliveResponseKey.getId() == keepAlive.getRandomId())) {
continue;
}
instance.getCore().debug("KeepAlivePackets matched to DebugKeepAlivePacket");
for (ProxiedPlayer player : BungeeCord.getInstance().getPlayers()) {
if (!(player).getPendingConnection().getSocketAddress().equals(inetAddress.get())) {
continue;
}
instance.getCore().debug("Player matched to DebugKeepAlivePacket (loading data...)");
EpollTcpInfo tcpInfo = ((EpollSocketChannel) channel).tcpInfo();
EpollTcpInfo tcpInfoBackend = ((EpollSocketChannel) ((UserConnection) player).getServer().getCh().getHandle()).tcpInfo();
long ping = System.currentTimeMillis() - pingMap.get(keepAliveResponseKey);
long neoRTT = 0;
long backendRTT = 0;
if (tcpInfo != null) {
neoRTT = tcpInfo.rtt() / 1000;
}
if (tcpInfoBackend != null) {
backendRTT = tcpInfoBackend.rtt() / 1000;
}
ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();
if (!map.containsKey(player.getName())) {
| instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>()); |
}
map.get(player.getName()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));
instance.getCore().debug("Loading completed");
instance.getCore().debug(" ");
}
instance.getCore().getPingMap().remove(keepAliveResponseKey);
}
}
});
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if (!ipRange.contains("/")) {
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
| src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (tcpInfo != null) {\n neoRTT = tcpInfo.rtt() / 1000;\n }\n if (tcpInfoBackend != null) {\n backendRTT = tcpInfoBackend.rtt() / 1000;\n }\n ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();\n if (!map.containsKey(player.getUsername())) {\n instance.getCore().getDebugPingResponses().put(player.getUsername(), new ArrayList<>());\n }",
"score": 153.37547319612463
},
{
"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": 60.89616886188487
},
{
"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": 44.88276738282367
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Core.java",
"retrieved_chunk": " }\n public ConcurrentHashMap<Long, Timestamp> getTimestampsMap() {\n return timestampsMap;\n }\n public ConcurrentHashMap<String, ArrayList<DebugPingResponse>> getDebugPingResponses() {\n return debugPingResponses;\n }\n public VersionUtils.Result getVersionResult() {\n return versionResult;\n }",
"score": 30.28394248539297
},
{
"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": 25.602589705652562
}
] | java | instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>()); |
package de.cubeattack.neoprotect.bungee.proxyprotocol;
import de.cubeattack.api.util.JavaUtils;
import de.cubeattack.neoprotect.bungee.NeoProtectBungee;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import de.cubeattack.neoprotect.core.model.debugtool.KeepAliveResponseKey;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.epoll.EpollTcpInfo;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.UserConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.HandlerBoss;
import net.md_5.bungee.netty.PipelineUtils;
import net.md_5.bungee.protocol.PacketWrapper;
import net.md_5.bungee.protocol.packet.KeepAlive;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
public class ProxyProtocol {
private final Reflection.FieldAccessor<ChannelWrapper> channelWrapperAccessor = Reflection.getField(HandlerBoss.class, "channel", ChannelWrapper.class);
private final ChannelInitializer<Channel> bungeeChannelInitializer = PipelineUtils.SERVER_CHILD;
private final Reflection.MethodInvoker initChannelMethod = Reflection.getMethod(bungeeChannelInitializer.getClass(), "initChannel", Channel.class);
public ProxyProtocol(NeoProtectBungee instance) {
instance.getLogger().info("Proceeding with the server channel injection...");
try {
ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
try {
instance.getCore().debug("Open channel (" + channel.remoteAddress().toString() + ")");
initChannelMethod.invoke(bungeeChannelInitializer, channel);
AtomicReference<InetSocketAddress> playerAddress = new AtomicReference<>();
String sourceAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
if (channel.localAddress().toString().startsWith("local:") || sourceAddress.equals(Config.getGeyserServerIP())) {
instance.getCore().debug("Detected bedrock player (return)");
return;
}
if (!instance.getCore().getDirectConnectWhitelist().contains(sourceAddress)) {
if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||
instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, sourceAddress)))) {
channel.close();
instance.getCore().debug("Close connection IP (" + channel.remoteAddress() + ") doesn't match to Neo-IPs (close / return)");
return;
}
instance.getCore().debug("Adding handler...");
if (instance.getCore().isSetup() && Config.isProxyProtocol()) {
addProxyProtocolHandler(channel, playerAddress);
instance.getCore().debug("Plugin is setup & ProxyProtocol is on (Added proxyProtocolHandler)");
}
addKeepAlivePacketHandler(channel, playerAddress, instance);
instance.getCore().debug("Added KeepAlivePacketHandler");
}
instance.getCore().debug("Connecting finished");
} catch (Exception ex) {
instance.getLogger().log(Level.SEVERE, "Cannot inject incoming channel " + channel, ex);
}
}
};
Field serverChild = PipelineUtils.class.getField("SERVER_CHILD");
serverChild.setAccessible(true);
if (JavaUtils.javaVersionCheck() == 8) {
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(serverChild, serverChild.getModifiers() & ~Modifier.FINAL);
serverChild.set(PipelineUtils.class, channelInitializer);
} else {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Unsafe unsafe = (Unsafe) unsafeField.get(null);
unsafe.putObject(unsafe.staticFieldBase(serverChild), unsafe.staticFieldOffset(serverChild), channelInitializer);
}
instance.getLogger().info("Found the server channel and added the handler. Injection successfully!");
} catch (Exception ex) {
instance.getLogger().log(Level.SEVERE, "An unknown error has occurred", ex);
}
}
public void addProxyProtocolHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress) {
channel.pipeline().names().forEach((n) -> {
if (n.equals("HAProxyMessageDecoder#0"))
channel.pipeline().remove("HAProxyMessageDecoder#0");
});
channel.pipeline().addFirst("haproxy-decoder", new HAProxyMessageDecoder());
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HAProxyMessage) {
HAProxyMessage message = (HAProxyMessage) msg;
inetAddress.set(new InetSocketAddress(message.sourceAddress(), message.sourcePort()));
channelWrapperAccessor.get(channel.pipeline().get(HandlerBoss.class)).setRemoteAddress(inetAddress.get());
} else {
super.channelRead(ctx, msg);
}
}
});
}
public void addKeepAlivePacketHandler(Channel channel, AtomicReference<InetSocketAddress> inetAddress, NeoProtectPlugin instance) {
channel.pipeline().addAfter(PipelineUtils.PACKET_DECODER, "neo-keep-alive-handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
super.channelRead(ctx, msg);
if (!(msg instanceof PacketWrapper)) {
return;
}
if (!(((PacketWrapper) msg).packet instanceof KeepAlive)) {
return;
}
KeepAlive keepAlive = (KeepAlive) ((PacketWrapper) msg).packet;
ConcurrentHashMap<KeepAliveResponseKey, Long> pingMap = instance.getCore().getPingMap();
instance.getCore().debug("Received KeepAlivePackets (" + keepAlive.getRandomId() + ")");
for (KeepAliveResponseKey keepAliveResponseKey : pingMap.keySet()) {
if (!keepAliveResponseKey.getAddress().equals(inetAddress.get()) || !(keepAliveResponseKey.getId() == keepAlive.getRandomId())) {
continue;
}
instance.getCore().debug("KeepAlivePackets matched to DebugKeepAlivePacket");
for (ProxiedPlayer player : BungeeCord.getInstance().getPlayers()) {
if (!(player).getPendingConnection().getSocketAddress().equals(inetAddress.get())) {
continue;
}
instance.getCore().debug("Player matched to DebugKeepAlivePacket (loading data...)");
EpollTcpInfo tcpInfo = ((EpollSocketChannel) channel).tcpInfo();
EpollTcpInfo tcpInfoBackend = ((EpollSocketChannel) ((UserConnection) player).getServer().getCh().getHandle()).tcpInfo();
long ping = System.currentTimeMillis() - pingMap.get(keepAliveResponseKey);
long neoRTT = 0;
long backendRTT = 0;
if (tcpInfo != null) {
neoRTT = tcpInfo.rtt() / 1000;
}
if (tcpInfoBackend != null) {
backendRTT = tcpInfoBackend.rtt() / 1000;
}
ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();
if (!map.containsKey(player.getName())) {
instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>());
}
map.get(player.getName()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));
instance.getCore().debug("Loading completed");
instance.getCore().debug(" ");
}
| instance.getCore().getPingMap().remove(keepAliveResponseKey); |
}
}
});
}
public static boolean isIPInRange(String ipRange, String ipAddress) {
if (!ipRange.contains("/")) {
ipRange = ipRange + "/32";
}
long targetIntAddress = ipToDecimal(ipAddress);
int range = Integer.parseInt(ipRange.split("/")[1]);
String startIP = ipRange.split("/")[0];
long startIntAddress = ipToDecimal(startIP);
return targetIntAddress <= (startIntAddress + (long) Math.pow(2, (32 - range))) && targetIntAddress >= startIntAddress;
}
public static long ipToDecimal(String ipAddress) throws IllegalArgumentException {
String[] parts = ipAddress.split("\\.");
if (parts.length != 4) {
return -1;
}
long decimal = 0;
for (int i = 0; i < 4; i++) {
int octet = Integer.parseInt(parts[i]);
if (octet < 0 || octet > 255) {
return -1;
}
decimal += (long) (octet * Math.pow(256, 3 - i));
}
return decimal;
}
}
| src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " 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": 120.85282720626103
},
{
"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": 109.91135732649549
},
{
"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": 59.170371991940016
},
{
"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": 56.44598135312589
},
{
"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": 45.69781811675737
}
] | java | instance.getCore().getPingMap().remove(keepAliveResponseKey); |
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest | .request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject(); |
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
| src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/ResponseManager.java",
"retrieved_chunk": " }\n public JSONObject getResponseBodyObject() {\n try {\n return new JSONObject(responseBody);\n } catch (JSONException ignored) {}\n return new JSONObject();\n }\n public JSONArray getResponseBodyArray() {\n try {\n return new JSONArray(responseBody);",
"score": 41.84759250932232
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RequestType.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\n@SuppressWarnings(\"unused\")\npublic enum RequestType {\n GET_ATTACKS,\n GET_ATTACKS_GAMESHIELD,\n GET_GAMESHIELD_BACKENDS,\n POST_GAMESHIELD_BACKEND_CREATE,\n POST_GAMESHIELD_BACKEND_UPDATE,\n DELETE_GAMESHIELD_BACKEND_UPDATE,\n POST_GAMESHIELD_BACKEND_AVAILABLE,",
"score": 40.00372951657245
},
{
"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": 39.6184536542287
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " }\n public static String getLanguage() {\n return language;\n }\n public static String getGameShieldID() {\n return gameShieldID;\n }\n public static String getBackendID() {\n return backendID;\n }",
"score": 34.485220790766334
},
{
"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": 33.51515776253052
}
] | java | .request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject(); |
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType. | POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200); |
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
| src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/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": 91.97022810205331
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " }\n public static String getLanguage() {\n return language;\n }\n public static String getGameShieldID() {\n return gameShieldID;\n }\n public static String getBackendID() {\n return backendID;\n }",
"score": 49.572239983561225
},
{
"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": 49.15073418718938
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " }\n protected Response callRequest(Request request) {\n try {\n return client.newCall(request).execute();\n } catch (UnknownHostException | SocketTimeoutException | SocketException connectionException) {\n if(!request.url().toString().equals(core.getRestAPI().getStatsServer())) {\n core.severe(request + \" failed cause (\" + connectionException + \")\");\n }else\n core.debug(request + \" failed cause (\" + connectionException + \")\");\n } catch (Exception exception) {",
"score": 41.35863130677082
},
{
"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": 40.236628276664234
}
] | 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/ResponseManager.java",
"retrieved_chunk": " }\n public JSONObject getResponseBodyObject() {\n try {\n return new JSONObject(responseBody);\n } catch (JSONException ignored) {}\n return new JSONObject();\n }\n public JSONArray getResponseBodyArray() {\n try {\n return new JSONArray(responseBody);",
"score": 40.356503229401504
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RequestType.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\n@SuppressWarnings(\"unused\")\npublic enum RequestType {\n GET_ATTACKS,\n GET_ATTACKS_GAMESHIELD,\n GET_GAMESHIELD_BACKENDS,\n POST_GAMESHIELD_BACKEND_CREATE,\n POST_GAMESHIELD_BACKEND_UPDATE,\n DELETE_GAMESHIELD_BACKEND_UPDATE,\n POST_GAMESHIELD_BACKEND_AVAILABLE,",
"score": 28.20566263971953
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " }\n public static String getLanguage() {\n return language;\n }\n public static String getGameShieldID() {\n return gameShieldID;\n }\n public static String getBackendID() {\n return backendID;\n }",
"score": 26.082412602602307
},
{
"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": 22.241557675655464
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java",
"retrieved_chunk": " getServer().getOnlineMode(),\n Config.isProxyProtocol()\n );\n }\n @Override\n public void sendMessage(Object receiver, String text) {\n sendMessage(receiver, text, null, null, null, null);\n }\n @Override\n @SuppressWarnings(\"deprecation\")",
"score": 21.61582808256312
}
] | java | (isAPIInvalid(Config.getAPIKey())) { |
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest | .request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true"); |
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
| src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/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": 61.07011890210506
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " }\n public static String getLanguage() {\n return language;\n }\n public static String getGameShieldID() {\n return gameShieldID;\n }\n public static String getBackendID() {\n return backendID;\n }",
"score": 31.992113819107008
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/model/Backend.java",
"retrieved_chunk": " this.geyser = geyser;\n }\n public boolean compareById(String otherId) {\n return id.equals(otherId);\n }\n public String getId() {\n return id;\n }\n public String getIp() {\n return ip;",
"score": 31.37453820694092
},
{
"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": 29.235645695156222
},
{
"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": 28.82479285651469
}
] | 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/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": 103.61117097205678
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " }\n public static String getLanguage() {\n return language;\n }\n public static String getGameShieldID() {\n return gameShieldID;\n }\n public static String getBackendID() {\n return backendID;\n }",
"score": 48.29567465297526
},
{
"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": 44.00798047947727
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " private static boolean proxyProtocol;\n private static String gameShieldID;\n private static String backendID;\n private static String geyserBackendID;\n private static boolean updateIP;\n private static boolean debugMode;\n private static String geyserServerIP;\n private static String updateSetting;\n private static Core core;\n private static FileUtils fileUtils;",
"score": 43.19497684858041
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": " }\n protected Response callRequest(Request request) {\n try {\n return client.newCall(request).execute();\n } catch (UnknownHostException | SocketTimeoutException | SocketException connectionException) {\n if(!request.url().toString().equals(core.getRestAPI().getStatsServer())) {\n core.severe(request + \" failed cause (\" + connectionException + \")\");\n }else\n core.debug(request + \" failed cause (\" + connectionException + \")\");\n } catch (Exception exception) {",
"score": 35.10055674114953
}
] | java | Config.getGameShieldID()); |
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
| if (Config.isUpdateIP()) { |
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic"));
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
| src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIManager.java",
"retrieved_chunk": "import java.util.Formatter;\nimport java.util.concurrent.TimeUnit;\npublic class RestAPIManager {\n private final OkHttpClient client = new OkHttpClient();\n private final String baseURL = \"https://api.neoprotect.net/v2\";\n private final Core core;\n public RestAPIManager(Core core) {\n this.core = core;\n }\n {",
"score": 46.1258747323532
},
{
"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": 29.276920170685898
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/NeoProtectVelocity.java",
"retrieved_chunk": " core = new Core(this);\n new Startup(this);\n }\n public Core getCore() {\n return core;\n }\n @Override\n public Stats getStats() {\n return new Stats(\n getPluginType(),",
"score": 27.0695471247169
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/NeoProtectSpigot.java",
"retrieved_chunk": " public void onLoad() {\n Metrics metrics = new Metrics(this, 18725);\n metrics.addCustomChart(new SimplePie(\"language\", Config::getLanguage));\n }\n @Override\n public void onEnable() {\n core = new Core(this);\n new Startup(this);\n }\n public Core getCore() {",
"score": 24.92671198919829
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/NeoProtectBungee.java",
"retrieved_chunk": " new Startup(this);\n }\n public Core getCore() {\n return core;\n }\n @Override\n public Stats getStats() {\n return new Stats(\n getPluginType(),\n getProxy().getVersion(),",
"score": 21.769597419445294
}
] | 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": " 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": 54.63610436022612
},
{
"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": 30.00351059507934
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() & !args[0].equals(\"setup\") & !args[0].equals(\"setgameshield\") & !args[0].equals(\"setbackend\")) {\n instance.sendMessage(sender, localization.get(locale, \"setup.command.required\"));\n return;\n }\n switch (args[0].toLowerCase()) {\n case \"setup\": {\n if (isViaConsole) {\n instance.sendMessage(sender, localization.get(Locale.getDefault(), \"console.command\"));\n } else {",
"score": 29.617969317776346
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " @Override\n protected void initChannel(Channel channel) {\n if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {\n instance.getCore().debug(\"Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)\");\n return;\n }\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {\n channel.close();\n instance.getCore().debug(\"Player connected over IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (warning)\");",
"score": 29.486259985755165
},
{
"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": 29.05920353386661
}
] | java | setProxyProtocol(Config.isProxyProtocol()); |
package de.cubeattack.neoprotect.core.request;
import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import de.cubeattack.api.libraries.org.json.JSONArray;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.api.util.versioning.VersionUtils;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.Core;
import de.cubeattack.neoprotect.core.JsonBuilder;
import de.cubeattack.neoprotect.core.Permission;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Firewall;
import de.cubeattack.neoprotect.core.model.Gameshield;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class RestAPIRequests {
@SuppressWarnings("FieldCanBeLocal")
private final String ipGetter = "https://api4.my-ip.io/ip.json";
@SuppressWarnings("FieldCanBeLocal")
private final String pasteServer = "https://paste.neoprotect.net/documents";
@SuppressWarnings("FieldCanBeLocal")
private final String statsServer = "https://metrics.einfachesache.de/api/stats/plugin";
private JSONArray neoServerIPs = null;
private boolean setup = false;
private final Core core;
private final RestAPIManager rest;
public RestAPIRequests(Core core) {
this.core = core;
this.rest = new RestAPIManager(core);
testCredentials();
attackCheckSchedule();
statsUpdateSchedule();
versionCheckSchedule();
neoServerIPsUpdateSchedule();
if (Config.isUpdateIP()) {
backendServerIPUpdater();
}
}
private String getIpv4() {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(ipGetter).build())).getResponseBodyObject().getString("ip");
}catch (Exception ignore){}
return null;
}
private JSONArray getNeoIPs() {
return new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_NEO_SERVER_IPS)).build())).getResponseBodyArray();
}
public boolean isAPIInvalid(String apiKey) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder(apiKey).url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_ATTACKS)).build())).checkCode(200);
}
public boolean isGameshieldInvalid(String gameshieldID) {
return !new ResponseManager(rest.callRequest(rest.defaultBuilder().url(rest.getBaseURL() + rest.getSubDirectory(RequestType.GET_GAMESHIELD_INFO, gameshieldID)).build())).checkCode(200);
}
public boolean isBackendInvalid(String backendID) {
return getBackends().stream().noneMatch(e -> e.compareById(backendID));
}
private boolean isAttack() {
return rest.request(RequestType.GET_GAMESHIELD_ISUNDERATTACK, null, Config.getGameShieldID()).getResponseBody().equals("true");
}
public String getPlan() {
try {
return rest.request(RequestType.GET_GAMESHIELD_PLAN, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldPlan").getJSONObject("options").getString("name");
}catch (Exception ignore){}
return null;
}
private boolean updateStats(RequestBody requestBody, String gameshieldID, String backendID) {
return new ResponseManager(rest.callRequest(new Request.Builder().url(statsServer).header("GameshieldID", gameshieldID).header("BackendID", backendID).post(requestBody).build())).checkCode(200);
}
private boolean updateBackend(RequestBody requestBody, String backendID) {
return rest.request(RequestType.POST_GAMESHIELD_BACKEND_UPDATE, requestBody, Config.getGameShieldID(),backendID).checkCode(200);
}
public void setProxyProtocol(boolean setting) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE, RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("proxyProtocol", String.valueOf(setting)).build().toString()), Config.getGameShieldID());
}
public JSONObject getAnalytics() {
return rest.request(RequestType.GET_GAMESHIELD_LASTSTATS, null, Config.getGameShieldID()).getResponseBodyObject();
}
public JSONObject getTraffic() {
return rest.request(RequestType.GET_GAMESHIELD_BANDWIDTH, null, Config.getGameShieldID()).getResponseBodyObject();
}
public void testCredentials() {
if (isAPIInvalid(Config.getAPIKey())) {
core.severe("API is not valid! Please run /neoprotect setup to set the API Key");
setup = false;
return;
} else if (isGameshieldInvalid(Config.getGameShieldID())) {
core.severe("Gameshield is not valid! Please run /neoprotect setgameshield to set the gameshield");
setup = false;
return;
} else if (isBackendInvalid(Config.getBackendID())) {
core.severe("Backend is not valid! Please run /neoprotect setbackend to set the backend");
setup = false;
return;
}
this.setup = true;
setProxyProtocol(Config.isProxyProtocol());
| Config.addAutoUpdater(getPlan().equalsIgnoreCase("Basic")); |
}
public String paste(String content) {
try {
return new ResponseManager(rest.callRequest(new Request.Builder().url(pasteServer)
.post(RequestBody.create(MediaType.parse("text/plain"), content)).build())).getResponseBodyObject().getString("key");
} catch (Exception ignore) {}
return null;
}
public boolean togglePanicMode() {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
String mitigationSensitivity = settings.getString("mitigationSensitivity");
if (mitigationSensitivity.equals("UNDER_ATTACK")) {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "MEDIUM").toString()),
Config.getGameShieldID());
return false;
} else {
rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put("mitigationSensitivity", "UNDER_ATTACK").toString()),
Config.getGameShieldID());
return true;
}
}
public int toggle(String mode) {
JSONObject settings = rest.request(RequestType.GET_GAMESHIELD_INFO, null, Config.getGameShieldID()).getResponseBodyObject().getJSONObject("gameShieldSettings");
if(!settings.has(mode)) return -1;
boolean mitigationSensitivity = settings.getBoolean(mode);
if (mitigationSensitivity) {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, false).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 0 : code;
} else {
int code = rest.request(RequestType.POST_GAMESHIELD_UPDATE,
RequestBody.create(MediaType.parse("application/json"), settings.put(mode, true).toString()),
Config.getGameShieldID()).getCode();
return code == 200 ? 1 : code;
}
}
public List<Gameshield> getGameshields() {
List<Gameshield> list = new ArrayList<>();
JSONArray gameshields = rest.request(RequestType.GET_GAMESHIELDS, null).getResponseBodyArray();
for (Object object : gameshields) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Gameshield(jsonObject.getString("id"), jsonObject.getString("name")));
}
return list;
}
public List<Backend> getBackends() {
List<Backend> list = new ArrayList<>();
JSONArray backends = rest.request(RequestType.GET_GAMESHIELD_BACKENDS, null, Config.getGameShieldID()).getResponseBodyArray();
for (Object object : backends) {
JSONObject jsonObject = (JSONObject) object;
list.add(new Backend(jsonObject.getString("id"), jsonObject.getString("ipv4"), String.valueOf(jsonObject.getInt("port")), jsonObject.getBoolean("geyser")));
}
return list;
}
public List<Firewall> getFirewall(String mode) {
List<Firewall> list = new ArrayList<>();
JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();
for (Object object : firewalls) {
JSONObject firewallJSON = (JSONObject) object;
list.add(new Firewall(firewallJSON.getString("ip"), firewallJSON.get("id").toString()));
}
return list;
}
public int updateFirewall(String ip, String action, String mode) {
if(action.equalsIgnoreCase("REMOVE")){
Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);
if(firewall == null){
return 0;
}
return rest.request(RequestType.DELETE_FIREWALL, null, Config.getGameShieldID(), firewall.getId()).getCode();
}else if(action.equalsIgnoreCase("ADD")){
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("entry", ip).build().toString());
return rest.request(RequestType.POST_FIREWALL_CREATE, requestBody, Config.getGameShieldID(), mode).getCode();
}
return -1;
}
private void statsUpdateSchedule() {
core.info("StatsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(core.getPlugin().getStats()));
if(!updateStats(requestBody, Config.getGameShieldID(),Config.getBackendID()))
core.debug("Request to Update stats failed");
}
}, 1000, 1000 * 5);
}
private void neoServerIPsUpdateSchedule() {
core.info("NeoServerIPsUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
JSONArray IPs = getNeoIPs();
neoServerIPs = IPs.isEmpty() ? neoServerIPs : IPs;
}
}, 0, 1000 * 60);
}
private void versionCheckSchedule() {
core.info("VersionCheck scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
core.setVersionResult(VersionUtils.checkVersion("NeoProtect", "NeoPlugin", "v" + core.getPlugin().getPluginVersion(), Config.getAutoUpdaterSettings()));
}
}, 1000 * 10, 1000 * 60 * 5);
}
private void attackCheckSchedule() {
core.info("AttackCheck scheduler started");
final Boolean[] attackRunning = {false};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
if (!isAttack()) {
attackRunning[0] = false;
return;
}
if (!attackRunning[0]) {
core.warn("Gameshield ID '" + Config.getGameShieldID() + "' is under attack");
core.getPlugin().sendAdminMessage(Permission.NOTIFY, "Gameshield ID '" + Config.getGameShieldID() + "' is under attack", null, null, null, null);
attackRunning[0] = true;
}
}
}, 1000 * 5, 1000 * 10);
}
private void backendServerIPUpdater() {
core.info("BackendServerIPUpdate scheduler started");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!setup) return;
Backend javaBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getBackendID())).findAny().orElse(null);
Backend geyserBackend = getBackends().stream().filter(unFilteredBackend -> unFilteredBackend.compareById(Config.getGeyserBackendID())).findAny().orElse(null);
String ip = getIpv4();
if (ip == null) return;
if (javaBackend != null) {
if (!ip.equals(javaBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getBackendID())) {
core.warn("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update java backendserver ID '" + Config.getBackendID() + "' to IP '" + ip + "' success");
javaBackend.setIp(ip);
}
}
}
if (geyserBackend != null) {
if (!ip.equals(geyserBackend.getIp())) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JsonBuilder().appendField("ipv4", ip).build().toString());
if (!updateBackend(requestBody, Config.getGeyserBackendID())) {
core.warn("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' failed");
} else {
core.info("Update geyser backendserver ID '" + Config.getGeyserBackendID() + "' to IP '" + ip + "' success");
geyserBackend.setIp(ip);
}
}
}
}
}, 1000, 1000 * 20);
}
public JSONArray getNeoServerIPs() {
return neoServerIPs;
}
public String getStatsServer() {
return statsServer;
}
public boolean isSetup() {
return setup;
}
}
| src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/Config.java",
"retrieved_chunk": " 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": 32.797911586372685
},
{
"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": 27.284272295785602
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": " }\n if (!instance.getCore().isSetup() & !args[0].equals(\"setup\") & !args[0].equals(\"setgameshield\") & !args[0].equals(\"setbackend\")) {\n instance.sendMessage(sender, localization.get(locale, \"setup.command.required\"));\n return;\n }\n switch (args[0].toLowerCase()) {\n case \"setup\": {\n if (isViaConsole) {\n instance.sendMessage(sender, localization.get(Locale.getDefault(), \"console.command\"));\n } else {",
"score": 25.944577402948187
},
{
"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": 24.98180210492231
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " @Override\n protected void initChannel(Channel channel) {\n if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {\n instance.getCore().debug(\"Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)\");\n return;\n }\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {\n channel.close();\n instance.getCore().debug(\"Player connected over IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (warning)\");",
"score": 24.039758225833708
}
] | 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": " instance.sendMessage(sender, \"IP: \" + firewall.getIp() + \" ID(\" + firewall.getId() + \")\")));\n } else if (args.length == 3) {\n String ip = args[2];\n String action = args[1];\n String mode = args[0].toUpperCase();\n int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);\n if (response == -1) {\n instance.sendMessage(sender, localization.get(locale, \"usage.firewall\"));\n return;\n }",
"score": 37.02181848623601
},
{
"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": 34.70044356566636
},
{
"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": 28.278901706078678
},
{
"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": 25.847847320267814
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RequestType.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\n@SuppressWarnings(\"unused\")\npublic enum RequestType {\n GET_ATTACKS,\n GET_ATTACKS_GAMESHIELD,\n GET_GAMESHIELD_BACKENDS,\n POST_GAMESHIELD_BACKEND_CREATE,\n POST_GAMESHIELD_BACKEND_UPDATE,\n DELETE_GAMESHIELD_BACKEND_UPDATE,\n POST_GAMESHIELD_BACKEND_AVAILABLE,",
"score": 25.13264338237706
}
] | 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": " 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": 69.89519172898632
},
{
"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": 52.52176728071674
},
{
"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": 33.782610841224326
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.executor;\nimport de.cubeattack.api.API;\nimport de.cubeattack.api.language.Localization;\nimport de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;\nimport de.cubeattack.api.libraries.org.json.JSONObject;\nimport de.cubeattack.neoprotect.core.Config;\nimport de.cubeattack.neoprotect.core.NeoProtectPlugin;\nimport de.cubeattack.neoprotect.core.model.Backend;\nimport de.cubeattack.neoprotect.core.model.Gameshield;\nimport de.cubeattack.neoprotect.core.model.Stats;",
"score": 31.59374280654902
},
{
"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": 29.473966877864036
}
] | 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": " 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": 46.09415651282469
},
{
"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": 42.176919956090295
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/ResponseManager.java",
"retrieved_chunk": " }\n public JSONObject getResponseBodyObject() {\n try {\n return new JSONObject(responseBody);\n } catch (JSONException ignored) {}\n return new JSONObject();\n }\n public JSONArray getResponseBodyArray() {\n try {\n return new JSONArray(responseBody);",
"score": 40.356503229401504
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RequestType.java",
"retrieved_chunk": "package de.cubeattack.neoprotect.core.request;\n@SuppressWarnings(\"unused\")\npublic enum RequestType {\n GET_ATTACKS,\n GET_ATTACKS_GAMESHIELD,\n GET_GAMESHIELD_BACKENDS,\n POST_GAMESHIELD_BACKEND_CREATE,\n POST_GAMESHIELD_BACKEND_UPDATE,\n DELETE_GAMESHIELD_BACKEND_UPDATE,\n POST_GAMESHIELD_BACKEND_AVAILABLE,",
"score": 33.08387268851176
},
{
"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": 29.036298171702374
}
] | 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/request/ResponseManager.java",
"retrieved_chunk": " }\n public JSONObject getResponseBodyObject() {\n try {\n return new JSONObject(responseBody);\n } catch (JSONException ignored) {}\n return new JSONObject();\n }\n public JSONArray getResponseBodyArray() {\n try {\n return new JSONArray(responseBody);",
"score": 38.227062723745576
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " return CompletableFuture.supplyAsync(() -> {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();\n String[] args = invocation.arguments();\n 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\");",
"score": 35.766718895820574
},
{
"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": 28.98629103453087
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " // We need to synchronize against this list\n networkManagers = Reflection.isNewerPackage() || Reflection.VERSION.contains(\"16\") ? networkManagersFieldAccessor.get(serverConnection) : (List<Object>) getNetworkMarkers.invoke(null, serverConnection);\n createServerChannelHandler();\n // Find the correct list, or implicitly throw an exception\n for (int i = 0; looking; i++) {\n List<Object> list = Reflection.getField(serverConnection.getClass(), List.class, i).get(serverConnection);\n for (Object item : list) {\n if (!(item instanceof ChannelFuture))\n break;\n // Channel future that contains the server connection",
"score": 28.738727575747248
},
{
"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": 28.3618274733906
}
] | java | null, Config.getGameShieldID()).getResponseBodyArray(); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
| Config.setGeyserBackendID(args[1]); |
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " 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": 41.165554203007794
},
{
"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": 39.16621608572482
},
{
"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": 37.50986421505421
},
{
"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": 37.50986421505421
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " }\n if (tab.toLowerCase().startsWith(args[args.length - 1].toLowerCase())) {\n completorList.add(tab);\n }\n }\n return completorList;\n }\n}",
"score": 36.46475066358338
}
] | 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": " 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": 45.371830571715876
},
{
"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": 39.36595241358798
},
{
"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": 39.36595241358798
},
{
"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": 39.16621608572482
},
{
"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": 38.471140648896636
}
] | 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/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": 66.80953090738463
},
{
"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": 62.61649911501685
},
{
"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": 62.61649911501685
},
{
"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": 58.12652158269771
},
{
"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": 57.07311368209083
}
] | 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": 102.924769063997
},
{
"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": 44.45644888424578
},
{
"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": 40.2873826318335
},
{
"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": 32.55145883198292
},
{
"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": 32.391375985423764
}
] | java | getBackends().stream().noneMatch(e -> e.compareById(backendID)); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic | = instance.getCore().getRestAPI().getTraffic(); |
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\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": 39.465379065941036
},
{
"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": 38.91150084877153
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " @Override\n protected void initChannel(Channel channel) {\n if (!Config.isProxyProtocol() | !instance.getCore().isSetup() | instance.getCore().getDirectConnectWhitelist().contains(((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())) {\n instance.getCore().debug(\"Plugin is not setup / ProxyProtocol is off / Player is on DirectConnectWhitelist (return)\");\n return;\n }\n if (instance.getCore().isSetup() && (instance.getCore().getRestAPI().getNeoServerIPs() == null ||\n instance.getCore().getRestAPI().getNeoServerIPs().toList().stream().noneMatch(ipRange -> isIPInRange((String) ipRange, ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress())))) {\n channel.close();\n instance.getCore().debug(\"Player connected over IP (\" + channel.remoteAddress() + \") doesn't match to Neo-IPs (warning)\");",
"score": 35.206885862931024
},
{
"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": 33.75290785632483
},
{
"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": 33.54131300716752
}
] | 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/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": 39.16621608572482
},
{
"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": 38.81704824191594
},
{
"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": 38.471140648896636
},
{
"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": 37.50986421505421
},
{
"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": 37.50986421505421
}
] | 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/spigot/command/NeoProtectCommand.java",
"retrieved_chunk": " .neoProtectPlugin(instance)\n .sender(sender)\n .args(args)\n .executeCommand();\n return false;\n }\n}",
"score": 36.87614523358191
},
{
"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": 35.48229343501398
},
{
"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": 35.34705770327863
},
{
"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": 34.65998624523786
},
{
"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": 32.64701767246086
}
] | java | instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----"); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
| Config.setAPIKey(msg); |
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/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": 26.098246221664454
},
{
"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": 25.265374458138602
},
{
"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": 25.265374458138602
},
{
"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": 24.98251541259747
},
{
"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": 24.150424253045323
}
] | 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/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": 33.28539644193377
},
{
"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": 31.24395305302066
},
{
"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": 30.756921719393656
},
{
"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": 29.454591397954374
},
{
"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": 29.454591397954374
}
] | java | (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) { |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
| instance.getCore().severe(ex.getMessage(), ex); |
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"plugin.outdated.message\", result.getCurrentVersion(), result.getLatestVersion()));\n instance.sendMessage(player, MessageFormat.format(\"§7-> §b{0}\",\n result.getReleaseUrl().replace(\"/NeoPlugin\", \"\").replace(\"/releases/tag\", \"\")),\n \"OPEN_URL\", result.getReleaseUrl(), null, null);\n }\n if (result.getVersionStatus().equals(VersionUtils.VersionStatus.REQUIRED_RESTART)) {\n instance.sendMessage(player, localization.get(locale, \"plugin.restart-required.message\", result.getCurrentVersion(), result.getLatestVersion()));\n }\n if (!instance.getCore().isSetup() && instance.getCore().getPlayerInSetup().isEmpty()) {\n instance.sendMessage(player, localization.get(locale, \"setup.required.first\"));",
"score": 111.59892818446761
},
{
"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": 99.01199551338021
},
{
"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": 99.01199551338021
},
{
"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": 96.37211929689411
},
{
"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": 94.54493221834547
}
] | java | instance.getCore().severe(ex.getMessage(), ex); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int | response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode); |
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/core/request/RestAPIRequests.java",
"retrieved_chunk": " JSONArray firewalls = rest.request(RequestType.GET_FIREWALLS, null, Config.getGameShieldID(), mode.toUpperCase()).getResponseBodyArray();\n for (Object object : firewalls) {\n JSONObject firewallJSON = (JSONObject) object;\n list.add(new Firewall(firewallJSON.getString(\"ip\"), firewallJSON.get(\"id\").toString()));\n }\n return list;\n }\n public int updateFirewall(String ip, String action, String mode) {\n if(action.equalsIgnoreCase(\"REMOVE\")){\n Firewall firewall = getFirewall(mode).stream().filter(f -> f.getIp().equals(ip)).findFirst().orElse(null);",
"score": 72.59969097897765
},
{
"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": 68.05125566619245
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " for (String tab : list) {\n if (args.length == 0) {\n completorList.add(tab);\n continue;\n }\n if (tab.toLowerCase().startsWith(args[args.length - 1].toLowerCase())) {\n completorList.add(tab);\n }\n }\n return completorList;",
"score": 66.41680196309045
},
{
"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": 64.6311274261265
},
{
"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": 62.641084247025304
}
] | 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/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": 65.26446230738928
},
{
"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": 62.77523867319282
},
{
"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": 62.77523867319282
},
{
"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": 56.31747037608524
},
{
"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": 55.27531177157273
}
] | 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/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"setup.required.second\"));\n }\n if (instance.getCore().isPlayerMaintainer(player.getUniqueId(), instance.getServer().getOnlineMode())) {\n Stats stats = instance.getStats();\n String infos =\n \"§bOsName§7: \" + System.getProperty(\"os.name\") + \" \\n\" +\n \"§bJavaVersion§7: \" + System.getProperty(\"java.version\") + \" \\n\" +\n \"§bPluginVersion§7: \" + stats.getPluginVersion() + \" \\n\" +\n \"§bVersionStatus§7: \" + instance.getCore().getVersionResult().getVersionStatus() + \" \\n\" +\n \"§bUpdateSetting§7: \" + Config.getAutoUpdaterSettings() + \" \\n\" +",
"score": 48.699631687078444
},
{
"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": 46.85724961605516
},
{
"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": 44.066168071079744
},
{
"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": 40.884217831681795
},
{
"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": 40.884217831681795
}
] | 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/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": 36.13039812901189
},
{
"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": 30.54131291622817
},
{
"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": 30.268744552111315
},
{
"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": 29.91585316928137
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": "public class NeoProtectCommand extends Command implements TabExecutor {\n private final NeoProtectPlugin instance;\n public NeoProtectCommand(NeoProtectPlugin instance, String name, String permission, String... aliases) {\n super(name, permission, aliases);\n this.instance = instance;\n }\n @Override\n public void execute(CommandSender sender, String[] args) {\n new NeoProtectExecutor.ExecutorBuilder()\n .viaConsole(!(sender instanceof ProxiedPlayer))",
"score": 28.42409246875685
}
] | java | if (instance.getCore().getRestAPI().isAPIInvalid(msg)) { |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
| instance.getCore().setDebugRunning(false); |
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/command/NeoProtectCommand.java",
"retrieved_chunk": " if (args.length == 2) {\n if (args[0].equalsIgnoreCase(\"debugtool\")) {\n for (int i = 10; i <= 100; i = i + 10) {\n list.add(String.valueOf(i));\n }\n list.add(\"cancel\");\n }\n if ((args[0].equalsIgnoreCase(\"whitelist\") || args[0].equalsIgnoreCase(\"blacklist\"))) {\n list.add(\"add\");\n list.add(\"remove\");",
"score": 37.758645194421845
},
{
"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": 37.492109458757334
},
{
"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": 36.75556510201707
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/command/NeoProtectCommand.java",
"retrieved_chunk": " return CompletableFuture.supplyAsync(() -> {\n List<String> list = new ArrayList<>();\n List<String> completorList = new ArrayList<>();\n String[] args = invocation.arguments();\n 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\");",
"score": 36.639185044079824
},
{
"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": 35.09233920982448
}
] | 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/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": 47.40218783071483
},
{
"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": 44.79097977378002
},
{
"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": 44.79097977378002
},
{
"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": 43.11466323148631
},
{
"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": 42.317402675885376
}
] | java | instance.getCore().isDebugRunning()) { |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
| instance.getCore().getPlayerInSetup().add(sender); |
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/listener/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": 15.816167952798075
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/velocity/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": 13.455088941579794
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/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": 13.455088941579794
},
{
"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": 13.408115224811095
},
{
"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": 12.653683292874312
}
] | 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/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": 76.0657777854929
},
{
"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": 67.8289013223164
},
{
"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": 67.8289013223164
},
{
"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": 66.27191883301344
},
{
"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": 65.00429562039581
}
] | java | , instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated"))); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
| instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); |
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"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": 54.25637450477182
},
{
"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": 53.71942428270778
},
{
"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": 53.71942428270778
},
{
"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": 49.63076001525558
},
{
"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": 48.70077970119435
}
] | java | instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------"); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
| instance.getCore().getDebugPingResponses().clear(); |
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
instance.sendMessage(sender, " - /np analytics");
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " if (tcpInfoBackend != null) {\n backendRTT = tcpInfoBackend.rtt() / 1000;\n }\n ConcurrentHashMap<String, ArrayList<DebugPingResponse>> map = instance.getCore().getDebugPingResponses();\n if (!map.containsKey(player.getName())) {\n instance.getCore().getDebugPingResponses().put(player.getName(), new ArrayList<>());\n }\n map.get(player.getName()).add(new DebugPingResponse(ping, neoRTT, backendRTT, inetAddress.get(), channel.remoteAddress()));\n instance.getCore().debug(\"Loading completed\");\n instance.getCore().debug(\" \");",
"score": 38.976345751111126
},
{
"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": 36.022874064137504
},
{
"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": 31.684600588295407
},
{
"filename": "src/main/java/de/cubeattack/neoprotect/bungee/proxyprotocol/ProxyProtocol.java",
"retrieved_chunk": " }\n instance.getCore().debug(\"Player matched to DebugKeepAlivePacket (loading data...)\");\n EpollTcpInfo tcpInfo = ((EpollSocketChannel) channel).tcpInfo();\n EpollTcpInfo tcpInfoBackend = ((EpollSocketChannel) ((UserConnection) player).getServer().getCh().getHandle()).tcpInfo();\n long ping = System.currentTimeMillis() - pingMap.get(keepAliveResponseKey);\n long neoRTT = 0;\n long backendRTT = 0;\n if (tcpInfo != null) {\n neoRTT = tcpInfo.rtt() / 1000;\n }",
"score": 26.993794992276943
},
{
"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": 25.866375658870833
}
] | 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": 50.843854963090735
},
{
"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": 46.897023960263304
},
{
"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": 46.73300284207036
},
{
"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": 46.73300284207036
},
{
"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": 46.049398314481465
}
] | 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": 52.196492443328914
},
{
"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": 50.53074891627722
},
{
"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": 50.53074891627722
},
{
"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": 46.95891304378515
},
{
"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": 46.09169251534907
}
] | java | instance.getCore().setDebugRunning(true); |
package de.cubeattack.neoprotect.core.executor;
import de.cubeattack.api.API;
import de.cubeattack.api.language.Localization;
import de.cubeattack.api.libraries.org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import de.cubeattack.api.libraries.org.json.JSONObject;
import de.cubeattack.neoprotect.core.Config;
import de.cubeattack.neoprotect.core.NeoProtectPlugin;
import de.cubeattack.neoprotect.core.model.Backend;
import de.cubeattack.neoprotect.core.model.Gameshield;
import de.cubeattack.neoprotect.core.model.Stats;
import de.cubeattack.neoprotect.core.model.debugtool.DebugPingResponse;
import java.io.File;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class NeoProtectExecutor {
private static Timer debugTimer = new Timer();
private NeoProtectPlugin instance;
private Localization localization;
private Object sender;
private Locale locale;
private String msg;
private String[] args;
private boolean isViaConsole;
private void initials(ExecutorBuilder executeBuilder) {
this.instance = executeBuilder.getInstance();
this.localization = instance.getCore().getLocalization();
this.sender = executeBuilder.getSender();
this.locale = executeBuilder.getLocal();
this.args = executeBuilder.getArgs();
this.msg = executeBuilder.getMsg();
this.isViaConsole = executeBuilder.isViaConsole();
}
private void chatEvent(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (instance.getCore().getRestAPI().isAPIInvalid(msg)) {
instance.sendMessage(sender, localization.get(locale, "apikey.invalid"));
return;
}
Config.setAPIKey(msg);
instance.sendMessage(sender, localization.get(locale, "apikey.valid"));
gameshieldSelector();
}
private void command(ExecutorBuilder executorBuilder) {
initials(executorBuilder);
if (args.length == 0) {
showHelp();
return;
}
if (!instance.getCore().isSetup() & !args[0].equals("setup") & !args[0].equals("setgameshield") & !args[0].equals("setbackend")) {
instance.sendMessage(sender, localization.get(locale, "setup.command.required"));
return;
}
switch (args[0].toLowerCase()) {
case "setup": {
if (isViaConsole) {
instance.sendMessage(sender, localization.get(Locale.getDefault(), "console.command"));
} else {
setup();
}
break;
}
case "ipanic": {
iPanic(args);
break;
}
case "directconnectwhitelist": {
directConnectWhitelist(args);
break;
}
case "toggle": {
toggle(args);
break;
}
case "analytics": {
analytics();
break;
}
case "whitelist":
case "blacklist": {
firewall(args);
break;
}
case "debugtool": {
debugTool(args);
break;
}
case "setgameshield": {
if (args.length == 1 && !isViaConsole) {
gameshieldSelector();
} else if (args.length == 2) {
setGameshield(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgameshield"));
}
break;
}
case "setbackend": {
if (args.length == 1 && !isViaConsole) {
javaBackendSelector();
} else if (args.length == 2) {
setJavaBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setbackend"));
}
break;
}
case "setgeyserbackend": {
if (args.length == 1 && !isViaConsole) {
bedrockBackendSelector();
} else if (args.length == 2) {
setBedrockBackend(args);
} else {
instance.sendMessage(sender, localization.get(locale, "usage.setgeyserbackend"));
}
break;
}
default: {
showHelp();
}
}
}
private void setup() {
instance.getCore().getPlayerInSetup().add(sender);
instance.sendMessage(sender, localization.get(locale, "command.setup") + localization.get(locale, "utils.click"),
"OPEN_URL", "https://panel.neoprotect.net/profile",
"SHOW_TEXT", localization.get(locale, "apikey.find"));
}
private void iPanic(String[] args) {
if (args.length != 1) {
instance.sendMessage(sender, localization.get(locale, "usage.ipanic"));
} else {
instance.sendMessage(sender, localization.get(locale, "command.ipanic",
localization.get(locale, instance.getCore().getRestAPI().togglePanicMode() ? "utils.activated" : "utils.deactivated")));
}
}
private void directConnectWhitelist(String[] args) {
if (args.length == 2) {
instance.getCore().getDirectConnectWhitelist().add(args[1]);
instance.sendMessage(sender, localization.get(locale, "command.directconnectwhitelist", args[1]));
} else {
instance.sendMessage(sender, localization.get(locale, "usage.directconnectwhitelist"));
}
}
private void toggle(String[] args) {
if (args.length != 2) {
instance.sendMessage(sender, localization.get(locale, "usage.toggle"));
} else {
int response = instance.getCore().getRestAPI().toggle(args[1]);
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
if (response == -1) {
instance.sendMessage(sender, "§cCan not found setting '" + args[1] + "'");
return;
}
instance.sendMessage(sender, localization.get(locale, "command.toggle", args[1],
localization.get(locale, response == 1 ? "utils.activated" : "utils.deactivated")));
}
}
private void analytics() {
instance.sendMessage(sender, "§7§l--------- §bAnalytics §7§l---------");
JSONObject analytics = instance.getCore().getRestAPI().getAnalytics();
instance.getCore().getRestAPI().getAnalytics().keySet().forEach(ak -> {
if (ak.equals("bandwidth")) {
return;
}
if (ak.equals("traffic")) {
instance.sendMessage(sender, ak.replace("traffic", "bandwidth") + ": " +
new DecimalFormat("#.####").format((float) analytics.getInt(ak) * 8 / (1000 * 1000)) + " mbit/s");
JSONObject traffic = instance.getCore().getRestAPI().getTraffic();
AtomicReference<String> trafficUsed = new AtomicReference<>();
AtomicReference<String> trafficAvailable = new AtomicReference<>();
traffic.keySet().forEach(bk -> {
if (bk.equals("used")) {
trafficUsed.set(traffic.getFloat(bk) / (1000 * 1000 * 1000) + " gb");
}
if (bk.equals("available")) {
trafficAvailable.set(String.valueOf(traffic.getLong(bk)).equals("999999999") ? "unlimited" : traffic.getLong(bk) + " gb");
}
});
instance.sendMessage(sender, "bandwidth used" + ": " + trafficUsed.get() + "/" + trafficAvailable.get());
return;
}
instance.sendMessage(sender, ak
.replace("onlinePlayers", "online players")
.replace("cps", "connections/s") + ": " + analytics.get(ak));
});
}
private void firewall(String[] args) {
if (args.length == 1) {
instance.sendMessage(sender, "§7§l----- §bFirewall (" + args[0].toUpperCase() + ")§7§l -----");
instance.getCore().getRestAPI().getFirewall(args[0]).forEach((firewall ->
instance.sendMessage(sender, "IP: " + firewall.getIp() + " ID(" + firewall.getId() + ")")));
} else if (args.length == 3) {
String ip = args[2];
String action = args[1];
String mode = args[0].toUpperCase();
int response = instance.getCore().getRestAPI().updateFirewall(ip, action, mode);
if (response == -1) {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
return;
}
if (response == 0) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.notfound", ip, mode));
return;
}
if (response == 400) {
instance.sendMessage(sender, localization.get(locale, "command.firewall.ip-invalid", ip));
return;
}
if (response == 403) {
instance.sendMessage(sender, localization.get(locale, "err.upgrade-plan"));
return;
}
if (response == 429) {
instance.sendMessage(sender, localization.get(locale, "err.rate-limit"));
return;
}
instance.sendMessage(sender, (action.equalsIgnoreCase("add") ? "Added '" : "Removed '") + ip + "' to firewall (" + mode + ")");
} else {
instance.sendMessage(sender, localization.get(locale, "usage.firewall"));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void debugTool(String[] args) {
if (instance.getPluginType() == NeoProtectPlugin.PluginType.SPIGOT) {
instance.sendMessage(sender, localization.get(locale, "debug.spigot"));
return;
}
if (args.length == 2) {
if (args[1].equals("cancel")) {
debugTimer.cancel();
instance.getCore().setDebugRunning(false);
instance.sendMessage(sender, localization.get(locale, "debug.cancelled"));
return;
}
if (!isInteger(args[1])) {
instance.sendMessage(sender, localization.get(locale, "usage.debug"));
return;
}
}
if (instance.getCore().isDebugRunning()) {
instance.sendMessage(sender, localization.get(locale, "debug.running"));
return;
}
instance.getCore().setDebugRunning(true);
instance.sendMessage(sender, localization.get(locale, "debug.starting"));
int amount = args.length == 2 ? (Integer.parseInt(args[1]) <= 0 ? 1 : Integer.parseInt(args[1])) : 5;
debugTimer = new Timer();
debugTimer.schedule(new TimerTask() {
int counter = 0;
@Override
public void run() {
counter++;
instance.getCore().getTimestampsMap().put(instance.sendKeepAliveMessage(new Random().nextInt(90) * 10000 + 1337), new Timestamp(System.currentTimeMillis()));
instance.sendMessage(sender, localization.get(locale, "debug.sendingPackets") + " (" + counter + "/" + amount + ")");
if (counter >= amount) this.cancel();
}
}, 500, 2000);
debugTimer.schedule(new TimerTask() {
@Override
public void run() {
API.getExecutorService().submit(() -> {
try {
long startTime = System.currentTimeMillis();
Stats stats = instance.getStats();
File file = new File("plugins/NeoProtect/debug" + "/" + new Timestamp(System.currentTimeMillis()) + ".yml");
YamlConfiguration configuration = new YamlConfiguration();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.load(file);
configuration.set("general.osName", System.getProperty("os.name"));
configuration.set("general.javaVersion", System.getProperty("java.version"));
configuration.set("general.pluginVersion", stats.getPluginVersion());
configuration.set("general.ProxyName", stats.getServerName());
configuration.set("general.ProxyVersion", stats.getServerVersion());
configuration.set("general.ProxyPlugins", instance.getPlugins());
instance.getCore().getDebugPingResponses().keySet().forEach((playerName -> {
List<DebugPingResponse> list = instance.getCore().getDebugPingResponses().get(playerName);
long maxPlayerToProxyLatenz = 0;
long maxNeoToProxyLatenz = 0;
long maxProxyToBackendLatenz = 0;
long maxPlayerToNeoLatenz = 0;
long avgPlayerToProxyLatenz = 0;
long avgNeoToProxyLatenz = 0;
long avgProxyToBackendLatenz = 0;
long avgPlayerToNeoLatenz = 0;
long minPlayerToProxyLatenz = Long.MAX_VALUE;
long minNeoToProxyLatenz = Long.MAX_VALUE;
long minProxyToBackendLatenz = Long.MAX_VALUE;
long minPlayerToNeoLatenz = Long.MAX_VALUE;
configuration.set("players." + playerName + ".playerAddress", list.get(0).getPlayerAddress());
configuration.set("players." + playerName + ".neoAddress", list.get(0).getNeoAddress());
for (DebugPingResponse response : list) {
if (maxPlayerToProxyLatenz < response.getPlayerToProxyLatenz())
maxPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (maxNeoToProxyLatenz < response.getNeoToProxyLatenz())
maxNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (maxProxyToBackendLatenz < response.getProxyToBackendLatenz())
maxProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (maxPlayerToNeoLatenz < response.getPlayerToNeoLatenz())
maxPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
avgPlayerToProxyLatenz = avgPlayerToProxyLatenz + response.getPlayerToProxyLatenz();
avgNeoToProxyLatenz = avgNeoToProxyLatenz + response.getNeoToProxyLatenz();
avgProxyToBackendLatenz = avgProxyToBackendLatenz + response.getProxyToBackendLatenz();
avgPlayerToNeoLatenz = avgPlayerToNeoLatenz + response.getPlayerToNeoLatenz();
if (minPlayerToProxyLatenz > response.getPlayerToProxyLatenz())
minPlayerToProxyLatenz = response.getPlayerToProxyLatenz();
if (minNeoToProxyLatenz > response.getNeoToProxyLatenz())
minNeoToProxyLatenz = response.getNeoToProxyLatenz();
if (minProxyToBackendLatenz > response.getProxyToBackendLatenz())
minProxyToBackendLatenz = response.getProxyToBackendLatenz();
if (minPlayerToNeoLatenz > response.getPlayerToNeoLatenz())
minPlayerToNeoLatenz = response.getPlayerToNeoLatenz();
}
configuration.set("players." + playerName + ".ping.max.PlayerToProxyLatenz", maxPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.NeoToProxyLatenz", maxNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.max.ProxyToBackendLatenz", maxProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.max.PlayerToNeoLatenz", maxPlayerToNeoLatenz);
configuration.set("players." + playerName + ".ping.average.PlayerToProxyLatenz", avgPlayerToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.NeoToProxyLatenz", avgNeoToProxyLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.ProxyToBackendLatenz", avgProxyToBackendLatenz / list.size());
configuration.set("players." + playerName + ".ping.average.PlayerToNeoLatenz", avgPlayerToNeoLatenz / list.size());
configuration.set("players." + playerName + ".ping.min.PlayerToProxyLatenz", minPlayerToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.NeoToProxyLatenz", minNeoToProxyLatenz);
configuration.set("players." + playerName + ".ping.min.ProxyToBackendLatenz", minProxyToBackendLatenz);
configuration.set("players." + playerName + ".ping.min.PlayerToNeoLatenz", minPlayerToNeoLatenz);
}));
configuration.save(file);
final String content = new String(Files.readAllBytes(file.toPath()));
final String pasteKey = instance.getCore().getRestAPI().paste(content);
instance.getCore().getDebugPingResponses().clear();
instance.sendMessage(sender, localization.get(locale, "debug.finished.first") + " (took " + (System.currentTimeMillis() - startTime) + "ms)");
if(pasteKey != null) {
final String url = "https://paste.neoprotect.net/" + pasteKey + ".yml";
instance.sendMessage(sender, localization.get(locale, "debug.finished.url") + url + localization.get(locale, "utils.open"), "OPEN_URL", url, null, null);
} else {
instance.sendMessage(sender, localization.get(locale, "debug.finished.file") + file.getAbsolutePath() + localization.get(locale, "utils.copy"), "COPY_TO_CLIPBOARD", file.getAbsolutePath(), null, null);
}
instance.getCore().setDebugRunning(false);
} catch (Exception ex) {
instance.getCore().severe(ex.getMessage(), ex);
}
});
}
}, 2000L * amount + 500);
}
private void gameshieldSelector() {
instance.sendMessage(sender, localization.get(locale, "select.gameshield"));
List<Gameshield> gameshieldList = instance.getCore().getRestAPI().getGameshields();
for (Gameshield gameshield : gameshieldList) {
instance.sendMessage(sender, "§5" + gameshield.getName() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgameshield " + gameshield.getId(),
"SHOW_TEXT", localization.get(locale, "hover.gameshield", gameshield.getName(), gameshield.getId()));
}
}
private void setGameshield(String[] args) {
if (instance.getCore().getRestAPI().isGameshieldInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.gameshield", args[1]));
return;
}
Config.setGameShieldID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.gameshield", args[1]));
javaBackendSelector();
}
private void javaBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
instance.sendMessage(sender, localization.get(locale, "select.backend", "java"));
for (Backend backend : backendList) {
if(backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setJavaBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "java", args[1]));
return;
}
Config.setBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend", "java", args[1]));
instance.getCore().getRestAPI().testCredentials();
bedrockBackendSelector();
}
private void bedrockBackendSelector() {
List<Backend> backendList = instance.getCore().getRestAPI().getBackends();
if(backendList.stream().noneMatch(Backend::isGeyser))return;
instance.sendMessage(sender, localization.get(locale, "select.backend", "geyser"));
for (Backend backend : backendList) {
if(!backend.isGeyser())continue;
instance.sendMessage(sender, "§5" + backend.getIp() + ":" + backend.getPort() + localization.get(locale, "utils.click"),
"RUN_COMMAND", "/np setgeyserbackend " + backend.getId(),
"SHOW_TEXT", localization.get(locale, "hover.backend", backend.getIp(), backend.getPort(), backend.getId()));
}
}
private void setBedrockBackend(String[] args) {
if (instance.getCore().getRestAPI().isBackendInvalid(args[1])) {
instance.sendMessage(sender, localization.get(locale, "invalid.backend", "geyser", args[1]));
return;
}
Config.setGeyserBackendID(args[1]);
instance.sendMessage(sender, localization.get(locale, "set.backend","geyser", args[1]));
if (instance.getCore().getPlayerInSetup().remove(sender)) {
instance.sendMessage(sender, localization.get(locale, "setup.finished"));
}
}
private void showHelp() {
instance.sendMessage(sender, localization.get(locale, "available.commands"));
instance.sendMessage(sender, " - /np setup");
instance.sendMessage(sender, " - /np ipanic");
| instance.sendMessage(sender, " - /np analytics"); |
instance.sendMessage(sender, " - /np toggle (option)");
instance.sendMessage(sender, " - /np whitelist (add/remove) (ip)");
instance.sendMessage(sender, " - /np blacklist (add/remove) (ip)");
instance.sendMessage(sender, " - /np debugTool (cancel / amount)");
instance.sendMessage(sender, " - /np directConnectWhitelist (ip)");
instance.sendMessage(sender, " - /np setgameshield [id]");
instance.sendMessage(sender, " - /np setbackend [id]");
instance.sendMessage(sender, " - /np setgeyserbackend [id]");
}
public static class ExecutorBuilder {
private NeoProtectPlugin instance;
private Object sender;
private String[] args;
private Locale local;
private String msg;
private boolean viaConsole;
public ExecutorBuilder neoProtectPlugin(NeoProtectPlugin instance) {
this.instance = instance;
return this;
}
public ExecutorBuilder sender(Object sender) {
this.sender = sender;
return this;
}
public ExecutorBuilder args(String[] args) {
this.args = args;
return this;
}
public ExecutorBuilder local(Locale local) {
this.local = local;
return this;
}
public ExecutorBuilder msg(String msg) {
this.msg = msg;
return this;
}
public ExecutorBuilder viaConsole(boolean viaConsole) {
this.viaConsole = viaConsole;
return this;
}
public void executeChatEvent() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().chatEvent(this));
}
public void executeCommand() {
API.getExecutorService().submit(() -> new NeoProtectExecutor().command(this));
}
public NeoProtectPlugin getInstance() {
return instance;
}
public Object getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public Locale getLocal() {
return local;
}
public String getMsg() {
return msg;
}
public boolean isViaConsole() {
return viaConsole;
}
}
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| src/main/java/de/cubeattack/neoprotect/core/executor/NeoProtectExecutor.java | NeoProtect-NeoPlugin-a71f673 | [
{
"filename": "src/main/java/de/cubeattack/neoprotect/spigot/listener/LoginListener.java",
"retrieved_chunk": " instance.sendMessage(player, localization.get(locale, \"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": 95.85780197768399
},
{
"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": 92.90137937479116
},
{
"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": 92.90137937479116
},
{
"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": 78.04638892267846
},
{
"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": 76.69067952415323
}
] | 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/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": 39.1194690364756
},
{
"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": 35.706755325625096
},
{
"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": 34.68867586998852
},
{
"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": 29.95476228740263
},
{
"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": 29.95476228740263
}
] | 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.