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:org.teiid.resource.adapter.mongodb.MongoDBManagedConnectionFactory.java

License:Open Source License

protected List<ServerAddress> getServers() throws ResourceException {
    String serverlist = getRemoteServerList();
    if (!serverlist.startsWith("mongodb://")) { //$NON-NLS-1$
        List<ServerAddress> addresses = new ArrayList<ServerAddress>();
        StringTokenizer st = new StringTokenizer(serverlist, ";"); //$NON-NLS-1$
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            int idx = token.indexOf(':');
            if (idx < 0) {
                throw new InvalidPropertyException(UTIL.getString("no_database")); //$NON-NLS-1$
            }//from ww w . ja  v  a2s.c o m
            try {
                addresses.add(
                        new ServerAddress(token.substring(0, idx), Integer.valueOf(token.substring(idx + 1))));
            } catch (UnknownHostException e) {
                throw new ResourceException(e);
            }
        }
        return addresses;
    }
    return null;
}

From source file:org.test.falcon.config.MongoProperties.java

License:Apache License

/**
 * Creates a {@link MongoClient} using the given {@code options} and
 * {@code environment}. If the configured port is zero, the value of the
 * {@code local.mongo.port} property retrieved from the {@code environment}
 * is used to configure the client.//w w  w. j  a v  a2  s. c  om
 *
 * @param options
 *            the options
 * @return the Mongo client
 * @throws UnknownHostException
 *             if the configured host is unknown
 */
public MongoClient createMongoClient(MongoClientOptions options) throws UnknownHostException {
    try {
        if (options == null) {
            options = MongoClientOptions.builder().build();
        }
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        String database = this.authenticationDatabase == null ? getMongoClientDatabase()
                : this.authenticationDatabase;
        credentials.add(MongoCredential.createCredential(this.username, database, this.password));
        String host = this.host == null ? "localhost" : this.host;
        int port = determinePort();
        return new MongoClient(Arrays.asList(new ServerAddress(host, port)), credentials, options);
    } finally {
        clearPassword();
    }
}

From source file:org.trustedanalytics.modelcatalog.storage.db.MongoConfig.java

License:Apache License

@Bean
@Override//from ww  w  . j av a 2  s.  co  m
public Mongo mongo() throws UnknownHostException {
    ServerAddress serverAddress = new ServerAddress(mongoProperties.getServerName(),
            mongoProperties.getServerPort());
    List<MongoCredential> credentialList = new ArrayList<>();

    String user = mongoProperties.getUser();
    if (user != null && !user.isEmpty()) {
        credentialList.add(MongoCredential.createMongoCRCredential(user, mongoProperties.getDbName(),
                mongoProperties.getPassword().toCharArray()));
    }

    return new MongoClient(serverAddress, credentialList);
}

From source file:org.twentyn.proteintodna.ProteinToDNADriver.java

License:Open Source License

