Cannot make a static reference to the non-static method getConfig() from the type JavaPlugin - static

I am trying to create a Minecraft plugin with a command that will set the world name into config.yml. Except I keep getting "Cannot make a static reference to the non-static method getConfig() from the type JavaPlugin" when I attempt to set the config. I have already searched around for several way to fix this but I have not understood have to implement other situations into mine.
Here is my code:
Main.java:
package me.Liam22840.MurderRun;
import org.bukkit.plugin.java.JavaPlugin;
import me.Liam22840.MurderRun.commands.HelpCommand;
import me.Liam22840.MurderRun.commands.SetmapCommand;
public class Main extends JavaPlugin {
#Override
public void onEnable(){
loadConfig();
new HelpCommand(this);
new SetmapCommand(this);
}
public void loadConfig(){
getConfig().options().copyDefaults(true);
saveConfig();
}
}
SetmapCommand.java:
package me.Liam22840.MurderRun.commands;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import Utils.Utils;
import me.Liam22840.MurderRun.Main;
import me.Liam22840.MurderRun.getConfig;
public class SetmapCommand implements CommandExecutor{
private int count;
public SetmapCommand(Main plugin){
plugin.getCommand("Setmap").setExecutor(this);
}
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)){
sender.sendMessage("Only players can execute this command!");
return true;
}
Player p = (Player) sender;
Location b_loc = p.getLocation();
if(p.hasPermission("MurderRun.Setworld")){
Main.getConfig().set("Maps." + p.getName() + count + ".World", b_loc.getWorld().getName());
Main.saveConfig();
p.sendMessage(Utils.chat("&4Map Set"));
return true;
} else{
p.sendMessage("You do not have the required permissions to execute this command!");
}
return false;
}
}

You can't directly call the Main class, because it is not static. To call it, you should do this in your Setmap class and the constructor:
private Main plugin;
public SetmapCommand(Main plugin){
this.plugin = plugin;
plugin.getCommand("Setmap").setExecutor(this);
}
After you did this, you can use in your Setmap class:
plugin.saveConfig();

Related

why pass arguments to the constructor of operator function class is null of Flink?

I am studying Flink, I want to build an operator function which extends ProcessWindowFunction and overload a new constructor with a parameter as a field value of the class, but when this class is instanced, without of this field, I am confused. code as follow.
import com.aliyun.datahub.client.model.Field;
import com.aliyun.datahub.client.model.FieldType;
import com.aliyun.datahub.client.model.PutRecordsResult;
import io.github.streamingwithflink.chapter8.PoJoElecMeterSource;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
public class DataHubSinkDemo {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);
env.enableCheckpointing(10_000L);
env.setParallelism(2);
RecordSchemaSer schema = new RecordSchemaSer();
schema.addField(new Field("id", FieldType.STRING));
DataStream<PutRecordsResult> out = env
.addSource(new PoJoElecMeterSource())
.keyBy( r -> r.getId())
.window(TumblingProcessingTimeWindows.of(Time.seconds(3)))
.process(new PutDatahubFunction<>(schema)); // PutDatahubFunction is my build a new Operator function class
env.execute();
}
}
variable schema is a parameter which I want to send to the constructor, it is an instance of RecordSchemaSer Class
import com.aliyun.datahub.client.model.RecordSchema;
import java.io.Serializable;
public class RecordSchemaSer
extends RecordSchema
implements Serializable {
}
PutDatahubFunction is a class extends ProcessWindowFunction, code as follows
import com.aliyun.datahub.client.model.*;
import io.github.streamingwithflink.chapter8.PUDAPoJo;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class PutDatahubFunction<IN extends PUDAPoJo, KEY>
extends ProcessWindowFunction<IN, PutRecordsResult, KEY, TimeWindow> {
private DataHubBase dataHubHandler;
private List<RecordEntry> recordEntries;
private RecordSchema schema;
public PutDatahubFunction(RecordSchema schema) {
this.schema = schema;
System.out.println("field 'id' not exist ? " + this.schema.containsField("id")); // it's true
}
#Override
public void open(Configuration parameters) throws Exception {
.........
}
#Override
public void process(KEY KEY,
Context context,
Iterable<IN> elements,
Collector<PutRecordsResult> out)
throws Exception {
RecordEntry entry = new RecordEntry();
for (IN e : elements) {
System.out.println("field 'id' not exist ? " + this.schema.containsField("id")); // it's false
......
}
}
}
the first system.out in the constructor, this.schema.containsField("id") is true, but the second system.out in process method, this.schema.containsField("id") is false! why? I have system.out two class name of the instance which both are PutDatahubFunction.
use ValueState not working, because constructor not call getRuntimeContext(), otherwise Exception in thread "main" java.lang.IllegalStateException: The runtime context has not been initialized. code as follow:
private ValueState<RecordSchema> schema;
public PutTupleDatahubFunction(RecordSchema schema) throws IOException {
ValueStateDescriptor schemaDes =
new ValueStateDescriptor("datahub schema", TypeInformation.of(RecordSchema.class));
/*
* error Exception in thread "main" java.lang.IllegalStateException:
* The runtime context has not been initialized.
*/
this.schema = getRuntimeContext().getState(schemaDes);
this.schema.update(schema);
}
I am very fuzzing, who can tell me the reason, Is there any way to pass arguments to the constructor of this operator function class? thanks.
I finally figured out why,the reason is Serialize and Deserialize. I am not coding RecordSchemaSer reason is Serialize content, due to null
public class RecordSchemaSer
extends RecordSchema
implements Serializable
{
}

