Java & XML: Fixing a few things - java

I'm making an attempt to load my npc drops for a game via xml. I've started the loading processes but I'm encountered a few problems. First of all, I can only have 1 drop per npc without creating another case of 'newNpc' with the same npc id or I get a load error. I'd like to have multiple drops per npc. Also I need help reading and using a definition by rarity. Example:
if (Math.random(100) > 95) {
// Drop VERY_RARE item here
|
My XStreamUtil Class (loads xml files):
package server.engine.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import server.game.entity.npc.impl.drops.NpcDropDefinition;
import server.game.entity.npc.impl.drops.NpcDropDefinition.LoadDropDefinitions;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider;
public class XStreamUtil {
private static XStreamUtil instance = new XStreamUtil();
private static XStream xStream = new XStream(new Sun14ReflectionProvider());
public static XStreamUtil getInstance() {
return instance;
}
public static XStream getxStream() {
return xStream;
}
static {
xStream.alias("newNpc", NpcDropDefinition.class);
}
public static void loadAllFiles() throws IOException {
LoadDropDefinitions.load();
}
public static void writeXML(Object object, File file) throws IOException {
FileOutputStream out = new FileOutputStream(file);
try {
xStream.toXML(object, out);
out.flush();
} finally {
out.close();
}
}
}
My Xml Definition Class:
package server.game.entity.npc.impl.drops;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import server.engine.util.XStreamUtil;
/**
* NpcDropDefinition.java
*
* #author Notorious
*/
public class NpcDropDefinition {
private int npcId, itemId, itemAmount;
private DropRarity dropRarity;
enum DropRarity {
CONSTANT,
COMMON,
UNCOMMON,
RARE,
VERY_RARE;
}
/**
* #return the npcId
*/
public int getNpcId() {
return npcId;
}
/**
* #return the itemId
*/
public int getItemId() {
return itemId;
}
/**
* #return the itemAmount
*/
public int getItemAmount() {
return itemAmount;
}
public DropRarity getDropRarity() {
return dropRarity;
}
public static class LoadDropDefinitions {
/**
* Holds all of the definitions for prayer
*/
private static NpcDropDefinition[] def = null;
public static NpcDropDefinition[] getDefinitions() {
return def;
}
/**
* Loads the definitions of pvm points from the XML file
*
* #throws FileNotFoundException
*/
public static void load() throws FileNotFoundException {
#SuppressWarnings("unchecked")
List<NpcDropDefinition> XMLlist = (List<NpcDropDefinition>) XStreamUtil
.getxStream().fromXML(
new FileInputStream("./data/xml/npcDrops.xml"));
def = new NpcDropDefinition[XMLlist.size()];
for (int i = 0; i < def.length; i++) {
def[i] = XMLlist.get(i);
}
if (def.length > 1 || def.length < 1)
System.out.println("[Npc-Drops]: " + def.length
+ " npc drops have been loaded..");
else
System.out
.println("[Npc-Drops]: Only one npc drop has been loaded..");
}
}
}
My Drop Handler class:
package server.game.entity.npc.impl.drops;
import server.Server;
import server.game.entity.Client;
import server.game.entity.npc.NpcHandler;
import server.game.entity.player.PlayerHandler;
/**
* NpcDropHandler.java
*
* #author Notorious
*/
public class NpcDropHandler {
public void dropItems(int i) {
Client c = (Client) PlayerHandler.players[NpcHandler.npcs[i]
.getKillerIndex()];
if (c != null) {
Server.itemHandler.createGroundItem(c, 1, NpcHandler.npcs[i].absX,
NpcHandler.npcs[i].absY, 1, c.playerId);
}
}
}
My Current Xml file:
<list>
<newNpc>
<npcId>1265</npcId>
<itemId>995</itemId>
<itemAmount>10</itemAmount>
<dropRarity>COMMON</dropRarity>
</newNpc>
</list>

Related

ConcurrentSkipListMap firstKey() throws NoSuchElementException even though it contains data

I wrote a small application that receives data from a web socket, which I store in static ConcurrentSkipListMap.
The application initially creates a new thread where it runs infinitely while loop calling ConcurrentSkipListMap.firstKey(). After a while, this call throws a NoSuchElementException, even though the ConcurrentSkipListMap contains data.
break point in catch block
Example of my application:
I have cacher class that contains websocket implementation and NavigableMap init:
package solvethat.net.triobot.Example;
import com.binance.api.client.BinanceApiCallback;
import com.binance.api.client.BinanceApiClientFactory;
import com.binance.api.client.domain.event.DepthEvent;
import com.binance.api.client.domain.market.OrderBook;
import com.binance.api.client.domain.market.OrderBookEntry;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.NavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class AskCacher {
private long updateId;
private final BinanceApiClientFactory factory;
public AskCacher() {
factory = BinanceApiClientFactory.newInstance();
initAsks();
runWebsocket();
}
/**
* Init data getting order book snapshot
*/
private void initAsks() {
try {
OrderBook orderBook = factory.newRestClient().getOrderBook("btcusdt".toUpperCase(), 10);
updateId = orderBook.getLastUpdateId();
NavigableMap<Double, Double> asks = new ConcurrentSkipListMap<>(Comparator.naturalOrder());
for (OrderBookEntry ask : orderBook.getAsks()) {
asks.put(Double.parseDouble(ask.getPrice()), Double.parseDouble(ask.getQty()));
}
StaticData.ask = asks;
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
private void runWebsocket() {
factory.newWebSocketClient().onDepthEvent("btcusdt", new BinanceApiCallback<>() {
/**
* Set ask price and call analysis method
*/
#Override
public void onResponse(DepthEvent depthEvent) {
if (depthEvent.getFinalUpdateId() > updateId) {
updateId = depthEvent.getFinalUpdateId();
updateOrderBook(depthEvent.getAsks());
}
}
/**
* Just print err message
*/
#Override
public void onFailure(final Throwable cause) {
System.err.println(cause.getMessage());
}
});
}
/**
* Updates an order book (asks) with a delta received from the server.
* Whenever the qty specified is ZERO, it means the price should was removed from the order book.
*/
private void updateOrderBook(List<OrderBookEntry> orderBookDeltas) {
for (OrderBookEntry orderBookDelta : orderBookDeltas) {
Double price = Double.parseDouble(orderBookDelta.getPrice());
BigDecimal qty = new BigDecimal(orderBookDelta.getQty());
if (qty.compareTo(BigDecimal.ZERO) == 0) {
// qty=0 means remove this level
StaticData.ask.remove(price);
} else {
StaticData.ask.put(price, Double.parseDouble(orderBookDelta.getQty()));
}
}
// Print best ask to see if cacher is alive
System.out.println("btc-usdt best ask: " + StaticData.ask.firstKey());
// Edit map length
if (StaticData.ask.size() > 10) {
StaticData.ask.tailMap((Double) StaticData.ask.keySet().toArray()[10], true).clear();
}
}}
Then infinite loop:
package solvethat.net.triobot.Example;
public class InfiniteLoop {
public void loopProcess() {
Analyzer analyzer = new Analyzer();
while (true) {
analyzer.analyze(StaticData.ask.firstEntry());
}
}}
And analyzer class:
package solvethat.net.triobot.Example;
import java.util.Map;
public class Analyzer {
public void analyze(Map.Entry<Double, Double> entry) {
StaticData.AnalyzeObject analyzeObject = new StaticData.AnalyzeObject();
analyzeObject.setBestAsk(entry.getKey());
if (analyzeObject.getBestAsk() > 50000) {
System.out.println("It is a good price!!");
}
}
}
Static data model:
package solvethat.net.triobot.Example;
import java.util.NavigableMap;
public class StaticData {
public static NavigableMap<Double, Double> ask;
public static class AnalyzeObject {
double bestAsk;
public double getBestAsk() {
return bestAsk;
}
public void setBestAsk(double bestAsk) {
this.bestAsk = bestAsk;
}
}
}
Main class for example run:
package solvethat.net.triobot.Example;
public class Main {
public static void main(String[] arguments) {
new AskCacher();
new Thread(new InfiniteLoop()::loopProcess).start();
}
}
The example only shows how the application is composed, but I was not able to use it to raise an error but I opened my repo as public:
https://github.com/Sick-E/TrioBot
Can anyone please help me?
Thank you.
Tomas
You can replace your code with something like that (no exception handling is required)
Optional.ofNullable(trio.getThirdPair().getBids().firstEntry())
.map(Map.Entry::getKey)
.ifPresent(trio.getTrioAnalysis()::setBidThird);

Executing flush method, for sending mutations to accumulo without closing the writer

I am writing data to accumulo storage natively using Geomesa Native Client. Here is my java code
package org.locationtech.geomesa.api;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.mock.MockInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.security.Authorizations;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.AttributeTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.junit.Assert;
import org.junit.Test;
import org.locationtech.geomesa.accumulo.data.AccumuloDataStore;
import org.locationtech.geomesa.accumulo.index.AccumuloFeatureIndex;
import org.locationtech.geomesa.accumulo.index.AccumuloFeatureIndex$;
import org.locationtech.geomesa.utils.index.IndexMode$;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.filter.FilterFactory2;
import javax.annotation.Nullable;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class WorkerBeta {
public static void main(String[] args){
try {
DomainObjectValueSerializer dovs = new DomainObjectValueSerializer();
final GeoMesaIndex<DomainObject> index = AccumuloGeoMesaIndex.buildWithView(
"aj_v14",
"localhost:2181",
"hps",
"root", "9869547580",
false,
dovs,
new SimpleFeatureView<DomainObject>() {
AttributeTypeBuilder atb = new AttributeTypeBuilder();
private List<AttributeDescriptor> attributeDescriptors =
Lists.newArrayList(atb.binding(Integer.class).buildDescriptor("rId")
, atb.binding(String.class).buildDescriptor("dId")
, atb.binding(Integer.class).buildDescriptor("s")
, atb.binding(Integer.class).buildDescriptor("a")
, atb.binding(Integer.class).buildDescriptor("e")
);
#Override
public void populate(SimpleFeature f, DomainObject domainObject, String id, byte[] payload, Geometry geom, Date dtg) {
f.setAttribute("rId", domainObject.rideId);
f.setAttribute("dId", domainObject.deviceId);
f.setAttribute("s", domainObject.speed);
f.setAttribute("a", domainObject.angle);
f.setAttribute("e", domainObject.error);
}
#Override
public List<AttributeDescriptor> getExtraAttributes() {
return attributeDescriptors;
}
}
);
//Inserting
final DomainObject one = new DomainObject(1, "AJJASsP", 12, 40, 1);
final GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();
System.out.println(index.insert(
one,
gf.createPoint(new Coordinate(-74.0, 34.0)),
date("2017-03-31T01:15:00.000Z")
));
//Read
GeoMesaQuery q = GeoMesaQuery.GeoMesaQueryBuilder.builder()
.within(-90.0, -180, 90, 180)
.during(date("2017-01-01T00:00:00.000Z"), date("2017-04-01T00:00:00.000Z"))
.build();
Iterable<DomainObject> results = index.query(q);
int counter = 0;
for(DomainObject dm : results){
counter += 1;
System.out.println("result counter: " + counter);
dovs.toBytes(dm);
}
}
catch (Exception ex){
ex.printStackTrace();
}
index.close();
}
public static class DomainObject {
public final int rideId;
public final String deviceId;
public final int angle;
public final int speed;
public final int error;
public DomainObject(int rideId, String deviceId, int angle, int speed, int error) {
this.rideId = rideId;
this.deviceId = deviceId;
this.angle = angle;
this.speed = speed;
this.error = error;
}
}
public static class DomainObjectValueSerializer implements ValueSerializer<DomainObject> {
public static final Gson gson = new Gson();
#Override
public byte[] toBytes(DomainObject o) {
return gson.toJson(o).getBytes();
}
#Override
public DomainObject fromBytes(byte[] bytes) {
return gson.fromJson(new String(bytes), DomainObject.class);
}
}
public static Date date(String s) {
return Date.from(ZonedDateTime.parse(s).toInstant());
}
}
The problem with this code is, I need to create index object every time for a new insert request and call index.close() to reflect the same. But I can't execute insert() agin, once index.close() is called. However i will be accepting insert request from queue at very high rate and I don't want to create index object every time. How can i do that?
In short how i can flush writes without calling close().
I created geomesa Client class file to use geomesa natively. Below is the partial implementation of the same which shows how you can flush with AccumuloAppendFeatureWriter without calling to close.
public class GeomesaClient {
private AccumuloDataStore ds = null;
private AccumuloAppendFeatureWriter fw = null;
private SimpleFeatureSource sfs = null;
private String tableName = "";
private FeatureStore fst = null;
private SimpleFeatureType sft;
public GeomesaClient(Map<String, String> dsConf) throws Exception {
this.ds = (AccumuloDataStore) DataStoreFinder.getDataStore(dsConf);
this.tableName = dsConf.get("tableName");
sft = createFeatureType();
if(!Arrays.asList(this.ds.getTypeNames()).contains(sft.getTypeName())){
ds.createSchema(sft);
}
this.fst = (FeatureStore)sfs;
this.fw = (AccumuloAppendFeatureWriter) (this.ds.getFeatureWriterAppend(sft.getTypeName(),
Transaction.AUTO_COMMIT));
this.sfs = ds.getFeatureSource(sft.getTypeName());
}
/*
Flush with AccumuloAppendFeatureWriter
*/
public void flush(boolean force) {
fw.flush();
}
}

JUnit BeforeClass causes 'java.lang.ExceptionInInitializerError'

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'
}
}

Non-static variable this when putting into a static map

I have a static HashMap to which I'm adding a new item like so:
public static void addSession(Session session) {
if(!map.containsKey(session)){
map.put(session, new SessionThread(session));
}
}
SessionThread is declared locally like so:
public class SessionThread implements Runnable {
That map.put line has a compile error of non-static variable this cannot be referenced from a static context. What is causing the error? this is not referenced anywhere in that method, let alone any non-static members. Everything is either static or in the scope of the method.
Entire class...
package me.scratchjava;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
/**
* A class for managing websocket threads.
* #author James Smyth <jimsmyth at datafascia.com>
*/
public class SessionManager {
private static HashMap<Session, SessionThread> map = new HashMap<>();
/**
* Called whenever a new websocket is opened.
* #param session
*/
public static void addSession(Session session) {
if(!map.containsKey(session)){
map.put(session, new SessionThread(session));
}
}
public static void removeSession(Session session){
if(map.containsKey(session)){
map.remove(session);
}
}
public static void sendData(Session session, byte[] bytes){
if(map.containsKey(session)){
map.get(session).send(bytes);
}
}
public class SessionThread implements Runnable {
private Session session;
private boolean alive = true;
private final LinkedList<byte[]> messageQueue = new LinkedList<>();
public SessionThread(Session session){
}
#Override
public void run() {
while (alive) {
if(Thread.interrupted()){
alive = false;
return;
}
synchronized (messageQueue) {
while(!messageQueue.isEmpty()){
byte[] msg = messageQueue.poll();
try {
session.getBasicRemote().sendBinary(ByteBuffer.wrap(msg));
} catch (IOException ex) {
Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
public void send(byte[] bytes) {
synchronized (messageQueue) {
messageQueue.add(bytes);
}
}
public void kill(){
alive = false;
}
}
}
Your SessionThread inner class is not static. That means the compiler generates a constructor to capture the value of this, the enclosing class. Since you're trying to create a new SessionThread in a static method, there is no this to capture. Make the class static.
Edit
#directedition: SessionThread should be a static class. Actually it should be a stand alone interface and class.

javax.enterprise.event.Event: How to initialize the pushEvent

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.

Categories

Resources