public static void main(String[] args) throws Exception {
    CommandLine cl = CLI_UTIL.parseCommandLine(args);

    String reactionDbName = cl.getOptionValue(OPTION_INPUT_DB_NAME, DEFAULT_INPUT_DB_NAME);
    String dbHost = cl.getOptionValue(OPTION_DB_HOST, DEFAULT_DB_HOST);
    Integer dbPort = Integer.valueOf(cl.getOptionValue(OPTION_DB_PORT, DEFAULT_DB_PORT));
    MongoDB reactionDB = new MongoDB(dbHost, dbPort, reactionDbName);

    MongoClient inputClient = new MongoClient(new ServerAddress(dbHost, dbPort));
    String outDB = cl.getOptionValue(OPTION_OUTPUT_DB_NAME, DEFAULT_OUTPUT_DB_NAME);
    DB db = inputClient.getDB(outDB);//  ww  w.  j a v a2 s. com

    String inputPathwaysCollectionName = cl.getOptionValue(OPTION_INPUT_PATHWAY_COLLECTION_NAME,
            DEFAULT_INPUT_PATHWAY_COLLECTION_NAME);
    String outputPathwaysCollectionName = cl.getOptionValue(OPTION_OUTPUT_PATHWAY_COLLECTION_NAME,
            DEFAULT_OUTPUT_PATHWAY_COLLECTION_NAME);
    String outputDnaDeqCollectionName = cl.getOptionValue(OPTION_OUTPUT_DNA_SEQ_COLLECTION_NAME,
            DEFAULT_OUTPUT_DNA_SEQ_COLLECTION_NAME);

    JacksonDBCollection<ReactionPath, String> inputPathwayCollection = JacksonDBCollection
            .wrap(db.getCollection(inputPathwaysCollectionName), ReactionPath.class, String.class);
    JacksonDBCollection<DNADesign, String> dnaDesignCollection = JacksonDBCollection
            .wrap(db.getCollection(outputDnaDeqCollectionName), DNADesign.class, String.class);
    JacksonDBCollection<ReactionPath, String> outputPathwayCollection = JacksonDBCollection
            .wrap(db.getCollection(outputPathwaysCollectionName), ReactionPath.class, String.class);

    Map<String, Set<ProteinInformation>> proteinSeqToOrgInfo = new HashMap<>();

    ProteinsToDNA2 p2d = ProteinsToDNA2.initiate();

    List<Long> reachableIds = cl.hasOption(OPTION_DESIGN_SOME)
            ? Arrays.stream(cl.getOptionValues(OPTION_DESIGN_SOME)).map(m -> lookupMolecule(reactionDB, m))
                    .collect(Collectors.toList())
            : Collections.emptyList();

    // If there is a list of molecules for which to create designs, only consider their pathways.  Otherwise, find all.
    DBObject query = reachableIds.isEmpty() ? new BasicDBObject() : DBQuery.in("target", reachableIds);

    /* Extract all pathway ids, then read pathways one id at a time.  This will reduce the likelihood of the cursor
     * timing out, which has a tendency to happen when doing expensive operations before advancing (as done here). */
    DBCursor<ReactionPath> cursor = inputPathwayCollection.find(query, new BasicDBObject("_id", true));
    List<String> pathwayIds = new ArrayList<>();
    while (cursor.hasNext()) {
        pathwayIds.add(cursor.next().getId());
    }

    for (String pathwayId : pathwayIds) {
        ReactionPath reactionPath = inputPathwayCollection.findOne(DBQuery.is("_id", pathwayId));

        List<List<Pair<ProteinMetadata, Integer>>> processedP = RankPathway
                .processSinglePathAsJava(reactionPath, reactionDbName, outDB);
        if (processedP == null) {
            LOGGER.info(String.format(
                    "Process pathway was filtered out possibly because there were more than %s seqs for a given pathway",
                    RankPathway.MAX_PROTEINS_PER_PATH()));
            outputPathwayCollection.insert(reactionPath);
            continue;
        }

        Boolean atleastOneSeqMissingInPathway = false;
        List<Set<String>> proteinPaths = new ArrayList<>();

        for (Cascade.NodeInformation nodeInformation : reactionPath.getPath().stream()
                .filter(nodeInfo -> nodeInfo.getIsReaction()).collect(Collectors.toList())) {

            Set<String> proteinSeqs = new HashSet<>();

            for (Long id : nodeInformation.getReactionIds()) {

                // If the id is negative, it is a reaction in the reverse direction. Moreover, the enzyme for this reverse
                // reaction is the same, so can use the actual positive reaction id's protein seq reference.
                // TODO: Add a preference for the positive forward direction compared to the negative backward direction seq.
                if (id < 0) {
                    LOGGER.info("Found a negative reaction id", id);
                    id = Reaction.reverseID(id);
                }

                Reaction reaction = reactionDB.getReactionFromUUID(id);

                for (JSONObject data : reaction.getProteinData()) {
                    // Get the sequences
                    if (data.has("sequences")) {
                        JSONArray seqs = data.getJSONArray("sequences");

                        for (int i = 0; i < seqs.length(); i++) {
                            Long s = seqs.getLong(i);

                            if (s != null) {
                                Seq sequenceInfo = reactionDB.getSeqFromID(s);
                                String dnaSeq = sequenceInfo.getSequence();

                                if (dnaSeq == null) {
                                    LOGGER.info(String.format(
                                            "Sequence string for seq id %d, reaction id %d and reaction path %s is null",
                                            s, id, reactionPath.getId()));
                                    continue;
                                }

                                // odd sequence
                                if (dnaSeq.length() <= 80 || dnaSeq.charAt(0) != 'M') {
                                    JSONObject metadata = sequenceInfo.getMetadata();

                                    if (!metadata.has("inferred_sequences")
                                            || metadata.getJSONArray("inferred_sequences").length() == 0) {
                                        continue;
                                    }

                                    JSONArray inferredSequences = metadata.getJSONArray("inferred_sequences");

                                    // get the first inferred sequence since it has the highest hmmer score
                                    JSONObject object = inferredSequences
                                            .getJSONObject(HIGHEST_SCORING_INFERRED_SEQ_INDEX);

                                    for (String blacklistWord : BLACKLISTED_WORDS_IN_INFERRED_SEQ) {
                                        if (object.getString("fasta_header").contains(blacklistWord)) {
                                            continue;
                                        }
                                    }

                                    dnaSeq = object.getString("sequence");
                                }

                                proteinSeqs.add(dnaSeq);
                                ProteinInformation proteinInformation = new ProteinInformation(
                                        sequenceInfo.getOrgName(), sequenceInfo.getEc(),
                                        sequenceInfo.getSequence(), reaction.getReactionName());

                                if (!proteinSeqToOrgInfo.containsKey(dnaSeq)) {
                                    proteinSeqToOrgInfo.put(dnaSeq, new HashSet<>());
                                }
                                proteinSeqToOrgInfo.get(dnaSeq).add(proteinInformation);
                            }
                        }
                    }
                }
            }

            if (proteinSeqs.size() == 0) {
                LOGGER.info("The reaction does not have any viable protein sequences");
                atleastOneSeqMissingInPathway = true;
                break;
            }

            // Now we select two representative protein seqs from the reaction. In order to do this deterministically,
            // we sort and pick the first and middle index protein seqs.
            List<String> proteinSeqArray = new ArrayList<>(proteinSeqs);
            Collections.sort(proteinSeqArray);

            int firstIndex = 0;
            int middleIndex = proteinSeqs.size() / 2;

            // get first seq
            Set<String> combination = new HashSet<>();
            combination.add(proteinSeqArray.get(firstIndex));

            // get middle index of the protein seq array
            if (proteinSeqs.size() > 1) {
                combination.add(proteinSeqArray.get(middleIndex));
            }

            proteinPaths.add(combination);
        }

        if (atleastOneSeqMissingInPathway) {
            LOGGER.info(String.format("There is at least one reaction with no sequence in reaction path id: %s",
                    reactionPath.getId()));
        } else {
            LOGGER.info(String.format("All reactions in reaction path have at least one viable seq: %s",
                    reactionPath.getId()));

            // We only compute the dna design if we can find at least one sequence for each reaction in the pathway.
            Set<List<String>> pathwayProteinCombinations = makePermutations(proteinPaths);
            Set<DNAOrgECNum> dnaDesigns = new HashSet<>();

            for (List<String> proteinsInPathway : pathwayProteinCombinations) {
                try {
                    Construct dna = p2d.computeDNA(proteinsInPathway, Host.Ecoli);

                    List<Set<ProteinInformation>> seqMetadata = new ArrayList<>();
                    for (String protein : proteinsInPathway) {
                        seqMetadata.add(proteinSeqToOrgInfo.get(protein));
                    }

                    DNAOrgECNum instance = new DNAOrgECNum(dna.toSeq(), seqMetadata, proteinsInPathway.size());
                    dnaDesigns.add(instance);
                } catch (Exception ex) {
                    LOGGER.error("The error thrown while trying to call computeDNA", ex.getMessage());
                }
            }

            DNADesign dnaDesignSeq = new DNADesign(dnaDesigns);
            try {
                WriteResult<DNADesign, String> result = dnaDesignCollection.insert(dnaDesignSeq);
                String id = result.getSavedId();
                reactionPath.setDnaDesignRef(id);
            } catch (MongoInternalException e) {
                // This condition happens whent the protein designs are too big and cannot be inserted in to the JSON object.
                // TODO: Handle this case without dropping the record
                LOGGER.error(String.format("Mongo internal exception caught while inserting dna design: %s",
                        e.getMessage()));
            }

        }

        outputPathwayCollection.insert(reactionPath);
    }
}

