Example usage for java.lang Double toString

List of usage examples for java.lang Double toString

Introduction

In this page you can find the example usage for java.lang Double toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of this Double object.

Usage

From source file:com.likethecolor.alchemy.api.entity.ConceptAlchemyEntityTest.java

@Test
public void testLongitude_String() {
    final Double expectedLongitude = -22.87D;
    final String longitude = expectedLongitude.toString();

    final ConceptAlchemyEntity entity = new ConceptAlchemyEntity();

    entity.setLongitude(longitude);//from  ww w .j a va  2s  .  c  o m

    assertEquals(expectedLongitude, entity.getLongitude());

    // null - should not change value
    entity.setLongitude(longitude);
    entity.setLongitude(null);

    assertEquals(expectedLongitude, entity.getLongitude());

    // empty string - should not change value
    entity.setLongitude(longitude);
    entity.setLongitude("");

    assertEquals(expectedLongitude, entity.getLongitude());

    // empty white space string - should not change value
    entity.setLongitude(longitude);
    entity.setLongitude("\t   \r\n  ");

    assertEquals(expectedLongitude, entity.getLongitude());

    // should be trimmed
    entity.setLongitude("\t   \r\n  \n\n" + longitude + "   ");

    assertEquals(expectedLongitude, entity.getLongitude());

    // non-number - should not change value
    entity.setLongitude(longitude);
    entity.setLongitude("foo");

    assertEquals(expectedLongitude, entity.getLongitude());
}

From source file:com.aurel.track.json.JSONUtility.java

/**
 * Appends a double type field. Example: <code>fieldName:12.08,</code>.</br>
 * @param sb - the field name and value are appended to this <code>StringBuilder</code>
 * @param name - the field name//from   ww  w .j  a v  a2  s  . c o  m
 * @param value - the field value
 * @param last - if true, no comma is added as the last character, otherwise there will be a comma
 */
public static void appendDoubleValue(StringBuilder sb, String name, Double value, boolean last) {
    if (value != null) {
        //appendFieldName(sb, name).append(":'").append(DoubleNumberFormatUtil.formatISO(value)).append("'");
        appendFieldName(sb, name).append(":").append(value.toString()).append("");
        if (!last) {
            sb.append(",");
        }
    }
}

From source file:com.opensmile.maven.EmoRecService.java

