Minecraft Spigot Plugin YML File is overwriting custom input in file - java

I make a plugin for my Minecraft Server and everything works well.
I use a users.yml file to store some data for every user like the groups and uuid.
Something weird is happening now, and I don't know how to solve it:
My users.yml is generating fine, no problems. All data is saved in there and I can access it.
BUT when I try to edit for example the group of the user from the default (this is the group that's assigned to every new user) to admin in the file itself and the user is joining again, the file overwrites the group to default.
What do I not see in the codes below to prevent the overwrite or did I do something wrong?
This is the function that creates the users.yml file:
public class UserList {
private static File usersFile;
private static FileConfiguration usersConf;
public static void Setup(){
usersFile = new File(Main.getInstance().getDataFolder(), "users.yml");
if(!usersFile.exists()){
try {
usersFile.createNewFile();
} catch (Exception e){
System.out.println("Error creating Usersfile: " + e);
}
}
usersConf = YamlConfiguration.loadConfiguration(usersFile);
}
public static FileConfiguration get(){
return usersConf;
}
public static void Save(){
try {
usersConf.save(usersFile);
} catch (Exception e){
System.out.println("Error saving Usersfile: " + e);
}
}
public static void reload(){
usersConf = YamlConfiguration.loadConfiguration(usersFile);
}
}
This is the code in the onEnabled() function:
#Override
public void onEnable() {
instance = this;
if (!getDataFolder().exists()) getDataFolder().mkdir();
//Erstelle users.yml mit Standardwerten
UserList.Setup();
UserList.get().addDefault("groups.admin.prefix", "§c");
UserList.get().addDefault("groups.vip.prefix", "§6");
UserList.get().addDefault("groups.default.prefix", "§7");
UserList.get().options().copyDefaults(false);
UserList.Save();
//Hole alle Usergruppen
Set<String> groups = UserList.get().getConfigurationSection("groups").getKeys(false);
//Events Registrieren
getServer().getPluginManager().registerEvents(this, this);
}
And here is the code that executes when a player is joining on the server:
#EventHandler
public void onJoin(PlayerJoinEvent e){
Player p = e.getPlayer();
if (UserList.get().get("users." + p.getName() + ".group") == null){ //<- I tried to prevent it with this if-statement but the problem must be elsewhere
UserList.get().set("users." + p.getName() + ".group", "default");
}
UserList.get().set("users." + p.getName() + ".uuid", p.getUniqueId().toString());
UserList.Save();
if (!p.hasPlayedBefore()) e.setJoinMessage(ChatColor.YELLOW + p.getName() + ChatColor.WHITE + " is new on this Server!");
else e.setJoinMessage(ChatColor.YELLOW + p.getName() + ChatColor.WHITE + " is " + ChatColor.GREEN + "Online");
}

It's thie line that create the issue:
UserList.get().options().copyDefaults(false);
You should use saveDefaultConfig() which will write the config if (and only if) the config file doesn't exist.
This method should be call with your plugin instance, and will works with your config.yml file.
If you want to copy a file when it doesn't exist, you should do like that :
File usersFile = new File(Main.getInstance().getDataFolder(), "users.yml");
if(!usersFile.exists()){
try (InputStream in = pl.getResource("users.yml");
OutputStream out = new FileOutputStream(usersFile)) {
ByteStreams.copy(in, out);
} catch (Exception e) {
e.printStackTrace();
}
}
config = YamlConfiguration.loadConfiguration(usersFile);

Related

C++ API object instantiation issues in Android Studio project (android.system.ErrnoException: open failed: ENOENT (No such file or directory))

Skip to EDIT1 for updated info
What I am trying to achieve:
- I have two classes in my project, a Communicator which communicates with the third party API and the main class that I use to translate the info I receive from the communicator.
My question is: What do I need to do to get my "ds.config" file, which I'm passing as a string, to get loaded? That is if that is even the problem here.
Another Question is: How could I debug this to figure out what is going wrong?
First step is I "initialize my communicator" in the Main.java file:
try{
mDSC = Communicator.createDSCommunicator("ds.config", gRecordDevice, gPlaybackDevice);
} catch (IOException e1) {
// Failed
}
Inside of Communicator this looks like:
public static Communicator createDSCommunicator(String dsConfigFile, String captureMixerName, String playerMixerName) throws IOException {
DSRecognizer dsRecognizer = new DSRecognizer();
dsRecognizer.setInitInfo(dsConfigFile); //THIS LINE CAUSES PROBLEM
// Only applies if setting a filter
dsRecognizer.setLanguage(Language.ENGLISH);
DLog.setLogger(new DLogInterface() {
#Override
public void w(String s, String s2) {
System.out.println("DS log Warning s:" + s + " s2:" + s2);
}
#Override
public void v(String s, String s2) {
System.out.println("DS log Verbose s:" + s + " s2:" + s2);
}
#Override
public void e(String s, String s2) {
System.out.println("DS log Error s:" + s + " s2:" + s2);
}
#Override
public void i(String s, String s2) {
System.out.println("DS log Info s:" + s + " s2:" + s2);
}
#Override
public void d(String s, String s2) {
System.out.println("DS log Debug s:" + s + " s2:" + s2);
}
});
return new Communicator(dsRecognizer, captureMixerName, playerMixerName);
}
Now is where it kinda gets out of my hands, dsRecognizer is a C++ file from the API. This is the code:
public void setInitInfo(String infoFile) throws FileNotFoundException, IOException {
if(this.isInitialized()) {
SLog.v("DSRecognizer", "setInitInfo returning; can only be called prior to init()");
} else {
SLog.v("DSRecognizer", "Info file " + infoFile);
Properties p = new Properties();
FileInputStream fin = null;
try {
fin = new FileInputStream(infoFile); //It doesn't get past this line
p.load(fin);
} finally {
if(fin != null) {
try {
fin.close();
} catch (IOException var13) {
;
}
}
}
File f = new File(infoFile);
File parent = f.getParentFile();
String path = ".";
if(parent != null) {
path = parent.getAbsolutePath();
}
SLog.v("DSRecognizer", "Setting base directory: " + path);
this.mBaseDirectory = path;
if(!p.containsKey("SamplingRate")) {
p.setProperty("SamplingRate", Integer.toString(16000));
}
this.mSamplingRate = Integer.parseInt(p.getProperty("SamplingRate"));
this.mUrlAudio = new URLAudio(this.mSamplingRate);
if(p.containsKey("Parameters")) {
this.mParameters = p.getProperty("Parameters");
} else {
if(!p.containsKey("parameters")) {
throw new FileNotFoundException("parameters file not specified in info file");
}
this.mParameters = p.getProperty("parameters");
p.remove("parameters");
p.setProperty("Parameters", this.mParameters);
}
SLog.v("DSRecognizer", "parameters file set to: " + this.mParameters);
this.mGrammar = null;
if(p.containsKey("Grammar")) {
this.mGrammar = p.getProperty("Grammar");
} else if(p.containsKey("grammarentry")) {
this.mGrammar = p.getProperty("grammarentry");
p.remove("grammarentry");
p.setProperty("Grammar", this.mGrammar);
}
SLog.v("DSRecognizer", "default grammar entry set to: " + this.mGrammar);
if(!p.containsKey("RecognizerType")) {
boolean rescore = false;
if(p.containsKey("Rescore")) {
rescore = Boolean.parseBoolean(p.getProperty("Rescore"));
} else if(p.containsKey("rescore")) {
rescore = Boolean.parseBoolean(p.getProperty("rescore"));
}
if(rescore) {
p.setProperty("RecognizerType", "rescore");
} else {
p.setProperty("RecognizerType", "plain");
}
}
p.remove("Rescore");
p.remove("rescore");
this.mRecognizerType = p.getProperty("RecognizerType");
SLog.v("DSRecognizer", "recognizer type (plain|rescore|dnn) set to: " + this.mRecognizerType);
this.mEpParameters = "";
if(p.containsKey("EPParameters")) {
this.mEpParameters = p.getProperty("EPParameters");
} else if(p.containsKey("epparameters")) {
this.mEpParameters = p.getProperty("epparameters", "");
p.remove("epparameters");
p.setProperty("EPParameters", this.mEpParameters);
}
this.mEpGrammar = "";
if(p.containsKey("EPGrammar")) {
this.mEpGrammar = p.getProperty("EPGrammar");
} else if(p.containsKey("epgrammarentry")) {
this.mEpGrammar = p.getProperty("epgrammarentry", "");
p.remove("epgrammarentry");
p.setProperty("EPGrammar", this.mEpGrammar);
}
StringBuffer sb = new StringBuffer();
Enumeration en = p.keys();
while(en.hasMoreElements()) {
String key = (String)en.nextElement();
sb.append(key);
sb.append(" ");
sb.append(p.getProperty(key));
sb.append("\n");
}
this.mInitString = sb.toString();
SLog.v("DSRecognizer", "DS initialization config: " + this.mInitString);
}
}
Somewhere my "ds.config" file, which is in the assets folder of my android studio project, is not being recognized.
Communicator.createDSCommunicator exits after the line marked with the comment "This line causes problem"
I tried loading the file the same way it's done in dsRecognizer in my main java file, tried loading it using just plain File a = new File().
My question is: What do I need to do to get my "ds.config" file, which I'm passing as a string, to get loaded? That is if that is even the problem here.
Another Question is: How could I debug this to figure out what is going wrong?
EDIT1
Figured out what the problem is: My "ds.config" file is not being located and is giving the error "android.system.ErrnoException: open failed: ENOENT (No such file or directory)".
The file "ds.config" is located in the assets folder of my Android Studio project and any path I provide as a string input to my initializeDS() method causes this error. I need to pass a string to the API file to load the config file but what string do I pass?
Also interested in finding out if there is any other way I can acheive this?

Return output from completed command using RootTools

I'm trying to retrieve the output of commandOutput in order to pass it to another function, but commandCompleted is never ran. Any help?
Command command = new Command(0, "cat " + file){
private String output;
#Override
public void commandCompleted(int id, int exitCode) {
Log.d("Commands.Completed", output);
Log.d("Commands.Completed", "ID: " + id + " & exitCode: " + exitCode);
saveData(output);
}
#Override
public void commandOutput(int id, String line) {
output += line + "\n";
}
#Override
public void commandTerminated(int id, String reason) {
}
};
try {
RootTools.getShell(true).add(command);
} catch (IOException | RootDeniedException | TimeoutException e) {
e.printStackTrace();
}
Your commandCompleted(int id, int exitCode) implementation is missing
super.commandCompleted(id, exitCode);
could it be the problem?
If you imported RootTools as
import com.stericson.RootTools.*;
you could also be using RootTools.Log which is muted by default. Maybe try to use
android.util.Log.d("Commands.Completed", output);
just to exclude the case.

Jgit- Getting commit history of particular contributor

I am newbie to JGit (a pure java library for git works) and Git. I am trying to get commit history of particular member using java but i get nothing, to do this I am using JGit.
This is my code ,I think there is an error in if statement.
public class GitLogNew {
static PersonIdent person=new PersonIdent("someone","someone#gmail.com");
static String name =person.getName();
static String email=person.getEmailAddress();
public static void main(String[] args) {
try {
test4(name,email);
//System.out.println("----------------------------------------");
} catch (Exception e) {
System.out.println(" ERROR " + e.toString());
}
}
public static void test4(String name, String email){
try {
File gitWorkDir = new File("E:/test/evaluate_contribution");
Git git = null;
git = Git.open(gitWorkDir);
Repository repo = git.getRepository();
LogCommand log = git.log();
log.all();
ObjectId lastCommitId = repo.resolve(Constants.HEAD);
RevWalk rw = new RevWalk(repo);
RevCommit parent = rw.parseCommit(lastCommitId);
rw.sort(RevSort.COMMIT_TIME_DESC);
rw.markStart(parent);
log.setMaxCount(20);
Iterable<RevCommit> logMsgs = log.call();
for (RevCommit commit : logMsgs) {
System.out.println("\n\n\n----------------------------------------");
if(name == commit.getCommitterIdent().getName()){
System.out.println("commit " + commit);
System.out.println("commit Id " + commit.toObjectId());
System.out.println("commit authur " + commit.getAuthorIdent().getName());
System.out.println("commit email " + commit.getAuthorIdent().getEmailAddress());
System.out.println("commit time " + commit.getAuthorIdent().getWhen());
System.out.println(" commit Message " + commit.getFullMessage());
System.out.println("-----------------------------");
//System.out.println("parents");
}
}
}catch (Exception e) {
System.out.println("no head exception : " + e);
}
}
Your error is here (and has nothing to do with JGit):
if(name == commit.getCommitterIdent().getName()){
See this question for what the problem is.

Downloading GitHub issues to .csv file

GitHub issues download using eclipse egit doesn't return anything.
Recently, i've been attempting to create a java desktop application (for windows), that will download GitHub issues from a specific GitHub issue repository, and save them in a .csv file.
I've created a simple GUI using Swing to enable the input of repository names. I'm also using eclipse's egit library to establish a connection to GitHub in order to download issues. I use authentication, entered using a .properties file in order to authenticate egit's connection with GitHub.
Here is the main code my application uses to download the issues and write them to a .csv file:
package io.github.psgs.issuesdownload;
import io.github.psgs.issuesdownload.gui.GUI;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.IssueService;
import java.io.FileWriter;
import java.io.IOException;
public class IssuesDownload {
public static void main(String[] args) {
try {
Config.loadConfiguration();
} catch(IOException ex) {
}
GUI.main(args);
}
public static String saveIssues(String repoDetails) {
String[] repoInfo = repoDetails.split("/");
String repoOwner = repoInfo[0];
String repoName = repoInfo[1];
GitHubClient client = new GitHubClient();
client.setCredentials(Config.githubuser, Config.githubpass);
IssueService issueService = new IssueService(client);
try {
FileWriter writer = new FileWriter("issues.csv");
//String[] header = {"Id", "Title", "Creator", "Assignee", "Milestone", "State", "Body Text"};
writer.append("Id, Title, Creator, Assignee, Milestone, State, Body Text");
writer.append("\n");
for (Issue issue : issueService.getIssues(repoOwner, repoName, null)) {
//String[] data = {String.valueOf(issue.getId()), issue.getTitle(), issue.getUser().getName(), issue.getAssignee().getName(), issue.getMilestone().getTitle(), issue.getState(), issue.getBodyText()};
writer.append(String.valueOf(issue.getId()) + ",");
writer.append(issue.getTitle() + ",");
writer.append(issue.getUser().getName() + ",");
writer.append(issue.getAssignee().getName() + ",");
writer.append(issue.getMilestone().getTitle() + ",");
writer.append(issue.getState() + ",");
writer.append(issue.getBodyText());
writer.append("\n");
}
writer.flush();
writer.close();
return "Download Complete!";
} catch (IOException ex) {
System.out.println("An IOException has occured!");
ex.printStackTrace();
if (ex.getMessage().equalsIgnoreCase("api.github.com")) {
return "An error has occured, reaching " + ex.getMessage() + "! Please check your network connection.";
}
}
return "An error has occured!";
}
}
This code is also available at: https://gist.github.com/psgs/9048602
The whole repository can be found at: https://github.com/psgs/IssuesDownload
When I run this code, with the .properties file in the same directory as the compile .jar file, the GitHub issues don't appear in the .csv file. I've tested the .csv file output, and the headers write correctly when I remove the download code.
Would anybody know why this is happening? Perhaps it's an authentication problem that i've missed?
After trying a few new API wrappers, i've found an API library that works. I'm now using Kohsuke Kawaguchi's GitHub API for Java to connect to GitHub.
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>github-api</artifactId>
<version>1.49</version>
</dependency>
My code now reads as follows:
package io.github.psgs.issuesdownload;
import io.github.psgs.issuesdownload.gui.GUI;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import java.io.FileWriter;
import java.io.IOException;
public class IssuesDownload {
public static void main(String[] args) {
try {
Config.loadConfiguration();
} catch (IOException ex) {
System.out.println("An IOException had occured while loading the configuration!");
ex.printStackTrace();
}
GUI.main(args);
}
public static String saveIssues(String repoDetails, GHIssueState issueState) {
String[] repoInfo = repoDetails.split("/");
try {
GitHub github = GitHub.connectUsingOAuth(Config.githubtoken);
GHRepository repository = github.getUser(repoInfo[0]).getRepository(repoInfo[1]);
FileWriter writer = new FileWriter("issues.csv");
writer.append("Id, Title, Creator, Assignee, Milestone, State, Body Text");
writer.append("\n");
for (GHIssue issue : repository.getIssues(issueState)) {
writer.append(String.valueOf(issue.getNumber()) + ",");
writer.append(issue.getTitle() + ",");
writer.append(issue.getUser().getLogin() + ",");
if (issue.getAssignee() != null) {
writer.append(issue.getAssignee().getName() + ",");
} else {
writer.append(" ,");
}
if (issue.getMilestone() != null) {
writer.append(issue.getMilestone().getTitle() + ",");
} else {
writer.append(" ,");
}
writer.append(issue.getState() + ",");
writer.append(issue.getBody() + ",");
writer.append("\n");
}
writer.flush();
writer.close();
return "Download Complete!";
} catch (IOException ex) {
System.out.println("An IOException has occured!");
ex.printStackTrace();
if (ex.getMessage().equalsIgnoreCase("api.github.com")) {
return "An error has occurred reaching " + ex.getMessage() + "! Please check your network connection.";
}
}
return "An error has occured!";
}
}
It looks like the method you're using is meant to be used to retrieve the issues for the currently authenticated user.
Perhaps this test (in the project's repository) would be helpful. The only difference I see is that you're not passing a singletonMap and I'm not sure you exactly have to.
public static <T> void outputCsv(String fileName, String[] headerName,
List<T> listResult, HttpServletRequest request) {
HttpServletResponse response = ResponseUtil.getResponse();
OutputStream out;
try {
// Encode file name
fileName = Util.encodeUnicodeFile(fileName, request);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/octet-stream; charset="
+ Constant.CONST_SJIS_ENCODING);
response.setHeader("Content-disposition", "attachment; filename=\""
+ fileName + "\"");
response.setCharacterEncoding(Constant.CONST_SJIS_ENCODING);
out = response.getOutputStream();
CSVWriter writer = new CSVWriter(new OutputStreamWriter(out,
Constant.CONST_WINDOW_JAPAN_ENCODING),
Constant.CONST_CSV_SEPARATOR_COMMA);
// Convert list result data to List <String[]>
List<String[]> list = convertListDataToCsvArray(listResult,
headerName);
// Write list data
writer.writeAll(list);
writer.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static <T> List<String[]> convertListDataToCsvArray(
List<T> listResult, String[] headerName) {
List<String[]> listCsv = new ArrayList<String[]>();
// First row is header
listCsv.add(headerName);
for (T object : listResult) {
// Get all fields of object
Field[] fields = object.getClass().getFields();
// Init row
String[] row = new String[headerName.length];
int index = 0;
for (Field field : fields) {
try {
if (field.getType().equals(Long.class)) {
// Read field value and set to string array
Long value = (Long) field.get(object);
row[index] = value != null ? String.valueOf(value) : "";
} else if (field.getType().equals(String.class)) {
// Read field value and set to string array
String value = (String) field.get(object);
row[index] = value != null ? value : "";
} else if (field.getType().equals(BigDecimal.class)) {
// Read field value and set to string array
BigDecimal value = (BigDecimal) field.get(object);
row[index] = value != null ? String.valueOf(value) : "";
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
index++;
}
// Add row
listCsv.add(row);
}
return listCsv;
}

asynccallback failures

In my app I need to add string vallues to the file(.property file, if it is important). and user enter this values in gwt GUI. Here is it's important part:
final Button submit = new Button("Submit");
addButton(submit);
submit.addSelectionListener(new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
keyWord.selectAll();
regexp.selectAll();
if (keyWord.getValue() != null){
setKeyWord(customerId, keyWord.getValue());
keyWord.setValue("");
}
if (regexp.getValue() != null){
setRegExp(customerId, regexp.getValue());
regexp.setValue("");
}
}
});
}
private void setKeyWord(final String customerId, final String keyword){
final AsyncCallback<String> callbackItems = new AsyncCallback<String>() {
public void onFailure(final Throwable caught) {
Window.alert("unable to add " + caught.toString());
}
public void onSuccess(final String x) {
Window.alert(x);
}
};
serverManagementSvc.setKeyWords(customerId, keyword, callbackItems);
}
private void setRegExp(final String customerId, final String regexp){
final AsyncCallback<String> calbackItems = new AsyncCallback<String>() {
#Override
public void onFailure(Throwable throwable) {
Window.alert("unable to add " + throwable.toString());
}
#Override
public void onSuccess(String s) {
Window.alert(s);
}
};
serverManagementSvc.setRegExp(customerId, regexp, calbackItems);
}
So I need to use Asunccallback to call methods which are in the "server part".
here are these methods:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords" + "," + word));
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps" + "," + regexp));
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
all interfaces are present.
when I run my code And press "submit" button in gui I see that both asynccallback failured(Window.alert, as you can see, shows "null pointer exception" despite of the fact that values which I send to methods are not null). why can it be? can you suggest me something?
UPD here is error which is shown by firebug:
uncaught exception: java.lang.ClassCastException
function W8(){try{null.a()}catch(a){return a}}
the problem is solved: there were a simple mistake in the code. I've closed brackets at the wrong place:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords") + "," + word);
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps") + "," + regexp);
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
I recommend that you recompile the GWT code using
-style PRETTY
and then check that firebug output again; it may give you a better clue, compared to your updated uncaught exception.
Next, I suggest you run it in the eclipse debugger, and set breakpoints in both the client and server code, and then you can inspect the variables and step through the code.

Categories

Resources