Example usage for com.mongodb BasicDBObject getString

List of usage examples for com.mongodb BasicDBObject getString

Introduction

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

Prototype

public String getString(final String key) 

Source Link

Document

Returns the value of a field as a string

Usage

From source file:mx.org.cedn.avisosconagua.mongo.HtmlGenerator.java

License:Open Source License

/**
 * Generates the HTML view of the advice.
 * @param publish flag to indicate if the files must be provided for publishing
 * @return HTML String for the advice's view.
 *///  w  w w  . jav  a2  s .  c  om
public String generate(final boolean publish) {
    BasicDBObject aviso = MongoInterface.getInstance().getAdvice(currentId);
    BasicDBObject init = (BasicDBObject) aviso.get("init");
    BasicDBObject pronostico = (BasicDBObject) aviso.get("pronostico");
    BasicDBObject capInfo = (BasicDBObject) aviso.get("capInfo");
    BasicDBObject precapture = (BasicDBObject) aviso.get("precapture");
    String imagefolder = publish ? "" : "/getImage/";
    if (publish)
        backimg = prefix + "_f.gif";

    principalFile = init.getString("issueSateliteImg");
    if (null != pronostico) {
        pronosticoFile = pronostico.getString("issueSateliteLocationImg");
    }
    String interpol = init.getString("eventCCalc");
    interpol = "interpolation".equals(interpol) ? "(Por interpolación)" : "";
    String titulo = Utils.getTituloBoletinHtml(aviso.getString(MongoInterface.ADVICE_TYPE),
            init.getString("eventCoastDistance"));
    isDP = aviso.getString(MongoInterface.ADVICE_TYPE).endsWith("dp");
    title = capInfo.getString("issueDate") + " " + capInfo.getString("issueTime") + " - "
            + capInfo.getString("issueNumber") + " " + titulo;
    if (isDP) {
        return header
                + getEncabezado(backimg, titulo, Utils.getDiaText(capInfo.getString("issueDate")),
                        capInfo.getString("issueNumber"), capInfo.getString("issueTime"),
                        getSistemaLegend(init.getString("eventCoastDistance")))
                + getTitulo(escapeHtml4(capInfo.getString("eventHeadline")),
                        imagefolder
                                + (publish ? prefix + "_1" + convertFilename(principalFile) : principalFile),
                        "imagen de satélite del ciclón tropical",
                        //init.getString("issueSateliteImgFooter"),
                        cleanPs(init.getString("eventDescriptionHTML")))
                + get1r2c("HORA LOCAL (HORA GMT)", init.getString("issueLocalTime"))
                + get1r3c("UBICACIÓN DEL CENTRO DE BAJA PRESIÓN",
                        "LATITUD NORTE: " + init.getString("eventCLat") + "",
                        "LONGITUD OESTE: " + init.getString("eventCLon") + "", interpol)
                + get1r2c("DISTANCIA AL LUGAR MÁS CERCANO", escapeHtml4(init.getString("eventDistance")))
                + get1r2c("DESPLAZAMIENTO ACTUAL:", escapeHtml4(init.getString("eventCurrentPath")))
                + get1r3c("VIENTOS MÁXIMOS [Km/h]:",
                        "SOSTENIDOS: " + init.getString("eventWindSpeedSust"),
                        "RACHAS: " + init.getString("eventWindSpeedMax"), "")
                + get1r2c("PRESIÓN MÍNIMA CENTRAL [hPa]:", init.getString("eventMinCP"))
                + get1r2c("POTENCIAL DE DESARROLLO EN 48 HORAS", init.getString("eventForecast48h") + "%")
                + get1r2c("POTENCIAL DE DESARROLLO EN CINCO DÍAS",
                        init.getString("eventForecast5d") + "%")
                + get1r2c("PRONÓSTICO DE LLUVIA:", escapeHtml4(init.getString("eventRainForecast")))
                + getFooter(escapeHtml4(capInfo.getString("issueMetheorologist")),
                        escapeHtml4(capInfo.getString("issueShiftBoss")),
                        escapeHtml4(capInfo.getString("issueFooter")));
    } else {
        previous = precapture.getString("previousIssue");
        String wind = "";
        if ((!"".equals(init.getString("eventWind120kmNE"))) || (!"".equals(init.getString("eventWind120kmSE")))
                || (!"".equals(init.getString("eventWind120kmSO")))
                || (!"".equals(init.getString("eventWind120kmNO")))) {
            wind += get1r5c("RADIO DE VIENTOS DE 120 km/h", init.getString("eventWind120kmNE"),
                    init.getString("eventWind120kmSE"), init.getString("eventWind120kmSO"),
                    init.getString("eventWind120kmNO"));
        }
        if ((!"".equals(init.getString("eventWind95kmNE"))) || (!"".equals(init.getString("eventWind95kmSE")))
                || (!"".equals(init.getString("eventWind95kmSO")))
                || (!"".equals(init.getString("eventWind95kmNO")))) {
            wind += get1r5c("RADIO DE VIENTOS DE 95 km/h", init.getString("eventWind95kmNE"),
                    init.getString("eventWind95kmSE"), init.getString("eventWind95kmSO"),
                    init.getString("eventWind95kmNO"));
        }
        if ((!"".equals(init.getString("eventWind63kmNE"))) || (!"".equals(init.getString("eventWind63kmSE")))
                || (!"".equals(init.getString("eventWind63kmSO")))
                || (!"".equals(init.getString("eventWind63kmNO")))) {
            wind += get1r5c("RADIO DE VIENTOS DE 63 km/h", init.getString("eventWind63kmNE"),
                    init.getString("eventWind63kmSE"), init.getString("eventWind63kmSO"),
                    init.getString("eventWind63kmNO"));
        }
        if ((!"".equals(init.getString("seas4mNE"))) || (!"".equals(init.getString("seas4mSE")))
                || (!"".equals(init.getString("seas4mSO"))) || (!"".equals(init.getString("seas4mNO")))) {
            wind += get1r5c("OLEAJE 4 m", init.getString("seas4mNE"), init.getString("seas4mSE"),
                    init.getString("seas4mSO"), init.getString("seas4mNO"));
        }

        String seccionB = "";
        if (null != pronostico || !"".equals(pronostico.getString("forecastData").trim())) { //siempre debera ser true
            String data = pronostico.getString("forecastData");
            ArrayList<String> rows = Utils.tokenize(data, "\\{(.*?)\\}");
            for (String row : rows) {
                String[] values = row.split("\\|");
                for (int i = 0; i < values.length; i++) {
                    if ("_".equals(values[i])) {
                        values[i] = "";
                    }
                }
                values[5] = values[5].replaceAll("\r\n", "<br/>");
                seccionB += getRowSecB(values[0], values[1], values[2], values[3], values[4], values[5]);
            }
        }
        String sectionC = "";
        ArrayList<Statistics> secclist = MongoInterface.getInstance().getAdviceChain(currentId);
        for (Statistics secc : secclist) {
            sectionC += getSectionCRow(secc.getAviso(), secc.getFecha(), secc.getLatitud(), secc.getLongitud(),
                    secc.getDistancia(), secc.getViento(), secc.getCategoria(), secc.getAvance());
        }

        return header
                + getEncabezado(backimg, titulo, Utils.getDiaText(capInfo.getString("issueDate")),
                        capInfo.getString("issueNumber"), capInfo.getString("issueTime"),
                        getSistemaLegend(init.getString("eventCoastDistance")))
                + getTitulo(escapeHtml4(capInfo.getString("eventHeadline")),
                        imagefolder
                                + (publish ? prefix + "_1" + convertFilename(principalFile) : principalFile),
                        "imagen de sat&eacute;lite del cicl&oacute;n tropical",
                        //init.getString("issueSateliteImgFooter"),
                        cleanPs(init.getString("eventDescriptionHTML")))
                + get1r2c("HORA LOCAL (HORA GMT)", init.getString("issueLocalTime"))
                + get1r3c("UBICACI&Oacute;N DEL CENTRO DEL CICL&Oacute;N",
                        "LATITUD NORTE: " + init.getString("eventCLat") + "",
                        "LONGITUD OESTE: " + init.getString("eventCLon") + "", interpol)
                + get1r2c("DISTANCIA AL LUGAR M&Aacute;S CERCANO",
                        addBr(escapeHtml4(init.getString("eventDistance"))))
                + getZonaAlerta(escapeHtml4(init.getString("areaDescription")))
                + get1r2c("DESPLAZAMIENTO ACTUAL:", escapeHtml4(init.getString("eventCurrentPath")))
                + get1r3c("VIENTOS M&Aacute;XIMOS [Km/h]:",
                        "SOSTENIDOS: " + init.getString("eventWindSpeedSust"),
                        "RACHAS: " + init.getString("eventWindSpeedMax"), "")
                + get1r2c("PRESI&Oacute;N M&Iacute;NIMA CENTRAL [hPa]:", init.getString("eventMinCP") + " hPa")
                + get1r2c("DIAMETRO DEL OJO [Km]", init.getString("eventCDiameter")) + vientosTitle + wind
                + get1r2c("DIAMETRO PROMEDIO DE FUERTE CONVECCI&Oacute;N",
                        escapeHtml4(init.getString("eventDiameterConvection")))
                + get1r2c("COMENTARIOS ADICIONALES:", cleanPs(escapeHtml4(init.getString("eventComments"))))
                + get1r2c("RECOMENDACIONES", escapeHtml4(init.getString("eventInstructions"))) + headerSecB
                + seccionB
                + getImagenSecB(
                        imagefolder
                                + (publish ? prefix + "_2" + convertFilename(pronosticoFile) : pronosticoFile),
                        escapeHtml4(pronostico.getString("issueSateliteLocationImgFooter")))
                + tituloSecC + sectionC
                + getFooter(escapeHtml4(capInfo.getString("issueMetheorologist")),
                        escapeHtml4(capInfo.getString("issueShiftBoss")),
                        escapeHtml4(capInfo.getString("issueFooter")));
    }
}

