MongoDB & Java Connection Error - java

I am trying to run a java program with the java/mongo driver on a separate computer than the one running mongod. I only modified the java/mongo tutorial code to include an ip address.
package mongotest;
import com.mongodb.*;
public class Main {
static DBCursor cur;
static DBCollection coll;
public static void main(String[] args) {
Mongo m;
try{
m = new Mongo("192.168.0.102"); // <---- This does not connect. It will eventually time out
DB db = m.getDB("playerdb");
coll = db.getCollection("players");
cur = coll.find();
//while (cur.hasNext())
// coll.remove(cur.next());
coll.ensureIndex(new BasicDBObject("playerID", 1).append("unique", true));
boolean unique = true;
cur = coll.find();
printResults(cur, "Find All Records");
boolean canCreate;
canCreate = createAccount("Josh", "1", cur, coll);
canCreate = createAccount("Jason", "1", cur, coll);
canCreate = createAccount("Ryan", "1", cur, coll);
canCreate = createAccount("Michael", "1", cur, coll);
canCreate = createAccount("John", "1", cur, coll);
canCreate = createAccount("Susan", "1", cur, coll);
cur = coll.find();
printResults(cur, "Find All Records After Insert");
}//try
catch(Exception e){
System.out.println(e);
}//catch
}
(Note: This will eventually time out and quit)
But when I run the same code on the computer running the database it's fine.
How can I get a connection between two computers on different networks to communicate?

First you need to ensure a network route:
can you ping computer b from computer a?
can you telnet to the mongo port from the second computer to the first?
If not, you have a networking problem not a programming one. In which case it might behoove you to ask this question on serverfault or superuser

Check if computer a can ping computer b. If it can, then check mongodb configuration parameters like auth and noauth and set the same according to your convinience.

Two computers on different networks? Because 192.168.0.102 sure looks like an internal address, not an external one.
You need to figure out what's the public IP address of the computer running mongodb, and use that.
What you're doing is almost like (but not quite as bad) as trying to connect to 127.0.0.1 and wondering why this only works when executed on the computer that hosts the service.

This is pretty much unrelated to MongoDB. Either your network connection is not working properly (firewall or routing issue) or your remote mongod daemon is not listening on the related external IP address (ensure that is bound to the proper IP address using the --bind_ip commandline option).

Related

localhost/127.0.0.1:9042] Cannot connect

Trying to connect Cassandra with Java via below code and getting localhost/127.0.0.1:9042] Cannot connect error-
public static void main(String[] args)
{
Cluster cluster;
Session session;
//cluster connects to the address of the node provided.One contact point is required.Good to have multiple
cluster=Cluster.builder().addContactPoint("localhost").build();
session=cluster.connect("ecommerce");
session.execute("INSERT INTO products (pdt_id, cat_id, pdt_name, pdt_desc, price, shipping) VALUES (002,105, 'Candy 0.9 cu. ft. Washing Machine', 'Capacity of 1 cu. ft.10 different power levels', 64.00, 'Expedited')");
session.execute("INSERT INTO products (pdt_id, cat_id, pdt_name, pdt_desc, price, shipping) VALUES (003,106, 'Prestige 0.9 cu.cm. Pressure Cooker', 'Capacity: 18 qt.', 70.00, 'Dispatched from warehouse')");
String pdtid = null, pdtname = null, pdtdesc = null;
float price = 0;
ResultSet resultSet=session.execute("select * from products");
for(Row row:resultSet)
{
pdtid = Integer.toString(row.getInt("pdt_id"));
pdtname = row.getString("pdt_name");
}
cluster.close();
}
}
The java code syntax looks correct to me.
Please Make sure you have Cassandra is running on your machine and port 9042 open (check firewall). You can check to execute cqlsh and see if Cassandra is responding.
I see you are using an outdated version of the driver. You should consider updgrading to 4.x. Here is the complete documentation: https://docs.datastax.com/en/developer/java-driver/4.4/manual/core/

Cannot read Gremlin data from remote after writing