@Path("/getdims")
@GET//  w w  w.j  a v  a  2  s.c  o m
@Produces("application/json")
public Response getdims(@QueryParam("dims") String dim, @QueryParam("url") String url,
        @DefaultValue("") @QueryParam("json") String jsonfile,
        @DefaultValue("-1,-1") @QueryParam("timing") String time,
        @DefaultValue("false") @QueryParam("mobile") String mobilemode,
        @DefaultValue("") @QueryParam("texts") String texts) throws JSONException {

    logger_instance.write(1, "Inside getdims");
    if (dim == null) {
        return (Response.status(200).entity(genderateHelp()).build());
    }
    dim = dim.toLowerCase();
    File file = wget(url);// wget command to retrieve the video content
    logger_instance.write(1, "URL downloaded to " + file.getAbsolutePath());
    String extension = "";
    int i = file.getName().lastIndexOf('.');
    String[] splitedTexts = null;
    if (texts.length() > 0) {
        splitedTexts = texts.split(";");
    }
    if (i >= 0) {
        extension = file.getName().substring(i + 1);
    }
    File wavFile;
    wavFile = convertToWave(file);

    logger_instance.write(1, "File converted to wav: " + wavFile.getAbsolutePath());
    String[] times = time.split(";");
    String asrname = "____________________";
    String text = "";
    boolean doingASR = false;
    boolean asr_error = false;
    String temp_text = "";
    if (times[0].toLowerCase().compareTo("asr") == 0 || times[0].toLowerCase().compareTo("asr_word") == 0) {
        if (DOCKER) {
            return Response.status(200).entity("ASR and Sentiment are not available for the Docker version")
                    .build();
        }
        logger_instance.write(1, " Perform ASR");
        doingASR = true;
        try {
            double audioDuration = getAudioDuration(wavFile.getAbsolutePath());

            String tim = "";
            double asraudioleng = 120;// audioDuration;
            for (double startTime = 0; startTime < audioDuration; startTime += asraudioleng) {
                double ending = Math.min(startTime + asraudioleng, audioDuration);
                double duration = ending - startTime;
                logger_instance.write(1, " Perform ASR, time:" + startTime + " - " + ending);
                if (duration < .5)
                    break;
                File cuttedaudioasr = cutAudio(wavFile, String.valueOf(startTime), String.valueOf(duration),
                        100000 + startTime);
                JSONArray jasr = null;
                try {
                    jasr = performASR2(cuttedaudioasr.getAbsolutePath());
                } catch (JSONException e) {

                }
                if (jasr == null) {
                    temp_text += "Problem with ASR (probably license is expired);";
                    tim += ((Double) startTime).toString() + "," + ((Double) ending).toString() + ";";
                    continue;
                }
                if (jasr.length() == 0) {
                    temp_text += "NO TEXT IS DETECTED!;";
                    tim += ((Double) startTime).toString() + "," + ((Double) ending).toString() + ";";
                } else {
                    ArrayList<String> temp_texta = new ArrayList<String>();
                    ArrayList<Integer> start_time = new ArrayList<Integer>();
                    ArrayList<Integer> end_time = new ArrayList<Integer>();
                    for (int iw = 0; iw < jasr.length(); iw++) {
                        if (jasr.getJSONObject(iw).getString("word").compareTo("<s>") != 0
                                && jasr.getJSONObject(iw).getString("word").compareTo("</s>") != 0) {
                            temp_texta.add(jasr.getJSONObject(iw).getString("word"));
                            start_time.add(jasr.getJSONObject(iw).getInt("start"));
                            end_time.add(jasr.getJSONObject(iw).getInt("end"));
                        }
                    }

                    if (times[0].toLowerCase().compareTo("asr_word") == 0) {
                        for (int iw = 0; iw < temp_texta.size(); iw++) {
                            if (temp_texta.get(iw).compareTo(".") == 0)
                                continue;
                            double vst = start_time.get(iw).doubleValue() / 10000000 + startTime;
                            double ven = end_time.get(iw).doubleValue() / 10000000 + startTime;
                            tim += ((Double) vst).toString() + "," + ((Double) ven).toString() + ";";
                            temp_text += temp_texta.get(iw) + ";";
                        }
                    } else {
                        boolean start = true;
                        boolean prevDot = false;
                        for (int iw = 0; iw < temp_texta.size(); iw++) {
                            if (temp_texta.get(iw).compareTo(".") == 0) {
                                if (prevDot)
                                    continue;// double dots
                                double v = start_time.get(iw).doubleValue() / 10000000 + startTime;
                                tim += ((Double) v).toString() + ";";

                                temp_text += ";";
                                start = true;
                                prevDot = true;
                                continue;
                            }
                            prevDot = false;
                            if (start == true) {
                                double v = start_time.get(iw).doubleValue() / 10000000 + startTime;
                                tim += ((Double) v).toString() + ",";
                                start = false;
                            }
                            temp_text += temp_texta.get(iw) + " ";
                            if (iw == temp_texta.size() - 1 && !temp_text.endsWith(".")) {
                                temp_text += ";";
                                double v = end_time.get(iw).doubleValue() / 10000000 + startTime;
                                tim += ((Double) v).toString() + ";";
                            }

                        }
                    }
                }
            }
            if (tim.endsWith(";"))
                tim = tim.substring(0, tim.length() - 1);
            if (temp_text.endsWith(";"))
                temp_text = temp_text.substring(0, temp_text.length() - 1);
            splitedTexts = temp_text.split(";");
            times = tim.split(";");
        } catch (IOException e) {
            splitedTexts = "IOException during ASR".split(",");
            logger_instance.write(1, "IOException during ASR" + e.getMessage());
            asr_error = true;
            dim = dim.replace("sentiment,", "").replace(",sentiment", "").replace("sentiment", "");
            times = "-1,-1".split(";");
        } catch (InterruptedException e) {
            e.printStackTrace();
            return Response.status(200).entity("InterruptedException during ASR").build();
        }
    }
    if (mobilemode.compareTo("true") == 0) {
        times = new String[] { "-1,-1" };
        if (doingASR)
            splitedTexts = new String[] { temp_text.replace("%20", " ").replace(";", ". ") };
    }
    String finalJSONString = "[";
    String[] dims = dim.split(",");
    ArrayList<Classifier> clf = new ArrayList<Classifier>();
    logger_instance.write(1, "Loading config.json from :" + paths.getVar("REST_OPENSMILE") + "configs.json");
    JSONObject jo = loadJsonObject(paths.getVar("REST_OPENSMILE") + "configs.json");
    logger_instance.write(1, "JSON is loaded: " + jo.toString());
    JSONArray ja = jo.getJSONArray("configs");
    logger_instance.write(1, "dims:" + dims.length);
    for (int d = 0; d < dims.length; d++) {
        if ((dims[d].toLowerCase().compareTo("sentiment") == 0 || dims[d].toLowerCase().compareTo("asr") == 0)
                && DOCKER) {
            return Response.status(200).entity("ASR and Sentiment are not available for the Docker version")
                    .build();
        }

        boolean added = false;
        for (int j = 0; j < ja.length(); j++) {
            if (((JSONObject) ja.get(j)).getString("id").compareTo(dims[d].toLowerCase()) == 0) {
                Classifier c = ClassifierFactory.createClassifier((JSONObject) ja.get(j), logger_instance);
                c.configure((JSONObject) ja.get(j));
                clf.add(c);
                added = true;
                break;
            }
        }
        if (!added)
            return Response.status(200).entity(dims[d] + " is not supported!").build();/**/
    }
    logger_instance.write(1, "" + clf.size() + " classifiers are added");
    ExecutorService exec = Executors.newFixedThreadPool(times.length);
    logger_instance.write(1, "times:" + times.length);
    JSONObject finalJson = new JSONObject();

    finalJson.put("@context", "http://senpy.cluster.gsi.dit.upm.es/api/contexts/Results.jsonld");
    finalJson.put("@type", "results");

    for (i = 0; i < times.length; i++) {
        String[] timesplit = times[i].split(",");
        String duration = "-1";
        if (timesplit[1].trim().compareTo("-1") == 0)
            duration = "-1";
        else {
            Double d = Double.valueOf(timesplit[1].trim()) - Double.valueOf(timesplit[0].trim());
            duration = d.toString();
        }
        final File cuttedAudio = cutAudio(wavFile, timesplit[0], duration, i);
        final JSONArray jaresult = new JSONArray();
        final CountDownLatch latch = new CountDownLatch(clf.size());
        final String[] textttt = splitedTexts;
        final String[] jsonresultstr = new String[clf.size()];
        final boolean da = doingASR;
        final int iiii = i;
        for (int iclf = 0; iclf < clf.size(); iclf++) {
            final Classifier cl = clf.get(iclf);
            final int iiclf = iclf;
            exec.submit(new Runnable() {
                @Override
                public void run() {
                    logger_instance.write(1, " run ");
                    try {
                        if (cl.getInType().compareTo("audio") == 0) {
                            JSONObject res = cl.classify(cuttedAudio.getAbsolutePath());
                            jaresult.put(res);
                        } else if (cl.getInType().compareTo("text") == 0 && da == true && textttt != null) {
                            JSONObject res = cl.classify(textttt[iiii].replace(" ", "_"));
                            jaresult.put(res);
                        }
                    } catch (Exception e) {
                        logger_instance.write(1, " classification exception: " + e.getMessage());
                        e.printStackTrace();
                    } finally {
                    }
                    logger_instance.write(1, " finished ");
                    latch.countDown();
                }
            });
        }
        logger_instance.write(1, " latch wait ");
        try {
            latch.await();
        } catch (InterruptedException e) {
            logger_instance.write(1, " latch InterruptedException: " + e.getMessage());
            e.printStackTrace();
        }
        // create json

        JSONObject job = jaresult.getJSONObject(0);
        for (int ij = 1; ij < jaresult.length(); ij++)
            mergeJSONsFull(job, jaresult.getJSONObject(ij));

        if (splitedTexts != null && splitedTexts.length > 0 && i < splitedTexts.length) {
            job.put("Text", splitedTexts[i]);
        }
        job.put("@id", url + "#time=" + times[i]);
        finalJson.append("entries", job);

        System.out.println("" + i + "/" + times.length + " processed.");
    }

    if (doingASR) {
        JSONObject j = new JSONObject();
        j.put("ASR", "Powered by Phonexia");
        finalJson.append("analysis", j);
    }

    // deleting
    String[] ss = asrname.split("/");
    final String ffnn = ss[ss.length - 1];
    ss = file.toString().split("/");
    final String wwfn = ss[ss.length - 1];
    final File folder = new File(paths.FileDirectory);
    final File[] files = folder.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String name) {
            boolean b = false;
            b = b | name.startsWith(ffnn);
            b = b | name.startsWith(wwfn);
            return b;
        }
    });
    for (final File ffile : files) {
        if (!ffile.delete()) {
            System.err.println("Can't remove " + ffile.getAbsolutePath());
        }
    }
    return Response.status(200).entity(finalJson.toString(4)).build();
}

