Example usage for com.mongodb MongoClient close

List of usage examples for com.mongodb MongoClient close

Introduction

In this page you can find the example usage for com.mongodb MongoClient close.

Prototype

public void close() 

Source Link

Document

Closes all resources associated with this instance, in particular any open network connections.

Usage

From source file:org.eclipse.leshan.server.californium.impl.LeshanServer.java

License:Open Source License

private void observeResource(final Client client) {
    // ObserveRequest request = new ObserveRequest("2050/0/0");
    String contentFormatParam = "TLV";
    ContentFormat contentFormat = contentFormatParam != null
            ? ContentFormat.fromName(contentFormatParam.toUpperCase())
            : null;//from w w  w.ja v  a 2  s  .co m
    ObserveRequest request = new ObserveRequest(contentFormat, "/3/0/13");
    // ObserveRequest request = new ObserveRequest(contentFormat, "/2050/0/0");
    ObserveResponse cResponse = null;
    try {

        long i = 50000L;
        cResponse = this.send(client, request, i);

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    LOG.debug("cResponse : " + cResponse);

    Observation observation = cResponse.getObservation();

    observationRegistry.addListener(new ObservationRegistryListener() {

        @Override
        public void newObservation(Observation observation) {
            // TODO Auto-generated method stub

        }

        @Override
        public void cancelled(Observation observation) {
            LOG.debug("Observation Cancelled ....");

        }

        @Override
        public void newValue(Observation observation, ObserveResponse response) {
            // writeToFile(observation, mostRecentValue,timestampedValues );
            // TODO Auto-generated method stub
            if (client.getRegistrationId().equals(observation.getRegistrationId())) {

                // initialize("document");

                /*
                 * try { publishMesssage(); } catch (Exception e1) { // TODO Auto-generated catch block
                 * e1.printStackTrace(); }
                 */

                // ********Saving into database**************************
                Gson gson = new Gson();
                // List<TimestampedLwM2mNode> obresp = response.getTimestampedLwM2mNode();
                JsonObject jsonObject = new JsonParser().parse(gson.toJson(response.getContent()))
                        .getAsJsonObject();

                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                java.util.Date date = new java.util.Date();
                String timestamp = dateFormat.format(date);

                try {

                    MongoClient mongoClient = new MongoClient(mongoDBAdd, mongoDBPort);
                    MongoDatabase database = mongoClient.getDatabase("qolsys");
                    MongoCollection<Document> collection = database.getCollection("events");
                    String event = jsonObject.get("value").getAsString().trim();
                    Document document = new Document();
                    document.put("client_ep", client.getEndpoint());
                    document.put("event", event);
                    document.put("timestamp", timestamp);
                    collection.insertOne(document);
                    json = document.toJson();
                    sendToBroker(topic, json);
                    mongoClient.close();
                    producer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println(e.getClass().getName() + ": " + e.getMessage());
                    System.exit(0);
                }

                // ******************************************************

                LOG.debug("recent observation ...." + observation);
            }
        }

        // *************************************************************

        /*
         * private static Producer<Integer, String> producer; private static final String topic = "mytopic";
         */

        @SuppressWarnings("deprecation")
        public void sendToBroker(String topic, String msg) {

            Properties producerProps = new Properties();
            producerProps.put("metadata.broker.list", kafkaBroker1Add + ":" + kafkaBroker1Port);
            producerProps.put("serializer.class", "kafka.serializer.StringEncoder");
            producerProps.put("request.required.acks", "1");
            ProducerConfig producerConfig = new ProducerConfig(producerProps);
            producer = new Producer<Integer, String>(producerConfig);
            KeyedMessage<Integer, String> keyedMsg = new KeyedMessage<Integer, String>(topic, msg);
            producer.send(keyedMsg);

        }

    });

}

From source file:org.eclipse.leshan.server.demo.servlet.FetchServlet.java

License:Open Source License

/**
 * {@inheritDoc}//from ww  w.  j  a v  a 2 s  .c o m
 */

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Properties props = new Properties();
    props.put("zookeeper.connect", "localhost:2181");
    props.put("group.id", "testgroup");
    props.put("zookeeper.session.timeout.ms", "400");
    props.put("zookeeper.sync.time.ms", "300");
    props.put("auto.commit.interval.ms", "1000");
    ConsumerConfig conConfig = new ConsumerConfig(props);
    consumerConnector = Consumer.createJavaConsumerConnector(conConfig);
    resp.setContentType("application/json");
    MongoClient client = new MongoClient(mongoDBAdd, mongoDBPort);
    // MongoClient client = new MongoClient("54.161.178.113", 27017);
    MongoDatabase database = client.getDatabase(mongoDBName);
    MongoCollection<Document> collection = database.getCollection("events");
    Gson gson = new Gson();

    ArrayList<ClientDao> clientDaoList = new ArrayList<ClientDao>();
    if (req.getPathInfo() == null) {
        try {
            MongoCursor<String> mongoCursor = database.getCollection("events")
                    .distinct("client_ep", String.class).iterator();
            while (mongoCursor.hasNext()) {
                String clientEp = mongoCursor.next();
                ClientDao clientDao = new ClientDao();
                clientDao.setClientEP(clientEp);
                clientDao.setTimestamp(null);
                clientDaoList.add(clientDao);
            }

            String json = gson.toJson(clientDaoList);
            resp.getWriter().write(json.toString());
            resp.setStatus(HttpServletResponse.SC_OK);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
    }

    if (req.getPathInfo() != null) {
        String[] path = StringUtils.split(req.getPathInfo(), '/');
        if (path.length == 1) {
            try {

                BasicDBObject query1 = new BasicDBObject();
                BasicDBObject sort = new BasicDBObject();
                sort.put("timestamp", -1);

                query1.put("client_ep", path[0].toString());
                Iterable<Document> cur = collection.find(query1).sort(sort);
                Iterator<Document> itr = cur.iterator();
                while (itr.hasNext()) {

                    Document document = itr.next();
                    ClientDao clientDao = new ClientDao();
                    clientDao.setClientEP(document.getString("client_ep"));
                    clientDao.setEvent(document.getString("event"));
                    clientDao.setTimestamp(document.getString("timestamp"));
                    clientDaoList.add(clientDao);
                }

                //                    String json = gson.toJson(clientDaoList);
                //                    resp.getWriter().write(json.toString());
                //                    resp.setStatus(HttpServletResponse.SC_OK);

                Map<String, Integer> topicCount = new HashMap<String, Integer>();
                topicCount.put(topic, new Integer(1));

                //ConsumerConnector creates the message stream for each topic
                Map<String, List<KafkaStream<byte[], byte[]>>> consumerStreams = consumerConnector
                        .createMessageStreams(topicCount);

                // Get Kafka stream for topic 'mytopic'
                List<KafkaStream<byte[], byte[]>> kStreamList = consumerStreams.get(topic);
                // Iterate stream using ConsumerIterator
                for (final KafkaStream<byte[], byte[]> kStreams : kStreamList) {
                    ConsumerIterator<byte[], byte[]> consumerIte = kStreams.iterator();
                    int count = 0;
                    while (consumerIte.hasNext()) {
                        count++;

                        // Shutdown the consumer connector
                        if (consumerConnector != null && count == 10)
                            consumerConnector.shutdown();
                        Message msg = new Message(consumerIte.next().message());
                        ByteBuffer buffer = msg.payload();
                        byte[] bytes = new byte[buffer.remaining()];
                        buffer.get(bytes);
                        String result = new String(bytes);
                        JSONObject jsonObj = new JSONObject(result);

                        ClientDao clientDao = new ClientDao();
                        clientDao.setClientEP(jsonObj.getString("client_ep"));
                        clientDao.setEvent(jsonObj.getString("event"));
                        clientDao.setTimestamp(jsonObj.getString("timestamp"));
                        clientDaoList.add(clientDao);

                    }
                }

                String json = gson.toJson(clientDaoList);
                resp.getWriter().write(json.toString());
                resp.setStatus(HttpServletResponse.SC_OK);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                client.close();
            }

        }

    }

}

From source file:org.exist.mongodb.xquery.mongodb.client.Close.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    // User must either be DBA or in the JMS group
    if (!context.getSubject().hasDbaRole() && !context.getSubject().hasGroup(Constants.MONGODB_GROUP)) {
        String txt = String.format("Permission denied, user '%s' must be a DBA or be in group '%s'",
                context.getSubject().getName(), Constants.MONGODB_GROUP);
        LOG.error(txt);/*from   www  .ja va 2  s  .  c o m*/
        throw new XPathException(this, txt);
    }

    // Get connection URL
    String mongodbClientId = args[0].itemAt(0).getStringValue();

    // Handle ()
    try {
        MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId);

        if (client == null) {
            throw new XPathException(this,
                    String.format("Mongoclient %s could not be found.", mongodbClientId));
        }

        // Close connector with all connections
        client.close();

        // Remove from cache
        MongodbClientStore.getInstance().remove(mongodbClientId);

        // Report identifier
        return EmptySequence.EMPTY_SEQUENCE;

    } catch (XPathException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, ex.getMessage(), ex);

    } catch (MongoException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0002, ex.getMessage());

    } catch (Throwable ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0003, ex.getMessage());
    }

}