I use Java to connect to a "remote" (localhost:8182) Gremlin server g this way:
traversalSource = traversal().withRemote(DriverRemoteConnection.using("localhost", 8182, "g"));
Then, I write some node like this:
traversalSource.addV("TenantProfile");
From Gremlin console, connected to the same Gremlin server, I see all created nodes and edges
gremlin> g==>graphtraversalsource[tinkergraph[vertices:42 edges:64], standard]
and queries work, but if I read graph from Java, it results empty, so querying e.g. like
traversalSource.V()
.has("label", TENANT_PROFILE_LABEL)
.has("fiscal id", "04228480408")
.out(OWNS_LABEL)
.has("type", "SH")
.values("description")
.toList();
returns an emtpy list.
Could anyone help me solve this mistery, please?
Thanks.
In reply to Stephen, I post the last instructions before iterate()
for (final Map<String, String> edgePropertyMap : edgePropertyTable) {
edgeTraversal = traversalSource
.V(vertices.get(edgePropertyMap.get(FROM_KEY)))
.addE(edgeLabel)
.to(vertices.get(edgePropertyMap.get(TO_KEY)));
final Set<String> edgePropertyNames = edgePropertyMap.keySet();
for (final String nodePropertyName : edgePropertyNames)
if ((!nodePropertyName.equals(FROM_KEY)) && (!nodePropertyName.equals(TO_KEY))) {
final String edgePropertyValue = edgePropertyMap.get(nodePropertyName);
edgeTraversal = edgeTraversal.property(nodePropertyName, edgePropertyValue);
}
edgeTraversal.as(edgePropertyMap.get(IDENTIFIER_KEY)).iterate();
}
Anyway, if no iterate() were present, how could nodes and edges be visible from inside console? How could they have been "finalized" on remote server?

How do I get connection string for brokers in Kafka

I am new to Kafka. Tried to implement consumer and producer classes to send and receive messages. Need to configure bootstrap.servers for both classes which is a list of broker's ip and port separated by ,. For example,
producerConfig.put("bootstrap.servers",
"172.16.20.207:9946,172.16.20.234:9125,172.16.20.36:9636");
Since the application will be running on the master node of a cluster, it should be able to retrieve the broker information from ZooKeeper just like the answer to Kafka: Get broker host from ZooKeeper.
public static void main(String[] args) throws Exception {
ZooKeeper zk = new ZooKeeper("localhost:2181", 10000, null);
List<String> ids = zk.getChildren("/brokers/ids", false);
for (String id : ids) {
String brokerInfo = new String(zk.getData("/brokers/ids/" + id, false, null));
System.out.println(id + ": " + brokerInfo);
}
}
However this brokerInfo is in Json format which looks like this:
{"jmx_port":-1,"timestamp":"1428512949385","host":"192.168.0.11","version":1,"port":9093}
In this same post, another one suggested the following way of getting connection string for each broker and join them together with comma.
for (String id : ids) {
String brokerInfoString = new String(zk.getData("/brokers/ids/" + id, false, null));
Broker broker = Broker.createBroker(Integer.valueOf(id), brokerInfoString);
if (broker != null) {
brokerList.add(broker.connectionString());
}
}
If this Broker class is from org.apache.kafka.common.requests.UpdateMetadataRequest.Broker, it does not have methods createBroker and connectionString.
Found another similar post Getting the list of Brokers Dynamically. But it did not say how to get the attribute from broker info such as host and port. I can probably write a parser for the json like string to extract them, but I suspect there is more Kafka native way to do that. Any suggestions?
EDIT: I realized the Broker class is from kafka.cluster.Broker. Still it does not have method connectionstring().
You could use ZkUtils to retrieve all the broker information in the cluster, as show below:
ZkUtils zk = ZkUtils.apply("zkHost:2181", 6000, 6000, true);
List<Broker> brokers = JavaConversions.seqAsJavaList(zk.getAllBrokersInCluster());
for (Broker broker : brokers) {
//assuming you do not enable security
System.out.println(broker.getBrokerEndPoint(SecurityProtocol.PLAINTEXT).host());
}
zk.close();