From source file:us.mschmidt.komo.CalcEngine.java

/**
 * Performs number conversion computations.
 * /*  ww  w .  j a v  a  2  s  .co  m*/
 * @param numString   the number to be converted
 * @param opVal      designation of the operation to be performed
 * @return         the converted value
 */
private String doConvert(final String numString, final char opVal) {
    char opChar = opVal;
    String valString = numString;
    Double valA = 0.0;
    Double valAnswer = 0.0;

    // Make sure String is a number.  If it is zero-length, assume the
    // keystroke was inadvertent and return "".
    if (valString.length() > 0) {
        try {
            valA = Double.parseDouble(valString);
        } catch (final NumberFormatException e) {
            return nanErr;
        }
    } else {
        return "";
    }

    switch (opChar) {
    case 'Q': // Square Root
        valAnswer = Math.sqrt(valA);
        break;

    case 'I': // Inverse
        valAnswer = 1.0 / valA;
        break;

    default: // Do nothing - this should never happen
        break;
    }

    // Return properly formatted result String.
    return trimString(valAnswer.toString());
}

From source file:at.alladin.rmbt.statisticServer.OpenTestSearchResource.java

/**
 * Transforms the given parameters in a psql where-clause, starting with "AND"
 * @param attr the attribute name from the get-request - is replaced with the real column name
 * @param value what the column given in 'attr' should have as value
 * @param comperator the comparator, eg. '=', '>=', '<=' 'LIKE'
 * @param negate true, if the results should NOT match the criteria
 * @param type the type of the column (numeric, string, uuid, date)
 * @param queue the queue where the resulting transformed value should be put in
 * @return the formatted AND-Clause for the prepared statement (AND xxx = ?)
 *//*from   w  w w . j  a  v a 2  s  .  c o m*/
