I am currently working CDI pushevent. I plan to trigger the pushevent by backend Java code instead of frontend jsf by commandButton.
Here is the code for PushCdiBean.java
import java.io.Serializable;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.enterprise.event.Event;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import org.richfaces.application.push.MessageException;
import org.richfaces.application.push.TopicKey;
import org.richfaces.application.push.TopicsContext;
import org.richfaces.cdi.push.Push;
/**
* #author Lukas Fryc
*/
#javax.inject.Named("pushCdiBean")
#javax.enterprise.context.RequestScoped
//#ManagedBean(name="pushCdiBean")
//#ViewScoped
public class PushCdiBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5241937306040858158L;
private static final String CDI_PUSH_TOPIC = "pushCdi";
private String userIdentifier;
private String message;
#Inject
#Push(topic=CDI_PUSH_TOPIC)//i thought that the topic is initialized with this ?!
private Event<String> pushEvent;
#PostConstruct
public void initialize() {
if(userIdentifier == null) {
userIdentifier = UUID.randomUUID().toString().replace("-", "");
}
TopicsContext topicsContext = TopicsContext.lookup();
topicsContext.getOrCreateTopic(new TopicKey(CDI_PUSH_TOPIC, userIdentifier));//initialize the topic and make the troublesome message disappears
}
public synchronized void sendMessage() throws MessageException {
pushEvent.fire(message);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Event<String> getPushEvent() {
return pushEvent;
}
public void setPushEvent(Event<String> pushEvent) {
this.pushEvent = pushEvent;
}
public String getUserIdentifier() {
return userIdentifier;
}
public void setUserIdentifier(String userIdentifier) {
this.userIdentifier = userIdentifier;
}
When I try to create the PushCdiBean class and call sendMessage() function, however, pushEvent.fire fails.
The code is here.
/**
*
*/
public void run() {
while (running) {
try {
PushCdiBean pushTest = new PushCdiBean();
pushTest.setMessage("This is CDI push Test");
pushTest.sendMessage();
}
catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
sleep(4000);
}
}
Could you please give me some suggestions? Thank you very much.
You have to #Inject the CDI bean, not instantiate it on your own via new.
Related
I have a data like this, and i want get report and criteria data.
{
"response_code": 200,
"message": "Your report data has been loaded.",
"data": {
"report": [
{
"id_report": 1,
"report_name": "report name A"
},
{
"id_report": 2,
"report_name": "report name B"
}
],
"criteria": [
{
"id_criteria": 1,
"criteria_name": "criteria name A"
},
{
"id_criteria": 2,
"criteria_name": "criteria name B"
}
]
}
}
And i get data in java using retrofit. And this is my java class.
GetReport.java
#SerializedName("response_code")
private int response_code;
#SerializedName("status")
private boolean status;
#SerializedName("message")
private String message;
#SerializedName("data")
Call<Data> listData;
Data.java
#SerializedName("report")
private List<Report> reportList;
#SerializedName("criteria")
private List<Criteria> criteriaList;
And this how i call the data.
public void populateData() {
Call<GetReport> getReportCall = apiInterface.getReportCall();
getReportCall.enqueue(new Callback<GetReport>() {
#Override
public void onResponse(Call<GetReport> call, Response<GetReport> response) {
response.body().getListData().enqueue(new Callback<Data>() {
#Override
public void onResponse(Call<Data> call, Response<Data> response) {
List<Report> reportList = response.body().getReportList();
Log.d("TAGGGGGGGGGG", String.valueOf(reportList.size()));
}
#Override
public void onFailure(Call<Data> call, Throwable t) {
t.printStackTrace();
}
});
}
#Override
public void onFailure(Call<GetReport> call, Throwable t) {
t.printStackTrace();
}
});
}
When I run the program, my activity closes immediately. When I look at logcat, there is too much running log data so I can't see where the error is.
I have managed to attempt and solve your problem with the following code. I copied and pasted the JSON you provided above at JSONbin.io so that I can be able to call it using an API call. I did not modify the structure of the JSON at all.
App build.gradle
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
GetReport.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class GetReport {
#SerializedName("response_code")
int response_code;
#SerializedName("message")
String message;
#SerializedName("data")
Data data;
public int getResponse_code() {
return response_code;
}
public void setResponse_code(int response_code) {
this.response_code = response_code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}}
Data.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Data {
#SerializedName("report")
List<Report> reportList;
#SerializedName("criteria")
List<Criteria> criteriaList;
public List<Report> getReportList() {
return reportList;
}
public void setReportList(List<Report> reportList) {
this.reportList = reportList;
}
public List<Criteria> getCriteriaList() {
return criteriaList;
}
public void setCriteriaList(List<Criteria> criteriaList) {
this.criteriaList = criteriaList;
}}
Criteria.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class Criteria {
#SerializedName("id_criteria")
int id_criteria;
#SerializedName("criteria_name")
String criteria_name;
public Criteria(int id_criteria, String criteria_name) {
this.id_criteria = id_criteria;
this.criteria_name = criteria_name;
}
public int getId_criteria() {
return id_criteria;
}
public void setId_criteria(int id_criteria) {
this.id_criteria = id_criteria;
}
public String getCriteria_name() {
return criteria_name;
}
public void setCriteria_name(String criteria_name) {
this.criteria_name = criteria_name;
}}
Report.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class Report {
#SerializedName("id_report")
int id_report;
#SerializedName("report_name")
String report_name;
public Report(int id_report, String report_name) {
this.id_report = id_report;
this.report_name = report_name;
}
public int getId_report() {
return id_report;
}
public void setId_report(int id_report) {
this.id_report = id_report;
}
public String getReport_name() {
return report_name;
}
public void setReport_name(String report_name) {
this.report_name = report_name;
}}
RetrofitClient.java
package com.example.retrofitapp.api;
import com.google.gson.*;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
public static Retrofit retrofit;
public static Retrofit getRetrofitClient(String baseUrl){
if(retrofit==null){
Gson gson = new GsonBuilder().setLenient().create();
retrofit = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create(gson)).build();
}
return retrofit;
}}
Constants.java
package com.example.retrofitapp;
public class Constants {
public static String base_url = "https://api.jsonbin.io/";
}
Api.java
package com.example.retrofitapp.api;
import com.example.retrofitapp.GetReport;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;
public interface Api {
#Headers("Secret-key:$2a$10$WxkkTylkdR7NwGSoPwrfy.Odxtj7MR2vDtYZBp9cOd0SaYGVRmhOm")
#GET("/b/5ff8172e63e86571a2e35639")
Call<GetReport> getReport();
}
MainActivity.java
package com.example.retrofitapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.retrofitapp.api.Api;
import com.example.retrofitapp.api.RetrofitClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//call method here
populateData();
}
private void populateData() {
Retrofit retrofit = RetrofitClient.getRetrofitClient(Constants.base_url);
Api api = retrofit.create(Api.class);
Call<GetReport> getReportCall = api.getReport();
//make asynchronous request
getReportCall.enqueue(new Callback<GetReport>() {
#Override
public void onResponse(Call<GetReport> call, Response<GetReport> response) {
if(response.code() == 200){
GetReport getReport = (GetReport) response.body();
//get response code
int responseCode = getReport.getResponse_code();
//get message
String message = getReport.getMessage();
//get data
Data data = getReport.getData();
//get reports(loop)
for(Report report : data.getReportList()){
//your report here
}
//get criteria(loop)
for(Criteria criteria : data.getCriteriaList()){
//your criteria here
}
}
}
#Override
public void onFailure(Call<GetReport> call, Throwable t) {
//do something if the request failed
}
});
}}
That is how I solved it.
I need help creating a null-safe BooleanBinding. It has to be null-safe since I can not provide default values for all attributes in the model (one reason: the model contains enumerations). My first approach has been as follows:
executeButtonDisabled.bind(missionProperty().isNotNull().and(missionProperty().get().statusProperty().isNotEqualTo(MissionStatus.CREATED)));
final BooleanBinding isNotExecutingBinding = missionProperty().isNotNull().and(missionProperty().get().statusProperty().isNotEqualTo(MissionStatus.EXECUTING));
completeButtonDisabled.bind(isNotExecutingBinding);
cancelButtonDisabled.bind(isNotExecutingBinding)
But that approach does not work because the complete expression is evaluated which results in a NullPointerException (but it correctly updates the buttons, when a property is provided). Now I am trying to use the Bindings class as suggested in JavaFX binding and null values, but I can't make it work. Here's my current approach:
final BooleanBinding isNotCreatedBinding = Bindings.createBooleanBinding(
() -> mission.isNull().getValue()
? true
: missionProperty().get().statusProperty().isNotEqualTo(MissionStatus.CREATED).getValue());
final BooleanBinding isNotExecutingBinding = Bindings.createBooleanBinding(
() -> mission.isNull().getValue()
? true
: missionProperty().get().statusProperty().isNotEqualTo(MissionStatus.EXECUTING).getValue());
executeButtonDisabled.bind(isNotCreatedBinding);
completeButtonDisabled.bind(isNotExecutingBinding);
cancelButtonDisabled.bind(isNotExecutingBinding);
But this does not work and I do not understand why. It seems that the property binding for modelProperty() does not work here! Can you explain to me how-to convert the first working solution (at least without null) to a proper null-safe solution?
Edit 2016-04-26: The suggested solution does not work, therefore I created a simple fully-working example:
Mission.java:
package de.florianwolters.example.javafx.bindings;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Mission {
enum Status {
CREATED,
EXECUTING,
COMPLETED,
CANCELED;
}
private final StringProperty shortName = new SimpleStringProperty();
private final ObjectProperty<Status> status = new SimpleObjectProperty<>();
public Mission(final String shortName) {
this.setShortName(shortName);
this.setStatus(Status.CREATED);
}
public String getShortName() {
return shortNameProperty().get();
}
public void setShortName(final String shortName) {
shortNameProperty().set(shortName);
}
public StringProperty shortNameProperty() {
return shortName;
}
public Status getStatus() {
return statusProperty().get();
}
public void setStatus(final Status status) {
statusProperty().set(status);
}
public ObjectProperty<Status> statusProperty() {
return status;
}
}
MissionDetailsViewModel.java:
package de.florianwolters.example.javafx.bindings;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.beans.property.SimpleObjectProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class MissionDetailsViewModel {
/**
* The logger used for logging in the `MissionDetailsViewModel` class.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(
MissionDetailsViewModel.class);
private ObjectProperty<Mission> mission = new SimpleObjectProperty<>();
private final ReadOnlyBooleanWrapper executeButtonDisabled = new ReadOnlyBooleanWrapper(true);
private final ReadOnlyBooleanWrapper completeButtonDisabled = new ReadOnlyBooleanWrapper(true);
private final ReadOnlyBooleanWrapper cancelButtonDisabled = new ReadOnlyBooleanWrapper(true);
/**
* Constructs a `MissionDetailsViewModel`.
*/
public MissionDetailsViewModel(final ObjectProperty<Mission> mission) {
this.mission.bind(mission);
// partialWorkingBinding();
notWorkingBinding();
}
private void notWorkingBinding() {
final BooleanBinding isNotCreatedBinding = Bindings.createBooleanBinding(
() -> missionProperty().isNull().get()
? true
: missionProperty().get().statusProperty().isNotEqualTo(Mission.Status.CREATED).get(),
missionProperty());
final BooleanBinding isNotExecutingBinding = Bindings.createBooleanBinding(
() -> mission.isNull().get()
? true
: missionProperty().get().statusProperty().isNotEqualTo(Mission.Status.EXECUTING).get(),
missionProperty());
executeButtonDisabled.bind(isNotCreatedBinding);
completeButtonDisabled.bind(isNotExecutingBinding);
cancelButtonDisabled.bind(isNotExecutingBinding);
}
private void partialWorkingBinding() {
executeButtonDisabled.bind(missionProperty().isNotNull().and(missionProperty().get().statusProperty().isNotEqualTo(Mission.Status.CREATED)));
final BooleanBinding isNotExecutingBinding = missionProperty().isNotNull().and(missionProperty().get().statusProperty().isNotEqualTo(Mission.Status.EXECUTING));
completeButtonDisabled.bind(isNotExecutingBinding);
cancelButtonDisabled.bind(isNotExecutingBinding);
}
public boolean isExecuteButtonDisabled() {
return executeButtonDisabledProperty().get();
}
public ReadOnlyBooleanProperty executeButtonDisabledProperty() {
return executeButtonDisabled;
}
public boolean isCompleteButtonDisabled() {
return completeButtonDisabledProperty().get();
}
public ReadOnlyBooleanProperty completeButtonDisabledProperty() {
return completeButtonDisabled;
}
public boolean isCancelButtonDisabled() {
return cancelButtonDisabledProperty().get();
}
public ReadOnlyBooleanProperty cancelButtonDisabledProperty() {
return cancelButtonDisabled;
}
public Mission getMission() {
return missionProperty().get();
}
public void setMission(final Mission mission) {
missionProperty().set(mission);
}
public ObjectProperty<Mission> missionProperty() {
return mission;
}
}
MissionDetailsViewModelTest.java:
package de.florianwolters.example.javafx.bindings;
import static eu.lestard.assertj.javafx.api.Assertions.assertThat;
import javafx.beans.property.SimpleObjectProperty;
import org.junit.Before;
import org.junit.Test;
public final class MissionDetailsViewModelTest {
private Mission mission;
private MissionDetailsViewModel viewModel;
#Before
public void setUp() {
mission = new Mission("My Short Name");
viewModel = new MissionDetailsViewModel(new SimpleObjectProperty<Mission>(mission));
}
#Test
public void testInitialValues() {
assertThat(viewModel.executeButtonDisabledProperty()).isFalse();
assertThat(viewModel.completeButtonDisabledProperty()).isTrue();
assertThat(viewModel.cancelButtonDisabledProperty()).isTrue();
}
#Test
public void testMissionStatusSetToExecuting() {
mission.setStatus(Mission.Status.EXECUTING);
assertThat(viewModel.executeButtonDisabledProperty()).isTrue();
assertThat(viewModel.completeButtonDisabledProperty()).isFalse();
assertThat(viewModel.cancelButtonDisabledProperty()).isFalse();
}
#Test
public void testMissionStatusSetToCompleted() {
mission.setStatus(Mission.Status.COMPLETED);
assertThat(viewModel.executeButtonDisabledProperty()).isTrue();
assertThat(viewModel.completeButtonDisabledProperty()).isTrue();
assertThat(viewModel.cancelButtonDisabledProperty()).isTrue();
}
#Test
public void testMissionStatusSetToCanceled() {
mission.setStatus(Mission.Status.CANCELED);
assertThat(viewModel.executeButtonDisabledProperty()).isTrue();
assertThat(viewModel.completeButtonDisabledProperty()).isTrue();
assertThat(viewModel.cancelButtonDisabledProperty()).isTrue();
}
}
The unit test fails with the code above (the method notWorkingBinding() is used) but works with the method partialWorkingBinding(). What am I doing wrong?
You set up the calculation function for isNotCreatedBinding, but you didn't set the dependencies for the binding. You need to add mision as dependency:
Bindings.createBooleanBinding(
() -> mission.isNull().getValue()
? true
: missionProperty().get().statusProperty().isNotEqualTo(MissionStatus.CREATED).getValue(), mission);
EDIT
You need to listen to the statusProperty instead of missionProperty, which will not work with createBooleanBinding when missionProperty().get() == null.
But you can use a When binding:
(is causing a NullPointerException as already mentioned in the question)
BooleanBinding isNotCreatedBinding = new When(mission.isNotNull()).then(mission.get().statusProperty().isNotEqualTo(Mission.Status.CREATED)).otherwise(false);
Or a more low-level solution:
missionProperty().addListener((ov, m, m1) -> {
if (m1 != null) {
executeButtonDisabled.bind(m1.statusProperty().isNotEqualTo(Mission.Status.CREATED));
}else {
executeButtonDisabled.unbind();
executeButtonDisabled.set(false);
}
});
Tomas Mikula's ReactFX framework (v 2.0) has this functionality built in:
import org.reactfx.value.Val;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
public class NestedBindingTest {
public static void main(String[] args) {
BooleanProperty disable = new SimpleBooleanProperty();
disable.addListener((obs, wasDisabled, isNowDisabled) ->
System.out.println("disable: "+wasDisabled+" -> "+isNowDisabled));
ObjectProperty<Item> item = new SimpleObjectProperty<>();
Val<Item.Status> status = Val.flatMap(item, Item::statusProperty);
disable.bind(status.map(s -> s == Item.Status.PENDING).orElseConst(true));
Item i = new Item();
System.out.println("Setting item");
item.set(i);
System.out.println("Setting item status to PENDING");
i.setStatus(Item.Status.PENDING);
System.out.println("Setting item status to READY");
i.setStatus(Item.Status.READY);
System.out.println("Setting item to null");
item.set(null);
}
public static class Item {
public enum Status {PENDING, READY}
private final ObjectProperty<Status> status = new SimpleObjectProperty<>();
public final ObjectProperty<Status> statusProperty() {
return this.status;
}
public final NestedBindingTest.Item.Status getStatus() {
return this.statusProperty().get();
}
public final void setStatus(final NestedBindingTest.Item.Status status) {
this.statusProperty().set(status);
}
}
}
I have static variables in my test class, which I attempt to initialize using a static #BeforeClass method. However, I keep on getting the java.lang.ExceptionInInitializerError exception, and I cannot figure out what in the world I am doing wrong.
Below is my code - I get the exception at the first line of setupLocators():
package com.stuhrling.warehouse.inventoryTransactions.sales;
import com.stuhrling.warehouse.inventoryObjects.Container;
import com.stuhrling.warehouse.inventoryObjects.InventoryItem;
import com.stuhrling.warehouse.inventoryObjects.InventoryQuantity;
import com.stuhrling.warehouse.inventoryObjects.Location;
import com.stuhrling.warehouse.inventoryObjects.Locator;
import com.stuhrling.warehouse.inventoryTransactions.TransactionStatus;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* #author Mwaldner
*/
public class SaleTest
{
#SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(SaleTest.class);
Sale sale;
List<InventoryQuantity> inventory;
List<InventoryQuantity> itemsToRemove;
private static Locator l1;
private static Locator l2;
private static InventoryItem i1;
private static InventoryItem i2;
#BeforeClass
public static void setupTest()
{
setupLocators();
setupItems();
}
private static void setupLocators()
{
try
{
l1 = new Location();
l1.setCode("L1");
l2 = new Container();
l2.setCode("C1");
}
catch (Exception e)
{
log.error("error",e);
log.error(e.getStackTrace());
}
}
private static void setupItems()
{
i1 = new InventoryItem();
i1.setBarcode("B1");
i2 = new InventoryItem();
i2.setBarcode("B2");
}
#Before
public void setUp()
{
setupFakeInventory();
}
private void setupFakeInventory()
{
inventory = new ArrayList<InventoryQuantity>();
InventoryQuantity iq1 = new InventoryQuantity();
iq1.setItem(i1);
iq1.setLocator(l1);
iq1.setQuantityOnHand(15);
InventoryQuantity iq2 = new InventoryQuantity();
iq2.setItem(i2);
iq2.setLocator(l2);
iq2.setQuantityOnHand(35);
inventory.add(iq1);
inventory.add(iq2);
}
/**
* <strong>Given</strong><br/>
* a list of <code>InventoryQuantity</code> <br/>
* <strong>Then</strong><br/>
* remove said watches at said location from inventory
*/
#Test
public void testSellWatches() throws Exception
{
try
{
sale = new Sale();
int user = sale.getCreatedBy();
Date date = sale.getDateTimeFulfilled();
sale.inventory = inventory;
SaleLine line1 = new SaleLine(l1, i1, 5);
SaleLine line2 = new SaleLine(l2, i2, 7);
sale.add(line1);
sale.add(line2);
sale.execute(0);
assertTrue(checkInventory(l1, i1) == 10);
assertTrue(checkInventory(l2, i2) == 28);
assertTrue(sale.getStatus() == TransactionStatus.COMPLETED);
assertTrue(sale.toString().equals("Sale performed by '' on "));
assertTrue(line1.toString().equals("Sold 5 of item 'i1' from locator 'l1'"));
assertTrue(line2.toString().equals("Sold 7 of item 'i2' from locator 'l2'"));
}
catch (Exception e)
{
log.error(e.getCause());
log.error(e.getMessage());
log.error("error", e);
}
}
private int checkInventory(Locator locator, InventoryItem item)
{
List<InventoryQuantity> inventory = sale.inventory;
for (InventoryQuantity iq : inventory)
{
if (iq.getLocator().equals(locator) && iq.getItem().equals(item))
{
return iq.getQuantityOnHand();
}
}
return 0;
}
}
Here is the Location class:
package com.stuhrling.warehouse.inventoryObjects;
import com.stuhrling.warehouse.exceptions.LocationsDisabledException;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import com.stuhrling.warehouse.exceptions.ParentContainerException;
import com.stuhrling.warehouse.exceptions.PersistenceException;
import com.stuhrling.warehouse.inventoryObjects.Sequence.LocationSequence;
import com.stuhrling.warehouse.inventoryObjects.locationHeirarchy.LocationNameFactory;
import com.stuhrling.warehouse.persistence.WH_HibernateUtil;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
/**
* #author Brian Horn
*/
#Entity
#DiscriminatorValue("L")
public class Location extends Container
{
private static final Logger log = Logger.getLogger(Location.class);
#Column(name = "location_type")
#Enumerated(EnumType.STRING)
private LocationType locationType = LocationType.DEFAULT;
public Location()
{
}
public Location(String code)
{
this.code = code;
}
public Location(String code, String name)
{
this.code = code;
this.name = name;
}
/**
* Create a new <code>Location</code> for storing inventory;<br>
* a unique sequence# is automatically assigned to the <code>Location</code>
* .<br>
* <Strong>Use this method to create new Locations, <i>do not use the
* <code>Location</code> class!</i></Strong>
*
* #return
* #throws PersistenceException
*/
public static Location newLocation() throws PersistenceException
{
Location loc = new Location(LocationSequence.getNext());
return loc;
}
/**
* Create a new <code>Location</code> for storing inventory;<br>
* a unique sequence# is automatically assigned to the <code>Location</code>
* .<br>
* <Strong>Use this method to create new Locations, <i>do not use the
* <code>Location</code> class!</i></Strong>
*
* #param locationType
* #param parent
* #return
* #throws PersistenceException
* #throws com.stuhrling.warehouse.exceptions.ParentContainerException
*/
public static Location newLocation(LocationType locationType, Locator parent) throws PersistenceException, ParentContainerException, LocationsDisabledException
{
Location loc = new Location(LocationSequence.getNext());
loc.addTo(parent);
log.debug(parent.getCode());
loc.setLocationType(locationType);
List<Location> siblings = getSiblings(loc);
LocationNameFactory lFactory = new LocationNameFactory(loc, siblings);
loc.setName(lFactory.getName());
return loc;
}
#SuppressWarnings("unchecked")
private static List<Location> getSiblings(Location location) throws PersistenceException
{
Session session = WH_HibernateUtil.getCurrentSession();
List<Location> l = session.createCriteria(Location.class).add(Restrictions.eq("parent", location.getParent())).add(Restrictions.isNotNull("name")).list();
return l;
}
#Override
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public LocationType getLocationType()
{
return locationType;
}
public void setLocationType(LocationType locationType)
{
this.locationType = locationType;
}
public void createHierarchicalName(LocationNameFactory factory) throws Exception
{
if (!(locationType.equals(LocationType.DEFAULT)))
{
name = factory.getName();
}
}
#Override
public void addTo(Locator locator) throws ParentContainerException, LocationsDisabledException
{
if (locator instanceof Location || locator instanceof Subinventory)
{
super.addTo(locator);
}
else
{
throw new ParentContainerException("Cannot add location to container");
}
}
}
Here is the StackTrace:
java.lang.ExceptionInInitializerError: null
at com.stuhrling.warehouse.inventoryObjects.Location.<clinit> (Location.java:17)
at com.stuhrling.warehouse.inventoryTransactions.sales.SaleTest.setupLocators(SaleTest.java:47)
at com.stuhrling.warehouse.inventoryTransactions.sales.SaleTest.setupTest(SaleTest.java:39)
Thank You in advance for your time.
Edit: BTW, I forgot to mention that Location and Container are subclasses of Locator.
The error means that Java couldn't construct an instance of Location or InventoryItem because of an exception that is thrown in a static block of code. Basically, you have this:
public class Location {
static { throw new RuntimeException("Foo"); }
}
or, more likely,
public class Location {
static Bar BAR = null;
static Foo FOO = BAR.x(); // NPE
if you are using Mac M1 chip and room lib , try this : In project-level build.gradle, add the following configuration in allprojects :
allprojects {
repositories {
// ...
}
// ADD THE FOLLOWING
configurations.all {
resolutionStrategy {
force 'org.xerial:sqlite-jdbc:3.34.0'
}
}
I would like to run AsyncPlayerChatEvent.java inside adminchat.java, specifically when person types command /ac it would use AsycPlayerChatEvent.java to handle it. ive googled it but it doesnt seem to work out, i tried adding AsyncPlayerChatEvent.AsyncPlayerChatEvent(); but it didnt work, here's the code.
adminchat.java
package alo.adminchat;
import java.util.IllegalFormatException;
import java.util.Set;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
public final class adminchat extends JavaPlugin
{
#Override
public void onEnable()
{
System.out.println("Adminchat by Alo k2ivitus!");
// TODO Insert logic to be performed when the plugin is enabled
}
#Override
public void onDisable()
{
System.out.println("Adminchat by Alo sulgus!");
// TODO Insert logic to be performed when the plugin is disabled
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
if(cmd.getName().equalsIgnoreCase("achelp"))
{ // If the player typed /ac then do the following...
// doSomething
return false;
} //If this has happened the function will return true.
// If this hasn't happened the a value of false will be returned.
return false;
}
public boolean onCommand2(CommandSender sender, Command cmd, String label, String[] args)
{
if(cmd.getName().equalsIgnoreCase("ac"))
{ // If the player typed /ac then do the following...
AsyncPlayerChatEvent.AsyncPlayerChatEvent(); //This is what needs fixing
return true;
} //If this has happened the function will return true.
// If this hasn't happened the a value of false will be returned.
return false;
}
}
AsyncPlayerChatEvent.java
package alo.adminchat;
import java.util.IllegalFormatException;
import java.util.Set;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
public class AsyncPlayerChatEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancel = false;
private String message;
private String format = "<%1$s> %2$s";
private final boolean recipients;
public AsyncPlayerChatEvent(final boolean async, final Player who, final String message, final Set<Player> players) {
super(who, async);
this.message = message;
recipients = player.hasPermission("adminchat.use");
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFormat() {
return format;
}
public void setFormat(final String format) throws IllegalFormatException, NullPointerException {
// Oh for a better way to do this!
try {
String.format(format, player, message);
} catch (RuntimeException ex) {
ex.fillInStackTrace();
throw ex;
}
this.format = format;
}
public boolean getRecipients() {
return recipients;
}
public boolean isCancelled() {
return cancel ;
}
public void setCancelled(boolean cancel) {
this.cancel = cancel;
}
#Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
I think what you mean is you want create an instance of AsyncPlayerChatEvent?
new AsyncPlayerChatEvent();
But you need to pass in your arguments:
boolean async, Player who, String message, Set<Player> players
Instead of calling the constructor with AsyncPlayerChatEvent.AsyncPlayerChatEvent(), you should use new AsyncPlayerChatEvent() instead. This will create a new AsyncPlayerChatEvent and call the constructor on it.
Need to setup JMock code to test call back with google protobuf
Full project is located at http://github.com/andrewmilkowski/template-transport
In short, following are methods signatures (below)
what I need to do is to test method getLongValue, using Jmock JUnit4Mockery
what is the best and cleanest way to go about this
thanks much!
package com.argmaps.client.proto;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fepss.rpc.server.RpcApplication;
import com.fepss.rpc.client.RpcChannelImpl;
import org.apache.tapestry5.ioc.MappedConfiguration;
import com.google.protobuf.RpcController;
import com.google.protobuf.RpcCallback;
import com.argmaps.transport.proto.generated.TransportServer.ProtoService;
import com.argmaps.transport.proto.generated.TransportServer.ProtoService.Stub;
import com.argmaps.transport.proto.generated.TransportServer.DefaultLongValue;
import com.argmaps.transport.proto.generated.TransportServer.LongValue;
import com.argmaps.transport.proto.fepss.ProtoServer.TransportHandler;
public class TransportClient {
protected final Log LOG = LogFactory.getLog(this.getClass().getName());
private RpcController controller;
private TransportHandler transportHandler;
private ProtoService.Interface service;
private void open(String host, int port) {
RpcChannelImpl channel = new RpcChannelImpl(host, port);
controller = channel.newRpcController();
service = ProtoService.newStub(channel);
}
protected static class LongValueRpcCallback implements RpcCallback<LongValue> {
private long longValue = 0L;
#Override
public void run(LongValue result) {
longValue = result.getLongValue();
}
private long getLongValue() {
return longValue;
}
}
private void close() {
}
public long getLongValue(LongValueRpcCallback longValueRpcCallback) {
DefaultLongValue defaultLongValue = DefaultLongValue.newBuilder().setLongValue(0L).build();
service.getLongValue(controller, defaultLongValue, longValueRpcCallback);
if (LOG.isDebugEnabled()) {
LOG.debug("Long value from server:" + longValueRpcCallback.getLongValue());
}
return longValueRpcCallback.getLongValue();
}
public static void main(String[] args) {
String host = "localhost";
int port = 9090;
final String portArgKey = "--port=";
for (String cmd : args) {
if (cmd.startsWith(portArgKey)) {
port = Integer.parseInt(cmd.substring(portArgKey.length()));
break;
}
}
TransportClient c = new TransportClient();
c.open(host, port);
c.getLongValue(new LongValueRpcCallback());
c.close();
}
public TransportClient() {
}
public static class TransportModule {
public static void contributeIoHandler(MappedConfiguration<String, ProtoService> configruation) {
configruation.add(ProtoService.getDescriptor().getFullName(), new TransportHandler());
}
}
}
Because of the callback, needed to:
create abstract class LongValueRpcCallbackTemplate implements RpcCallback
create class LongValueRpcCallback extends LongValueRpcCallbackTemplate
and then complete implementation in the test class
Test class:
package com.argmaps.client.proto;
import com.argmaps.transport.proto.generated.TransportServer;
import com.fepss.rpc.client.RpcChannelImpl;
import com.google.protobuf.RpcController;
import org.jmock.Expectations;
import org.junit.Test;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import static org.junit.Assert.assertEquals;
public class TransportClientTest {
Mockery context;
#Before
public void before() {
context = new JUnit4Mockery();
}
private class TestLongValueRpcCallback extends LongValueRpcCallbackTemplate {
private long longValue = 123456789L;
#Override
protected long getLongValue() {
return longValue;
}
}
#Test
public void testGetLongValue() {
final TransportServer.ProtoService.Interface mockedTransportServer = context.mock(TransportServer.ProtoService.Interface.class);
final RpcChannelImpl channel = new RpcChannelImpl("localhost", 9090);
final RpcController controller = channel.newRpcController();
final TransportServer.DefaultLongValue defaultLongValue = TransportServer.DefaultLongValue.newBuilder().setLongValue(0L).build();
com.argmaps.client.proto.TransportClient testObject = new TransportClient(controller, mockedTransportServer);
final TestLongValueRpcCallback testLongValueRpcCallback = new TestLongValueRpcCallback();
final long testLongValue = 123456789L;
context.checking(new Expectations() {
{
one(mockedTransportServer).getLongValue(controller, defaultLongValue, testLongValueRpcCallback);
}
});
assertEquals(testLongValue, testObject.getLongValue(testLongValueRpcCallback));
}
}