How do I connect to device using jamod and interpret the data

My client wants to control the HVAC systems installed in their site with a custom solution. The HVAC devices provide MODBUS TCP/IP connectivity. I'm new to this field and have no knowledge of MODBUS. I searched the internet and found jamod as a java library for MODBUS. Now I would like to write a program using jamod. But my confusion is how do I get the address of the device I want to connect. And my second problem is even if I manage to connect the device , how can I get required data (in engineering units like temperature) from MODBUS. My questions may sound awful but please forgive me as I'm a novice in this field.
How do I get the address of the device I want to connect to?
This kind of depends on if you're connecting over Modbus RTU or Modbus TCP. RTU (serial) will have a slave id you'll specify while tcp is more direct and the slave id should always be 1.
How can I get required data (in engineering units like temperature) from MODBUS?
Hopefully the data is already formatted in engineering units. Check the device's manual and there should be a table or chart mapping registers to values.
Example:
String portname = "COM1"; //the name of the serial port to be used
int unitid = 1; //the unit identifier we will be talking to, see the first question
int ref = 0; //the reference, where to start reading from
int count = 0; //the count of IR's to read
int repeat = 1; //a loop for repeating the transaction
// setup the modbus master
ModbusCoupler.createModbusCoupler(null);
ModbusCoupler.getReference().setUnitID(1); <-- this is the master id and it doesn't really matter
// setup serial parameters
SerialParameters params = new SerialParameters();
params.setPortName(portname);
params.setBaudRate(9600);
params.setDatabits(8);
params.setParity("None");
params.setStopbits(1);
params.setEncoding("ascii");
params.setEcho(false);
// open the connection
con = new SerialConnection(params);
con.open();
// prepare a request
req = new ReadInputRegistersRequest(ref, count);
req.setUnitID(unitid); // <-- remember, this is the slave id from the first connection
req.setHeadless();
// prepare a transaction
trans = new ModbusSerialTransaction(con);
trans.setRequest(req);
// execute the transaction repeat times because serial connections arn't exactly trustworthy...
int k = 0;
do {
trans.execute();
res = (ReadInputRegistersResponse) trans.getResponse();
for (int n = 0; n < res.getWordCount(); n++) {
System.out.println("Word " + n + "=" + res.getRegisterValue(n));
}
k++;
} while (k < repeat);
// close the connection
con.close();
First, "address" is ambiguous when you're working with Modbus/TCP since there is the IP address of the slave, the unit number of the thing you're talking to (typically 0 for Modbus/TCP), and the address of any registers.
For the "engineering units" question, what you're going to want is the Modbus register map, with any units or conversion factors included. You may also need to know data types, since all Modbus registers are 16 bits.

cassandra stop writing after some time

I have a problem: i write entries from java code to cassandra database, it works for a while, and then stops writing. (nodetool cfstats keyspace.users -H on all nodes show no changes in Number of keys (estimate))
Configuration : 4 nodes (4GB, 4GB, 4GB, and 6GB RAM).
I am using datastax driver, and connection like
private Cluster cluster = Cluster.builder()
.addContactPoints(<points>)
.build();
private Session session = cluster.connect("keyspace");
private MappingManager mappingManager = new MappingManager(session);
...
I do insert in database like
public void writeUser(User user) {
Mapper<User> mapper = mappingManager.mapper(User.class);
mapper.saveAsync(user, Mapper.Option.timestamp(TimeUnit.NANOSECONDS.toMicros(System.nanoTime())));
}
I also tried
public void writeUser(User user) {
Mapper<User> mapper = mappingManager.mapper(User.class);
mapper.save(user);
}
And two variants between.
In debug.log from server i see
DEBUG [GossipStage:1] 2016-05-11 12:21:14,565 FailureDetector.java:456 - Ignoring interval time of 2000380153 for /node
Maybe the problem is, that server in another country? But why it is writing entities at the beginning? How can i fix my problem?
Another update: session.execute on mapper.save returns ResultSet[ exhausted: true, Columns[]]

Categories

Resources