I am using python to create a server, and Java(Android) to create a client. The problem I am facing is getting the data correctly from one to the other.
I let the Java client attempt a login like this:
SettingsManager settingsman = SettingsManager.getInstance(params[0]);
int port = Integer.parseInt(settingsman.getPort());
String ip = settingsman.getIp();
server = new Socket(ip, port);
input = new DataInputStream(server.getInputStream());
output = new DataOutputStream(server.getOutputStream());
output.writeChars(LOGIN_REQ);
output.writeChars(settingsman.getUserName());
output.writeChars(settingsman.getPassword());
String token = Integer.toString(input.read());
//Check if the login has failed
if(token == "0"){
token = null;
}
return token;
And the Python server receives it like this:
opcode = c.recv(2)
opcode = opcode.decode('utf-8')
print("OPCODE:" + opcode + str(type(opcode)))
if(opcode == "0"):
"Login action"
print("STARTING TO RECV!")
login = c.recv(1024).decode('utf-8')
print("RECEIVED LOGIN: " + login)
password = c.recv(1024).decode('utf-8')
print("PASSWORD: " + password)
print("USERNAME: " + username)
setman = SettingsManager()
setuser = setman.seccam_user()
setpass = setman.seccam_password()
if login == setuser & password == setpass:
print("Login is good!")
"""Generate random token and save it to the settings file"""
elif(opcode == "1"):
pass
else:
print("OTHER!")
This is the output:
OPCODE:0<class 'str'>
OTHER!
Even though the Opcode seems to be a string and is the right value, the program doesn't enter the If statement correctly
Can anyone tell me what I am doing wrong?
Thanks
Alright, I fixed my issue. Using WriteBytes in my Java code is working better!
Related
I'm trying to configure the data source using SSH to access the Database from IntelliJ off-campus. The configuration is as shown in the screenshots, and I got
[08006][17002] IO Error: Got minus one from a read call, connect lapse 30003 ms., Authentication lapse 0 ms. oracle.net.ns.NetException: Got minus one from a read call.
In fact, I've succeeded to connect to the DB with the loginProxy() and loginDB() in a Java program. From running the code, I knew that the jdbcPort should be dynamic, and I assume that's also what should be filled in the "Port" blank in the "General" tab in "Data Source and Drivers" configuration window.
So here comes the problem, how can I configure it if the Port to be filled in is DYNAMIC? Or did I get anything wrong so that actually there should be another approach?
An additional question: String URL = "jdbc:oracle:thin:#" + jdbcHost + ":" + jdbcPort + "/" + database; What URL format is used here? It doesn't look like SID, Service Name, or TNS, but it does work... and it's funny that when I substitute the "/" with ":", which matches the SID format, it doesn't work anymore...
/**
* Login the proxy. Do not change this function.
*
* #return boolean
*/
public boolean loginProxy() {
if (getYESorNO("Using ssh tunnel or not?")) { // if using ssh tunnel
String[] namePwd = getUsernamePassword("Login cs lab computer");
String sshUser = namePwd[0];
String sshPwd = namePwd[1];
try {
proxySession = new JSch().getSession(sshUser, proxyHost, proxyPort);
proxySession.setPassword(sshPwd);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
proxySession.setConfig(config);
proxySession.connect();
proxySession.setPortForwardingL(forwardHost, 0, databaseHost, databasePort);
forwardPort = Integer.parseInt(proxySession.getPortForwardingL()[0].split(":")[0]);
// 👆 forwardPort is set here, seems to be dynamic...
} catch (JSchException e) {
e.printStackTrace();
return false;
}
jdbcHost = forwardHost; // 👈 this is used in case of SSH connection, which is "localhost"
jdbcPort = forwardPort; // 👈 this is used in case of SSH connection
} else {
jdbcHost = databaseHost;
jdbcPort = databasePort;
}
return true;
}
/**
* Login the oracle system. Change this function under instruction.
*
* #return boolean
*/
public boolean loginDB() {
String username = "myDBUsername";
String password = "myDBPassword";
/* Do not change the code below */
String URL = "jdbc:oracle:thin:#" + jdbcHost + ":" + jdbcPort + "/" + database;
try {
System.out.println("Logging " + URL + " ...");
conn = DriverManager.getConnection(URL, username, password);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
On general tab you need to specify real db server hostname and port, not localhost. With configured SSH tunnel on next tab all the things for connection will be done automatically.
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.
Here is my code for mysql database restore code .when i tried this code app works without exception but application get hangs and database is not restored ..please help me
String databaseName = "sample"; //database name
String userName = "root"; // MySQL username
String password = ""; // MySQL password
int processComplete; // this variable for verify the process
String[] executeCmd = new String[]{"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",
databaseName, "-u" + userName, "-p" + password, "-e", " source D:/data.sql"};
System.out.println(executeCmd);
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);// execute the command
processComplete = runtimeProcess.waitFor();
System.out.println(processComplete);
if (processComplete == 1) { // if return value equal to 1 then failed the process
JOptionPane.showMessageDialog(null, "Restore Failed");
} else if (processComplete == 0) {{// if return value equal to 0 then failed the process
JOptionPane.showMessageDialog(null, "Restore Completed");
}
I suspect that the last parameter is been mishandled
String[] executeCmd = new String[]{
"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",
databaseName,
"-u" + userName,
"-p" + password,
"-e",
" source D:/data.sql" }
It should probably look more like...
String[] executeCmd = new String[]{
"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",
databaseName,
"-u" + userName,
"-p" + password,
"-e",
"source",
"D:/data.sql" }
Each element in the array will be a separate argument passed to the command, this allows you the flexibility of passing arguments that have spaces in them without need to first escape them using quotes
You should consider using ProcessBuilder instead of trying to build the Process yourself, apart from allowing you to re-direct the error stream to the input stream, it also allows you to specify the starting context for the process.
You should also be reading the output of the process (via it's InputStream) which would possibly highlight issues and may also allow the process to exit (as some process won't exit until there stdout is read completely)
For example: How do I execute Windows commands in Java?
I am currently trying to create a cookie in JavaScript. The idea is that when the user clicks the extension icon whilst watching a YouTube video it gets the tab name and saves it as a cookie. This is so that I can then access the cookie from my Java program.
I am using chrome and I can't see the cookie in the list when I have pressed it even though the alert successfully displays so I am wondering if anyone can see an issue with my code.
Also if anyone has a better idea of how to get the tab name to my Java program I would be happy to hear your ideas.
Thanks everyone, here's my code:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
createCookie(cookieName, cookieValue);
});
}
function createCookie(name, value)
{
var expires = new Date().getTime() + (1000 * 3600);
var domain = ";domain=.youtube.com";
document.cookie = name + "=" + value + ";expires=" + expires + domain + ";path=/";
alert(name + " = " + value + ". Date = " + expires);
}
EDIT: I have changed my code to use the chrome API's provided by Google, great success!
If anyone has the same problem I have used the Google API's for chrome concerning cookies.
My new code is the following:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue, cookieURL;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
cookieURL = tab.url;
createCookie(cookieName, cookieValue, cookieURL);
});
}
function createCookie(cookieName, cookieValue, cookieURL)
{
chrome.cookies.set({name: cookieName, value: cookieValue, domain: ".youtube.com", url: cookieURL});
}
Note: In the manifest file you will need permissions for tabs, cookies and the website domain. Furthermore I have not stated when the cookie expires thus it expires when the session is closed.
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
}