private String formatWhereClause(String attr, String value, String comperator, boolean negate, FieldType type,
        Queue<Map.Entry<String, FieldType>> queue) {
    //if it is a array => remove the brackets
    if (attr.endsWith("[]")) {
        attr = attr.substring(0, attr.length() - 2);
    }

    //because we use aliases, some modifications have to be made
    if (attr.equals("download_kbit")) {
        attr = "t.speed_download";
        //histogram
        if (comperator.equals(">="))
            this.histogramInfo.min_download = Long.parseLong(value);
        else if (comperator.equals("<="))
            this.histogramInfo.max_download = Long.parseLong(value);
    } else if (attr.equals("upload_kbit")) {
        attr = "t.speed_upload";
        //histogram
        if (comperator.equals(">="))
            this.histogramInfo.min_upload = Long.parseLong(value);
        else if (comperator.equals("<="))
            this.histogramInfo.max_upload = Long.parseLong(value);
    } else if (attr.equals("ping_ms")) {
        attr = "t.ping_median";
        Double v = Double.parseDouble(value) * 1000000;
        //histogram
        if (comperator.equals(">="))
            this.histogramInfo.min_ping = Double.parseDouble(value);
        else if (comperator.equals("<="))
            this.histogramInfo.max_ping = Double.parseDouble(value);
        value = v.toString();
    } else if (attr.equals("time")) {
        attr = "t.time";
    } else if (attr.equals("cat_technology")) {
        attr = "nt.group_name";
    } else if (attr.equals("client_version")) {
        attr = "client_software_version";
    } else if (attr.equals("model")) {
        attr = "(adm.fullname ILIKE ? OR t.model ILIKE ?)";
        queue.add(new AbstractMap.SimpleEntry<>(value, type));
        queue.add(new AbstractMap.SimpleEntry<>(value, type));
        if (!negate) {
            return " AND " + attr;
        } else {
            return " AND NOT " + attr;
        }
    } else if (attr.equals("provider_name")) {
        attr = "(mprov.name ILIKE ? OR (mprov.name IS NULL AND  prov.name ILIKE ?))";
        queue.add(new AbstractMap.SimpleEntry<>(value, type));
        queue.add(new AbstractMap.SimpleEntry<>(value, type));
        if (!negate) {
            return " AND " + attr;
        } else {
            return " AND NOT " + attr;
        }
    } else if (attr.equals("mobile_provider_name")) {
        attr = "mprov.name";
    } else if (attr.equals("network_name")) {
        attr = "network_operator_name";
    } else if (attr.equals("network_type")) {
        attr = "t.network_group_type";
    } else if (attr.equals("cursor") || attr.equals("max_results")) {
        return "";
    } else if (attr.equals("platform")) {
        attr = "(t.plattform ILIKE ? OR (t.plattform IS NULL AND t.client_name ILIKE ?))";
        queue.add(new AbstractMap.SimpleEntry<>(value, type));
        queue.add(new AbstractMap.SimpleEntry<>(value, type));
        if (!negate) {
            return " AND " + attr;
        } else {
            return " AND NOT " + attr;
        }
    } else if (attr.equals("signal_strength")) {
        attr = "t.signal_strength";
    } else if (attr.equals("open_uuid")) {
        attr = "t.open_uuid";
    } else if (attr.equals("lat")) {
        attr = "t.geo_lat";
    } else if (attr.equals("long")) {
        attr = "t.geo_long";
    } else if (attr.equals("sim_mcc_mnc")) {
        attr = "network_sim_operator";
    } else if (attr.equals("sim_country")) {
        attr = "network_sim_country";
    } else if (attr.equals("asn")) {
        attr = "public_ip_asn";
    } else if (attr.equals("implausible")) {
        //if false -> also allow null
        if (value.toLowerCase().equals("true")) {
            this.excludeImplausible = false;
            //return " AND (t.implausible = FALSE or t.implausible IS NULL)";
        }
    } else if (attr.equals("loc_accuracy")) {
        attr = "t.geo_accuracy";

        //special case: if value > threshold -> ignore and find no results (?)
        if (comperator.equals(">=") || comperator.equals("=")) {
            long val = Long.parseLong(value);
            if (val > Double.parseDouble(getSetting("rmbt_geo_accuracy_detail_limit"))) {
                return " AND 1=0";
            }
        }

        //special case: if (-1) than NULL values should be found
        if (value.equals("-1")) {
            return " AND t.geo_accuracy IS NULL";
        }
    } else if (attr.equals("ip_anonym")) {
        attr = "client_public_ip_anonymized";
    } else if (attr.equals("ip_version")) {
        attr = "family(client_public_ip::inet)";
    }

    //, zip_code are not renamed

    queue.add(new AbstractMap.SimpleEntry<>(value, type));
    if (negate) {
        return " AND NOT " + attr + " " + comperator + " ?";
    } else {
        return " AND " + attr + " " + comperator + " ?";
    }
}