From source file:org.unitedid.shibboleth.config.attribute.resolver.dataConnector.MongoDbDataConnectorBeanDefinitionParser.java

License:Apache License

/**
 * Parse mongodb connection entries/*w ww  .  ja v  a  2 s .c o  m*/
 *
 * @param pluginId the id of this connector
 * @param pluginConfigChildren configuration elements
 * @return the server addresses extracted from mongohost elements
 */
protected List<ServerAddress> parseMongoHostNames(String pluginId,
        Map<QName, List<Element>> pluginConfigChildren) {
    List<ServerAddress> hosts = new ArrayList<ServerAddress>();
    String host;
    int port;

    if (pluginConfigChildren.containsKey(HOST_ELEMENT_NAME)) {
        for (Element e : pluginConfigChildren.get(HOST_ELEMENT_NAME)) {
            host = DatatypeHelper.safeTrimOrNullString(e.getAttributeNS(null, "host"));
            try {
                if (e.hasAttributeNS(null, "port")) {
                    port = Integer.parseInt(e.getAttributeNS(null, "port"));
                    hosts.add(new ServerAddress(host, port));
                } else {
                    hosts.add(new ServerAddress(host));
                }
            } catch (UnknownHostException err) {
                log.error("Data connector {} unknown host {}", pluginId, err);
            }
        }
    }
    return hosts;
}

