Bukkit - Displaying null when getting a string from the config file - plugins

So I've been working on a custom feature for my minecraft server, one of the things that I need to do is get an integer from the config file that is specific to each player to display how many Packages(keys) they have (Virtual items)
The issue that I am having is that in the GUI it is displaying 'null' instead of how many they have... Could anyone help me please?
Item in the gui
Code for creating the player's instance in the config (Using a custom file class that was provided to me by a friend of mine.)
#EventHandler
public void playerJoin(PlayerJoinEvent event) {
Main main = Main.getPlugin(Main.class);
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
if (!main.getDataFolder().exists())
main.getDataFolder().mkdirs();
File file = new File(main.getDataFolder(), "players.yml");
FileConfiguration config = YamlConfiguration.loadConfiguration(file);
if (!config.contains("Users." + uuid + ".Username")) {
try {
System.out.println("Creating entry for " + player + " (" + uuid + ")");
config.set("Users." + uuid + ".Username", player);
config.set("Users." + uuid + ".Packages.Common", 0);
config.set("Users." + uuid + ".Packages.Rare", 0);
config.set("Users." + uuid + ".Packages.Epic", 0);
config.set("Users." + uuid + ".Packages.Legendary", 0);
config.set("Users." + uuid + ".Packages.Exotic", 0);
config.save(file);
System.out.println("Successfully created the entry for " + " (" + uuid + ")");
} catch (Exception e) {
}
}
}
Code for the creation of the item in the gui:
public static String inventoryname = Utils.chat("&fWhite Backpack");
public static Inventory WhiteBackpack(Player player) {
UUID uuid = player.getUniqueId();
Inventory inv = Bukkit.createInventory(null, 27, (inventoryname));
ItemStack common = new ItemStack(Material.INK_SACK);
common.setDurability((byte) 8);
ItemMeta commonMeta = common.getItemMeta();
commonMeta.setDisplayName(Utils.chat("&fCommon Packages &8» &f&l" + Main.pl.getFileControl().getConfig().getString("Users." + uuid + ".Packages.Common")));
common.setItemMeta(commonMeta);
inv.setItem(10, common);
return inv;
}

There are a couple things wrong with your code.
First, you never account for what happens if the config you are loading does not exist. When you do main.getDataFolder().mkdirs(), you account for if the folder is missing, but not the file.
Second, you are doing the following operation:
config.set("Users." + uuid + ".Username", player);
This is incorrect because the player variable is of the type Player, not of the type String. To fix this, you need to instead do the following:
config.set("Users." + uuid + ".Username", player.getName());
Third, you are attempting to write to a file that might not exist. When you initialize you file, you need to also make sure it exists, and if it does not, you need to create it. Right now you have the following:
File file = new File(main.getDataFolder(), "players.yml");
It must be changed to this block of code:
File file = new File(main.getDataFolder(), "players.yml");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
You could just have it be created when you attempt to save the file later on, but that is not ideal since it's safer to let Bukkit write to a file that already exists.
Fourth, and I'm not necessarily sure that this is a problem per se, but you are trying to access an Integer value from the config file as if it were a String. Try to replace the following:
commonMeta.setDisplayName(Utils.chat("&fCommon Packages &8» &f&l"
+ Main.pl.getFileControl().getConfig().getString("Users." + uuid + ".Packages.Common")));
with this instead:
commonMeta.setDisplayName(Utils.chat("&fCommon Packages &8» &f&l"
+ Main.pl.getFileControl().getConfig().getInt("Users." + uuid + ".Packages.Common")));
Hope this gets you moving in the right direction!

Related

Parallel execution with Jbehave with pico (jbehave-pico)