From source file:com.esri.geoevent.solutions.adapter.cap.CAPInboundAdapter.java

private GeoEvent parseInfoAreaGeom(Element polygon, Element circle, Element geocode, String identifier,
        String infoID, String areaID) {
    GeoEvent msg;/* ww  w .j  a  v  a2s  . c o  m*/
    try {
        msg = geoEventCreator
                .create(((AdapterDefinition) definition).getGeoEventDefinition("CAPInfoAreaGeom").getGuid());
        Integer len = identifier.length();
        try {
            msg.setField(0, identifier);
        } catch (Exception ex) {
            LOG.debug("Failed to set 'identifier': " + identifier);
        }
        try {
            msg.setField(1, infoID);
        } catch (Exception ex) {
            LOG.debug("Failed to set 'infoID': " + infoID);
        }
        try {
            msg.setField(2, areaID);
        } catch (Exception ex) {
            LOG.debug("Failed to set 'areaID': " + areaID);
        }
        SpatialReference sr = SpatialReference.create(4326);
        String tagName;
        NodeList nodeList;
        Element line;
        String strValue = "";

        if (polygon != null) {
            tagName = "polygon";

            try {
                strValue = getCharacterDataFromElement(polygon);
                msg.setField(3, strValue);
            } catch (Exception ex) {
                LOG.debug("Failed to set '" + tagName + "': " + strValue);
            }

            String[] coords = strValue.split(" ");
            if (coords.length >= 4) {
                String firstCoordPair = coords[0].trim();
                String lastCoordPair = coords[coords.length - 1].trim();
                boolean firstAndLastCoordsAreEqual = firstCoordPair.equals(lastCoordPair);
                if (!firstAndLastCoordsAreEqual) {
                    System.out.println("      Invalid coordinate list.");
                    System.out.println("      The first (" + firstCoordPair + ") and last (" + lastCoordPair
                            + ") coordinate pairs are not identical.");
                    //return null;
                }

                try {

                    com.esri.core.geometry.Polygon capPoly = new com.esri.core.geometry.Polygon();
                    Boolean first = true;
                    for (String pair : coords) {
                        String[] xyArr = pair.split(",");
                        Double y = Double.parseDouble(xyArr[0].trim());
                        Double x = Double.parseDouble(xyArr[1].trim());
                        if (Double.isNaN(y) | y == 0)
                            continue;
                        if (Double.isNaN(x) | x == 0)
                            continue;
                        Point p = new Point(x, y);

                        //com.esri.core.geometry.Point p = GeometryEngine.project(x, y, sr);
                        if (first) {
                            capPoly.startPath(p);
                            first = false;
                        } else {
                            capPoly.lineTo(p);
                        }
                    }
                    capPoly.closeAllPaths();
                    Geometry simple = GeometryEngine.simplify(capPoly, sr);
                    MapGeometry mapGeo = new MapGeometry(simple, sr);

                    msg.setGeometry(mapGeo);

                } catch (Exception ex) {
                    LOG.debug("Failed to set polygon");
                }
            }
        }

        if (circle != null) {
            tagName = "circle";
            try {
                strValue = getCharacterDataFromElement(circle);
                msg.setField(4, strValue);
            } catch (Exception ex) {
                LOG.debug("Failed to set '" + tagName + "': " + strValue);
            }

            String coordPair = "";
            String radString = "";
            try {
                String[] coords = strValue.split(" ");
                coordPair = coords[0];
                String[] xAndY = coordPair.split(",");
                Double y = Double.parseDouble(xAndY[0]);
                Double x = Double.parseDouble(xAndY[1]);

                radString = coords[1];
                Double radius = Double.parseDouble(radString);
                if (radius == null | radius <= 0) {
                    System.out.println("      Invalid radius. Radius is " + radius.toString()
                            + ". It must be non-null and > 0. Setting radius at 0.1.");
                    //return null;
                    radius = 0.1;
                }
                Geometry pointBuffer = buffer(x, y, radius);
                MapGeometry mapGeo = new MapGeometry(pointBuffer, sr);
                msg.setField(7, mapGeo);
                System.out.println("");
                System.out.println("      Set a circle geometry for " + areaID + ".");
                System.out.println("");
            } catch (Exception ex) {
                LOG.debug("Failed to set circle");
                System.out.println(
                        "     Error parsing coordinates (" + coordPair + ") or radius (" + radString + ").");
                return null;
            }
        }

        if (geocode != null) {
            tagName = "valueName";
            nodeList = geocode.getElementsByTagName(tagName);
            line = (Element) nodeList.item(0);
            try {
                strValue = getCharacterDataFromElement(line);
                msg.setField(5, strValue);
            } catch (Exception ex) {
                LOG.debug("Failed to set 'Geocode Name': " + strValue);
            }

            tagName = "value";
            nodeList = geocode.getElementsByTagName(tagName);
            line = (Element) nodeList.item(0);
            try {
                strValue = getCharacterDataFromElement(line);
                msg.setField(6, strValue);
            } catch (Exception ex) {
                LOG.debug("Failed to set 'Geocode Value': " + strValue);
            }
        }

    } catch (MessagingException e) {
        return null;
    }
    return msg;
}

