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(@Nullable final String host, final int port) 

Source Link

Document

Creates a ServerAddress

Usage

From source file:net.ymate.platform.persistence.mongodb.MongoDB.java

License:Apache License

/**
 * ?MongoDB?/*from   www  .j av  a2 s  .  co m*/
 * 
 * @param config
 */
public static void initialize(IMongoConfig config) throws ConnectionException {
    if (!isInited) {
        __config = config;
        DATASOURCE_DEFAULT_NAME = StringUtils.defaultIfEmpty(config.getDefaultDataSourceName(), "default");
        COLLECTION_PREFIX = StringUtils.trimToEmpty(config.getCollectionPrefix());
        //
        try {
            for (DataSourceCfgMeta _cfgMeta : config.getDataSourceCfgMetas()) {
                List<ServerAddress> _addrs = new ArrayList<ServerAddress>();
                String[] _hosts = StringUtils.split(_cfgMeta.getConnectionUrl(), "|");
                if (_hosts == null || _hosts.length == 0) {
                    _addrs.add(new ServerAddress(DEFAULT_MONGODB_HOST, DEFAULT_MONGODB_PORT));
                } else {
                    for (String _host : _hosts) {
                        String[] _tmpAddr = StringUtils.split(_host, ":");
                        if (_tmpAddr.length == 1) {
                            _addrs.add(new ServerAddress(_tmpAddr[0], DEFAULT_MONGODB_PORT));
                        } else {
                            _addrs.add(new ServerAddress(_tmpAddr[0], Integer.valueOf(_tmpAddr[1])));
                        }
                    }
                }
                //
                MongoClientOptions.Builder _builder = new MongoClientOptions.Builder();
                // TODO ?Meta?
                _builder.connectionsPerHost(200);
                MongoClient _client = new MongoClient(_addrs, _builder.build());
                // TODO ?
                // _client.setReadPreference(...);
                //
                __DATASOURCE_CACHE.put(_cfgMeta.getName(), _client);
                __DATASOURCE_CFG_METAS.put(_cfgMeta.getName(), _cfgMeta);
            }
            //
            __REPOSTORY_BEAN_FACTORY = new RepositoryBeanFactory(config.getRepositoryPackages());
            isInited = true;
        } catch (Exception e) {
            throw new ConnectionException(RuntimeUtils.unwrapThrow(e));
        }
    }
}

From source file:nl.knaw.huygens.timbuctoo.storage.mongo.MongoDB.java

License:Open Source License

@Inject
public MongoDB(Configuration config) throws UnknownHostException {
    MongoOptions options = new MongoOptions();
    options.safe = true;//w ww . j  a va 2s  .co  m

    String host = config.getSetting("database.host", "localhost");
    int port = config.getIntSetting("database.port", 27017);
    mongo = new Mongo(new ServerAddress(host, port), options);

    String dbName = config.getSetting("database.name");
    db = mongo.getDB(dbName);

    String user = config.getSetting("database.user");
    if (!user.isEmpty()) {
        String password = config.getSetting("database.password");
        db.authenticate(user, password.toCharArray());
    }
}

From source file:nl.mawoo.wcmscript.modules.mongodb.MongoDB.java

License:Apache License

/**
 * Connect to MongoDB without authentication
 * This methods opens the connection to the MongoDB server and sets the database that is set.
 * @return this// w  w w.  j a  v  a  2s.  c  om
 */
public MongoDB connect() {
    client = new MongoClient(new ServerAddress(host, port));
    database = client.getDatabase(currentDatabase);
    return this;
}

From source file:nl.mawoo.wcmscript.modules.mongodb.MongoDB.java

License:Apache License

/**
 * Connect to MongoDB with authentication
 * This methods opens the connection to the MongoDB server and sets the database that is set.
 * @param username the username of the MongoDB server
 * @param password the password of the MongoDB server
 * @return this//w w w .  ja va 2s.  c  o  m
 */
public MongoDB connectAuthenticated(String username, String password) {
    MongoCredential mongoCredential = MongoCredential.createMongoCRCredential(username, this.currentDatabase,
            password.toCharArray());
    client = new MongoClient(new ServerAddress(host, port), Arrays.asList(mongoCredential));
    database = client.getDatabase(currentDatabase);
    return this;
}

From source file:nosqltools.AddUsersDialog.java