I'm new Jbehave. Im trying to find a way to achieve world in cucumber with Jbehave.
I generated project with jbehave with pico archetype. Im trying to run two stories in parallel. I updated threads in pom.xml to 2.
Consider a sample stepdef class as below
public class PojoSteps {
public Pojo pojo;
public PojoSteps(Pojo pojo){
this.pojo = pojo;
System.out.println(" ##" + new Timestamp(System.currentTimeMillis()) + " * this is " + this + ". In PojoSteps constructor. Pojo created is:" + this.pojo + ". Thread = " + Thread.currentThread().getId());
}
#Given("I have a pojo with $i")
public void iHaveAPojoWith1(int i){
pojo.setI(i);
System.out.println(" ##" + new Timestamp(System.currentTimeMillis()) + " * this is " + this + ".In iHaveAPojoWith1. pojo = " + this.pojo +". Value of To be set = " + i +". Value set Pojo.getI() = " + this.pojo.getI() + ". Thread = " + Thread.currentThread().getId());
}
#When("I wait for some time")
public void randomWait() throws InterruptedException {
Thread.sleep(new Random().nextInt(200));
}
#Then("my pojo should still have $expectedi")
public void myPojoShouldStillHave1(int expectedi){
System.out.println(" ##" + new Timestamp(System.currentTimeMillis()) + " * this is " + this +". In myPojoShouldStillHave1. pojo = " + this.pojo + ". expected = " + expectedi + ". actual = " + this.pojo.getI() + ". Thread = " + Thread.currentThread().getId());
Assert.assertEquals(this.pojo.getI(), expectedi);
}
}
I have Pojo model as below
public class Pojo {
private int i;
public void setI(int i){
this.i = i;
}
public int getI(){
return this.i;
}
}
My two stories are as below
PojoOne.story
Scenario: scenario description
Given I have a pojo with 1
When I wait for some time
Then my pojo should still have 1
PojoTwo.story
Scenario: random description
Given I have a pojo with 2
When I wait for some time
Then my pojo should still have 2
I have MyStories class which extends JUnitStories as below
public class MyStories extends JUnitStories {
....
private PicoContainer createPicoContainer() {
MutablePicoContainer container = new DefaultPicoContainer(new Caching().wrap(new ConstructorInjection()));
container.addComponent(PojoSteps.class);
container.addComponent(Pojo.class);
return container;
}
}
When I don't run stories in parallel, they succeed. When I run stories in parallel, they are failing.
##2020-01-02 20:35:36.53 * this is learning.steps.PojoSteps#49f3f232. In PojoSteps constructor. Pojo created is:learning.Support.Pojo#4aa9e824. Thread = 12
##2020-01-02 20:35:36.531 * this is learning.steps.PojoSteps#49f3f232.In iHaveAPojoWith1. pojo = learning.Support.Pojo#4aa9e824. Value of To be set = 1. Value set Pojo.getI() = 1. Thread = 12
##2020-01-02 20:35:36.532 * this is learning.steps.PojoSteps#6136e035. In PojoSteps constructor. Pojo created is:learning.Support.Pojo#1f4412c8. Thread = 13
##2020-01-02 20:35:36.533 * this is learning.steps.PojoSteps#6136e035.In iHaveAPojoWith1. pojo = learning.Support.Pojo#1f4412c8. Value of To be set = 2. Value set Pojo.getI() = 2. Thread = 13
##2020-01-02 20:35:36.558 * this is learning.steps.PojoSteps#6136e035. In myPojoShouldStillHave1. pojo = learning.Support.Pojo#1f4412c8. expected = 1. actual = 2. Thread = 12
##2020-01-02 20:35:36.668 * this is learning.steps.PojoSteps#6136e035. In myPojoShouldStillHave1. pojo = learning.Support.Pojo#1f4412c8. expected = 2. actual = 2. Thread = 13
...
Then my pojo should still have 1 (FAILED)
(java.lang.AssertionError: expected:<2> but was:<1>)
I'm not able to find documentation on how to run tests in parallel with Jbehave and pico. Also I need to have a model outside my stepdef class as I will be having multiple stefdef classes which will share the same model instance.
After reading a bit more and trying out Jbehave with spring,
1. I think there is no way to get different instances of stepdef created per thread.
2. In Jbehave, there is no equivalent of cucumber's world object which is threadsafe.
As #VaL mentioned in the comments of the questions, we have to make thinks threadsafe explicitly.
This is my understanding as of now. If there is any better way - kindly let me know.

AWS Device Farm.How can i save the custom report being generated after the test case into my local space