From source file:org.geogit.storage.mongo.MongoConnectionManager.java

License:Open Source License

@Override
protected void disconnect(MongoClient client) {
    client.close();
}

From source file:org.immutables.mongo.fixture.MongoContext.java

License:Apache License

private MongoContext(final MongoClient client) {
    Preconditions.checkNotNull(client, "client");

    // allows to cleanup resources after each test
    final Closer closer = Closer.create();

    closer.register(new Closeable() {
        @Override/*w  ww .jav a  2  s  .  c  om*/
        public void close() throws IOException {
            client.close();
        }
    });

    // drop database if exists (to have a clean test)
    if (Iterables.contains(client.listDatabaseNames(), DBNAME)) {
        client.getDatabase(DBNAME).drop();
    }

    this.database = client.getDatabase(DBNAME);

    closer.register(new Closeable() {
        @Override
        public void close() throws IOException {
            database.drop();
        }
    });

    final ListeningExecutorService executor = MoreExecutors
            .listeningDecorator(Executors.newSingleThreadExecutor());

    closer.register(new Closeable() {
        @Override
        public void close() throws IOException {
            MoreExecutors.shutdownAndAwaitTermination(executor, 100, TimeUnit.MILLISECONDS);
        }
    });

    this.setup = RepositorySetup.builder().gson(createGson()).executor(executor).database(database).build();

    this.closer = closer;
}