From source file:com.esri.ges.solutions.adapter.cap.CAPInboundAdapter.java

private GeoEvent parseInfoAreaGeom(Element polygon, Element circle, Element geocode, String identifier,
        String infoID, String areaID) {
    GeoEvent msg;//from  ww w . j  av a2 s. c  o m
    try {
        msg = geoEventCreator
                .create(((AdapterDefinition) definition).getGeoEventDefinition("CAPInfoAreaGeom").getGuid());

        try {
            msg.setField(0, identifier);
        } catch (Exception ex) {
            LOG.debug("Failed to set 'identifier': " + identifier);
        }
        try {
            msg.setField(1, infoID);
        } catch (Exception ex) {
            LOG.debug("Failed to set 'infoID': " + infoID);
        }
        try {
            msg.setField(2, areaID);
        } catch (Exception ex) {
            LOG.debug("Failed to set 'areaID': " + areaID);
        }

        String tagName;
        NodeList nodeList;
        Element line;
        String strValue = "";

        if (polygon != null) {
            tagName = "polygon";

            try {
                strValue = getCharacterDataFromElement(polygon);
                msg.setField(3, strValue);
            } catch (Exception ex) {
                LOG.debug("Failed to set '" + tagName + "': " + strValue);
            }

            String[] coords = strValue.split(" ");
            if (coords.length >= 4) {
                String firstCoordPair = coords[1];
                String lastCoordPair = coords[coords.length - 1];
                boolean firstAndLastCoordsAreEqual = firstCoordPair.equals(lastCoordPair);
                if (!firstAndLastCoordsAreEqual) {
                    System.out.println("      Invalid coordinate list.");
                    System.out.println("      The first (" + firstCoordPair + ") and last (" + lastCoordPair
                            + ") coordinate pairs are not identical.");
                    //return null;
                }

                try {
                    Point gepPt = spatial.createPoint(-10, 10, 4326);
                    gepWGS = gepPt.getSpatialReference();
                    com.esri.ges.spatial.Polygon polyG = spatial.createPolygon();
                    String coordPair = coords[0];
                    String[] xAndY = coordPair.split(",");
                    Double y = Double.parseDouble(xAndY[0]);
                    Double x = Double.parseDouble(xAndY[1]);
                    polyG.setSpatialReference(gepWGS);
                    polyG.startPath(x, y, 0);
                    for (int p = 2; p < coords.length; p++) {
                        coordPair = coords[p];
                        xAndY = coordPair.split(",");
                        y = Double.parseDouble(xAndY[0]);
                        x = Double.parseDouble(xAndY[1]);
                        if (Double.isNaN(y) | y == 0)
                            continue;
                        if (Double.isNaN(x) | x == 0)
                            continue;
                        polyG.lineTo(x, y, 0);
                    }
                    if (!firstAndLastCoordsAreEqual) {

                    }
                    polyG.closeAllPaths();
                    msg.setField(7, polyG);
                    System.out.println("");
                    System.out.println("      Set a polygon geometry for " + areaID + ".");
                    System.out.println("");
                } catch (Exception ex) {
                    LOG.debug("Failed to set polygon");
                }
            }
        }

        if (circle != null) {
            tagName = "circle";
            try {
                strValue = getCharacterDataFromElement(circle);
                msg.setField(4, strValue);
            } catch (Exception ex) {
                LOG.debug("Failed to set '" + tagName + "': " + strValue);
            }

            String coordPair = "";
            String radString = "";
            try {
                String[] coords = strValue.split(" ");
                coordPair = coords[0];
                String[] xAndY = coordPair.split(",");
                Double y = Double.parseDouble(xAndY[0]);
                Double x = Double.parseDouble(xAndY[1]);

                radString = coords[1];
                Double radius = Double.parseDouble(radString);
                if (radius == null | radius <= 0) {
                    System.out.println("      Invalid radius. Radius is " + radius.toString()
                            + ". It must be non-null and > 0. Setting radius at 0.1.");
                    //return null;
                    radius = 0.1;
                }
                com.esri.ges.spatial.Polygon pointBuffer = buffer(x, y, radius);
                msg.setField(7, pointBuffer);
                System.out.println("");
                System.out.println("      Set a circle geometry for " + areaID + ".");
                System.out.println("");
            } catch (Exception ex) {
                LOG.debug("Failed to set circle");
                System.out.println(
                        "     Error parsing coordinates (" + coordPair + ") or radius (" + radString + ").");
                return null;
            }
        }

        if (geocode != null) {
            tagName = "valueName";
            nodeList = geocode.getElementsByTagName(tagName);
            line = (Element) nodeList.item(0);
            try {
                strValue = getCharacterDataFromElement(line);
                msg.setField(5, strValue);
            } catch (Exception ex) {
                LOG.debug("Failed to set 'Geocode Name': " + strValue);
            }

            tagName = "value";
            nodeList = geocode.getElementsByTagName(tagName);
            line = (Element) nodeList.item(0);
            try {
                strValue = getCharacterDataFromElement(line);
                msg.setField(6, strValue);
            } catch (Exception ex) {
                LOG.debug("Failed to set 'Geocode Value': " + strValue);
            }
        }

    } catch (MessagingException e) {
        return null;
    }
    return msg;
}