I am working with AWS device farm.My test script when run on my local system works as expected and generates a report in my local system at specified path.Now when i run the code in the device farm the report does not get generated.Am i missing something?
This is my test code to write the test cases to a html report.
package testOutput;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import report.TestReportSteps;
public class TestResultHtml {
public static void WriteResultToHtml(List<TestReportSteps> items, String getCurrentDateTime, String getCurrentTime) {
try {String filePath="C:\\\\Appium\\\\app-qc-debug.apk";
ApkFile apkFile = new ApkFile(new File(filePath));
ApkMeta apkMeta = apkFile.getApkMeta();
String Version=apkMeta.getVersionName();
DateFormat df = new SimpleDateFormat("dd/MM/yy, HH:mm:ss");
Date dateobj = new Date();
String currentDateTime = df.format(dateobj);
StringBuilder color = new StringBuilder();
StringBuilder status = new StringBuilder();
// define a HTML String Builder
StringBuilder actualResult = new StringBuilder();
StringBuilder htmlStringBuilder = new StringBuilder();
// append html header and title
htmlStringBuilder.append(
"<html><head><link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\">\r\n"
+ "<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"></script><title>Appium Test </title></head>");
// append body
htmlStringBuilder.append("<body>");
// append table
//if (count == 0)
{
htmlStringBuilder.append("<table class=\"table table-striped table-bordered\">");
htmlStringBuilder.append("<tr><th style=\"background-color:#a6a6a6\">Date Time</th><td>"
+ currentDateTime
+ "</td><th style=\"background-color:#a6a6a6\">Environment Tested</th><td>QC</td></tr>"
+ "<tr><th style=\"background-color:#a6a6a6\">OS</th><td>Android</td><th style=\"background-color:#a6a6a6\">Application</th><td>app-qc-debug.apk</td></tr>"
+ "<tr><th style=\"background-color:#a6a6a6\">Script Name</th><td colspan=\""
+ 3
+ "\">Cityvan Workflow</td>"
+ "<th style=\"background-color:#a6a6a6\">Build Version</th><td>"+Version+"</td></tr><tr><th style=\"background-color:#a6a6a6\">Objective</th><td colspan=\""
+ 3 + "\">To verify that cityvan app is working as expected</td><tr><tr></table>");
}
// append row
htmlStringBuilder.append("<table class=\"table table-striped\">");
htmlStringBuilder.append(
"<thead style=\"background-color:#007acc\"><tr><th><b>TestObjective</b></th><th><b>StepName</b></th><th><b>StepDescription</b></th><th><b>ExpectedResult</b></th><th><b>ActualResult</b></th><th><b>Status</b></th><th><b>Screenshot</b></th></tr></thead><tbody>");
// append row
for (TestReportSteps a : items) {
if (!a.getActualResultFail().isEmpty()) {
status.append("Fail");
color.append("red");
actualResult.append(a.getActualResultFail());
} else {
status.append("Pass");
color.append("green");
actualResult.append(a.getActualResultPass());
}
if (a.getScreenshotPath()!=null)
{
htmlStringBuilder.append("<tr><td>" + a.getTestObjective() + "</td><td>" + a.getStepName()
+ "</td><td>" + a.getStepDescription() + "</td><td>" + a.getExpectedResult() + "</td><td>"
+ actualResult + "</td><td style=\"color:" + color + ";font-weight:bolder;\">" + status
+ "</td><td>Click here</td></tr>");
}
else
{
htmlStringBuilder.append("<tr><td style=\"font-weight:bold\">" + a.getTestObjective() + "</td><td>"
+ a.getStepName() + "</td><td>" + a.getStepDescription() + "</td><td>"
+ a.getExpectedResult() + "</td><td>" + actualResult + "</td><td style=\"color:" + color
+ ";font-weight:bolder;\">" + status + "</td><td></td></tr>");
}
actualResult.delete(0, actualResult.length());
color.delete(0, color.length());
status.delete(0, status.length());
}
// close html file
htmlStringBuilder.append("</tbody></table></body></html>");
// write html string content to a file
String htmlFilepath = "";
htmlFilepath = "D:\\FinalAppiumWorkspace\\AppiumMavenProject2\\src\\test\\java\\testOutput\\HtmlReport\\" + getCurrentDateTime + "\\testfile"
+ getCurrentTime + "\\testfile.html";
WriteToFile(htmlStringBuilder.toString(), htmlFilepath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void WriteToFile(String fileContent, String fileName) throws IOException, FileNotFoundException {
File file = new File(fileName);
file.getParentFile().mkdirs();
PrintWriter out = null;
if (file.exists() && !file.isDirectory())
{
out = new PrintWriter(new FileOutputStream(new File(fileName), true));
out.append(fileContent);
out.close();
} else
{
// write to file with OutputStreamWriter
OutputStream outputStream = new FileOutputStream(file.getAbsoluteFile(), false);
Writer writer = new OutputStreamWriter(outputStream);
writer.write(fileContent);
writer.close();
}
}
}
The path the code is referencing doesn't exist in the device host for the farm. The Device Host for android tests is a Linux machine and from my experience we have access to the tmp directory. By using the custom artifacts feature of Device Farm and the tmp directory this should be possible. Try changing the path to the html file to:
htmlFilepath = "/tmp/reports/testfile.html";
Then, using the web console, explicitly mark that directory to be exported.
Once the testes finish, you should see a link for customer artifacts.
Additionally, you may be interested in other options for test reports like
extent reports
Allure reports
rather than writing your own from scratch.
HTH
-James
For the users who are receiving java.io.FileNotFoundException:(Permission denied) exception while trying to save test logs/reports in $WORKING_DIRECTORY or any other path. You can use $DEVICEFARM_LOG_DIR to save your artifacts, this worked for me.
String artifactsDir = System.getenv("DEVICEFARM_LOG_DIR");
Use this directory to store any artifacts.

How to create a derby user

I tried to set the DB schema name by schema.xml but it caused a schema name duplication in the generated SQL statement for ID generators. (Duplicate schema name in sequece generation)
I read the schema is defined by the passed user at connection time. Now I would like to set the schema by this way.
But I don't know how can I create a new Derby user and link it with the desired schema. Can somebody help me?
Environment: NetBeans, Glassfish, Derby
I have found this:
CALL SYSCS_UTIL.SYSCS_CREATE_USER('username', 'password')
But Derby answers:
Error code -1, SQL state 42Y03: 'SYSCS_UTIL.SYSCS_CREATE_USER' is not recognized as a function or procedure.
Why? I have connected to the db as the default admin user.
Or if I try to dispatch this command from a GUI tool, Derby says:
[Error Code: 0, SQL State: 42Y07] : Schema 'SYSCS_UTIL' does not exist
To Create user in Derby :
I am using Command Line Interface and I have already set my System environment variable to Derby.
Otherwise you can write these command into your CLI
java -jar %DERBY_HOME%\lib\derbyrun.jar ij
and hit Enter key to run ij tool, and you will see a prompt like this:
ij>
Now type the following command to create a user (replace sam by the desired username and sampass by the desired password):
CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.user.sam','sampass');
Now hit enter. This should give a message like this:
0 rows inserted/updated/deleted.
here is a solution (heavily commented):
String setProperty = "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(";
String getProperty = "VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY(";
String requireAuth = "'derby.connection.requireAuthentication'";
String sqlAuthorization = "'derby.database.sqlAuthorization'";
String defaultConnMode = "'derby.database.defaultConnectionMode'";
String fullAccessUsers = "'derby.database.fullAccessUsers'";
String readOnlyAccessUsers = "'derby.database.readOnlyAccessUsers'";
String provider = "'derby.authentication.provider'";
String propertiesOnly = "'derby.database.propertiesOnly'";
System.out.println("Turning on authentication and SQL authorization.");
Statement s = conn.createStatement();
// Set requireAuthentication
s.executeUpdate(setProperty + requireAuth + ", 'true')");
//CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.connection.requireAuthentication','true'
// Set sqlAuthorization
s.executeUpdate(setProperty + sqlAuthorization + ", 'true')");
//CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.database.sqlAuthentication','true'
// Retrieve and display property values
ResultSet rs = s.executeQuery(getProperty + requireAuth + ")");
rs.next();
System.out.println("Value of requireAuthentication is " + rs.getString(1));
rs = s.executeQuery(getProperty + sqlAuthorization + ")");
rs.next();
System.out.println("Value of sqlAuthorization is " + rs.getString(1));
// Set authentication scheme to Derby builtin
s.executeUpdate(setProperty + provider + ", 'BUILTIN')");
// Create some sample users
s.executeUpdate(setProperty + "'derby.user." + txtUname.getText() + "', '" + txtPw1.getText() + "')" );
// Define noAccess as default connection mode
s.executeUpdate(setProperty + defaultConnMode + ", 'noAccess')");
// Confirm default connection mode
rs = s.executeQuery(getProperty + defaultConnMode + ")");
rs.next();
System.out.println("Value of defaultConnectionMode is " + rs.getString(1));
// Define read-write users
s.executeUpdate(setProperty + fullAccessUsers + ", '" + txtUname.getText() + "')");
// Define read-only user
// s.executeUpdate(setProperty + readOnlyAccessUsers + ", 'guest')");
// Confirm full-access users
rs = s.executeQuery(getProperty + fullAccessUsers + ")");
rs.next();
System.out.println("Value of fullAccessUsers is " + rs.getString(1));
// Confirm read-only users
rs = s.executeQuery(getProperty + readOnlyAccessUsers + ")");
rs.next();
System.out.println("Value of readOnlyAccessUsers is " + rs.getString(1));
// We would set the following property to TRUE only when we were
// ready to deploy. Setting it to FALSE means that we can always
// override using system properties if we accidentally paint
// ourselves into a corner.
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" + "'derby.database.propertiesOnly', 'false')");
s.close();
Let me know if that works (or not) for you.

EF Code First - Create Rollback Script for First Migration

We've got a little console app that creates scripts based on to>from migrations ... we're using to do our rollback scripts as well.
With rollback we stick in null and the migration to rollback to.
We've just moved the Console app to a new solution, but I cannot get it to make the first rollback script when the is only one migration in _MigrationHistory.
Any ideas?
public static string CreateScriptBetween(string from, string to, string name)
{
var dbMigrator = new DbMigrator(new EmptyConfiguration());
var scriptor = new MigratorScriptingDecorator(dbMigrator);
var script = "USE MYCOOLSKILLZDB" + Environment.NewLine + Environment.NewLine + "GO" + Environment.NewLine
+ Environment.NewLine;
script += scriptor.ScriptUpdate(from, to);
var filename = FileGenerator.NewNamedFilename(name, "sql");
using (var writer = new StreamWriter(filename, false))
{
writer.Write(script);
}
return filename;
}

Template to show method name and parameter values in Eclipse

Is there any way to have a template (Java -> Editor -> Templates) in Eclipse that generate something like this
debug("methodName arg1=" + arg1 + " arg2=" + arg2 + " arg3=" + arg3);
When used in a method. For instance:
public void setImage(long rowId, long contactId, String thinggy) {
// invoking the template here, produces this:
debug("setImage rowId=" + rowId + " contactId=" + contactId + " thinggy=" + thinggy);
}
I couldn't find a way to do that with the standard template UI, maybe there exists a plugin to do this kinds of things?
This is a start:
debug("${enclosing_method_arguments}: ", ${enclosing_method_arguments});
which produces the following:
debug("arg1, arg2, arg3: ", arg1, arg2, arg3);
I haven't found a way to separate out each argument. I found this page that ran into the same problem.
For other Eclipse template stuff, look at this question.
I guess it's probably a bit too late to answer this question but maybe my answer will help someone :
System.out.println(String.format("%tH:% %s", java.util.Calendar.getInstance(), "${enclosing_package}.${enclosing_type}.${enclosing_method}(${enclosing_method_arguments})"));
String[] lArgsNames = new String("${enclosing_method_arguments}").split(", ");
Object[] lArgsValues = new Object[] {${enclosing_method_arguments}};
for (int i = 0; i < lArgsValues.length; i++) {
System.out.println("\t" + (lArgsValues[i] != null ? ("(" + lArgsValues[i].getClass().getSimpleName() + ") \"" + lArgsNames[i] + "\" = \"" + lArgsValues[i] + "\"") : "\"" + lArgsNames[i] + "\" is null"));
}
For this method :
public void foo(boolean arg){
// ...
}
the output would be:
18:43:43:076 > any.package.AnyClass.foo(arg)
(Boolean) "arg" = "true"
This code seems to be able to handle any object, primitive type and null value. And yes it's a little bit complicated for the purpose!
I've made small plugin that adds nicely formatted variable:
https://github.com/dernasherbrezon/eclipse-log-param
Eclipse doesnt provide any information about parameter type, so there is no Arrays.toString(...)
or template=
if (aLog.isDebugEnabled()) {
aLog.debug(String.format("${enclosing_method}:${enclosing_method_arguments}".replaceAll(", ", "=%s, ")+"=%s", ${enclosing_method_arguments}));
}
gives
public static void hesteFras(boolean connect, Object ged, String frans, int cykel) {
if (aLog.isDebugEnabled()) {
aLog.debug(String.format("hesteFras: connect, ged, frans, cykel".replaceAll(", ", "=%s, ") + "=%s",
connect, ged, frans, cykel));
}
which for
hesteFras(false, null, "sur", 89);
gives a log statement:
hesteFras: connect=false, ged=null, frans=sur, cykel=89
The eclipse-log-param plugin is useful to avoid having to type the logging line manually. However, it would be even nicer to have the line added automatically for all new methods.
Is this even possible? It looks like in Windows->Preferences->Code Style->Code Templates->Code there are ways to configure automatically added code like auto-generated methods ("Method body" template, which has an "Auto-generated method stub" comment). But there's no way to configure new methods which are not generated.
Furthermore, the variable formatted_method_parameters is not available when editing the template for "Method body".