How to use #DataProvider in TestNG

package com.xchanging.selenium.testcases.testng;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.xchanging.selenium.utility.CaptureScreenShot;
import com.xchanging.selenium.utility.ClearText;
import com.xchanging.selenium.utility.ClickEvent;
import com.xchanging.selenium.utility.GlobalVariables;
import com.xchanging.selenium.utility.ReadRows;
import com.xchanging.selenium.utility.SelectCheckBox;
import com.xchanging.selenium.utility.SelectDropDown;
import com.xchanging.selenium.utility.Text;
import com.xchanging.selenium.utility.VerifyText;
public class RegisterAccount extends GlobalVariables {
#Test(dataProvider = "getData")
public static void register() throws IOException {
ClickEvent.clickAt("createAccount_xpath");
Text.enterText("username_name", "username");
Text.enterText("password_name", "machans");
Text.enterText("confirmPassword_name", "machans");
ClickEvent.clickAt("securityquestion_name");
SelectDropDown.select("securityquestion_name", "petname");
Text.enterText("securityanswer_xpath", "vsbhss");
Text.enterText("fullName_name", "Chandrasekaran");
Text.enterText("email_name", "xx#gmail.com");
ClearText.clear("dob_name");
Text.enterText("dob_name", "11/11/1982");
SelectDropDown.select("gender_name", 1);
SelectDropDown.select("marital_name", 1);
SelectDropDown.select("country_name", "India");
SelectCheckBox.selectchkbox("checkbox_xpath");
ClickEvent.clickAt("register_xpath");
VerifyText.verify("Congratulations.. You have registered successfully");
VerifyText.verify("Login now");
CaptureScreenShot.screenshot("Registration_Successful");
ClickEvent.clickAt("closebutton_xpath");
}
#DataProvider
public ArrayList<HashMap> getData() throws IOException {
ArrayList<HashMap> table = ReadRows.readExcel("Sheet1");
return table;
}
}
Now I wanted to use this DataProvider and get values from xls and have to use it in my #Test Part.
Can any one help out???
If I use, this way it is working fine..
ArrayList<HashMap> table = ReadRows.readExcel("Sheet1");
table.get(0).get("email")
But I wanted to use #DataProvider..
Some How managed..
#Test(dataProvider="getData")
public static void register(ArrayList<HashMap> table) throws IOException {
}
This solves my problem.
If you want to use dataProvider annotation. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method.
You can try something like this:
#DataProvider
public Object[][] getData() throws IOException {
Object[][] data = new Object[3][2] // based on the size of your excel rows & cols.
// Write the code to read data from excel and store.
data[][] = //your Code.
return data;
}
And your test method can use the data.
//Lets say your Object[][] data returns 2 arguments.
#Test(dataProvider="getData")
public void testMethod(firstArgument, secondArgument){
// your code to use the arguments supplied by data.
}

