Example usage for com.mongodb ServerAddress ServerAddress

List of usage examples for com.mongodb ServerAddress ServerAddress

Introduction

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

Prototype

public ServerAddress(final InetSocketAddress inetSocketAddress) 

Source Link

Document

Creates a ServerAddress

Usage

From source file:io.prestosql.plugin.mongodb.MongoClientConfig.java

License:Apache License

private List<ServerAddress> buildSeeds(Iterable<String> hostPorts) {
    ImmutableList.Builder<ServerAddress> builder = ImmutableList.builder();
    for (String hostPort : hostPorts) {
        List<String> values = PORT_SPLITTER.splitToList(hostPort);
        checkArgument(values.size() == 1 || values.size() == 2,
                "Invalid ServerAddress format. Requires host[:port]");
        try {// w  ww .ja v a2  s  . co m
            if (values.size() == 1) {
                builder.add(new ServerAddress(values.get(0)));
            } else {
                builder.add(new ServerAddress(values.get(0), Integer.parseInt(values.get(1))));
            }
        } catch (NumberFormatException e) {
            throw e;
        }
    }
    return builder.build();
}

From source file:kr.debop4j.data.mongodb.spring.MongoGridDatastoreConfigBase.java

License:Apache License

@Bean
public ServerAddress serverAddress() {
    try {//ww w . java2  s . com
        return new ServerAddress("localhost");
    } catch (UnknownHostException e) {
        log.error("  .", e);
        throw new RuntimeException(e);
    }
}

From source file:me.konglong.momei.mongodb.config.ServerAddressPropertyEditor.java

License:Apache License

/**
 * Parses the given source into a {@link ServerAddress}.
 *
 * @param source/*  ww w .j  a  v a  2  s.c om*/
 * @return the
 */
private ServerAddress parseServerAddress(String source) {

    if (!StringUtils.hasText(source)) {
        LOGGER.warn(COULD_NOT_PARSE_ADDRESS_MESSAGE, "source", source);
        return null;
    }

    String[] hostAndPort = extractHostAddressAndPort(source.trim());

    if (hostAndPort.length > 2) {
        LOGGER.warn(COULD_NOT_PARSE_ADDRESS_MESSAGE, "source", source);
        return null;
    }

    try {
        InetAddress hostAddress = InetAddress.getByName(hostAndPort[0]);
        Integer port = hostAndPort.length == 1 ? null : Integer.parseInt(hostAndPort[1]);

        return port == null ? new ServerAddress(hostAddress) : new ServerAddress(hostAddress, port);
    } catch (UnknownHostException e) {
        LOGGER.warn(COULD_NOT_PARSE_ADDRESS_MESSAGE, "host", hostAndPort[0]);
    } catch (NumberFormatException e) {
        LOGGER.warn(COULD_NOT_PARSE_ADDRESS_MESSAGE, "port", hostAndPort[1]);
    }

    return null;
}

From source file:me.photomap.web.config.MongoConfig.java

@Bean
@Override/*from   www .ja  va  2  s.co m*/
public Mongo mongo() throws Exception {

    int port = env.getProperty("mongodb.dbport", Integer.class);
    String host = env.getProperty("mongodb.dbhostname");
    String user = env.getProperty("mongodb.dbusername");
    String pass = env.getProperty("mongodb.dbpassword");
    MongoCredential credential = MongoCredential.createMongoCRCredential(user, "admin", pass.toCharArray());
    MongoClient m = new MongoClient(new ServerAddress(host), Arrays.asList(credential));
    return m;
}

From source file:net.gtaun.wl.race.RacePlugin.java

License:Open Source License

@Override
protected void onEnable() throws Throwable {
    config = new RaceConfig(new File(getDataDir(), "config.yml"));

    if (config.getDbUser().isEmpty() || config.getDbPass().isEmpty()) {
        mongoClient = new MongoClient(config.getDbHost());
    } else {/* w w  w  . j a  va2s .  co m*/
        mongoClient = new MongoClient(Arrays.asList(new ServerAddress(config.getDbHost())),
                Arrays.asList(MongoCredential.createMongoCRCredential(config.getDbName(), config.getDbName(),
                        config.getDbPass().toCharArray())));
    }

    morphia = new Morphia();
    morphia.getMapper().getOptions().objectFactory = new DefaultCreator() {
        @Override
        protected ClassLoader getClassLoaderForClass(String clazz, DBObject object) {
            return getClass().getClassLoader();
        }
    };

    datastore = morphia.createDatastore(mongoClient, config.getDbName());

    vehicleManagerSerivce = new RaceServiceImpl(getEventManager(), this, datastore);
    registerService(RaceService.class, vehicleManagerSerivce);

    LOGGER.info(getDescription().getName() + " " + getDescription().getVersion() + " Enabled.");
}