From source file:org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor.java

License:Apache License

@PostConstruct
private void initialize() {
    try {/* w ww. j av  a 2s  . c o m*/
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        // Enable SSL if the `mongossl` Profile is enabled
        if (Arrays.stream(environment.getActiveProfiles()).anyMatch(env -> env.equalsIgnoreCase("mongossl"))) {
            builder.sslEnabled(true);
            builder.sslInvalidHostNameAllowed(true);
        }
        // If a username and password are provided, then associate these credentials with the connection
        if ((!StringUtils.isEmpty(DATABASE_USERNAME)) && (!StringUtils.isEmpty(DATABASE_CREDENTIAL))) {
            mongoClient = new MongoClient(new ServerAddress(DATABASE_HOST, DATABASE_PORT),
                    Arrays.asList(MongoCredential.createCredential(DATABASE_USERNAME, DATABASE_NAME,
                            DATABASE_CREDENTIAL.toCharArray())),
                    builder.threadsAllowedToBlockForConnectionMultiplier(mongoThreadMultiplier).build());
        } else {
            mongoClient = new MongoClient(new ServerAddress(DATABASE_HOST, DATABASE_PORT),
                    builder.threadsAllowedToBlockForConnectionMultiplier(mongoThreadMultiplier).build());
        }

    } catch (Exception exception) {
        LOGGER.error(String.format("Error connecting to MongoDB Instance. %s", exception.getMessage()),
                exception);

    }
}

From source file:org.wso2.carbon.dataservices.core.description.config.MongoConfig.java

License:Open Source License

private List<ServerAddress> createServerAddresses(String[] servers) throws Exception {
    List<ServerAddress> result = new ArrayList<>();
    String[] tmpAddr;/*from ww  w  . j a  va 2s  .  c  om*/
    for (String server : servers) {
        tmpAddr = server.split(":");
        if (tmpAddr.length == 2) {
            result.add(new ServerAddress(tmpAddr[0], Integer.parseInt(tmpAddr[1])));
        } else {
            result.add(new ServerAddress(tmpAddr[0]));
        }
    }
    return result;
}

From source file:org.wso2.carbon.datasource.reader.mongo.MongoDataSourceReaderUtil.java

License:Open Source License