From source file:org.janusgraph.diskstorage.es.ElasticSearchIndexTest.java

@Test
public void testCustomMappingProperty() throws BackendException, IOException, ParseException {

    String mappingTypeName = "vertex";
    String indexPrefix = "janusgraph";
    String parameterName = "boost";
    Double parameterValue = 5.5;

    String field = "field_with_custom_prop";

    KeyInformation keyInfo = new StandardKeyInformation(String.class, Cardinality.SINGLE,
            Mapping.STRING.asParameter(),
            Parameter.of(ParameterType.customParameterName(parameterName), parameterValue));

    index.register(mappingTypeName, field, keyInfo, tx);

    String indexName = indexPrefix + "_" + mappingTypeName;

    CloseableHttpResponse response = getESMapping(indexName, mappingTypeName);

    // Fallback to multitype index
    if (response.getStatusLine().getStatusCode() != 200) {
        indexName = indexPrefix;/*from  ww  w.  jav a2s .com*/
        response = getESMapping(indexName, mappingTypeName);
    }

    HttpEntity entity = response.getEntity();

    JSONObject json = (JSONObject) new JSONParser().parse(EntityUtils.toString(entity));

    String returnedProperty = retrieveValueFromJSON(json, indexName, "mappings", mappingTypeName, "properties",
            field, parameterName);

    assertEquals(parameterValue.toString(), returnedProperty);

    IOUtils.closeQuietly(response);
}