From source file:net.gtaun.wl.vehicle.VehicleManagerPlugin.java

License:Open Source License

@Override
protected void onEnable() throws Throwable {
    config = new VehicleManagerConfig(new File(getDataDir(), "config.yml"));

    if (config.getDbUser().isEmpty() || config.getDbPass().isEmpty()) {
        mongoClient = new MongoClient(config.getDbHost());
    } else {/*from  www. ja v  a2 s. co m*/
        mongoClient = new MongoClient(Arrays.asList(new ServerAddress(config.getDbHost())),
                Arrays.asList(MongoCredential.createMongoCRCredential(config.getDbName(), config.getDbName(),
                        config.getDbPass().toCharArray())));
    }

    morphia = new Morphia();
    morphia.getMapper().getOptions().objectFactory = new DefaultCreator() {
        @Override
        protected ClassLoader getClassLoaderForClass(String clazz, DBObject object) {
            return getClass().getClassLoader();
        }
    };
    morphia.map(GlobalVehicleStatisticImpl.class);
    morphia.map(PlayerVehicleStatisticImpl.class);

    datastore = morphia.createDatastore(mongoClient, config.getDbName());

    vehicleManagerSerivce = new VehicleManagerServiceImpl(getEventManager(), this, datastore);
    registerService(VehicleManagerService.class, vehicleManagerSerivce);

    LOGGER.info(getDescription().getName() + " " + getDescription().getVersion() + " Enabled.");
}

