localdomain.localhost.MyServlet.java Source code

Java tutorial

Introduction

Here is the source code for localdomain.localhost.MyServlet.java

Source

/*
 * Copyright 2010-2013, CloudBees Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package localdomain.localhost;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

/**
 * @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
 */
@WebServlet(value = "/MyServlet")
public class MyServlet extends HttpServlet {
    protected final Logger logger = Logger.getLogger(getClass().getName());

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        logger.info("Init");
        System.out.println(getClass().getName() + ".init");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();

        writer.println("<html>");
        writer.println("<head><title>MyServlet</title></head>");
        writer.println("<body><h1>MyServlet</h1>");

        writer.println("<h2>MongoDB</h2>");

        String uriAsString = System.getProperty("MONGOHQ_URL_MYDB", "mongodb://localhost/local");

        MongoClient mongoClient = null;
        try {
            writer.println("<h4>MongoClientURI</h4>");

            MongoClientURI uri = new MongoClientURI(uriAsString);
            writer.println("<p>" + "host=" + uri.getHosts() + ",username=" + uri.getUsername() + ",database="
                    + uri.getDatabase() + ",collection=" + uri.getCollection() + "</p>");

            writer.println("<h4>MongoClient</h4>");

            mongoClient = new MongoClient(uri);
            writer.println("<p>" + mongoClient + "</p>");

            writer.println("<h4>Databases</h4>");

            try {
                List<String> databaseNames = mongoClient.getDatabaseNames();
                writer.println("<ul>");
                for (String databaseName : databaseNames) {
                    writer.println("<li>" + databaseName
                            + (databaseName.equals(uri.getDatabase()) ? " - default database" : ""));
                }
                writer.println("</ul>");
            } catch (Exception e) {
                writer.println("<p>Could not list the databases of the MongoDB instance: <code>" + e.getMessage()
                        + "</code></p>");

            }

            writer.println("<h4>Database</h4>");

            DB db = mongoClient.getDB(uri.getDatabase());
            writer.println("<p>DB: " + db.getName() + "</p>");

            writer.println("<h4>Collections</h4>");
            Set<String> myCollections = db.getCollectionNames();
            if (myCollections.isEmpty()) {
                writer.println("<p>NO COLLECTIONS!</p>");

            } else {

                writer.println("<ul>");
                for (String collection : myCollections) {
                    DBCollection dbCollection = db.getCollection(collection);
                    writer.println(
                            "<li>" + dbCollection.getName() + " - " + dbCollection.getCount() + " entries</li>");
                }
                writer.println("</ul>");
            }
            writer.println("<h4>Success!</h4>");
            writer.println("SUCCESS to access the mongodb database");

        } catch (Exception e) {
            writer.println("<code><pre>");
            e.printStackTrace(writer);
            writer.println("</pre></code>");

            e.printStackTrace();
        } finally {
            if (mongoClient != null) {
                try {
                    mongoClient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        writer.println("</body></html>");

    }
}