public AddUsersDialog(MainForm parent) {
    this.parent = parent;
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints cs = new GridBagConstraints();

    try {/*from www  .  ja v a  2 s  . c o  m*/
        mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
    } catch (UnknownHostException ex) {
        ex.printStackTrace();
    }

    cs.fill = GridBagConstraints.HORIZONTAL;

    //The components used in the dialog box
    lbUsername = new JLabel("Username: ");
    cs.gridx = 0;
    cs.gridy = 0;
    cs.gridwidth = 1;
    panel.add(lbUsername, cs);

    tfUsername = new JTextField(20);
    cs.gridx = 1;
    cs.gridy = 0;
    cs.gridwidth = 2;
    panel.add(tfUsername, cs);

    lbPassword = new JLabel("Password: ");
    cs.gridx = 0;
    cs.gridy = 1;
    cs.gridwidth = 1;
    panel.add(lbPassword, cs);

    tfPassword = new JPasswordField(20);
    cs.gridx = 1;
    cs.gridy = 1;
    cs.gridwidth = 2;
    panel.add(tfPassword, cs);

    lbDatabase = new JLabel("Database: ");
    cs.gridx = 0;
    cs.gridy = 2;
    cs.gridwidth = 1;
    panel.add(lbDatabase, cs);

    cbDatabases = new JComboBox<>();
    cbDatabases.setEditable(true);
    cs.gridx = 1;
    cs.gridy = 2;
    cs.gridwidth = 1;
    panel.add(cbDatabases, cs);
    List<String> dbs = mongoClient.getDatabaseNames();
    for (String d : dbs) {
        cbDatabases.addItem(d);
    }

    lbRole = new JLabel("Role: ");
    cs.gridx = 0;
    cs.gridy = 3;
    cs.gridwidth = 1;
    panel.add(lbRole, cs);

    cbRoles = new JComboBox<>();
    cbRoles.addItem("read");
    cbRoles.addItem("readWrite");
    cs.gridx = 1;
    cs.gridy = 3;
    cs.gridwidth = 1;
    panel.add(cbRoles, cs);

    btnAdd = new JButton("Add");
    this.getRootPane().setDefaultButton(btnAdd);

    btnAdd.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            ostja();
        }
    });

    btnCancel = new JButton("Cancel");
    btnCancel.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            choice = false;
            succeeded = false;
            dispose();
        }
    });

    JPanel bp = new JPanel();
    //Add the buttons to the panel
    bp.add(btnAdd);
    bp.add(btnCancel);

    getContentPane().add(panel, BorderLayout.CENTER);
    getContentPane().add(bp, BorderLayout.PAGE_END);

    pack();
    setResizable(false);
    setLocationRelativeTo(parent);
}

From source file:nosqltools.MainForm.java

private void jList2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList2MouseClicked
    final AddUsersDialog dlg_addusers = new AddUsersDialog(this);
    ActionListener al3 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dlg_addusers.setVisible(true);
            viewUsersMenuItem.doClick();
            Text_MessageBar.setText(jList2.getSelectedValue().toString());
        }/* w  ww .  j  a v a  2 s . c  om*/
    };

    ActionListener al1 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Text_MessageBar.setText(jList2.getSelectedValue().toString());
                MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
                DB db = mongoClient.getDB(DBList.getSelectedValue().toString()); //To arrange to be the database which is connected to.
                db.removeUser(jList2.getSelectedValue().toString());
                viewUsersMenuItem.setEnabled(true);
                viewUsersMenuItem.doClick();
                viewUsersMenuItem.setEnabled(false);
            } catch (Exception ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };

    //Create the JPopupMenu with three options.
    final JPopupMenu popupMenu = new JPopupMenu();
    JMenuItem item1 = new JMenuItem("Delete");
    item1.addActionListener(al1);
    popupMenu.add(item1);
    popupMenu.add(new JPopupMenu.Separator());
    JMenuItem item3 = new JMenuItem("Add");
    item3.addActionListener(al3);
    popupMenu.add(item3);

    jList2.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent me) {
            if (SwingUtilities.isRightMouseButton(me) // if right mouse button clicked
                    && !jList2.isSelectionEmpty() // and list selection is not empty
                    && jList2.locationToIndex(me.getPoint()) // and clicked point is
            == jList2.getSelectedIndex()) { // inside selected item bounds
                //Text_MessageBar.setText(jList2.getSelectedValue().toString() + " RIGHT");
                Text_MessageBar.setForeground(Color.blue);
                popupMenu.show(jList2, me.getX(), me.getY());
            } else {
                //Text_MessageBar.setText(jList2.getSelectedValue().toString() + " LEFT");
                Text_MessageBar.setForeground(Color.MAGENTA);
            }
        }
    });
}

