First of all, I'll admit I am new to this and I've probably just forgotten to set an option somewhere to the correct variable, but my Googling has failed me and I have no idea what to do, so I was hoping to get some help.
I have based this on the SecureChat example, it can be located here: http://netty.io/docs/unstable/xref/org/jboss/netty/example/securechat/package-summary.html
And the difference I have made, have been only in the SecureChatServerHandler. More precisely in the messageRecieved block:
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
// Convert the message to a string
String request = (String) e.getMessage();
System.out.println("Message recieved: " + request);
if (request.equalsIgnoreCase("clients")) {
channels.write("We currently have: " + channels.size() + " clients");
} else if (request.toLowerCase().equals("koko"))
for (Channel c : channels) {
if (c == e.getChannel())
c.write("HELLO WORLD");
}
else {
// Then send it to all channels, but the current one.
for (Channel c : channels)
if (c != e.getChannel())
c.write("[" + e.getChannel().getRemoteAddress() + "] " + request + "\n");
else
c.write("[you] " + request + "\n");
}
if (request.equalsIgnoreCase("bye"))
e.getChannel().close();
}
If I send a normal message that is getting broadcasted, everything works. But if I send a command, like clients or koko, I get no response, until I press enter again and send a empty message. First then I get the response back.
C:\Device Manager\Application Server\Examp
les\SecureChat\SecureChatClient\bin>java -jar client.jar 127.0.0.1 8080
UNKNOWN SERVER CERTIFICATE: CN=securechat.example.netty.gleamynode.net, OU=Contr
ibutors, O=The Netty Project, L=Seongnam-si, ST=Kyunggi-do, C=KR
Welcome to Electus secure chat service!
Your session is protected by TLS_DHE_RSA_WITH_AES_128_CBC_SHA cipher suite
You are the 1th user
koko<ENTER>
<PRESS ENTER AGAIN>
HELLO WORLD[you]
clients<ENTER>
<AND ENTER ONCE AGAIN>
We currently have: 1 clients[you]
What I don't understand, and don't want, is the -pressing of enter button twice- thing. It seems highly inlogical and it is irritating. I didn't have these problem with the Telnet Example.
Thank you for your time.
Regards,
Aldrian.
This is one of those humiliating times where you just forgot one small detail, and that messes everything up.
if (request.equalsIgnoreCase("clients")) {
channels.write("We currently have: " + channels.size() + " clients /n"); // Forgot /n here
} else if (request.toLowerCase().equals("koko"))
for (Channel c : channels) {
if (c == e.getChannel())
c.write("HELLO WORLD /n"); // <- Forgot /n here as well
}
Related
i have a button which sends a message into a specific textchannel to ping authorised staff, but everytime its throwing UNKNOWN INTERACTION and is not sending the message. Ive tried many things and i dont know whats wrong and how to fix it, because other buttons work. ereignis is the "event" in german
public void onButtonInteraction(ButtonInteractionEvent ereignis) {
if (ereignis.getButton().getId().equals("ssuuii")) {
if (ereignis.getGuild().getId().equals("GUILD_ID")) {
ereignis.deferReply().queue();
ereignis.getGuild().getTextChannelById("TEXTCHANNEL_ID").sendMessage(ereignis.getGuild().getRoleById("ROLE_ID")
.getAsMention() + ", " + ereignis.getMember().getAsMention() + " möchte Support haben").queue();
} else if (ereignis.getGuild().getId().equals("GUILD_ID_A")) {
ereignis.deferReply().queue();
ereignis.getGuild().getTextChannelById("TEXTCHANNEL_ID_A").sendMessage("exampleman, " +
ereignis.getMember().getAsMention() + " wants Support").queue();
}
}
}
and the Button:
e.getChannel().sendMessageEmbeds(s.build()).setActionRow(Button.success("ssuuii", "Call Support"))
.complete().delete().queueAfter(15, TimeUnit.SECONDS);
I downloaded a lot of blockchain data using https://bitcoin.org, I took some file and I try to analyse it with bitcoinj library.
I would like to get information from every transaction:
-who send bitcoins,
-how much,
-who receive bitcoins.
I use:
<dependency>
<groupId>org.bitcoinj</groupId>
<artifactId>bitcoinj-core</artifactId>
<version>0.15.10</version>
</dependency>
I have a code:
NetworkParameters np = new MainNetParams();
Context.getOrCreate(MainNetParams.get());
BlockFileLoader loader = new BlockFileLoader(np,List.of(new File("test/resources/blk00450.dat")));
for (Block block : loader) {
for (Transaction tx : block.getTransactions()) {
System.out.println("Transaction ID" + tx.getTxId().toString());
for (TransactionInput ti : tx.getInputs()) {
// how to get wallet addresses of inputs?
}
// this code works for 99% of transactions but for some throws exceptions
for (TransactionOutput to : tx.getOutputs()) {
// sometimes this line throws: org.bitcoinj.script.ScriptException: Cannot cast this script to an address
System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
System.out.println("out value:" + to.getValue().toString());
}
}
}
Can you share some snippet that will work for all transactions in the blockchain?
There are at least two type of transaction, P2PKH and P2SH.
Your code would work well with P2PKH, but wouldn not work with P2SH.
You can change the line from:
System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
to:
System.out.println("out address:" + to.getAddressFromP2PKHScript(np)!=null?to.getAddressFromP2PKHScript(np):to.getAddressFromP2SH(np));
The API of Bitcoin says the methods getAddressFromP2PKHScript() and getAddressFromP2SH() are deprecated, and I have not find suitable method.
However, P2SH means "Pay to Script Hash", which means it could contain two or more public keys to support multi-signature. Moreover, getAddressFromP2SH() returns only one address, perhaps this is the reason why it is deprecated.
I also wrote a convinient method to check the inputs and outputs of a block:
private void printCoinValueInOut(Block block) {
Coin blockInputSum = Coin.ZERO;
Coin blockOutputSum = Coin.ZERO;
System.out.println("--------------------Block["+block.getHashAsString()+"]------"+block.getPrevBlockHash()+"------------------------");
for(Transaction tx : block.getTransactions()) {
Coin txInputSum = tx.getOutputSum();
Coin txOutputSum = tx.getOutputSum();
blockInputSum = blockInputSum.add(txInputSum);
blockOutputSum = blockOutputSum.add(txOutputSum);
System.out.println("Tx["+tx.getTxId()+"]:\t" + txInputSum + "(satoshi) IN, " + txOutputSum + "(satoshi) OUT.");
}
System.out.println("Block total:\t" + blockInputSum + "(satoshi) IN, " + blockOutputSum + "(satoshi) OUT. \n");
}
I use fabrc-sdk-java to operate the e2e_cli network.The e2e uses CA and the TLS is disabled.
I successfully create the channel and install the chaincode.
create channel:
Channel newChannel = client.newChannel(myChannel.getChannelName(), orderer, channelConfiguration, channelConfigurationSignatures.toArray(new byte[myPeerOrgs.size()][]));
channelConfigurationSignatures contains signatures from two organizations.
install chaincode:
Every organization has to send an installation proposal once, using its own peerAdmin organization.
reference:https://github.com/IBM/blockchain-application-using-fabric-java-sdk
But,when I prepare to instantiate chaincode,I get the error:
0endorser failed with Sending proposal to peer0.org1.example.com failed because of: gRPC failure=Status{code=UNKNOWN, description=Failed to deserialize creator identity, err MSP Org1 is unknown, cause=null}. Was verified:false
These are related codes:
client.setUserContext(myPeerOrgs.get(0).getPeerAdmin());
InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest();
instantiateProposalRequest.setProposalWaitTime(fabricConfig.getProposalWaitTime());
instantiateProposalRequest.setChaincodeID(chaincodeID);
instantiateProposalRequest.setFcn(ininFun);
instantiateProposalRequest.setArgs(args);
Map<String, byte[]> tm = new HashMap<>();
tm.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
tm.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
instantiateProposalRequest.setTransientMap(tm);
ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
chaincodeEndorsementPolicy.fromYamlFile(new File(myChaincode.getChaincodeEndorsementPolicyPath()));
instantiateProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
logger.trace("Sending instantiateProposalRequest to all peers with arguments: " + Arrays.toString(args));
Collection<ProposalResponse> successful = new LinkedList<>();
Collection<ProposalResponse> failed = new LinkedList<>();
Collection<ProposalResponse> responses = channel.sendInstantiationProposal(instantiateProposalRequest);
for (ProposalResponse response : responses) {
if (response.isVerified() && response.getStatus() == ProposalResponse.Status.SUCCESS) {
successful.add(response);
logger.trace(String.format("Succesful instantiate proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName()));
} else {
failed.add(response);
}
}
logger.trace(String.format("Received %d instantiate proposal responses. Successful+verified: %d . Failed: %d", responses.size(), successful.size(), failed.size()));
if (failed.size() > 0) {
ProposalResponse first = failed.iterator().next();
logger.error("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + first.getMessage() + ". Was verified:" + first.isVerified());
System.exit(1);
}
I thought it was a serialization problem,but the MyUser class and the MyEnrollement class both inherit the Serializable interface, and both define the serialVersionUID.
I have compared blockchain-application-using-fabric-java-sdk and have not identified the problem.
I finally solved this problem.The problem is in the following code:
Channel newChannel = client.newChannel(myChannel.getChannelName(), orderer, channelConfiguration, channelConfigurationSignatures.toArray(new byte[myPeerOrgs.size()][]));
The above code is written by me with reference to End2endIT:
//Create channel that has only one signer that is this orgs peer admin. If channel creation policy needed more signature they would need to be added too.
Channel newChannel = client.newChannel(name, anOrderer, channelConfiguration, client.getChannelConfigurationSignature(channelConfiguration, sampleOrg.getPeerAdmin()));
I don't know if it is wrong with my usage.But my code, the error is in this sentence, when joining the node later, the error is reported.
I referenced https://github.com/IBM/blockchain-application-using-fabric-java-sdk/blob/master/java/src/main/java/org/app/network/CreateChannel.java and found the correct way of writing.
public Channel createChannel() {
logger.info("Begin create channel: " + myChannel.getChannelName());
ChannelConfiguration channelConfiguration = new ChannelConfiguration(new File(fabricConfig.getChannelArtifactsPath() + "/" + myChannel.getChannelName() + ".tx"));
logger.trace("Read channel " + myChannel.getChannelName() + " configuration file:" + fabricConfig.getChannelArtifactsPath() + "/" + myChannel.getChannelName() + ".tx");
byte[] channelConfigurationSignatures = client.getChannelConfigurationSignature(channelConfiguration, myPeerOrgs.get(0).getPeerAdmin());
Channel newChannel = client.newChannel(myChannel.getChannelName(), orderer, channelConfiguration, channelConfigurationSignatures);;
for (Peer peer : myPeerOrgs.get(0).getPeers()) {
// create a channel for the first time, only `joinPeer` here, not `addPeer`
newChannel.joinPeer(peer);
}
for (EventHub eventHub : myPeerOrgs.get(0).getEventHubs()) {
newChannel.addEventHub(eventHub);
}
if (!newChannel.isInitialized()) {
newChannel.initialize();
}
// I have only tested two organizations
// I don’t know if there are any errors in the three organizations.
for (int i = 1; i < myPeerOrgs.size(); i++) {
client.setUserContext(myPeerOrgs.get(i).getPeerAdmin());
newChannel = client.getChannel(myChannel.getChannelName());
for (Peer peer : myPeerOrgs.get(i).getPeers()) {
newChannel.joinPeer(peer);
}
for (EventHub eventHub : myPeerOrgs.get(i).getEventHubs()) {
newChannel.addEventHub(eventHub);
}
}
logger.trace("Node that has joined the channel:");
Collection<Peer> peers = newChannel.getPeers();
for (Peer peer : peers) {
logger.trace(peer.getName() + " at " + peer.getUrl());
}
logger.info("Success, end create channel: " + myChannel.getChannelName() + "\n");
return newChannel;
}
Related code later, such as installing and initializing chaincode, also refer to https://github.com/IBM/blockchain-application-using-fabric-java-sdk. This is an excellent example.
If anyone knows how to use the fourth variable parameter of newChannel, please let me know. Thanks.
Finally, I don't know how to dynamically join nodes, organizations and channels, I am looking for and testing, there are only examples of nodejs on the network, there is no java, if anyone knows, please tell me, I really need. Thanks.
I am developing a multiplayer game in Java built around my own client-server architecture. In short, the client requests a copy of the server's World object 30 times a second and, upon receiving it, sets its client-side copy to the response. This is all done using Java's standard net API.
The issue I am having is that I also store an ArrayList of Player objects in the world, and when I add a Player to this list, the client doesn't get the update. It still receives a copy of the world from the server, but its not up to date.
I experienced a similar problem in a past project that was caused by write/readObject and fixed it by using write/readUnshared, but even that isn't working.
Here's the important stuff from the server end of the communication:
String message;
int sum = 0;
while(active)
{
message = "";
try {
message = in.readUTF();
} catch (IOException e) {
active = false;
System.out.println("Lost connection with client " + socket.getInetAddress());
}
if(message.equals("GETWORLD"))
{
try {
sum++;
if(sum == 100)
main.world.addPlayer(999, 2, 2);
System.out.println("Client requested world (#" + sum + ")");
System.out.println(main.world.players.size());
out.writeUnshared(main.world);
out.flush();
System.out.println("Sent client world (#" + sum + ")");
} catch (IOException e) {
active = false;
System.out.println("Lost connection with client " + socket.getInetAddress());
}
}
if(message.equals("DISCONNECT"))
{
active = false;
System.out.println("Client " + socket.getInetAddress() + " requested disconnect");
}
}
And then the client end:
Object read = null;
int sum = 0;
while(active)
{
try {
Thread.sleep((long)(1000 / 30.0));
if(connected)
{
sum++;
System.out.println("Asking server for world (#" + sum + ")");
out.writeUTF("GETWORLD");
out.flush();
read = in.readUnshared();
if(read instanceof World)
{
World temp = (World)read;
System.out.println(temp.players.size());
frame.panel.updateWorld((World)read);
System.out.println("Got world from server (#" + sum + ")");
}
}
} catch (InterruptedException | ClassNotFoundException e1) {
active = false;
e1.printStackTrace();
} catch (IOException e2) {
active = false;
System.out.println("Lost connection with server # " + socket.getInetAddress());
frame.dispose();
System.exit(0);
}
}
Obviously the sum variable is for debugging.
I further tested this with some output, here's what is scaring me:
Client log:
...
Asking server for world (#99)
1
Got world from server (#99)
Asking server for world (#100)
1
Got world from server (#100)
Asking server for world (#101)
1
Got world from server (#101)
...
Server log:
...
Client requested world (#99)
1
Sent client world (#99)
Client requested world (#100)
2
Sent client world (#100)
Client requested world (#101)
2
Sent client world (#101)
...
You can see here that even though the request numbers match up, there's a clear discrepancy between the number of Player objects in the World object.
Here's the important stuff from the World and Player classes for those curious:
public class World implements Serializable
{
public ArrayList<Room> rooms;
public ArrayList<Player> players;
private QuickMaths qm;
...
public class Player implements Serializable
{
private double xPos;
private double yPos;
private Color color;
int id;
...
I apologize if this is a long yet easy problem. I'm not sure if it's a referencing issue or some other network quirk, but it's really driving me nuts. Thanks in advance.
Your problem is with writeUnshared which is a little misleading.
Read here:
"Note that the rules described above only apply to the base-level
object written with writeUnshared, and not to any transitively
referenced sub-objects in the object graph to be serialized. "
This means that the player object will not be written twice but the old reference to that object in the serialization tree will be used.
The solution to this would be to call the reset method after each write call to ensure that the old written objects will not be referenced again.
So:
out.writeUnshared(main.world);
out.flush();
out.reset();
I’m using FreePBX with Asterisk’s Java API.
For the moment, I’m able to display all my SIP peers with their respective states:
public void onManagerEvent(ManagerEvent event)
{
// Look if the event is a IP phone (Peer entry)
if(event instanceof PeerEntryEvent)
{
PeerEntryEvent ev = (PeerEntryEvent)event;
// Get the user extension
peer = ev.getObjectName();
// Add to the array
peersName.add(peer);
}
}
I’m able to display the phone number and name of both callers when a channel is open:
private String GetExtensionPeer(String extension)
{
for (AsteriskChannel e : channels)
if (e.number.equals(extension) && e.bridge != null )
for (AsteriskChannel channel : channels)
if (z.channel.equals(e.bridge))
return " with " + channel.number + " - " + channel.name;
return "";
}
But now, I would like to display the name of my extensions without a channel connection.
In FreePBX's panel, it's look like :
In freepbx you can get list of extensions from asterisk db. To see info, do
asterisk -rx "database show"
To get info use manager action "command" with DBGET.
Other option - got that info from freepbx's mysql db.