From source file:nopaper.Server.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    String databaseHostname = System.getProperty("database.hostname");
    if (null == databaseHostname)
        databaseHostname = "localhost";
    logger.info("Using {}", databaseHostname);
    Route.client = new MongoClient(new ServerAddress(databaseHostname),
            new MongoClientOptions.Builder().connectionsPerHost(2).build());

    Spark.options(new Route("/*") {
        @Override//from  w  ww  .  j  a v a  2 s .  c o  m
        public Object handle(final Request request, final Response response) {
            setCORSResponseHeader(response);
            response.status(200);
            return new StringWriter();
        }

        @Override
        public Object myHandle(Request request, Response response, DBCollection collection) {
            return null;
        }
    });

    Spark.get(new Route("/system/:command") {
        @Override
        public Object myHandle(final Request request, final Response response, DBCollection collection) {
            String command = request.params(":command");
            System.out.println("system command:" + command);
            if (command.equals("shutdown")) {
                System.exit(0);
            }
            if (command.equals("ls")) {
                String path = request.queryParams("path");
                if (null == path) {
                    path = "/";
                }
                return Files.list(path);
            }
            if (command.equals("sleep")) {
                String seconds = request.queryParams("seconds");
                if (null == seconds) {
                    seconds = "1";
                }
                int i = Integer.parseInt(seconds);
                try {
                    Thread.sleep(i * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return System.currentTimeMillis();
            }
            return null;
        }
    });

    PDF pdf = new PDF();
    pdf.setDatabase(Route.client.getDB("test"));
    pdf.addRoutes();

    controller.DB db = new controller.DB();
    db.addRoutes();

    Spark.get(new Route("/") {
        @Override
        public Object myHandle(final Request request, final Response response, DBCollection collection) {
            try {
                return new BasicDBObject(
                        dict("status", "ok", "hostname", InetAddress.getLocalHost().getHostName()));
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }
        }
    });

    controller.Convert convert = new controller.Convert();
    convert.setDatabase(Route.client.getDB("test"));
    convert.addRoutes();

    controller.Map map = new controller.Map();
    map.addRoutes();

}

From source file:oopproject1.MakaleDaoImpl.java

public MakaleDaoImpl() {
    try {//from  w w w .j a  va 2 s.  c om
        this.mongo = new MongoClient(new ServerAddress("localhost"));
        this.db = mongo.getDB("testdb");

    } catch (UnknownHostException ex) {
        Logger.getLogger(MakaleDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.drill.exec.store.mongo.MongoGroupScan.java

License:Apache License

@SuppressWarnings({ "rawtypes" })
private void init() throws IOException {

    List<String> h = storagePluginConfig.getHosts();
    List<ServerAddress> addresses = Lists.newArrayList();
    for (String host : h) {
        addresses.add(new ServerAddress(host));
    }/*from   ww  w  .  jav  a  2  s.  com*/
    MongoClient client = storagePlugin.getClient();
    chunksMapping = Maps.newHashMap();
    chunksInverseMapping = Maps.newLinkedHashMap();
    if (isShardedCluster(client)) {
        MongoDatabase db = client.getDatabase(CONFIG);
        MongoCollection<Document> chunksCollection = db.getCollection(CHUNKS);
        Document filter = new Document();
        filter.put(NS, this.scanSpec.getDbName() + "." + this.scanSpec.getCollectionName());

        Document projection = new Document();
        projection.put(SHARD, select);
        projection.put(MIN, select);
        projection.put(MAX, select);

        FindIterable<Document> chunkCursor = chunksCollection.find(filter).projection(projection);
        MongoCursor<Document> iterator = chunkCursor.iterator();

        MongoCollection<Document> shardsCollection = db.getCollection(SHARDS);

        projection = new Document();
        projection.put(HOST, select);

        boolean hasChunks = false;
        while (iterator.hasNext()) {
            Document chunkObj = iterator.next();
            String shardName = (String) chunkObj.get(SHARD);
            String chunkId = (String) chunkObj.get(ID);
            filter = new Document(ID, shardName);
            FindIterable<Document> hostCursor = shardsCollection.find(filter).projection(projection);
            MongoCursor<Document> hostIterator = hostCursor.iterator();
            while (hostIterator.hasNext()) {
                Document hostObj = hostIterator.next();
                String hostEntry = (String) hostObj.get(HOST);
                String[] tagAndHost = StringUtils.split(hostEntry, '/');
                String[] hosts = tagAndHost.length > 1 ? StringUtils.split(tagAndHost[1], ',')
                        : StringUtils.split(tagAndHost[0], ',');
                List<String> chunkHosts = Arrays.asList(hosts);
                Set<ServerAddress> addressList = getPreferredHosts(storagePlugin.getClient(addresses),
                        chunkHosts);
                if (addressList == null) {
                    addressList = Sets.newHashSet();
                    for (String host : chunkHosts) {
                        addressList.add(new ServerAddress(host));
                    }
                }
                chunksMapping.put(chunkId, addressList);
                ServerAddress address = addressList.iterator().next();
                List<ChunkInfo> chunkList = chunksInverseMapping.get(address.getHost());
                if (chunkList == null) {
                    chunkList = Lists.newArrayList();
                    chunksInverseMapping.put(address.getHost(), chunkList);
                }
                List<String> chunkHostsList = new ArrayList<String>();
                for (ServerAddress serverAddr : addressList) {
                    chunkHostsList.add(serverAddr.toString());
                }
                ChunkInfo chunkInfo = new ChunkInfo(chunkHostsList, chunkId);
                Document minMap = (Document) chunkObj.get(MIN);

                Map<String, Object> minFilters = Maps.newHashMap();
                Set keySet = minMap.keySet();
                for (Object keyObj : keySet) {
                    Object object = minMap.get(keyObj);
                    if (!(object instanceof MinKey)) {
                        minFilters.put(keyObj.toString(), object);
                    }
                }
                chunkInfo.setMinFilters(minFilters);

                Map<String, Object> maxFilters = Maps.newHashMap();
                Map maxMap = (Document) chunkObj.get(MAX);
                keySet = maxMap.keySet();
                for (Object keyObj : keySet) {
                    Object object = maxMap.get(keyObj);
                    if (!(object instanceof MaxKey)) {
                        maxFilters.put(keyObj.toString(), object);
                    }
                }

                chunkInfo.setMaxFilters(maxFilters);
                chunkList.add(chunkInfo);
            }
            hasChunks = true;
        }
        // In a sharded environment, if a collection doesn't have any chunks, it is considered as an
        // unsharded collection and it will be stored in the primary shard of that database.
        if (!hasChunks) {
            handleUnshardedCollection(getPrimaryShardInfo(client));
        }
    } else {
        handleUnshardedCollection(storagePluginConfig.getHosts());
    }

}

From source file:org.apache.drill.exec.store.mongo.MongoGroupScan.java

License:Apache License

private void handleUnshardedCollection(List<String> hosts) {
    String chunkName = Joiner.on('.').join(scanSpec.getDbName(), scanSpec.getCollectionName());
    Set<ServerAddress> addressList = Sets.newHashSet();

    for (String host : hosts) {
        addressList.add(new ServerAddress(host));
    }/*from  www  . j av  a  2 s . c  o m*/
    chunksMapping.put(chunkName, addressList);

    String host = hosts.get(0);
    ServerAddress address = new ServerAddress(host);
    ChunkInfo chunkInfo = new ChunkInfo(hosts, chunkName);
    chunkInfo.setMinFilters(Collections.<String, Object>emptyMap());
    chunkInfo.setMaxFilters(Collections.<String, Object>emptyMap());
    List<ChunkInfo> chunksList = Lists.newArrayList();
    chunksList.add(chunkInfo);
    chunksInverseMapping.put(address.getHost(), chunksList);
}