RMI chat program, need red "error" message - java

public String commando(String username, String channel, String text) throws RemoteException{
String[] result = text.split(" ", 3);
if(result[0].equalsIgnoreCase("/join")){
channel = result[1];
setChannel(channel);
joinChannel(username, channel);
}
else if(result[0].equalsIgnoreCase("/leave")){
channel = result[1];
setChannel(channel);
leaveChannel(username, channel);
}
else if(result[0].equalsIgnoreCase("/whisper")){
for (int x=2; x<result.length; x++)
newPrivateMessage(username, result[1], result[x]);
}
else if(result[0].equalsIgnoreCase("/exit")){
System.exit(0);
}
else{
error(brukernavn, "Wrong!");
}
return tekst;
}
I need the error to be in red. This message ("Wrong!") goes to the user that wrote something like /dfdsfsd
I get the message up on the screen, but i cant get it in red. Some idea?
EDIT:
Interference:
public interface ChatFront extends Remote {
void error(String to, String message) throws RemoteException;
}
public interface Klient extends Remote {
void error(String to, String message) throws RemoteException;
}
In the server:
class ChatFrontImpl extends UnicastRemoteObject implements ChatFront {
private UserDAO b = new UserDAO();
private Hashtable<String, ArrayList<String>> chanel = new Hashtable<String, ArrayList<String>>();
private ArrayList<Klient> clients= new ArrayList<Client>();
public ChatFrontImpl() throws RemoteException {
}
public void error(String to, String message) throws RemoteException{
errorTo(to, message);
}
private void errorTo(String to, String message) throws RemoteException{
for(Client k: clients){
if(k.findName().equals(to)){
k.error(to, message);
}
}
}
I have edited some of the names (use Norwegian) so this can be a problem for u, but the program works. The only problem is that i cant get red color on the error message
EDIT 2: Forgot the GUI in client:
public class GUI extends javax.swing.JFrame {
GUILogikk gl = new GUILogikk(this);
public void error(String to, String message){
//chatFelt.setCaretColor(Color.RED);
chatFelt.append("" + message + "\n");
chatFelt.setCaretPosition(chatFelt.getText().length());
}
}

If you're using a console window, you'll have to find functions specific to your operating system to set text color. Those functions vary across operating systems, so either reconsider using a console window or address the issue for each system you plan to use your application on. If you're using something like Swing, you can inspect available text color properties associated with the component you're attempting to draw on (setSelectedTextColor(), etc). More here: JTextArea
If you simply want to draw on a Graphics object, you can do the following:
g.setColor(Color.RED);
g.drawString("WRONG!", 32, 32); // text, x, y

Related

How can I detect when an order fills using the Interactive Brokers Java API?

Problem
The IBKR TWS (Trader Workstation) is a tool for managing stock orders in the stock market, by Interactive Brokers. They provide an API to automate orders, like placing orders, cancelling orders, and more.
I'm creating a program to handle executed orders in my Trader Workstation using the Interactive Brokers Java API.
I'm having trouble detecting when an order fills.
The documentation describes that the execDetails callback (which is an EWrapper method, see code below) is invoked when an order is filled, but I tried using that and the execDetails callback was never invoked (I tested this by logging the reqid int in that callback, and I never got any log).
I have also researched about the completedOrder callback, which I'm not sure if that's the callback that will be invoked when an order is filled, because I tested both callbacks with a simple log, and nothing was outputting in the console.
I don't understand the reqExecutions function and whether I need that. I have already read the documentation on this callback, and I don't understand what I'm doing wrong. I want to know I how can detect when an order fills, or executes in the TWS using their API.
Code
Here is my current code:
import com.ib.client.*;
import java.util.*;
public class Main implements EWrapper {
private static EClientSocket clientSocket;
private static EJavaSignal readerSignal;
public static void main(String[] args) throws InterruptedException, IOException {
readerSignal = new EJavaSignal();
clientSocket = new EClientSocket(this, readerSignal);
clientSocket.eConnect("127.0.0.1", 7497, 0);
}
clientSocket.placeOrder(orderidE, contractFill("CUSIP", "USD", tickSymbol, "STK", "SMART"), orderFill(lmtPriceDouble, actionString, "LMT", "GTC", orderQuantity, account, 0));
//Order executes successfully after sometime
public static Order orderFill(double lmtPrice, String action, String orderType, String tif, int totalQuantity, String account, int clientId){
Order order = new Order();
order.m_lmtPrice = lmtPrice;
order.m_action = action;
order.m_orderType = orderType;
order.m_tif = tif;
order.m_totalQuantity = totalQuantity;
order.m_account = account;
order.m_clientId = clientId;
return order;
}
public static Contract contractFill(String secIdType, String currency, String symbol, String secType, String exchange){
Contract contract = new Contract();
contract.m_secIdType = secIdType;
contract.m_currency = currency;
contract.m_symbol = symbol;
contract.m_secType = secType;
contract.m_exchange = exchange;
return contract;
}
/*Implemented EWrapper methods
...
*/
#Override
public void execDetails(int reqId, Contract contract, Execution execution) {
System.out.println(execution + " " + contract + " " + reqId);
}
#Override
public void execDetailsEnd(int reqId) {
System.out.println(reqId);
}
/*Implemented EWrapper methods
...
*/
#Override
public void completedOrder(Contract contract, Order order, OrderState orderState) {
System.out.println(contract);
System.out.println(order);
System.out.println(orderState);
}
#Override
public void completedOrdersEnd() {
System.out.println("cOE");
}/*Implemented rest of EWrapper methods
...
*/
}
I am placing the orders by hand while this code is running, and the order fills fairly quickly (while the code is running), so the code should detect it, but (my problem -->)none of the callbacks are being invoked.
What am I supposed to be doing to detect order executions?
(Note: I'm placing the orders by hand and by code in the TWS as of now).
Here is code that works, I tested with api 9.81.
Note that if you're using clientID 0 then you should also get callbacks from trades place in TWS. I've never tried, but the docs are clear.
import com.ib.client.*;
import java.io.IOException;
import java.util.*;
public class MainIB implements EWrapper {
private EClientSocket clientSocket;
private EJavaSignal readerSignal;
public static void main(String[] args) throws IOException {
new MainIB().connect();
System.in.read();//press enter to exit
System.exit(0);
}
private void connect() {
readerSignal = new EJavaSignal();
clientSocket = new EClientSocket(this, readerSignal);
clientSocket.eConnect("127.0.0.1", 7497, 0);
//Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue
EReader reader = new EReader(clientSocket, readerSignal);
reader.start();
//Once the messages are in the queue, an additional thread can be created to fetch them
Thread processer = new Thread(() -> {
while ( clientSocket.isConnected() ) {
readerSignal.waitForSignal();
try {
reader.processMsgs();
} catch (IOException ex) {}
}
});
processer.setDaemon(true);
processer.start();
}
public Order orderFill(double lmtPrice, String action, String orderType, String tif, int totalQuantity, String account, int clientId){
Order order = new Order();
order.lmtPrice(lmtPrice);
order.action(action);
order.orderType(orderType);
order.tif(tif);
order.totalQuantity(totalQuantity);
//order.account(account);
//order.clientId(clientId);
return order;
}
public Contract contractFill(String secIdType, String currency, String symbol, String secType, String exchange){
Contract contract = new Contract();
//contract.secIdType(secIdType);
contract.currency(currency);
contract.symbol(symbol);
contract.secType(secType);
contract.exchange(exchange);
return contract;
}
#Override
public void error(int id, int errorCode, String errorMsg) {
System.out.println(errorCode + " " + errorMsg);
}
#Override
public void nextValidId(int i) {
int orderidE = i;
clientSocket.placeOrder(orderidE++, contractFill("", "CAD", "USD", "CASH", "IDEALPRO"),
orderFill(0, "SELL", "MKT", "GTC", 100000, "", 0));
}
#Override
public void orderStatus(int i, String status, double d, double d1, double d2, int i1, int i2, double d3, int i3, String string1, double d4) {
System.out.println("status " + status);
}
#Override
public void execDetails(int reqId, Contract contract, Execution execution) {
System.out.println(execution + " " + contract + " " + reqId);
}
/*Implemented rest of EWrapper methods
...
*/
}
Here is bit of my api.Day.0.log file
t:ms <-> msg# # desc
9:064 -> 15-1-DU123456- 15 my account #
9:065 -> 9-1-2- 9 next valid id
9:065 -> 4-2--1-2104-Market da 4 errors(or info)
9:065 -> 4-2--1-2104-Market da
9:072 <- 3-45-2-0-USD-CASH--0. <- 3 means an order I sent
9:671 -> 5-34-2-15016062-USD-C 5 order status
9:722 -> 11--1-2-15016062-USD- 11 exec
9:724 -> 5-34-2-15016062-USD-C more status
9:727 -> 5-34-2-15016062-USD-C
9:728 -> 59-1-0000e215.60b94f1 59 commission report

Abstract Generic Object class

Hi
In the game Minecraft you have to send data between the client and the server in order to sync stuff, one of the things that need to be synced in particular circumstances is TileEntities with a render. The data is stored on the server and sent to the client which is thereafter used for render.
You create a class that contains the data that needs to be synced and attach it to a channel creation API called "SimpleImpl". My Network object and a Message Object:
public class IntercraftPacketHandler
{
private static int index = 1;
private static final ResourceLocation CHANNEL_NAME = new ResourceLocation(Reference.MODID,"network");
private static final String PROTOCOL_VERSION = new ResourceLocation(Reference.MODID,"1").toString();
public static SimpleChannel getNetworkChannel()
{
final SimpleChannel channel = NetworkRegistry.ChannelBuilder.named(CHANNEL_NAME)
.clientAcceptedVersions(version -> true)
.serverAcceptedVersions(version -> true)
.networkProtocolVersion(() -> PROTOCOL_VERSION)
.simpleChannel();
// Sync Capability Identity Hidden data message.
channel.messageBuilder(MessageIdentityHidden.class,index)
.encoder(MessageIdentityHidden::encode)
.decoder(MessageIdentityHidden::decode)
.consumer(MessageIdentityHidden::handle)
.add(); index++;
// Send TreeTapTileEntity data to client.
channel.messageBuilder(MessageTreeTap.class,index)
.encoder(MessageTreeTap::encode)
.decoder(MessageTreeTap::decode)
.consumer(MessageTreeTap::handle)
.add(); index++;
// Send ChunkLoaderTileEntity data to client.
channel.messageBuilder(MessageChunkLoader.class,index)
.encoder(MessageChunkLoader::encode)
.decoder(MessageChunkLoader::decode)
.consumer(MessageChunkLoader::handle)
.add(); index++;
return channel;
}
}
public class MessageChunkLoader
{
private BlockPos pos;
private boolean canLoad;
public MessageChunkLoader(BlockPos pos,boolean canLoad)
{
this.pos = pos;
this.canLoad = canLoad;
}
public void handle(Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> {
try {
ChunkLoaderBaseTileEntity tile = (ChunkLoaderBaseTileEntity) Minecraft.getInstance().world.getTileEntity(pos);
tile.canLoad = canLoad;
} catch (NullPointerException err) {
System.out.println(String.format("Could not find ChunkLoaderTileEntity at %s %s %s!",pos.getX(),pos.getY(),pos.getZ()));
}
});
}
public static void encode(MessageChunkLoader message, PacketBuffer buffer)
{
buffer.writeBlockPos(message.pos);
buffer.writeBoolean(message.canLoad);
}
public static MessageChunkLoader decode(final PacketBuffer buffer)
{
return new MessageChunkLoader(buffer.readBlockPos(),buffer.readBoolean());
}
}
I then initialize it in my main mod class used by objects in my mod project.
#Mod(Reference.MODID)
public class IntercraftCore
{
public static final SimpleChannel NETWORK = IntercraftPacketHandler.getNetworkChannel();
...
The problem and this post's question; right now I create a new message class from the formula I follow in MessageChunkLoader (public static encode & decode method and a handle method). I would like to create a more generic class for creating message classes for TileEntities, but I'm having problems with that. Here's the current class:
public abstract class MessageTileEntity<T extends TileEntity>
{
protected final BlockPos pos;
protected final Class<T> clazz;
public MessageTileEntity(BlockPos pos, Class<T> clazz)
{
this.pos = pos;
this.clazz = clazz;
}
public abstract void handle(Supplier<NetworkEvent.Context> ctx);
protected T getTileEntity()
{
try {
return clazz.cast(Minecraft.getInstance().world.getTileEntity(pos));
} catch (NullPointerException e) {
System.out.println(String.format("Could not find %s at [%d %d %d]!",clazz.getSimpleName(),pos.getX(),pos.getY(),pos.getZ()));
throw e;
} catch (ClassCastException e) {
System.out.println(String.format("TileEntity at [%d %d %d] is not %s!",pos.getX(),pos.getY(),pos.getZ(),clazz.getSimpleName()));
throw e;
}
}
public static void encode(MessageTileEntity message, PacketBuffer buffer)
{
}
public static MessageTileEntity decode(final PacketBuffer buffer)
{
return null;
}
}
The main problem is I lack the proper Java skills to make it like I want it to function. The method handle is easy as it's non-static and needs to be custom to every TileEntity message, but the methods encode and decode which needs to be static gives me problems. I have no idea what I'm trying to achieve is possible, asking won't hurt. Maybe the solution is easier than I think.

Failure: org.junit.ComparisonFailure: File testfile_1.txt Line 1

Its me again...with the same context. I ran a test file in Dr.Java for my constructor. It is about reading a file in the directory to test. Here is part of content in test file:
public void cw_println_file1 () throws Exception {
String actual, msg, expect;
String filename;
CensoredWriter out;
for(int i=0; i<fileLines.length; i++){
String [][] test = fileLines[i];
String censor = test[0][0];
String [] outLines = test[1];
String [] expectLines = test[2];
filename = String.format("testfile_%d.txt",i);
out = new CensoredWriter(filename,censor);
for(int j=0; j<outLines.length; j++) {
out.println(outLines[j]);
}
out.close();
assertLines(expectLines, filename);
}
}
I got an error message like this:
File: C:\Users\jiangbuyun\Desktop\lab5\distrib-lab05\Lab05Tests.java [line: 137]
Failure: org.junit.ComparisonFailure: File testfile_1.txt Line 1
Expect: A %!^##er-scooper, or %!^## scoop, is a device used to pick up animal
Actual: A %!^##er-scooper, or %!^## scoop, is a device used to pick up animalfeces from public places and yards, particularly those ofdogs. %!^*##er-scooper devices often have a bag or bag attachment.
Expected:<...ed to pick up animal[]>
but was:<...ed to pick up animal[feces from public places and yards, particularly those ofdogs. %!^*##er-scooper devices often have a bag or bag attachment.]
I found it is supposed to stop at the brackets after "animal" and nothing is between the two brackets, but it actually continued to read text and put it into the brackets.
public class CensoredWriter extends PrintWriter {
String censored;
public CensoredWriter(OutputStream o, String c) {
super(o);
this.censored = c;
}
public CensoredWriter(File f, String c) throws Exception {
super(f);
this.censored = c;
}
public CensoredWriter(String s, String c) throws Exception {
super(s);
this.censored = c;
}
public String transform(String s) {
String a = s.replaceAll(censored, "%!^*##");
return a;
}
#Override
public void print(String s) {
super.print(transform(s));
}
#Override
public void println(String s) {
print(s);
flush();
}
}
From what you posted, the issue is that you seem to replace censored with "%!^*##", so that part of the implementation works. However, stopping after animal is the part you haven't implemented yet.
By the way, when asking questions, try to provide the necessary context. For example, I suppose your method cw_println_file1 is a test (#Test) method -- it would help to see that without guessing. Also, if your method requires some stuff from a #Before method (eg. fileLines seems to be declared somewhere else), it might help for the reader to understand your problem to see those required parts as well.

Java RMI with JFrame - Get text from client to GUI

Hey i just started with Java, RMI and JFrame about 2 weeks ago.
I'm doing a game, it works fine as a console but now i'm adding a GUI and i'm getting confused about how to get the Remote Client messages to my Text Area
Remote Client Interface
public interface IRemoteClientObject extends Remote {
public void notifyLogin(String player) throws RemoteException;
public void notifyLogout(String player) throws RemoteException;
public void notifyStatus(String player, PlayerStatus status) throws RemoteException;
public boolean challenge(String player) throws RemoteException;
}
Remote Client
public class RemoteClientObject extends UnicastRemoteObject implements
IRemoteClientObject {
/**
*
*/
private static final long serialVersionUID = -7209335248515276286L;
/**
* #throws RemoteException
*/
public RemoteClientObject() throws RemoteException {
}
#Override
public void notifyLogin(String player) throws RemoteException {
System.out.println("\n" + player + " joined the game");
}
#Override
public void notifyLogout(String player) throws RemoteException {
System.out.println("\n" + player + " left the game");
}
#Override
public void notifyStatus(String player, PlayerStatus status) throws RemoteException {
if (status.equals(PlayerStatus.PLAYING))
{
System.out.println("\n" + player + " is now playing");
}
else if (status.equals(PlayerStatus.READY))
{
System.out.println("\n" + player + " is available to play");
}
else
{
System.out.println("\n" + player + " is unavailable to play");
}
}
}
In my program without any GUI, for example when a player login (it sends a message to all players with that notification)
for (Player player : serverObject.getPlayers())
{
player.getClient().notifyLogin(username);
}
But now i don't want that text in the System.out, i want it in a text area
So can anyone make me a description about how to do this?Code is not the most important, i just want to understand how this works from a remote client to GUI (JTextArea)?
I'm not sure exactly what you have already. If the GUI in the picture is already built and you have your JTextArea object created, then just replace the line System.out.println(...) with myTextArea.setText(...) or myTextArea.append(...) depending if you want to keep previous content or replace it.
With my understanding you would have to add a button listener to a button (or a mouse listener for the text box) that would look for a certain keystroke (maybe the enter button) or you could even add a JButton to your GUI that the user would click to "submit" their text in that text area.
In the button listener you would just write something like JTextArea.getText(); (the "JTextArea" would just be whatever you called the text area variable.

SMack API in java

public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat)
System.out.println(chat.getParticipant() + " says: "+ message.getBody());
**processmsg** = message.getBody();
System.out.println("Message from Friend -----:"+**processmsg**);
}
Hi.how to use this processmsg String in another method.if i use outside this method i get null value. plz reply soon
Store processmsg as an instance variable in the class that contains processMessage
class Foo {
private String processmsg;
public void processMessage(Chat char, Message message) {
processmsg = message.getBody();
}
public void bar() {
// do whatever you want
}
}
Obviously you'll need to check that it's been assigned and so on before you use it (e.g. you couldn't use bar before processMessage), but you get the idea!

Categories