From source file:mx.org.cedn.avisosconagua.mongo.MongoInterface.java

License:Open Source License

/**
 * Gets the chain of tracking advices (from newest to oldest)
 * @param currentId ID for the current advice
 * @return list of previous advices starting from the current advice
 *///from   w ww  .  j  a  va 2  s .c  o  m
public ArrayList<Statistics> getAdviceChain(String currentId) {
    String searchId = currentId;
    DBCollection col = mongoDB.getCollection(CAPTURA_COL);
    Deque<String> deque = new ArrayDeque<>();
    while (searchId != null && !searchId.trim().equals("")) {
        deque.push(searchId);
        BasicDBObject current = (BasicDBObject) col.findOne(new BasicDBObject(INTERNAL_FORM_ID, searchId));
        if (null != current) {
            current = (BasicDBObject) current.get("precapture");
        }
        if (null != current) {
            searchId = current.getString("previousIssue");
        } else {
            searchId = null;
        }
    }
    ArrayList<Statistics> ret = new ArrayList<>();
    while (!deque.isEmpty()) {
        String curr = deque.pop();
        BasicDBObject lobj = (BasicDBObject) col.findOne(new BasicDBObject(INTERNAL_FORM_ID, curr));
        if (null != lobj) {
            ret.add(new Statistics(lobj));
        }
    }
    return ret;
}