From source file:org.jenkinsci.plugins.compatibilityaction.MongoProviderImpl.java

@Override
public <T> T create(T t) throws CompatibilityDataException {
    MongoClient client = null;
    try {/*from  w  ww .  ja  v  a2s .  c  o  m*/
        client = getService().createClient();
        JacksonDBCollection coll = JacksonDBCollection.wrap(client.getDB(database).getCollection(collection),
                t.getClass());
        return (T) coll.insert(t).getSavedObject();

    } catch (Exception ex) {
        throw new CompatibilityDataException(String.format("Failed to insert object %s", t), ex);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:org.jenkinsci.plugins.compatibilityaction.MongoProviderImpl.java

/**
 * Creates an instance of of a Java object in the database. 
         //from ww  w  . jav  a  2 s.c  o m
 * The class must have attributes a method/field annotated with @Id for Jackson to
 * use as an identity when data is inserted into our mongodb.     
 * @param <T>
 * @param t
 * @param listener
 * @return
 * @throws CompatibilityDataException 
 */
@Override
public <T> T create(T t, TaskListener listener) throws CompatibilityDataException {
    MongoClient client = null;
    try {
        DB db = getService().createClient().getDB(database);

        //If the collection name does not exists. Create it.
        if (!db.getCollectionNames().contains(collection)) {
            db.createCollection(collection, null);
        }

        JacksonDBCollection coll = JacksonDBCollection.wrap(db.getCollection(collection), t.getClass());
        listener.getLogger()
                .println(String.format("%s Collection initialized.", CompatibilityDataPlugin.LOG_PREFIX));
        T myobj = (T) coll.insert(t).getSavedObject();
        return myobj;
    } catch (Exception ex) {
        throw new CompatibilityDataException(String.format("Failed to insert object %s", t), ex);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:org.jenkinsci.plugins.compatibilityaction.MongoProviderImpl.java

@Override
public <T> T read(Object key, Class<T> clazz) throws CompatibilityDataException {
    MongoClient client = null;
    try {/*from w  ww. ja  v  a 2 s.  c om*/
        client = getService().createClient();
        JacksonDBCollection coll = JacksonDBCollection.wrap(client.getDB(database).getCollection(collection),
                clazz);
        return (T) coll.findOneById(key);
    } catch (Exception ex) {
        throw new CompatibilityDataException(String.format("Failed to fetch object with key %s", key), ex);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:org.jenkinsci.plugins.compatibilityaction.MongoProviderImpl.java

public <T> List<T> readMany(BasicDBObject query, Class<T> clazz) throws CompatibilityDataException {
    List<T> list = new ArrayList<T>();
    org.mongojack.DBCursor cursor = null;
    MongoClient client = null;
    try {/*from   w ww  . ja  v a  2 s  .  c o m*/
        client = getService().createClient();
        JacksonDBCollection coll = JacksonDBCollection.wrap(client.getDB(database).getCollection(collection),
                clazz);
        cursor = coll.find(query);
        while (cursor.hasNext()) {
            list.add((T) cursor.next());
        }
    } catch (Exception ex) {
        throw new CompatibilityDataException(String.format("Failed to fetch object with query %s", query), ex);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
        if (client != null) {
            client.close();
        }
    }
    return list;
}

From source file:org.jenkinsci.plugins.compatibilityaction.MongoProviderImpl.java

public int count(DBObject query) throws CompatibilityDataException {
    MongoClient client = null;
    try {//from w w w .  j a  va2s.c o m
        client = getService().createClient();
        return client.getDB(database).getCollection(collection).find(query)
                .sort(new BasicDBObject("registrationDate", 1)).size();
    } catch (Exception ex) {
        throw new CompatibilityDataException(
                String.format("(Unknown Host) Failed to fetch object with query %s", query), ex);
    } finally {
        if (client != null)
            client.close();
    }
}