I am working with java program connected with MongoDB when I run the program it will show an error but code is working.
MongoDB has a database called MongoDB and inside that, there is a collection called seatbooking with two columns(name,seatnumber).
This is my code:
MongoClient mongoClient = new MongoClient("localhost", 27017);
System.out.println("connection is established");
MongoDatabase mongoDatabase = mongoClient.getDatabase("MongoDB");
MongoCollection mongoCollection = mongoDatabase.getCollection("seatbooking");
Document document = new Document("name","shenal");
document.append("seatnumber",20);
mongoCollection.insertOne(document);
when I run this code my output is:
> Mar 09, 2020 12:41:36 PM
> com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created
> with settings {hosts=[localhost:27017], mode=SINGLE,
> requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms',
> maxWaitQueueSize=500}
> **connection is established** Mar 09, 2020 12:41:36 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster
> description not yet available. Waiting for 30000 ms before timing out
> Mar 09, 2020 12:41:36 PM com.mongodb.diagnostics.logging.JULLogger log
> INFO: Opened connection [connectionId{localValue:1, serverValue:309}]
> to localhost:27017 Mar 09, 2020 12:41:36 PM
> com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread
> successfully connected to server with description
> ServerDescription{address=localhost:27017, type=STANDALONE,
> state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2,
> 2]}, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216,
> logicalSessionTimeoutMinutes=30, roundTripTimeNanos=5168100} Mar 09,
> 2020 12:41:36 PM com.mongodb.diagnostics.logging.JULLogger log INFO:
> Opened connection [connectionId{localValue:2, serverValue:310}] to
> localhost:27017
The logging output doesn't show any result for the insertOne operation.
If you are using MongoDB Java Driver version prior to 4.0, there is no acknowledgement object returned. But, the version 4's insertOne method returns a InsertOneResult object. This is a new feature in 4.0 (in prior version's the method returned a void).
You can use the following code to check the insert's outcome as follows (with version 4.0):
try {
InsertOneResult insertResult = collection.insertOne(document);
System.out.println("Document inserted with ID: " + insertResult.getInsertedId());
}
catch(MongoWriteException e) {
// write failure happened, handle it here...
}
Related
I am trying to connect to one Kafka server.
in Java, I have configured:
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
.
.
Properties properties = new Properties();
String bootstrapServers = "localhost:9092";
properties.put("bootstrap.servers", bootstrapServers);
properties.put("connections.max.idle.ms", 10000);
properties.put("request.timeout.ms", 5000);
try {
AdminClient adminClient = AdminClient.create(properties);
NewTopic newTopic = new NewTopic("testtopic", 1, (short)1);
.
.
Although there is a configuration to use localhost, I get errors:
INFO: AdminClientConfig values:
bootstrap.servers = [localhost:9092]
Jan 22, 2021 9:48:01 PM org.apache.kafka.common.utils.AppInfoParser$AppInfo <init>
INFO: Kafka version: 2.7.0
Jan 22, 2021 9:48:01 PM org.apache.kafka.common.utils.AppInfoParser$AppInfo <init>
INFO: Kafka commitId: 448719dc99a19793
Jan 22, 2021 9:48:01 PM org.apache.kafka.common.utils.AppInfoParser$AppInfo <init>
INFO: Kafka startTimeMs: 1611348481265
Jan 22, 2021 9:48:03 PM org.apache.kafka.clients.NetworkClient initiateConnect
WARNING: [AdminClient clientId=adminclient-1] Error connecting to node e4f0851caf23:9092 (id: 1001 rack: null)
java.net.UnknownHostException: No such host is known (e4f0851caf23)
Is there any additional configuration that I am missing?
This is only a sample code, I am trying to create one topic.
thank you!
Thank you yuppie-flu!
I have to add:
KAFKA_CFG_ADVERTISED_LISTENERS=INTERNAL://kafka:9093,CLIENT://kafka:9092
I'm working with AWSIotMqttClient to subscribe and publish to topics. After I received all messages I want to stop my application. But it works infinitely long. Here a simple code which works infinitely, even without subscribes:
SampleUtil.KeyStorePasswordPair keyStorePasswordPair =
SampleUtil.getKeyStorePasswordPair("certificate.pem", "privateKey.pem");
AWSIotMqttClient client = new AWSIotMqttClient(
"mqtt-broker.address",
"deviceID",
keyStorePasswordPair.keyStore,
keyStorePasswordPair.keyPassword);
client.connect();
client.disconnect();
Here is my logs:
> Task :Application.main()
Cert file:certificate.pem Private key: privateKey.pem
????. 20, 2019 11:56:45 AM com.amazonaws.services.iot.client.core.AwsIotConnection onConnectionSuccess
INFO: Connection successfully established
????. 20, 2019 11:56:45 AM com.amazonaws.services.iot.client.core.AbstractAwsIotClient onConnectionSuccess
INFO: Client connection active: 5dcd561596c30e0001e4b5d5
????. 20, 2019 11:56:53 AM com.amazonaws.services.iot.client.core.AwsIotConnection onConnectionClosed
INFO: Connection permanently closed
????. 20, 2019 11:56:53 AM com.amazonaws.services.iot.client.core.AbstractAwsIotClient onConnectionClosed
INFO: Client connection closed: 5dcd561596c30e0001e4b5d5
I can stop my application with System.exit(0) but it is undesirable for me. I expect that after all code is passed, the application will stop.
Found here . Updating aws-iot-device-sdk to 1.3.4 version
implementation 'com.amazonaws:aws-iot-device-sdk-java:1.3.4'
implementation 'com.amazonaws:aws-iot-device-sdk-java-samples:1.3.4'
resolved the problem.
I am trying to connect to an Elasticsearch cluster form a Java application by using the TransportClient.
I have successfully tested connected to a cluster running locally.
Now we have set up a remote cluster in the EC2-Cloud. Accessing it via REST intefaces work, also Kibana works.
I can run my application on the Elasticsearch Node directly successfully.
However when I try to connect remotely from another host, the log indicates that the connection succeeds, but then immediately fails with "An established connection was aborted by the software in your host machine".
I have verified that both server and client run the same version of Elasticsearch. Also the firewall configuration should allow communication on port 9300 as this is also needed for the cluster-nodes to communicate between each other.
Okt 21, 2015 6:50:24 PM com.example.elasticsearch.visit.nativescript.ElasticsearchTest main
INFO: Setting adress to myhost.com:9300
Okt 21, 2015 6:50:24 PM org.elasticsearch.client.transport.TransportClientNodesService addTransportAddresses
FINE: [Master Man] adding address [[#transport#-1][LNZ123675N02][inet[myhost.com/1.1.1.1:9300]]]
Okt 21, 2015 6:50:24 PM org.elasticsearch.client.transport.TransportClientNodesService$SimpleNodeSampler doSample
FINEST: [Master Man] connecting to listed node (light) [[#transport#-1][LNZ123675N02][inet[myhost.com/1.1.1.1:9300]]]
Okt 21, 2015 6:50:24 PM org.elasticsearch.transport.netty.NettyTransport connectToNode
FINE: [Master Man] connected to node [[#transport#-1][LNZ123675N02][inet[myhost.com/1.1.1.1:9300]]]
Okt 21, 2015 6:50:24 PM org.elasticsearch.common.breaker.ChildMemoryCircuitBreaker addWithoutBreaking
FINEST: [Master Man] [REQUEST] Adjusted breaker by [16440] bytes, now [16440]
Okt 21, 2015 6:50:24 PM org.elasticsearch.transport.TransportService$Adapter traceRequestSent
FINEST: [Master Man] [0][cluster:monitor/nodes/info] sent to [[#transport#-1][LNZ123675N02][inet[myhost.com/1.1.1.1:9300]]] (timeout: [5s])
Okt 21, 2015 6:50:24 PM org.elasticsearch.common.breaker.ChildMemoryCircuitBreaker addWithoutBreaking
FINEST: [Master Man] [REQUEST] Adjusted breaker by [-16440] bytes, now [0]
Okt 21, 2015 6:50:24 PM org.elasticsearch.transport.netty.NettyTransport exceptionCaught
FINEST: [Master Man] close connection exception caught on transport layer [[id: 0xd938d867, /x.x.x.x:60058 => myhost.com/1.1.1.1:9300]], disconnecting from relevant node
java.io.IOException: An established connection was aborted by the software in your host machine
at sun.nio.ch.SocketDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at org.elasticsearch.common.netty.channel.socket.nio.NioWorker.read(NioWorker.java:64)
at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioWorker.process(AbstractNioWorker.java:108)
at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337)
at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:89)
at org.elasticsearch.common.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178)
at org.elasticsearch.common.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
at org.elasticsearch.common.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Okt 21, 2015 6:50:24 PM org.elasticsearch.transport.netty.NettyTransport disconnectFromNode
FINE: [Master Man] disconnecting from [[#transport#-1][LNZ123675N02][inet[myhost.com/1.1.1.1:9300]]], channel closed event
Okt 21, 2015 6:50:24 PM org.elasticsearch.transport.netty.NettyTransport disconnectFromNode
FINEST: [Master Man] disconnected from [[#transport#-1][LNZ123675N02][inet[myhost.com/1.1.1.1:9300]]], channel closed event
Okt 21, 2015 6:50:24 PM org.elasticsearch.client.transport.TransportClientNodesService$SimpleNodeSampler doSample
INFO: [Master Man] failed to get node info for [#transport#-1][LNZ123675N02][inet[myhost.com/1.1.1.1:9300]], disconnecting...
org.elasticsearch.transport.NodeDisconnectedException: [][inet[myhost.com/1.1.1.1:9300]][cluster:monitor/nodes/info] disconnected
Okt 21, 2015 6:50:24 PM com.example.elasticsearch.visit.nativescript.ElasticsearchTest main
INFO: Having: []
Exception in thread "main" org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: []
at org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:305)
at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:200)
at org.elasticsearch.client.transport.support.InternalTransportClient.execute(InternalTransportClient.java:106)
at org.elasticsearch.client.support.AbstractClient.bulk(AbstractClient.java:167)
at org.elasticsearch.client.transport.TransportClient.bulk(TransportClient.java:370)
at org.elasticsearch.action.bulk.BulkRequestBuilder.doExecute(BulkRequestBuilder.java:166)
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:91)
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:65)
at com.example.elasticsearch.visit.nativescript.ElasticsearchTest.main(ElasticsearchTest.java:68)
My simple test looks like this:
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", "cluster-name")
.build();
logger.info("Creating client");
try (final TransportClient client = new TransportClient(settings)) {
logger.info("Setting adress to " + host + ":" + port);
client.addTransportAddress(new InetSocketTransportAddress(host, port));
logger.info("Having: " + client.connectedNodes());
BulkRequestBuilder bulkRequest = client.prepareBulk();
String json= "{ id: \"12345678\", value: \"value\" }";
bulkRequest.add(client.prepareIndex(INDEX, TYPE, "12345678").
setSource(json));
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
logger.info("Could not write bulk: " + bulkResponse.buildFailureMessage());
} else {
logger.info("Wrote");
}
}
I also tried to verify some common things like cluster-name not set and others.
Also when I use a completely different port, I get a timeout as expected, not this error-message. So the port is definitely behaving different.
Where would I start to look? Can this still be a firewall issue where connections are dropped only after a short while instead of being rejected immediately?
With more testing I actually found out that a company-firewall was interfering in a strange way. When I run the same client-code on a machine outside the company-netowrk, it works fine.
I have written a JAXMPPClient.java program which uses tigase.jaxmpp.j2se.Jaxmpp 3.0.0
I have the following .jar files in my build path
jaxmpp-core-3.0.0
jaxmpp-j2se-3.0.0
and folder jaxmpp-all-3.0.0 containing many .jar files. The JAXMPPClient.java is as follows
Jaxmpp conn = new Jaxmpp();
conn.getConnectionConfiguration().setConnectionType(
ConnectionType.socket);
conn.getConnectionConfiguration().setDomain(IP_ADDRESS_OF_XMPP_SERVER);
conn.getConnectionConfiguration().setPort(PORT_NUMBER_OF_XMPP_SERVER);
conn.getConnectionConfiguration().setUserJID(FROM_USERID + "#" +
IP_ADDRESS_OF_XMPP_SERVER);
conn.getConnectionConfiguration().setUserPassword(FROM_PASSWORD);
String s = tigase.jaxmpp.j2se.connectors.socket.
SocketConnector.HOSTNAME_VERIFIER_DISABLED_KEY
conn.getSessionObject().setProperty(s, Boolean.TRUE);
try {
System.out.println("Before login");
conn.login();
System.out.println("After login");
} catch (final JaxmppException e) {
e.printStackTrace();
}
I am getting
Before login
Sep 29, 2015 5:17:12 PM tigase.jaxmpp.j2se.Jaxmpp createConnector
INFO: Using SocketConnector
Sep 29, 2015 5:17:12 PM tigase.jaxmpp.j2se.connectors.socket.SocketConnector start
INFO: Resolving SRV recrd of domain '123.45.678.910'
Sep 29, 2015 5:17:12 PM tigase.jaxmpp.j2se.connectors.socket.SocketConnector start
INFO: Opening connection to /123.45.678.910:5222
Sep 29, 2015 5:17:12 PM tigase.jaxmpp.j2se.connectors.socket.Worker run
WARNING: Exception in worker
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at tigase.jaxmpp.j2se.connectors.socket.TextStreamReader.read(TextStreamReader.java:49)
at tigase.jaxmpp.j2se.connectors.socket.Worker.run(Worker.java:99)
After login
The IP Address, Port number, From JabberID and Password are correct and are working fine from iOS and Android Apps. Also I am able to successfully ping the Tigase server IP address.
From where is the java.net.SocketException being thrown ? How can I fix this problem ?
I'm running the following code that errors when I try to commit my changes using Cayenne as my ORM. The code is pasted below and errors out on the context.commitChanges();line. The output messages are pasted below the code. Any help on figuring this out would be appreciated.
import org.apache.cayenne.access.DataContext;
import java.util.*;
import com.jared.*;
public class Main {
public static void main(String[] args) {
DataContext context = DataContext.createDataContext();
Stocks theStock=(Stocks) context.createAndRegisterNewObject(Stocks.class);
theStock.setAsk(3.4);
theStock.setAvgdailyvolume(323849);
theStock .setBid(5.29);
theStock.setChange(-1.22);
theStock.setDayhigh(9.21);
theStock.setDaylow(2.11);
theStock.setLasttradeprice(5.11);
theStock.setLasttradesize(3827);
theStock.setOpen(6.21);
theStock.setPriorclose(4.21);
theStock.setShortratio(1.1);
theStock.setSymbol("^SP%");
theStock.setVolume(28193);
theStock.setLasttradedate(new Date());
context.commitChanges();
System.out.println("Done with the database");
}
}
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate startedLoading
INFO: started configuration loading.
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate shouldLoadDataDomain
INFO: loaded domain: stocks
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate loadDataMap
INFO: loaded .
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate shouldLoadDataNode
INFO: loading .
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate shouldLoadDataNode
INFO: using factory: org.apache.cayenne.conf.DriverDataSourceFactory
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.DriverDataSourceFactory load
INFO: loading driver information from 'stocksNode.driver.xml'.
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.DriverDataSourceFactory$DriverHandler init
INFO: loading driver org.hsqldb.jdbcDriver
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.DriverDataSourceFactory$LoginHandler init
INFO: loading user name and password.
Nov 20, 2008 11:20:37 PM org.apache.cayenne.access.QueryLogger logPoolCreated
INFO: Created connection pool: jdbc:hsqldb:file:/hsqldb/data/stocks
Driver class: org.hsqldb.jdbcDriver
Min. connections in the pool: 1
Max. connections in the pool: 1
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate shouldLoadDataNode
INFO: loaded datasource.
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate initAdapter
INFO: no adapter set, using automatic adapter.
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate finishedLoading
INFO: finished configuration loading in 203 ms.
Exception in thread "main" org.apache.cayenne.CayenneRuntimeException: [v.3.0M4 May 18 2008 16:32:02] Commit Exception
at org.apache.cayenne.access.DataContext.flushToParent(DataContext.java:1192)
at org.apache.cayenne.access.DataContext.commitChanges(DataContext.java:1066)
at Main.main(Main.java:24)
Caused by: java.lang.NullPointerException
at org.apache.cayenne.access.DataDomainInsertBucket.createPermIds(DataDomainInsertBucket.java:101)
at org.apache.cayenne.access.DataDomainInsertBucket.appendQueriesInternal(DataDomainInsertBucket.java:76)
at org.apache.cayenne.access.DataDomainSyncBucket.appendQueries(DataDomainSyncBucket.java:80)
at org.apache.cayenne.access.DataDomainFlushAction.preprocess(DataDomainFlushAction.java:183)
at org.apache.cayenne.access.DataDomainFlushAction.flush(DataDomainFlushAction.java:135)
at org.apache.cayenne.access.DataDomain.onSyncFlush(DataDomain.java:821)
at org.apache.cayenne.access.DataDomain$2.transform(DataDomain.java:788)
at org.apache.cayenne.access.DataDomain.runInTransaction(DataDomain.java:847)
at org.apache.cayenne.access.DataDomain.onSync(DataDomain.java:785)
at org.apache.cayenne.access.DataContext.flushToParent(DataContext.java:1164)
... 2 more
user name, password?
ClientConnection connection = new
HessianConnection("http://localhost:8080/cayenne-service",
"cayenne-user", "secret",
null);