From source file:mx.org.cedn.avisosconagua.mongo.MongoInterface.java

License:Open Source License

/**
 * Gets the prefix of the HTML file name for the advice, depending on its type.
 * @param adviceID ID for the current advice
 * @return prefix for the file name. One of pacifico|atlantico.
 *//* ww w  .  j  av a  2s  .  co m*/
public String getHTMLFileNamePrefix(String adviceID) {
    BasicDBObject newdata = new BasicDBObject(INTERNAL_FORM_ID, adviceID);
    newdata = (BasicDBObject) mongoDB.getCollection(CAPTURA_COL).findOne(newdata);
    String type = newdata.getString("adviceType");
    String ret = null;
    if (type.indexOf("pac") > -1) {
        ret = "pacifico";
    }
    if (type.indexOf("atl") > -1) {
        ret = "atlantico";
    }
    return ret;
}

From source file:mx.org.cedn.avisosconagua.mongo.Statistics.java

License:Open Source License

/**
 * Constructor. Creates a new Statistics from the given BasicDBObject
 * @param aviso DBObject for the advice/*from   www . j  a va  2s  .c o m*/
 */
public Statistics(BasicDBObject aviso) {
    BasicDBObject capInfo = (BasicDBObject) aviso.get("capInfo");
    BasicDBObject init = (BasicDBObject) aviso.get("init");
    this.aviso = capInfo.getString("issueNumber");
    String tmp = init.getString("issueLocalTime");
    StringBuilder builder = new StringBuilder();
    int i = 0;
    for (; i < tmp.length(); i++) {
        if ((tmp.charAt(i) >= '0' && tmp.charAt(i) <= '9') || tmp.charAt(i) == ':') {
            builder.append(tmp.charAt(i));
        }
        if (tmp.charAt(i) == 'a' || tmp.charAt(i) == 'A') {
            builder.append(" am");
            break;
        }
        if (tmp.charAt(i) == 'p' || tmp.charAt(i) == 'P') {
            builder.append(" pm");
            break;
        }
        if (tmp.charAt(i) == 'h' || tmp.charAt(i) == 'H' || tmp.charAt(i) == '(') {
            break;
        }
    }
    String pattern = "dd/MM/yyyyHH:mm";
    String hora = builder.toString();
    if (hora.contains("am") || hora.contains("pm")) {
        pattern = "dd/MM/yyyyhh:mm aa";
    }
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    String fechaStr = capInfo.getString("issueDate") + hora;
    Date date = new Date();
    try {
        date = sdf.parse(fechaStr);
        //System.out.println("fecha: " + fechaStr + " : " + date);
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd MMM '/' HH:mm", Locale.forLanguageTag("es-mx"));
    this.fecha = sdf2.format(date);
    this.latitud = init.getString("eventCLat");
    this.longitud = init.getString("eventCLon");
    this.distancia = init.getString("eventDistance");
    this.viento = init.getString("eventWindSpeedSust") + " / " + init.getString("eventWindSpeedMax");
    this.categoria = capInfo.getString("eventCategory");
    this.avance = init.getString("eventCurrentPath");
}

From source file:net.jurre.edutil.persistence.MongoDB.java

License:Open Source License

public void saveEDDNData(String data) {
    BasicDBObject dataObj = (BasicDBObject) JSON.parse(data);

    String schema = dataObj.getString("$schemaRef");
    dataObj.removeField("$schemaRef");
    dataObj.append("schemaRef", schema);

    if (dataObj.getString("schemaRef").equalsIgnoreCase("http://schemas.elite-markets.net/eddn/commodity/2")) {
        BasicDBObject message = (BasicDBObject) dataObj.get("message");
        boolean stationupdated = updateStationMarketData(message.getString("stationName"),
                message.getString("systemName"), message.get("commodities"));
        if (stationupdated)
            dataObj.append("stationUpdated", true);
    }/*from   w ww.j  a  va  2 s  . com*/

    DBCollection collection = this.db.getCollection(MongoDB.EDDN_COLLECTION);
    collection.insert(dataObj);
}

From source file:net.scran24.datastore.mongodb.MongoDbDataStore.java

License:Apache License

private SecureUserRecord parseUserRecord(BasicDBObject record) {
    String username = record.getString(FIELD_USERNAME);
    String passwordHashBase64 = record.getString(FIELD_PASSWORD);
    String passwordSaltBase64 = record.getString(FIELD_SALT);
    String hasher = record.getString(FIELD_HASHER);

    if (hasher == null)
        hasher = "shiro-sha256";

    BasicDBList rolesList = (BasicDBList) record.get(FIELD_ROLES);

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

    if (rolesList != null)
        for (Object s : rolesList)
            roles.add((String) s);

    BasicDBList permissionsList = (BasicDBList) record.get(FIELD_PERMISSIONS);

    Set<String> permissions = new HashSet<String>();
    if (permissionsList != null)
        for (Object s : permissionsList)
            permissions.add((String) s);

    HashMap<String, String> customFields = new HashMap<String, String>();

    if (record.containsField(FIELD_USERDATA)) {
        BasicDBObject customData = (BasicDBObject) record.get(FIELD_USERDATA);

        for (String k : customData.keySet())
            customFields.put(k, customData.getString(k));
    }/*from w  w w.j a  va 2s .c o m*/

    return new SecureUserRecord(username, passwordHashBase64, passwordSaltBase64, hasher, Option.none(),
            Option.none(), Option.none(), roles, permissions, customFields);
}

From source file:net.scran24.datastore.mongodb.MongoDbDeserializer.java

License:Apache License

public NutritionMappedSurveyRecordWithId deserialize(DBObject obj) {
    ArrayList<NutritionMappedMeal> meals = new ArrayList<NutritionMappedMeal>();

    Long startTime = (Long) obj.get("startTime");
    Long endTime = (Long) obj.get("endTime");
    String userName = (String) obj.get("userName");

    BasicDBList mealsList = (BasicDBList) obj.get("meals");

    for (Object m : mealsList) {
        meals.add(parseMeal((DBObject) m));
    }// w  ww.j av  a2 s .c o m

    ArrayList<String> log = new ArrayList<String>();

    BasicDBList loglist = (BasicDBList) obj.get("log");

    for (Object o : loglist)
        log.add((String) o);

    Map<String, String> customFields = new HashMap<String, String>();

    if (obj.containsField("userData")) {
        BasicDBObject userCustomFields = (BasicDBObject) obj.get("userData");
        for (String k : userCustomFields.keySet())
            customFields.put(k, userCustomFields.getString(k));
    }

    return new NutritionMappedSurveyRecordWithId(
            new NutritionMappedSurvey(startTime, endTime, meals, log, userName,
                    parseData((DBObject) obj.get("customData"))),
            customFields, ((ObjectId) obj.get("_id")).toString());
}

From source file:nl.vu.psy.rite.persistence.mongo.MongoRecipeMapper.java

License:Open Source License

private static Operation DBObjectToOperation(DBObject dbo) {
    if (dbo.get("operation") == null || dbo.get("operation").equals("")) {
        return null;
    } else {/*from   w w  w  . jav a 2  s.co m*/
        BasicDBObject innerFields = (BasicDBObject) dbo.get("operation");
        Operation o = new GenericOperation();
        for (String key : innerFields.keySet()) {
            o.setProperty(key, innerFields.getString(key));
        }

        // FIXME move all this reflection garbage to the GenericOperation class (also see the ComputeService class)  
        Operation ro = null;
        if (o.getProperty(GenericOperation.PropertyKeys.CLASS) != null
                || o.getProperty(GenericOperation.PropertyKeys.CLASS) != "") {
            Class<?> c;
            try {
                c = Class.forName(o.getProperty(GenericOperation.PropertyKeys.CLASS));
                ro = (Operation) c.newInstance();
                for (String key : o.getCurrentOperationPropertyKeys()) {
                    ro.setProperty(key, o.getProperty(key));
                }
            } catch (Exception e) {
                System.out.println("Could not instantiate the operation class "
                        + o.getProperty(GenericOperation.PropertyKeys.CLASS) + ". Returning GenericOperation.");
            }
        }
        return (ro == null) ? o : ro;
    }
}

From source file:no.nlf.avvik.melwinSOAPconnection.MongoOperations.java

/**
 * /*from   ww w . ja  v a 2s. co m*/
 * @return
 */
public ArrayList<Club> getClubsFromDb() {

    ArrayList<Club> clubs = new ArrayList<>();
    DBCollection dbCollectionClubs = db.getCollection("clubs");

    DBCursor cursor = dbCollectionClubs.find();

    BasicDBObject mongoObject = new BasicDBObject();

    if (cursor == null)
        System.out.println("Cursor er null");

    try {
        while (cursor.hasNext()) {
            mongoObject = (BasicDBObject) cursor.next();
            clubs.add(new Club(mongoObject.getObjectId("_id"), mongoObject.getInt("id"),
                    mongoObject.getString("melwinId"), mongoObject.getString("name"),
                    mongoObject.getString("chiefInstructorMelwinId")));

        }
    } finally {
        cursor.close();
    }
    return clubs;
}

From source file:no.nlf.avvik.melwinSOAPconnection.MongoOperations.java

/**
 * //from   ww  w  .ja v  a 2s . c  o m
 * @return
 */
public ArrayList<License> getLicensesFromDb() {
    ArrayList<License> licenses = new ArrayList<>();

    DBCollection dbCollectionLicenses = db.getCollection("licenses");

    DBCursor cursor = dbCollectionLicenses.find();

    BasicDBObject mongoObject = new BasicDBObject();

    if (cursor == null)
        System.out.println("Cursor er null, licenses");

    try {
        while (cursor.hasNext()) {
            mongoObject = (BasicDBObject) cursor.next();
            licenses.add(new License(mongoObject.getObjectId("_id"), mongoObject.getInt("id"),
                    mongoObject.getString("melwinId"), mongoObject.getString("licenseName"), null, null));
        }
    } finally {
        cursor.close();
    }
    return licenses;
}