From source file:org.adoptopenjdk.jcountdown.control.MongoClientProducer.java

License:Apache License

@Produces
@ApplicationScoped/*from  w  w  w. j  a v  a2  s  .c o  m*/
public MongoClient produceClient() {
    // default host is localhost, default port is 27017       

    ServerAddress serverAddress = new ServerAddress(mongoConfiguration.getHost(), mongoConfiguration.getPort());

    MongoCredential mongoCredential = MongoCredential.createCredential(mongoConfiguration.getUsername(),
            mongoConfiguration.getDatabaseName(), mongoConfiguration.getPassword());

    List<MongoCredential> credentials = new ArrayList<>();
    credentials.add(mongoCredential);
    return new MongoClient(serverAddress, credentials);
}

From source file:org.alfresco.mongo.MongoDBForTestsFactory.java

License:Open Source License

/**
 * Constructor//from  ww  w  .  ja v  a 2s .co  m
 * 
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public MongoDBForTestsFactory() throws Exception {
    MongodStarter starter = MongodStarter.getDefaultInstance();
    IMongodConfig mongodConfig = new MongodConfigBuilder().version(version)
            .processListener(new MongoDBProcessListener()).build();

    mongodExecutable = starter.prepare(mongodConfig);
    mongodProcess = mongodExecutable.start();

    // We use a randomly-assigned port, so get it
    InetAddress address = mongodProcess.getConfig().net().getServerAddress();
    int port = mongodProcess.getConfig().net().getPort();

    mongo = new MongoClient(new ServerAddress(address, port));
    db = mongo.getDB(UUID.randomUUID().toString());
}

From source file:org.anyframe.logmanager.bundle.core.Activator.java

License:Apache License

/**
 * @param context//from w  w  w .j  a v  a2s .c o m
 * @throws Exception
 */
private void initMongo(BundleContext context) throws Exception {

    if (context == null) {
        throw new LogManagerBundleException("Context is null.");
    }

    String mongoSvr = context.getProperty("mongo.host");
    int mongoPort = Integer.parseInt(context.getProperty("mongo.port"));
    logger.info("MongoDB connect to - " + mongoSvr + ":" + mongoPort);

    MongoOptions options = new MongoOptions();
    options.connectionsPerHost = Integer.parseInt(context.getProperty("mongo.connectionsPerHost"));
    options.autoConnectRetry = Boolean.parseBoolean(context.getProperty("mongo.autoConnectRetry"));
    options.connectTimeout = Integer.parseInt(context.getProperty("mongo.connectTimeout"));
    options.threadsAllowedToBlockForConnectionMultiplier = Integer
            .parseInt(context.getProperty("mongo.threadsAllowedToBlockForConnectionMultiplier"));
    options.maxWaitTime = Integer.parseInt(context.getProperty("mongo.maxWaitTime"));
    options.connectTimeout = Integer.parseInt(context.getProperty("mongo.connectTimeout"));
    options.socketKeepAlive = Boolean.parseBoolean(context.getProperty("mongo.socketKeepAlive"));
    options.socketTimeout = Integer.parseInt(context.getProperty("mongo.socketTimeout"));

    ServerAddress addr = new ServerAddress(mongoSvr, mongoPort);

    mongo = new Mongo(addr, options);

    if (mongo != null) {
        logger.info("MongoDB connected - " + addr.getHost() + ":" + addr.getPort());
    }
}

From source file:org.apache.brooklyn.entity.nosql.mongodb.MongoDBClientSupport.java

License:Apache License

/**
 * Creates a {@link MongoDBClientSupport} instance in standalone mode.
 *//*from  w  w  w  .j a  va 2  s. co  m*/
public static MongoDBClientSupport forServer(AbstractMongoDBServer standalone) throws UnknownHostException {
    HostAndPort hostAndPort = BrooklynAccessUtils.getBrooklynAccessibleAddress(standalone,
            standalone.getAttribute(MongoDBServer.PORT));
    ServerAddress address = new ServerAddress(hostAndPort.getHostText(), hostAndPort.getPort());
    return new MongoDBClientSupport(address);
}