JAVAFX editable ComboBox: refresh after changing a value

I'm still new to JavaFX and need to create a combobox with objects (SimlpePerson) and not strings. I want to edit the shown value in the box itself. Works good for strings but I have problems with SimpleObjects. I made a StringConverter and it also works, I can edit the object shown in the comboBox. But the list itself is not rerendered after that. If I click on the ComboBox I see the original values. How can I change that?
Any suggestion is very welcome!=)
BR and Thank you!
Stefan
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class ComboBoxDemo extends Application{
public class SimplePerson {
private StringProperty name;
private String somethingElse;
public SimplePerson(String name) {
setName(name);
}
public final void setName(String value) { nameProperty().set(value); }
public String getName() { return nameProperty().get(); }
public StringProperty nameProperty() {
if (name == null) name = new SimpleStringProperty(this, "name");
return name;
}
}
final ObservableList<SimplePerson> persons = FXCollections.observableArrayList(
new SimplePerson("Jacob"),
new SimplePerson("Isabella"),
new SimplePerson("Ethan"),
new SimplePerson("Emma"),
new SimplePerson("Michael")
);
#Override
public void start(Stage stage) throws Exception {
// TODO Auto-generated method stub
final ComboBox cb = new ComboBox();
cb.setItems(persons);
cb.setEditable(true);
cb.setConverter(new StringConverter<SimplePerson>() {
#Override
public String toString(SimplePerson p)
{
if(p != null)
return p.getName();
return "";
}
#Override
public SimplePerson fromString(String name)
{
if(cb.getValue() != null)
{
((SimplePerson)cb.getValue()).setName(name);
cb.show();
return (SimplePerson)cb.getValue();
}
return null;
}
});
stage.setScene(new Scene(cb));
stage.show();
}
public static void main(String[] args) { launch(args); }
}
Check out this solution. There is a handler which is triggered when you've finished editing. There you may implement all the code which changes the model's state.
To update the combobox list the following approach work may:
cb.getEditor().setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
SimplePerson person = cb.getValue();
if (null != person) {
int idx = persons.indexOf(person);
person.setName(cb.getEditor().getText());
persons.set(idx, person);
cb.setValue(person);
}
}
});

Selenium Web driver--Failure Screenshot is not captured in TestNG report

With below mentioned code,if the test case is pass-screenshot captured successfully and displayed in report.But when the test is failed--screenshot is not displayed.Even screenshot hyperlink is not displayed in report.Anybody can sort out the mistake in code?
package listeners;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import java.util.logging.Logger;
#Listeners
public class CountryChoserLayer extends TestListenerAdapter {
#Test(priority=1)
public void choseCountry() throws Exception{
driver.findElement(By.id("intselect")).sendKeys("India");
driver.findElement(By.xpath(".//*[#id='countryChooser']/a/img")).click();
//window.onbeforeunload = null;
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
System.out.println(NewFileNamePath);
Reporter.log("Passed Screenshot");
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case-Success");
System.out.println("---------------------------------------");
}
public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
public WebDriver driver;
public int Count = 0;
#Test(priority=0)
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.get(baseurl);
}
#Test(priority=2)
public void closeBrowser() {
driver.quit();
}
#Override
public void onTestFailure(ITestResult result){
Reporter.log("Fail");
System.out.println("BBB");
//Reporter.setCurrentTestResult(result);
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//File scrFile = ((TakesScreenshot) WebDriver.globalDriverInstance).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
//System.out.println("AAA" + NewFileNamePath);
try {
//System.out.println("CCC");
FileUtils.copyFile(scrnsht,new File(NewFileNamePath));
System.out.println(NewFileNamePath);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("DDD");
e.printStackTrace();
}
Reporter.log("Failed Screenshot");
Reporter.setCurrentTestResult(null);
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case Failed");
System.out.println("---------------------------------------");
}
#Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
Reporter.log("Skip");
}
#Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass
Reporter.log("Pass");
}
}
Your onTestFailure method is not being called because you didn't specify listener for your test class. You are missing a value in #Listeners annotation. It should be something like
#Listeners({CountryChoserLayer.class})
You can find more ways of specifying a listener in official TestNg's documentation.
Another problem you are likely to encounter would be NullPointerException while trying to take screenshot in onTestFailure method. The easiest workaround for that would be changing the declaration of driver field to static. I run the code with those fixes and I got the report with screenshot.
I must add that in my opinion putting both test and listener methods into one class is not a good practice.