From source file:com.likethecolor.alchemy.api.entity.DisambiguatedAlchemyEntityTest.java

@Test
public void testLatitude_String() {
    final Double expectedLatitude = 35.123D;
    final String latitude = expectedLatitude.toString();

    final DisambiguatedAlchemyEntity entity = new DisambiguatedAlchemyEntity();

    entity.setLatitude(latitude);/* w  w  w  .j  av a 2  s .  c  o m*/

    assertEquals(expectedLatitude, entity.getLatitude());

    // null - should not change value
    entity.setLatitude(latitude);
    entity.setLatitude(null);

    assertEquals(expectedLatitude, entity.getLatitude());

    // empty string - should not change value
    entity.setLatitude(latitude);
    entity.setLatitude("");

    assertEquals(expectedLatitude, entity.getLatitude());

    // empty white space string - should not change value
    entity.setLatitude(latitude);
    entity.setLatitude("\t   \r\n  ");

    assertEquals(expectedLatitude, entity.getLatitude());

    // should be trimmed
    entity.setLatitude("\t   \r\n  \n\n" + latitude + "   ");

    assertEquals(expectedLatitude, entity.getLatitude());

    // non-number - should not change value
    entity.setLatitude(latitude);
    entity.setLatitude("foo");

    assertEquals(expectedLatitude, entity.getLatitude());
}

From source file:com.likethecolor.alchemy.api.entity.DisambiguatedAlchemyEntityTest.java

@Test
public void testLongitude_String() {
    final Double expectedLongitude = -22.87D;
    final String longitude = expectedLongitude.toString();

    final DisambiguatedAlchemyEntity entity = new DisambiguatedAlchemyEntity();

    entity.setLongitude(longitude);// ww  w.j  av a2s. c  o m

    assertEquals(expectedLongitude, entity.getLongitude());

    // null - should not change value
    entity.setLongitude(longitude);
    entity.setLongitude(null);

    assertEquals(expectedLongitude, entity.getLongitude());

    // empty string - should not change value
    entity.setLongitude(longitude);
    entity.setLongitude("");

    assertEquals(expectedLongitude, entity.getLongitude());

    // empty white space string - should not change value
    entity.setLongitude(longitude);
    entity.setLongitude("\t   \r\n  ");

    assertEquals(expectedLongitude, entity.getLongitude());

    // should be trimmed
    entity.setLongitude("\t   \r\n  \n\n" + longitude + "   ");

    assertEquals(expectedLongitude, entity.getLongitude());

    // non-number - should not change value
    entity.setLongitude(longitude);
    entity.setLongitude("foo");

    assertEquals(expectedLongitude, entity.getLongitude());
}