public static MongoClient loadConfiguration(String xmlConfiguration) throws DataSourceException {
    ByteArrayInputStream baos = null;
    try {//from   ww  w .  j  a v  a  2s.  co m
        xmlConfiguration = CarbonUtils.replaceSystemVariablesInXml(xmlConfiguration);
        JAXBContext ctx = JAXBContext.newInstance(MongoDataSourceConfiguration.class);
        baos = new ByteArrayInputStream(xmlConfiguration.getBytes());
        MongoDataSourceConfiguration fileConfig = (MongoDataSourceConfiguration) ctx.createUnmarshaller()
                .unmarshal(baos);
        MongoClient result = null;
        MongoClientOptions.Builder builder = MongoClientOptions.builder();
        if (fileConfig.getUrl() != null) {
            if (fileConfig.getSslInvalidHostNameAllowed() != null) {
                builder.sslInvalidHostNameAllowed(fileConfig.getSslInvalidHostNameAllowed());
            }
            MongoClientURI uri = new MongoClientURI(fileConfig.getUrl(), builder);
            result = new MongoClient(uri);
        } else {
            List<ServerAddress> addressList = new ArrayList<ServerAddress>();
            if (fileConfig.getReplicaSetConfig() != null) {
                ServerAddress address1 = new ServerAddress(fileConfig.getReplicaSetConfig().getHost1(),
                        Integer.parseInt(fileConfig.getReplicaSetConfig().getPort1()));
                addressList.add(address1);
                if (fileConfig.getReplicaSetConfig().getHost2() != null
                        && fileConfig.getReplicaSetConfig().getPort2() != null) {
                    ServerAddress address2 = new ServerAddress(fileConfig.getReplicaSetConfig().getHost2(),
                            Integer.parseInt(fileConfig.getReplicaSetConfig().getPort2()));
                    addressList.add(address2);
                }
                if (fileConfig.getReplicaSetConfig().getHost3() != null
                        && fileConfig.getReplicaSetConfig().getPort3() != null) {
                    ServerAddress address3 = new ServerAddress(fileConfig.getReplicaSetConfig().getHost3(),
                            Integer.parseInt(fileConfig.getReplicaSetConfig().getPort3()));
                    addressList.add(address3);
                }
            } else {
                ServerAddress address = new ServerAddress(fileConfig.getHost(),
                        Integer.parseInt(fileConfig.getPort()));
                addressList.add(address);
            }
            MongoCredential credential = null;
            if (fileConfig.getWithSSL() != null) {
                builder.sslEnabled(fileConfig.getWithSSL());
            }
            if (fileConfig.getSslInvalidHostNameAllowed() != null) {
                builder.sslInvalidHostNameAllowed(fileConfig.getSslInvalidHostNameAllowed());
            }
            if (fileConfig.getAuthenticationMethodEnum() != null && fileConfig.getUsername() != null) {
                credential = createCredentials(fileConfig);
            }
            if (credential != null) {
                result = new MongoClient(addressList, Arrays.asList(new MongoCredential[] { credential }),
                        builder.build());
            } else {
                result = new MongoClient(addressList, builder.build());
            }
        }
        return result;
    } catch (Exception e) {
        throw new DataSourceException("Error loading Mongo Datasource configuration: " + e.getMessage(), e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException ignore) {
                // ignore
            }
        }
    }
}

From source file:org.wso2.security.tools.util.DatabaseUtils.java

License:Open Source License

private static MongoClient getMongoClient_2() {
    MongoCredential credential = MongoCredential.createMongoCRCredential(USERNAME, Constants.DB_NAME,
            PASSWORD.toCharArray());/*  w ww .  j a va  2  s  .  c  om*/
    MongoClient mongoClient = new MongoClient(new ServerAddress(Constants.HOST, Constants.PORT),
            Arrays.asList(credential));
    return mongoClient;
}

From source file:Persistence.MongoMorphia.java

License:Open Source License

public void initialize() {
    try {//from   ww  w.  ja va2  s  .  co m
        MongoCredential credential = MongoCredential.createMongoCRCredential("admin", "admin",
                "$$PASdefumee1984".toCharArray());
        ServerAddress server = new ServerAddress(Admin.ipMongo(), 27017);
        mongoClient = new MongoClient(server, Arrays.asList(credential));
        morphia = new Morphia();
        dsOAuth = morphia.createDatastore(mongoClient, "oAuth");
        dsAccessToken = morphia.createDatastore(mongoClient, "AccessToken");
        dsSessions = morphia.createDatastore(mongoClient, "Session");
        dsUsers = morphia.createDatastore(mongoClient, "User");

        morphia.map(Record.class);
        morphia.map(AccessTokenPlus.class);
        morphia.map(User.class);
        morphia.map(Session.class);

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

}