injecting Session bean from another session bean in JBoss 7.1

I am not able to inject a SLSB in another SLSB. Actually created 3 projects
1) created a EJB project with an MDB
2) created a EJB project with a stateless session bean for posting the message
3) created a EJB project with a stateless session bean for injecting the above session bean
But while injecting I am not able to inject the EJB it is returning null
the code is as below
1) MDB:
#MessageDriven(
activationConfig = {
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty(propertyName = "destination", propertyValue = "activemq/queue/TestQueue"),
#ActivationConfigProperty(propertyName="acknowledgeMode", propertyValue="Auto-acknowledge")
})
#ResourceAdapter("activemq-ra.rar")
public class ConsumerMDB implements MessageListener {
public void onMessage(Message message) {
try {
System.out.println("Queue: Received a TextMessage at " + new Date());
TextMessage msg = (TextMessage) message;
System.out.println("Message is : " + msg.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
2) Session Bean 1
package com.springboard.session;
import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
#Stateless
#LocalBean
public class ProducerSession implements ProducerSessionLocal {
#Resource(mappedName="java:jboss/activemq/QueueConnectionFactory")
public static QueueConnectionFactory factory;
#Resource(mappedName = "java:jboss/activemq/queue/TestQueue")
public static Queue queue;
#Override
public void sendMessage(String msg) {
System.out.println("****************Entering into method********************");
try {
System.out.println(queue.getQueueName());
QueueConnection qConnection = factory.createQueueConnection();
QueueSession qSession = qConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
TextMessage message = qSession.createTextMessage();
message.setText(msg);
QueueSender qSender = qSession.createSender(queue);
qSender.send(message);
qSender.close();
qSession.close();
qConnection.close();
} catch (JMSException e) {
e.printStackTrace();
}
System.out.println("****************Exiting into method********************");
}
}
and the interface is
package com.springboard.session;
import javax.ejb.Local;
#Local
public interface ProducerSessionLocal {
public void sendMessage(String msg);
}
3) Second session bean to inject the first session
#Stateless
public class TestProducerLocalBean implements TestProducerLocalBeanLocal {
#EJB(mappedName = "java:global/ProducerSessionActiveMQ/ProducerSession!com.springboard.session.ProducerSessionLocal")
public ProducerSessionLocal producer;
public TestProducerLocalBean() {
System.out.println("*************Testing Producer****************");
if(producer!=null){
producer.sendMessage("This Message is from SessionBean to Session Bean to MDB");
}
else{
System.out.println("EJB is null");
}
System.out.println("**********End************************");
}
#Override
public void messageSend(String msg) {
// TODO Auto-generated method stub
}
and for testing purpose used a class
import javax.ejb.EJB;
import com.springboard.session.test.TestProducerLocalBean;
public class testEJB {
#EJB
public static TestProducerLocalBean local =new TestProducerLocalBean();
public static void main(String[] args) {
}
}
At producer EJB always retuns null. With using servlet to inject ProducerSession i am able to do it. but injecting with another EJB i not able to get it.
Could any one please help me out what i am missing
Thanks in advance
It's incorrect to use initialization ... = new Xyz() when using injection because initialization of those fields is the responsibility of the container. You probably attempted that because you noticed that the field was null, and that's because injection (including #EJB) is not supported in the main class unless you use an application client container.

Resources