List of usage examples for java.text ParseException ParseException
public ParseException(String s, int errorOffset)
From source file:edu.hawaii.soest.kilonalu.ctd.CTDParser.java
public void setMetadata() throws ParseException { logger.debug("CTDParser.setMetadata() called."); // Are we in profile or moored mode? if (this.SAMPLING_MODE != null) { this.samplingMode = this.metadataValuesMap.get(this.SAMPLING_MODE); logger.info("Sampling mode is: " + this.samplingMode); } else {/*from w w w . j ava 2 s . c o m*/ throw new ParseException( "There was an error parsing the data string. " + "The sampling mode is not stated correctly in " + "the metadata from the DS command. Please " + "check the output.", 0); } // Determine the output format if (this.OUTPUT_FORMAT != null) { this.outputFormat = this.metadataValuesMap.get(this.OUTPUT_FORMAT); logger.info("Data output format is: " + this.outputFormat); } else { throw new ParseException( "There was an error parsing the data string. " + "The output format is not stated correctly in " + "the metadata from the DS command. Please " + "check the output.", 0); } /* * @ todo - handle 'output salinity = "yes|no"' */ /* * @ todo - handle 'output sound velocity = "yes|no"' */ // Is there a pressure sensor? If so, what type? if (this.PRESSURE_SENSOR_TYPE != null) { this.pressureSensorType = this.metadataValuesMap.get(this.PRESSURE_SENSOR_TYPE).trim(); this.hasPressure = true; if (this.pressureSensorType.equals("strain gauge")) { this.hasStrainGaugePressure = true; } if (this.PRESSURE_SENSOR_RANGE != null) { this.pressureSensorRange = this.metadataValuesMap.get(this.PRESSURE_SENSOR_RANGE).trim(); } } else { logger.info("There is no pressure sensor."); } // Determine if there are external voltages to read // channel 0 if (this.EXTERNAL_VOLTAGE_CHANNEL_ZERO != null) { this.externalVoltageChannelZero = this.metadataValuesMap.get(this.EXTERNAL_VOLTAGE_CHANNEL_ZERO).trim(); if (this.externalVoltageChannelZero.equals("yes")) { this.hasVoltageChannelZero = true; logger.info("There is a channel 0 voltage."); } else { logger.info("There is no channel 0 voltage."); } } // channel 1 if (this.EXTERNAL_VOLTAGE_CHANNEL_ONE != null) { this.externalVoltageChannelOne = this.metadataValuesMap.get(this.EXTERNAL_VOLTAGE_CHANNEL_ONE).trim(); if (this.externalVoltageChannelOne.equals("yes")) { this.hasVoltageChannelOne = true; logger.info("There is a channel 1 voltage."); } else { logger.info("There is no channel 1 voltage."); } } // channel 2 if (this.EXTERNAL_VOLTAGE_CHANNEL_TWO != null) { this.externalVoltageChannelTwo = this.metadataValuesMap.get(this.EXTERNAL_VOLTAGE_CHANNEL_TWO).trim(); if (this.externalVoltageChannelTwo.equals("yes")) { this.hasVoltageChannelTwo = true; logger.info("There is a channel 2 voltage."); } else { logger.info("There is no channel 2 voltage."); } } // channel 3 if (this.EXTERNAL_VOLTAGE_CHANNEL_THREE != null) { this.externalVoltageChannelThree = this.metadataValuesMap.get(this.EXTERNAL_VOLTAGE_CHANNEL_THREE) .trim(); if (this.externalVoltageChannelThree.equals("yes")) { this.hasVoltageChannelThree = true; logger.info("There is a channel 3 voltage."); } else { logger.info("There is no channel 3 voltage."); } } // Determine if there is an SBE38 secondary temperature to read if (this.SBE38_TEMPERATURE_SENSOR != null) { this.sbe38TemperatureSensor = this.metadataValuesMap.get(this.SBE38_TEMPERATURE_SENSOR).trim(); if (this.sbe38TemperatureSensor.equals("yes")) { this.hasSBE38TemperatureSensor = true; } } // Determine if there is a gas tension device to read if (this.GAS_TENSION_DEVICE != null) { this.gasTensionDevice = this.metadataValuesMap.get(this.GAS_TENSION_DEVICE).trim(); if (this.gasTensionDevice.equals("yes")) { this.hasGasTensionDevice = true; } } // set each of the metadata fields // set the first sample time field if (this.FIRST_SAMPLE_TIME != null) { this.firstSampleTime = this.metadataValuesMap.get(this.FIRST_SAMPLE_TIME); logger.info("First sample time is: " + this.firstSampleTime); } // set the file name time field if (this.FILE_NAME != null) { this.fileName = this.metadataValuesMap.get(this.FILE_NAME); logger.info("File name is: " + this.fileName); } // set the temperature serial number field if (this.TEMPERATURE_SERIAL_NUMBER != null) { this.temperatureSerialNumber = this.metadataValuesMap.get(this.TEMPERATURE_SERIAL_NUMBER); logger.info("Temperature serial number is: " + this.temperatureSerialNumber); } // set the conductivity serial number field if (this.CONDUCTIVITY_SERIAL_NUMBER != null) { this.conductivitySerialNumber = this.metadataValuesMap.get(this.CONDUCTIVITY_SERIAL_NUMBER); logger.info("Conductivity serial number is: " + this.conductivitySerialNumber); } // set the system upload time field if (this.SYSTEM_UPLOAD_TIME != null) { this.systemUpLoadTime = this.metadataValuesMap.get(this.SYSTEM_UPLOAD_TIME); logger.info("System upload time is: " + this.systemUpLoadTime); } // set the cruise information field if (this.CRUISE_INFORMATION != null) { this.cruiseInformation = this.metadataValuesMap.get(this.CRUISE_INFORMATION); logger.info("Cruise information is: " + this.cruiseInformation); } // set the station information field if (this.STATION_INFORMATION != null) { this.stationInformation = this.metadataValuesMap.get(this.STATION_INFORMATION); logger.info("Station information is: " + this.stationInformation); } // set the ship information field if (this.SHIP_INFORMATION != null) { this.shipInformation = this.metadataValuesMap.get(this.SHIP_INFORMATION); logger.info("Ship information is: " + this.shipInformation); } // set the chief scientist field if (this.CHIEF_SCIENTIST != null) { this.chiefScientist = this.metadataValuesMap.get(this.CHIEF_SCIENTIST); logger.info("Chief scientist is: " + this.chiefScientist); } // set the organization field if (this.ORGANIZATION != null) { this.organization = this.metadataValuesMap.get(this.ORGANIZATION); logger.info("Organization is: " + this.organization); } // set the area of operation field if (this.AREA_OF_OPERATION != null) { this.areaOfOperation = this.metadataValuesMap.get(this.AREA_OF_OPERATION); logger.info("Area of operation is: " + this.areaOfOperation); } // set the instrument package field if (this.INSTRUMENT_PACKAGE != null) { this.instrumentPackage = this.metadataValuesMap.get(this.INSTRUMENT_PACKAGE); logger.info("Instrument package is: " + this.instrumentPackage); } // set the mooring number field if (this.MOORING_NUMBER != null) { this.mooringNumber = this.metadataValuesMap.get(this.MOORING_NUMBER); logger.info("Mooring number is: " + this.mooringNumber); } // set the instrument latitude field if (this.INSTRUMENT_LATITUDE != null) { this.instrumentLatitude = this.metadataValuesMap.get(this.INSTRUMENT_LATITUDE); logger.info("Instrument latitude is: " + this.instrumentLatitude); } // set the instrument longitude field if (this.INSTRUMENT_LONGITUDE != null) { this.instrumentLongitude = this.metadataValuesMap.get(this.INSTRUMENT_LONGITUDE); logger.info("Instrument longitude is: " + this.instrumentLongitude); } // set the depth sounding field if (this.DEPTH_SOUNDING != null) { this.depthSounding = this.metadataValuesMap.get(this.DEPTH_SOUNDING); logger.info("Depth sounding is: " + this.depthSounding); } // set the profile number field if (this.PROFILE_NUMBER != null) { this.profileNumber = this.metadataValuesMap.get(this.PROFILE_NUMBER); logger.info("Profile number is: " + this.profileNumber); } // set the profile direction field if (this.PROFILE_DIRECTION != null) { this.profileDirection = this.metadataValuesMap.get(this.PROFILE_DIRECTION); logger.info("Profile direction is: " + this.profileDirection); } // set the deployment notes field if (this.DEPLOYMENT_NOTES != null) { this.deploymentNotes = this.metadataValuesMap.get(this.DEPLOYMENT_NOTES); logger.info("Deployment notes are: " + this.deploymentNotes); } // set the main battery voltage field if (this.MAIN_BATTERY_VOLTAGE != null) { this.mainBatteryVoltage = this.metadataValuesMap.get(this.MAIN_BATTERY_VOLTAGE); logger.info("Main battery voltage is: " + this.mainBatteryVoltage); } // set the lithium battery voltage field if (this.LITHIUM_BATTERY_VOLTAGE != null) { this.lithiumBatteryVoltage = this.metadataValuesMap.get(this.LITHIUM_BATTERY_VOLTAGE); logger.info("Lithium battery voltage is: " + this.lithiumBatteryVoltage); } // set the operating current field if (this.OPERATING_CURRENT != null) { this.operatingCurrent = this.metadataValuesMap.get(this.OPERATING_CURRENT); logger.info("Operating current is: " + this.operatingCurrent); } // set the pump current field if (this.PUMP_CURRENT != null) { this.pumpCurrent = this.metadataValuesMap.get(this.PUMP_CURRENT); logger.info("Pump current is: " + this.pumpCurrent); } // set the channels 0 and 1 external current field if (this.CHANNELS_01_EXTERNAL_CURRENT != null) { this.channels01ExternalCurrent = this.metadataValuesMap.get(this.CHANNELS_01_EXTERNAL_CURRENT); logger.info("Channels 0 and 1 external current is: " + this.channels01ExternalCurrent); } // set the channels 2 and 3 external current field if (this.CHANNELS_23_EXTERNAL_CURRENT != null) { this.channels23ExternalCurrent = this.metadataValuesMap.get(this.CHANNELS_23_EXTERNAL_CURRENT); logger.info("Channels 2 and 3 external current is: " + this.channels23ExternalCurrent); } // set the logging status field if (this.LOGGING_STATUS != null) { this.loggingStatus = this.metadataValuesMap.get(this.LOGGING_STATUS); logger.info("Logging status is: " + this.loggingStatus); } // set the number of scans to average field if (this.NUMBER_OF_SCANS_TO_AVERAGE != null) { this.numberOfScansToAverage = this.metadataValuesMap.get(this.NUMBER_OF_SCANS_TO_AVERAGE); logger.info("Number of scans to average is: " + this.numberOfScansToAverage); } // set the number of samples field if (this.NUMBER_OF_SAMPLES != null) { this.numberOfSamples = this.metadataValuesMap.get(this.NUMBER_OF_SAMPLES); logger.info("Number of samples is: " + this.numberOfSamples); } // set the number of available samples field if (this.NUMBER_OF_AVAILABLE_SAMPLES != null) { this.numberOfAvailableSamples = this.metadataValuesMap.get(this.NUMBER_OF_AVAILABLE_SAMPLES); logger.info("Number of available samples is: " + this.numberOfAvailableSamples); } // set the sample interval field if (this.SAMPLE_INTERVAL != null) { this.sampleInterval = this.metadataValuesMap.get(this.SAMPLE_INTERVAL); logger.info("Sample interval is: " + this.sampleInterval); } // set the measurements per sample field if (this.MEASUREMENTS_PER_SAMPLE != null) { this.measurementsPerSample = this.metadataValuesMap.get(this.MEASUREMENTS_PER_SAMPLE); logger.info("Measurements per sample is: " + this.measurementsPerSample); } // set the transmit real time field if (this.TRANSMIT_REALTIME != null) { this.transmitRealtime = this.metadataValuesMap.get(this.TRANSMIT_REALTIME); logger.info("Transmit real time state is: " + this.transmitRealtime); } // set the number of casts field if (this.NUMBER_OF_CASTS != null) { this.numberOfCasts = this.metadataValuesMap.get(this.NUMBER_OF_CASTS); logger.info("Number of casts is: " + this.numberOfCasts); } // set the minimum conductivity frequency field if (this.MINIMUM_CONDUCTIVITY_FREQUENCY != null) { this.minimumConductivityFrequency = this.metadataValuesMap.get(this.MINIMUM_CONDUCTIVITY_FREQUENCY); logger.info("Minimum conductivity frequency is: " + this.minimumConductivityFrequency); } // set the pump delay field if (this.PUMP_DELAY != null) { this.pumpDelay = this.metadataValuesMap.get(this.PUMP_DELAY); logger.info("Pump delay is: " + this.pumpDelay); } // set the automatic logging field if (this.AUTOMATIC_LOGGING != null) { this.automaticLogging = this.metadataValuesMap.get(this.AUTOMATIC_LOGGING); logger.info("Automatic logging is: " + this.automaticLogging); } // set the ignore magnetic switch field if (this.IGNORE_MAGNETIC_SWITCH != null) { this.ignoreMagneticSwitch = this.metadataValuesMap.get(this.IGNORE_MAGNETIC_SWITCH); logger.info("Ignore magnetic switch is: " + this.ignoreMagneticSwitch); } // set the battery type field if (this.BATTERY_TYPE != null) { this.batteryType = this.metadataValuesMap.get(this.BATTERY_TYPE); logger.info("Battery type is: " + this.batteryType); } // set the echo commands field if (this.ECHO_COMMANDS != null) { this.echoCommands = this.metadataValuesMap.get(this.ECHO_COMMANDS); logger.info("Echo commands state is: " + this.echoCommands); } // set the temperature calibration date field if (this.TEMPERATURE_CALIBRATION_DATE != null) { this.temperatureCalibrationDate = this.metadataValuesMap.get(this.TEMPERATURE_CALIBRATION_DATE); logger.info("Temperature calibration date is: " + this.temperatureCalibrationDate); } // set the temperature coefficient TA0 field if (this.TEMPERATURE_COEFFICIENT_TA0 != null) { this.temperatureCoefficientTA0 = this.metadataValuesMap.get(this.TEMPERATURE_COEFFICIENT_TA0); logger.info("Temperature coefficient TA0 is: " + this.temperatureCoefficientTA0); } // set the temperature coefficient TA1 field if (this.TEMPERATURE_COEFFICIENT_TA1 != null) { this.temperatureCoefficientTA1 = this.metadataValuesMap.get(this.TEMPERATURE_COEFFICIENT_TA1); logger.info("Temperature coefficient TA1 is: " + this.temperatureCoefficientTA1); } // set the temperature coefficient TA2 field if (this.TEMPERATURE_COEFFICIENT_TA2 != null) { this.temperatureCoefficientTA2 = this.metadataValuesMap.get(this.TEMPERATURE_COEFFICIENT_TA2); logger.info("Temperature coefficient TA2 is: " + this.temperatureCoefficientTA2); } // set the temperature coefficient TA3 field if (this.TEMPERATURE_COEFFICIENT_TA3 != null) { this.temperatureCoefficientTA3 = this.metadataValuesMap.get(this.TEMPERATURE_COEFFICIENT_TA3); logger.info("Temperature coefficient TA3 is: " + this.temperatureCoefficientTA3); } // set the temperature offset coefficient field if (this.TEMPERATURE_OFFSET_COEFFICIENT != null) { this.temperatureOffsetCoefficient = this.metadataValuesMap.get(this.TEMPERATURE_OFFSET_COEFFICIENT); logger.info("Temperature offset coefficient is: " + this.temperatureOffsetCoefficient); } // set the conductivity calibration date field if (this.CONDUCTIVITY_CALIBRATION_DATE != null) { this.conductivityCalibrationDate = this.metadataValuesMap.get(this.CONDUCTIVITY_CALIBRATION_DATE); logger.info("Conductivity calibration date is: " + this.conductivityCalibrationDate); } // set the conductivity coefficient G field if (this.CONDUCTIVITY_COEFFICIENT_G != null) { this.conductivityCoefficientG = this.metadataValuesMap.get(this.CONDUCTIVITY_COEFFICIENT_G); logger.info("Conductivity coefficient G is: " + this.conductivityCoefficientG); } // set the conductivity coefficient H field if (this.CONDUCTIVITY_COEFFICIENT_H != null) { this.conductivityCoefficientH = this.metadataValuesMap.get(this.CONDUCTIVITY_COEFFICIENT_H); logger.info("Conductivity coefficient H is: " + this.conductivityCoefficientH); } // set the conductivity coefficient I field if (this.CONDUCTIVITY_COEFFICIENT_I != null) { this.conductivityCoefficientI = this.metadataValuesMap.get(this.CONDUCTIVITY_COEFFICIENT_I); logger.info("Conductivity coefficient I is: " + this.conductivityCoefficientI); } // set the conductivity coefficient J field if (this.CONDUCTIVITY_COEFFICIENT_J != null) { this.conductivityCoefficientJ = this.metadataValuesMap.get(this.CONDUCTIVITY_COEFFICIENT_J); logger.info("Conductivity coefficient J is: " + this.conductivityCoefficientJ); } // set the conductivity coefficient CF0 field if (this.CONDUCTIVITY_COEFFICIENT_CF0 != null) { this.conductivityCoefficientCF0 = this.metadataValuesMap.get(this.CONDUCTIVITY_COEFFICIENT_CF0); logger.info("Conductivity coefficient CF0 is: " + this.conductivityCoefficientCF0); } // set the conductivity coefficient CPCOR field if (this.CONDUCTIVITY_COEFFICIENT_CPCOR != null) { this.conductivityCoefficientCPCOR = this.metadataValuesMap.get(this.CONDUCTIVITY_COEFFICIENT_CPCOR); logger.info("Conductivity coefficient CPCOR is: " + this.conductivityCoefficientCPCOR); } // set the conductivity coefficient CTCOR field if (this.CONDUCTIVITY_COEFFICIENT_CTCOR != null) { this.conductivityCoefficientCTCOR = this.metadataValuesMap.get(this.CONDUCTIVITY_COEFFICIENT_CTCOR); logger.info("Conductivity coefficient CTCOR is: " + this.conductivityCoefficientCTCOR); } // set the conductivity coefficient CSLOPE field if (this.CONDUCTIVITY_COEFFICIENT_CSLOPE != null) { this.conductivityCoefficientCSLOPE = this.metadataValuesMap.get(this.CONDUCTIVITY_COEFFICIENT_CSLOPE); logger.info("Conductivity coefficient CSLOPE is: " + this.conductivityCoefficientCSLOPE); } // set the pressure serial number field if (this.PRESSURE_SERIAL_NUMBER != null) { this.pressureSerialNumber = this.metadataValuesMap.get(this.PRESSURE_SERIAL_NUMBER); logger.info("Pressure serial number is: " + this.pressureSerialNumber); } // set the pressure coefficient PA0 field if (this.PRESSURE_COEFFICIENT_PA0 != null) { this.pressureCoefficientPA0 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PA0); logger.info("Pressure coefficient PA0 is: " + this.pressureCoefficientPA0); } // set the pressure coefficient PA1 field if (this.PRESSURE_COEFFICIENT_PA1 != null) { this.pressureCoefficientPA1 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PA1); logger.info("Pressure coefficient PA1 is: " + this.pressureCoefficientPA1); } // set the pressure coefficient PA2 field if (this.PRESSURE_COEFFICIENT_PA2 != null) { this.pressureCoefficientPA2 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PA2); logger.info("Pressure coefficient PA2 is: " + this.pressureCoefficientPA2); } // set the pressure coefficient PTCA0 field if (this.PRESSURE_COEFFICIENT_PTCA0 != null) { this.pressureCoefficientPTCA0 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PTCA0); logger.info("Pressure coefficient PTCA0 is: " + this.pressureCoefficientPTCA0); } // set the pressure coefficient PTCA1 field if (this.PRESSURE_COEFFICIENT_PTCA1 != null) { this.pressureCoefficientPTCA1 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PTCA1); logger.info("Pressure coefficient PTCA1 is: " + this.pressureCoefficientPTCA1); } // set the pressure coefficient PTCA2 field if (this.PRESSURE_COEFFICIENT_PTCA2 != null) { this.pressureCoefficientPTCA2 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PTCA2); logger.info("Pressure coefficient PTCA2 is: " + this.pressureCoefficientPTCA2); } // set the pressure coefficient PTCB0 field if (this.PRESSURE_COEFFICIENT_PTCB0 != null) { this.pressureCoefficientPTCB0 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PTCB0); logger.info("Pressure coefficient PTCB0 is: " + this.pressureCoefficientPTCB0); } // set the pressure coefficient PTCB1 field if (this.PRESSURE_COEFFICIENT_PTCB1 != null) { this.pressureCoefficientPTCB1 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PTCB1); logger.info("Pressure coefficient PTCB1 is: " + this.pressureCoefficientPTCB1); } // set the pressure coefficient PTCB2 field if (this.PRESSURE_COEFFICIENT_PTCB2 != null) { this.pressureCoefficientPTCB2 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PTCB2); logger.info("Pressure coefficient PTCB2 is: " + this.pressureCoefficientPTCB2); } // set the pressure coefficient PTEMPA0 field if (this.PRESSURE_COEFFICIENT_PTEMPA0 != null) { this.pressureCoefficientPTEMPA0 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PTEMPA0); logger.info("Pressure coefficient PTEMPA0 is: " + this.pressureCoefficientPTEMPA0); } // set the pressure coefficient PTEMPA1 field if (this.PRESSURE_COEFFICIENT_PTEMPA1 != null) { this.pressureCoefficientPTEMPA1 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PTEMPA1); logger.info("Pressure coefficient PTEMPA1 is: " + this.pressureCoefficientPTEMPA1); } // set the pressure coefficient PTEMPA2 field if (this.PRESSURE_COEFFICIENT_PTEMPA2 != null) { this.pressureCoefficientPTEMPA2 = this.metadataValuesMap.get(this.PRESSURE_COEFFICIENT_PTEMPA2); logger.info("Pressure coefficient PTEMPA2 is: " + this.pressureCoefficientPTEMPA2); } // set the pressure offset coefficient field if (this.PRESSURE_OFFSET_COEFFICIENT != null) { this.pressureOffsetCoefficient = this.metadataValuesMap.get(this.PRESSURE_OFFSET_COEFFICIENT); logger.info("Pressure offset coefficient is: " + this.pressureOffsetCoefficient); } }
From source file:io.warp10.continuum.gts.GTSHelper.java
public static GTSEncoder parse_regexp(GTSEncoder encoder, String str, Map<String, String> extraLabels) throws ParseException, IOException { Matcher matcher = MEASUREMENT_RE.matcher(str); if (!matcher.matches()) { throw new ParseException(str, 0); }//w w w .ja va2 s . c om // // Check name // String name = matcher.group(6); if (name.contains("%")) { try { name = URLDecoder.decode(name, "UTF-8"); } catch (UnsupportedEncodingException uee) { // Can't happen, we're using UTF-8 } } // // Parse labels // Map<String, String> labels = parseLabels(matcher.group(7)); // // Add any provided extra labels // if (null != extraLabels) { labels.putAll(extraLabels); } // // Extract timestamp, optional location and elevation // long timestamp; long location = GeoTimeSerie.NO_LOCATION; long elevation = GeoTimeSerie.NO_ELEVATION; try { if (null != matcher.group(1)) { //timestamp = Long.valueOf(matcher.group(1)); timestamp = Long.parseLong(matcher.group(1)); } else { // No timestamp provided, use 'now' timestamp = TimeSource.getTime(); ; } if (null != matcher.group(2)) { //location = GeoXPLib.toGeoXPPoint(Double.valueOf(matcher.group(3)), Double.valueOf(matcher.group(4))); location = GeoXPLib.toGeoXPPoint(Double.parseDouble(matcher.group(3)), Double.parseDouble(matcher.group(4))); } if (null != matcher.group(5)) { //elevation = Long.valueOf(matcher.group(5)); elevation = Long.parseLong(matcher.group(5)); } } catch (NumberFormatException nfe) { throw new ParseException("", 0); } // // Extract value // String valuestr = matcher.group(8); Object value = parseValue_regexp(valuestr); if (null == value) { throw new ParseException("Unable to parse value '" + valuestr + "'", 0); } // Allocate a new Encoder if need be, with a base timestamp of 0L. if (null == encoder || !name.equals(encoder.getName()) || !labels.equals(encoder.getLabels())) { encoder = new GTSEncoder(0L); encoder.setName(name); encoder.setLabels(labels); } encoder.addValue(timestamp, location, elevation, value); /* GeoTimeSerie gts = new GeoTimeSerie(1); gts.setName(name); gts.setLabels(labels); GTSHelper.setValue(gts, timestamp, location, elevation, value, false); return gts; */ return encoder; }
From source file:io.warp10.continuum.gts.GTSHelper.java
public static GTSEncoder parseJSON(GTSEncoder encoder, String str, Map<String, String> extraLabels, Long now) throws IOException, ParseException { JsonParser parser = jpf.createFastParser(); //Gson gson = new Gson(); //Map<String,Object> o = gson.fromJson(str, GSON_MAP_TYPE); Map<String, Object> o = (Map<String, Object>) parser.parse(str); String name = (String) o.get("c"); Map<String, String> labels = (Map<String, String>) o.get("l"); ////w w w .j a va2 s .c o m // Add any provided extra labels // if (null != extraLabels) { labels.putAll(extraLabels); // // Remove labels with null values // // FIXME(hbs): may be removed when dummy tokens have disappeared // if (extraLabels.containsValue(null)) { Set<Entry<String, String>> entries = extraLabels.entrySet(); while (labels.containsValue(null)) { for (Entry<String, String> entry : entries) { if (null == entry.getValue()) { labels.remove(entry.getKey()); } } } } } Object ots = o.get("t"); long ts = (null != ots ? ((Number) ots).longValue() : (null != now ? (long) now : TimeSource.getTime())); long location = GeoTimeSerie.NO_LOCATION; if (o.containsKey("lat") && o.containsKey("lon")) { double lat = (double) o.get("lat"); double lon = (double) o.get("lon"); location = GeoXPLib.toGeoXPPoint(lat, lon); } long elevation = GeoTimeSerie.NO_ELEVATION; if (o.containsKey("elev")) { elevation = ((Number) o.get("elev")).longValue(); } Object v = o.get("v"); // Allocate a new Encoder if need be, with a base timestamp of 0L. if (null == encoder || !name.equals(encoder.getName()) || !labels.equals(encoder.getLabels())) { encoder = new GTSEncoder(0L); encoder.setName(name); encoder.setLabels(labels); } if (v instanceof Long || v instanceof Integer || v instanceof Short || v instanceof Byte || v instanceof BigInteger) { encoder.addValue(ts, location, elevation, ((Number) v).longValue()); } else if (v instanceof Double || v instanceof Float) { encoder.addValue(ts, location, elevation, ((Number) v).doubleValue()); } else if (v instanceof BigDecimal) { encoder.addValue(ts, location, elevation, v); } else if (v instanceof Boolean || v instanceof String) { encoder.addValue(ts, location, elevation, v); } else { throw new ParseException("Invalid value.", 0); } return encoder; }
From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java
/** * @param rootTable//from ww w .j a va2 s. c o m * @param distinct * @param qfps * @param tblTree * @param keysToRetrieve * @return HQLSpecs for the current fields and settings. */ public static HQLSpecs buildHQL(final TableQRI rootTable, final boolean distinct, final Vector<QueryFieldPanel> qfps, final TableTree tblTree, final RecordSetIFace keysToRetrieve, final boolean searchSynonymy, final boolean isSchemaExport, final Timestamp lastExportTime, final boolean disjunct) throws ParseException { if (qfps.size() == 0) return null; if (keysToRetrieve != null && keysToRetrieve.getNumItems() == 0) return null; StringBuilder fieldsStr = new StringBuilder(); Vector<BaseQRI> list = new Vector<BaseQRI>(); StringBuilder criteriaStr = new StringBuilder(); StringBuilder orderStr = new StringBuilder(); LinkedList<SortElement> sortElements = new LinkedList<SortElement>(); boolean postSortPresent = false; boolean debug = false; ProcessNode root = new ProcessNode(); int fldPosition = distinct ? 0 : 1; for (QueryFieldPanel qfi : qfps) { if (qfi.getFieldQRI() == null) { continue; } qfi.updateQueryField(); if (qfi.isForDisplay()) { fldPosition++; } if (debug) { log.debug("\nNode: " + qfi.getFieldName()); } SortElement orderSpec = qfi.getOrderSpec(distinct ? fldPosition - 1 : fldPosition - 2); if (orderSpec != null) { boolean isPostSortSpec = qfi.getFieldQRI() instanceof TreeLevelQRI || qfi.getFieldQRI() instanceof RelQRI; //dis regard post sorts that may have been saved before //fix for bug #9407 if (!isSchemaExport) { postSortPresent |= isPostSortSpec; } if (!isPostSortSpec || !isSchemaExport) { sortElements.add(orderSpec); } } // Create a Stack (list) of parent from // the current node up to the top // basically we are creating a path of nodes // to determine if we need to create a new node in the tree list.clear(); FieldQRI pqri = qfi.getFieldQRI(); TableTree parent = pqri.getTableTree(); if (qfi.isForDisplay() || qfi.hasCriteria() || orderSpec != null || pqri instanceof RelQRI) { boolean addToList = true; if (pqri instanceof RelQRI) { RelQRI relQRI = (RelQRI) pqri; RelationshipType relType = relQRI.getRelationshipInfo().getType(); // XXX Formatter.getSingleField() checks for ZeroOrOne and // OneToOne rels. if (!relType.equals(RelationshipType.ManyToOne) && !relType.equals(RelationshipType.ManyToMany)/* * treat * manytomany * as * onetomany */) // Maybe // need // to // consider // some // types // of // OneToOne // also????????? { parent = parent.getParent(); if (isSchemaExport && lastExportTime != null) { addToList = true; } else { // parent will initially point to the related table // and don't need to add related table unless it has // children displayed/queried, addToList = false; } } else { DataObjDataFieldFormatIFace formatter = relQRI.getDataObjFormatter(qfi.getFormatName()); if (formatter != null) { boolean isSingleSimpleFormat = formatter.getSingleField() != null && formatter.getFields()[0].getSep() == null; addToList = isSingleSimpleFormat || (isSchemaExport && lastExportTime != null); } else { addToList = false; } } } if (addToList) { list.insertElementAt(pqri, 0); } while (parent != tblTree) { list.insertElementAt(parent.getTableQRI(), 0); parent = parent.getParent(); } if (debug) { log.debug("Path From Top Down:"); for (BaseQRI qri : list) { log.debug(" " + qri.getTitle()); } } // Now walk the stack top (the top most parent) // down and if the path form the top down doesn't // exist then add a new node ProcessNode parentNode = root; int q = 0; for (BaseQRI qri : list) { if (debug) { log.debug("ProcessNode[" + qri.getTitle() + "]"); } q++; if (!parentNode.contains(qri) && (qri instanceof TableQRI || q == list.size())) { ProcessNode newNode = new ProcessNode(qri); parentNode.getKids().add(newNode); if (debug) { log.debug("Adding new node[" + newNode.getQri().getTitle() + "] to Node[" + (parentNode.getQri() == null ? "root" : parentNode.getQri().getTitle()) + "]"); } parentNode = newNode; } else { for (ProcessNode kidNode : parentNode.getKids()) { if (kidNode.getQri().equals(qri)) { parentNode = kidNode; break; } } } } if (debug) { log.debug("Current Tree:"); printTree(root, 0); } } } if (debug) { printTree(root, 0); } StringBuilder fromStr = new StringBuilder(); TableAbbreviator tableAbbreviator = new TableAbbreviator(); List<Pair<DBTableInfo, String>> fromTbls = new LinkedList<Pair<DBTableInfo, String>>(); boolean hqlHasSynJoins = processTree(root, fromStr, fromTbls, 0, tableAbbreviator, tblTree, qfps, searchSynonymy, isSchemaExport, lastExportTime); StringBuilder sqlStr = new StringBuilder(); sqlStr.append("select "); //if (distinct /*|| hqlHasSynJoins*/) { sqlStr.append("distinct "); } if (!distinct) { fieldsStr.append(tableAbbreviator.getAbbreviation(rootTable.getTableTree())); fieldsStr.append("."); fieldsStr.append(rootTable.getTableInfo().getIdFieldName()); } List<Pair<String, Object>> paramsToSet = new LinkedList<Pair<String, Object>>(); boolean visibleFldExists = false; for (QueryFieldPanel qfi : qfps) { if (qfi.getFieldQRI() == null) { continue; } if (qfi.isForDisplay()) { visibleFldExists = true; String fldSpec = qfi.getFieldQRI().getSQLFldSpec(tableAbbreviator, false, isSchemaExport, qfi.getFormatName()); if (StringUtils.isNotEmpty(fldSpec)) { if (fieldsStr.length() > 0) { fieldsStr.append(", "); } fieldsStr.append(fldSpec); } } if (keysToRetrieve == null || qfi.isEnforced()) { String criteria = qfi.getCriteriaFormula(tableAbbreviator, paramsToSet); boolean isDisplayOnly = StringUtils.isEmpty(criteria); if (!isDisplayOnly) { if (criteria.equals("2+2=2") && qfi.isNegated()) { criteria = ""; } if (criteria.length() > 0 && hqlHasSynJoins && isSynSearchable(qfi.getFieldQRI()) && !qfi.isEmptyCriterion()) { criteria = adjustForSynSearch( tableAbbreviator.getAbbreviation(qfi.getFieldQRI().getTable().getTableTree()), criteria, qfi.isNegated()); } if (!isDisplayOnly && criteriaStr.length() > 0 && criteria.length() > 0) { criteriaStr.append(disjunct ? " OR " : " AND "); } criteriaStr.append(criteria); } } } if (!visibleFldExists) { throw new ParseException(getResourceString("QueryBldrPane.NoVisibleColumns"), -1); } sqlStr.append(fieldsStr); sqlStr.append(" from "); sqlStr.append(fromStr); if (keysToRetrieve != null) { if (!StringUtils.isEmpty(criteriaStr.toString())) { criteriaStr.append(" and "); } criteriaStr.append("("); criteriaStr.append(tableAbbreviator.getAbbreviation(rootTable.getTableTree()) + "." + rootTable.getTableInfo().getIdFieldName() + " in("); boolean comma = false; int maxInClauseLen = 2500; int inClauseLen = 0; for (RecordSetItemIFace item : keysToRetrieve.getOrderedItems()) { if (inClauseLen == maxInClauseLen) { criteriaStr.append(") or "); criteriaStr.append(tableAbbreviator.getAbbreviation(rootTable.getTableTree()) + "." + rootTable.getTableInfo().getIdFieldName() + " in("); inClauseLen = 0; } else if (comma) { criteriaStr.append(","); } else { comma = true; } criteriaStr.append(item.getRecordId()); inClauseLen++; } criteriaStr.append("))"); } else { //Assuming that this not necessary when keysToRetrieve is non-null because //the keys will already been filtered properly. (???) // Add extra where's for system fields for root table only, see notes below at end of for block boolean isRootTbl = true; for (Pair<DBTableInfo, String> fromTbl : fromTbls) { String specialColumnWhere = null; if (fromTbl.getFirst().getTableId() == Attachment.getClassTableId()) { String prefix = fromTbl.getSecond() + "."; specialColumnWhere = "((" + prefix + "scopeType = 0 and " + prefix + "scopeID = " + AppContextMgr.getInstance() .getClassObject(edu.ku.brc.specify.datamodel.Collection.class).getCollectionId() + ") or" + "(" + prefix + "scopeType = 1 and " + prefix + "scopeID = " + AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId() + ") or" + "(" + prefix + "scopeType = 2 and " + prefix + "scopeID = " + AppContextMgr.getInstance().getClassObject(Division.class).getDivisionId() + ") or" + "(" + prefix + "scopeType = 3 and " + prefix + "scopeID = " + AppContextMgr.getInstance().getClassObject(Institution.class).getInstitutionId() + "))"; } else { specialColumnWhere = QueryAdjusterForDomain.getInstance().getSpecialColumns(fromTbl.getFirst(), true, !isRootTbl && true/* XXX should only use left join when necessary */, fromTbl.getSecond()); } isRootTbl = false; if (StringUtils.isNotEmpty(specialColumnWhere)) { if (criteriaStr.length() > 0) { criteriaStr.append(" AND "); } criteriaStr.append(specialColumnWhere); } //Actually, assuming data is valid, it should only be necessary to add the Adjustments for the root table? //XXX if this works, fix this loop. Also, join parameter code in getSpecialColumns will probably be irrelevant. break; } //...done adding system whereses //get only records modified/added since last export of the schema... if (isSchemaExport && lastExportTime != null) { if (criteriaStr.length() > 0) { criteriaStr.append(" AND ("); } String timestampParam = "spparam" + paramsToSet.size(); paramsToSet.add(new Pair<String, Object>(timestampParam, lastExportTime)); criteriaStr.append(getTimestampWhere(fromTbls, timestampParam, lastExportTime)); criteriaStr.append(") "); } } if (criteriaStr.length() > 0) { sqlStr.append(" where "); sqlStr.append(criteriaStr); } if (sortElements.size() > 0 && !postSortPresent) { for (SortElement se : sortElements) { if (!StringUtils.isEmpty(orderStr.toString())) { orderStr.append(", "); } orderStr.append(distinct ? se.getColumn() + 1 : se.getColumn() + 2); if (se.getDirection() == SortElement.DESCENDING) { orderStr.append(" DESC"); } } sortElements.clear(); } if (orderStr.length() > 0) { sqlStr.append(" order by "); sqlStr.append(orderStr); } if (debug) { log.debug(sqlStr.toString()); log.debug("sort:"); for (SortElement s : sortElements) { log.debug(" " + s.getColumn() + " - " + s.getDirection()); } } String result = sqlStr.toString(); if (!checkHQL(result)) return null; log.info(result); return new HQLSpecs(result, paramsToSet, sortElements, hqlHasSynJoins); }
From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.UploadTable.java
/** * @param fld//w w w. ja va2 s .c om * @return values of the correct class for fld's setter. * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws ParseException * * Converts fld's string value to the correct class for the field being uploaded to. */ protected Object[] getArgForSetter(final UploadField ufld) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, UploaderException { try { Object arg[] = new Object[1]; Class<?> fldClass; // if (tblClass.equals(DeterminationStatus.class) && ufld.getField().getName().equalsIgnoreCase("type")) // { // fldClass = Boolean.class; // } // else { fldClass = ufld.getSetter().getParameterTypes()[0]; } String fldStr; if (ufld.getValueObject() == null) { fldStr = null; } else { fldStr = fldClass.equals(String.class) ? ufld.getValueObject() : ufld.getValueObject().trim(); } if (fldClass == java.util.Calendar.class || fldClass == java.util.Date.class) { // There are problems with DateConverter (see DateConverter) if (fldStr == null || fldStr.equals("")) { arg[0] = null; } else { if (isDateWithPrecision(ufld.getField().getFieldInfo())) { fldStr = dateConverter.adjustForPrecision(fldStr); } else { //need to do this because even with lenient = false, Calendar.parse //will still interpret '00/Jun/2004' as '31/May/2004'. try { UIFieldFormatterIFace.PartialDateEnum prec = dateConverter.getDatePrecision(fldStr); if (prec.equals(UIFieldFormatterIFace.PartialDateEnum.Month) || prec.equals(UIFieldFormatterIFace.PartialDateEnum.Year)) { ParseException pex = new ParseException( UIRegistry.getResourceString("WB_UPLOAD_INVALID_FORMAT"), 0); throw new UploaderException(pex, UploaderException.INVALID_DATA); } } catch (ParseException pex) { //ignore. Problem should get caught in dateConverter.convert call below. } } arg[0] = dateConverter.convert(fldStr); } } else if (fldClass == BigDecimal.class) { if (fldStr == null || fldStr.equals("")) { arg[0] = null; } else { if (!isLatLongFld(ufld)) { if (!ufld.checkPrecisionAndScale(fldStr)) { //System.out.println("bam"); throw new UploaderException( String.format(getResourceString("WB_UPLOAD_INVALID_PREC_SCALE"), ufld.getPrecision() - ufld.getScale(), ufld.getScale()), UploaderException.INVALID_DATA); } } else { boolean gotANumber = UIHelper.parseDoubleToBigDecimal(fldStr) != null; if (!gotANumber) { try { fldStr = geoRefConverter.convert(StringUtils.stripToNull(fldStr), GeoRefFormat.D_PLUS_MINUS.name()); } catch (Exception ex) { throw new UploaderException(ex, UploaderException.INVALID_DATA); } } } BigDecimal val = UIHelper.parseDoubleToBigDecimal(fldStr); if (StringUtils.isNotEmpty(fldStr) && val == null) { throw new UploaderException(UIRegistry.getResourceString("WB_UPLOAD_INVALID_FORMAT"), UploaderException.INVALID_DATA); } if (isLatLongFld(ufld)) { Double maxVal = isLatFld(ufld) ? new Double("90") : new Double("180"); if (Math.abs(val.doubleValue()) > maxVal) { throw new UploaderException(getResourceString("WB_UPLOAD_INVALID_GEOREF_VALUE"), UploaderException.INVALID_DATA); } } arg[0] = val; } } else if (fldClass == Boolean.class) { if (fldStr == null || fldStr.equals("")) { arg[0] = null; } else { int i; for (i = 0; i < WorkbenchTask.boolStrings.length; i++) { if (fldStr.equalsIgnoreCase(WorkbenchTask.boolStrings[i])) break; } if (i == WorkbenchTask.boolStrings.length) { throw new UploaderException(getResourceString("WB_INVALID_BOOL_CELL_VALUE"), UploaderException.INVALID_DATA); } arg[0] = i % 2 == 0 ? true : false; } //grotesquery //sorry, too much extra processing involved with maintaining one and only one current determination //to mess around with the isCurrent workbench mapping. An uploaded co is current or not current. // if (tblClass.equals(DeterminationStatus.class) // && ufld.getField().getName().equalsIgnoreCase("type")) // { // if (arg[0] == null) { throw new UploaderException( // getResourceString("WB_INVALID_BOOL_CELL_VALUE"), // UploaderException.INVALID_DATA); } // Boolean c = (Boolean) arg[0]; // if (c) // { // arg[0] = DeterminationStatus.CURRENT; // } // else // { // arg[0] = DeterminationStatus.NOTCURRENT; // } // } } else if (fldClass != String.class) { Class<?> stringArg[] = new Class<?>[1]; stringArg[0] = String.class; Method converter = fldClass.getMethod("valueOf", stringArg); Object converterArg[] = new Object[1]; converterArg[0] = fldStr; if (converterArg[0] != null) { arg[0] = converter.invoke(fldClass, converterArg); } else { arg[0] = null; } } else { UIFieldFormatterIFace formatter = ufld.getField().getFieldInfo().getFormatter(); if (StringUtils.isBlank(fldStr) && (formatter == null || !formatter.isIncrementer()/* || !formatter.isNumeric()*/)) { arg[0] = null; } else { Object val = fldStr; if (ufld.getField().getFieldInfo() != null) { if (formatter != null) { if (isUploadRoot && StringUtils.isBlank(fldStr) && formatter.isIncrementer() && ufld.isAutoAssignForUpload()) { if (!this.validatingValues || autoAssignedVal == null) { if (autoAssignedVal == null) { if (prevAutoAssignedVal != null) { val = formatter.getNextNumber(formatter .formatFromUI(prevAutoAssignedVal.toString()).toString(), true); } else { val = formatter.getNextNumber(formatter.formatToUI("").toString()); } // XXX timo - Need to check here for a null return value. autoAssignedVal = formatter.formatToUI(val); prevAutoAssignedVal = autoAssignedVal; } else if (!this.validatingValues) { val = formatter.formatFromUI(autoAssignedVal); } } if (autoAssignedField == null) { autoAssignedField = ufld; } } else { if (StringUtils.isBlank(fldStr)) { if (ufld.isAutoAssignable()) { val = formatter.getNextNumber(formatter.formatToUI("").toString()); } else { val = null; } } else { val = formatter.formatFromUI(fldStr); if (!formatter.isValid((String) val)) { throw new UploaderException( UIRegistry.getResourceString("WB_UPLOAD_INVALID_FORMAT"), UploaderException.INVALID_DATA); } } } } } arg[0] = val; } } return arg; } catch (IllegalArgumentException ex) { throw new UploaderException(ex, UploaderException.INVALID_DATA); } catch (ParseException ex) { throw new UploaderException(ex, UploaderException.INVALID_DATA); } }
From source file:io.warp10.continuum.gts.GTSHelper.java
public static GTSEncoder parse(GTSEncoder encoder, String str, Map<String, String> extraLabels, Long now, long maxValueSize, boolean parseAttributes) throws ParseException, IOException { int idx = 0;//w w w . ja va2 s .co m int tsoffset = 0; if ('=' == str.charAt(0)) { if (null == encoder) { throw new ParseException("Invalid continuation.", 0); } tsoffset = 1; } //idx = str.indexOf("/"); idx = UnsafeString.indexOf(str, '/'); if (-1 == idx) { throw new ParseException("Missing timestamp separator.", idx); } long timestamp; if (tsoffset == idx) { // No timestamp provided, use 'now' timestamp = null != now ? (long) now : TimeSource.getTime(); } else { if ('T' == str.charAt(tsoffset)) { // Support T-XXX to record timestamps which are relative to 'now', useful for // devices with no time reference but only relative timestamps //timestamp = (null != now ? (long) now : TimeSource.getTime()) + Long.valueOf(str.substring(1 + tsoffset, idx)); timestamp = (null != now ? (long) now : TimeSource.getTime()) + Long.parseLong(str.substring(1 + tsoffset, idx)); } else { //timestamp = Long.valueOf(str.substring(tsoffset, idx)); timestamp = Long.parseLong(str.substring(tsoffset, idx)); } } // Advance past the '/' idx++; //int idx2 = str.indexOf("/", idx); int idx2 = UnsafeString.indexOf(str, '/', idx); if (-1 == idx2) { throw new ParseException("Missing location/elevation separator.", idx); } long location = GeoTimeSerie.NO_LOCATION; if (idx != idx2) { // We have a location (lat:lon) String latlon = str.substring(idx, idx2); // Advance past the second '/' idx = idx2 + 1; //idx2 = latlon.indexOf(":"); idx2 = UnsafeString.indexOf(latlon, ':'); //location = GeoXPLib.toGeoXPPoint(Double.valueOf(latlon.substring(0, idx2)), Double.valueOf(latlon.substring(idx2 + 1))); location = GeoXPLib.toGeoXPPoint(Double.parseDouble(latlon.substring(0, idx2)), Double.parseDouble(latlon.substring(idx2 + 1))); } else { // Advance past the second '/' idx = idx2 + 1; } //idx2 = str.indexOf(" ", idx); idx2 = UnsafeString.indexOf(str, ' ', idx); if (-1 == idx2) { throw new ParseException(str, idx); } long elevation = GeoTimeSerie.NO_ELEVATION; if (idx != idx2) { // We have an elevation //elevation = Long.valueOf(str.substring(idx, idx2)); elevation = Long.parseLong(str.substring(idx, idx2)); } // Advance past the ' ' idx = idx2 + 1; while (idx < str.length() && str.charAt(idx) == ' ') { idx++; } // If line started with '=', assume there is no class+labels component if (tsoffset > 0) { idx2 = -1; } else { //idx2 = str.indexOf("{", idx); idx2 = UnsafeString.indexOf(str, '{', idx); } String name = null; Map<String, String> labels = null; Map<String, String> attributes = null; boolean reuseLabels = false; if (-1 == idx2) { // If we are over the end of the string, we're missing a value if (idx >= str.length()) { throw new ParseException("Missing value", idx); } // No class+labels, assume same class+labels as those in encoder, except // if encoder is null in which case we throw a parse exception if (null == encoder) { throw new ParseException(str, idx); } name = encoder.getMetadata().getName(); labels = encoder.getMetadata().getLabels(); reuseLabels = true; } else { name = str.substring(idx, idx2); //if (name.contains("%")) { if (-1 != UnsafeString.indexOf(name, '%')) { try { name = URLDecoder.decode(name, "UTF-8"); } catch (UnsupportedEncodingException uee) { // Can't happen, we're using UTF-8 } } // Advance past the '{' idx = idx2 + 1; //idx2 = str.indexOf("}", idx); idx2 = UnsafeString.indexOf(str, '}', idx); if (-1 == idx2) { throw new ParseException(str, idx); } // // Parse labels // labels = parseLabels(null != extraLabels ? extraLabels.size() : 0, str.substring(idx, idx2)); // // FIXME(hbs): parse attributes???? // // Advance past the '}' and over spaces idx = idx2 + 1; // FIXME(hbs): should we skip over attributes if they are present? if (idx < str.length() && str.charAt(idx) == '{') { idx++; int attrstart = idx; while (idx < str.length() && str.charAt(idx) != '}') { idx++; } if (parseAttributes) { if (idx >= str.length()) { throw new ParseException("Missing attributes.", idx2); } attributes = parseLabels(str.substring(attrstart, idx)); } idx++; } while (idx < str.length() && str.charAt(idx) == ' ') { idx++; } if (idx >= str.length()) { throw new ParseException("Missing value.", idx2); } } // // Add any provided extra labels // // WARNING(hbs): as we check reuseLabels, note that extraLabels won't be pushed onto the GTS labels // if reuseLabels is 'true', this means that if you call parse on a continuation line with different extraLabels // than for previous lines, the new extra labels won't be set. But this is not something that should be done anyway, // so it should not be considered a problem... // if (!reuseLabels && null != extraLabels) { labels.putAll(extraLabels); // // Remove labels with null values // // FIXME(hbs): may be removed when dummy tokens have disappeared // if (extraLabels.containsValue(null)) { Set<Entry<String, String>> entries = extraLabels.entrySet(); while (labels.containsValue(null)) { for (Entry<String, String> entry : entries) { if (null == entry.getValue()) { labels.remove(entry.getKey()); } } } } } // // Extract value // String valuestr = str.substring(idx); if (valuestr.length() > maxValueSize) { throw new ParseException("Value too large at for GTS " + (null != encoder ? GTSHelper.buildSelector(encoder.getMetadata()) : ""), 0); } Object value = parseValue(valuestr); if (null == value) { throw new ParseException("Unable to parse value '" + valuestr + "'", 0); } // Allocate a new Encoder if need be, with a base timestamp of 0L. if (null == encoder || !name.equals(encoder.getName()) || !labels.equals(encoder.getMetadata().getLabels())) { encoder = new GTSEncoder(0L); encoder.setName(name); //encoder.setLabels(labels); encoder.getMetadata().setLabels(labels); if (null != attributes) { encoder.getMetadata().setAttributes(attributes); } } encoder.addValue(timestamp, location, elevation, value); return encoder; }
From source file:io.warp10.continuum.gts.GTSHelper.java
public static Object parseValue(String valuestr) throws ParseException { Object value;/* w w w . j a v a 2s . c om*/ try { if (('\'' == valuestr.charAt(0) && valuestr.endsWith("'")) || ('"' == valuestr.charAt(0) && valuestr.endsWith("\""))) { value = valuestr.substring(1, valuestr.length() - 1); if (((String) value).contains("%")) { try { value = URLDecoder.decode((String) value, "UTF-8"); } catch (UnsupportedEncodingException uee) { // Can't happen, we're using UTF-8 } } } else if ("t".equalsIgnoreCase(valuestr) || "true".equalsIgnoreCase(valuestr)) { value = Boolean.TRUE; } else if ("f".equalsIgnoreCase(valuestr) || "false".equalsIgnoreCase(valuestr)) { value = Boolean.FALSE; // // FIXME(hbs): add support for quaternions, for hex values??? // } else { boolean likelydouble = UnsafeString.isDouble(valuestr); if (!likelydouble) { //value = Long.valueOf(valuestr); value = Long.parseLong(valuestr); } else { // // If the double does not contain an 'E' or an 'N' or an 'n' (scientific notation or NaN or Infinity) // we use the following heuristic to determine if we should return a Double or a BigDecimal, // since we encode a mantissa of up to 46 bits, we will return a BigDecimal only if the size of the // input is <= 15 digits (log(46)/log(10) = 13.84 plus one digit for the dot plus one to tolerate values starting with low digits). // This will have the following caveats: // * leading or trailing 0s should be discarded, this heuristic won't do that // * negative values with 14 or more digits will be returned as Double, but we don't want to parse the // first char. // if (valuestr.length() <= 15 && UnsafeString.mayBeDecimalDouble(valuestr)) { value = new BigDecimal(valuestr); } else { value = Double.parseDouble(valuestr); } } } } catch (Exception e) { throw new ParseException(valuestr, 0); } return value; }
From source file:io.warp10.continuum.gts.GTSHelper.java
public static Object parseValue_regexp(String valuestr) throws ParseException { Object value;/*from www . j av a2 s.c o m*/ Matcher valuematcher = DOUBLE_VALUE_RE.matcher(valuestr); if (valuematcher.matches()) { // FIXME(hbs): maybe find a better heuristic to determine if we should // create a BigDecimal or a Double. BigDecimal is only meaningful if its encoding // will be less than 8 bytes. //value = Double.valueOf(valuestr); if (valuematcher.group(1).length() < 10 && valuematcher.group(2).length() < 10) { value = new BigDecimal(valuestr); } else { //value = Double.valueOf(valuestr); value = Double.parseDouble(valuestr); } } else { valuematcher = LONG_VALUE_RE.matcher(valuestr); if (valuematcher.matches()) { //value = Long.valueOf(valuestr); value = Long.parseLong(valuestr); } else { valuematcher = STRING_VALUE_RE.matcher(valuestr); if (valuematcher.matches()) { value = valuestr.substring(1, valuestr.length() - 1); } else { valuematcher = BOOLEAN_VALUE_RE.matcher(valuestr); if (valuematcher.matches()) { if ('t' == valuestr.charAt(0) || 'T' == valuestr.charAt(0)) { value = Boolean.TRUE; } else { value = Boolean.FALSE; } } else { throw new ParseException(valuestr, 0); } } } } return value; }
From source file:io.warp10.continuum.gts.GTSHelper.java
/** * Parses the string representation of labels. * The representation is composed of name=value pairs separated by commas (','). * Values are expected to be UTF-8 strings percent-encoded. * //from ww w . j a v a 2s .c o m * @param str * @return * @throws InvalidFormatException if a label name is incorrect. */ public static Map<String, String> parseLabels(int initialCapacity, String str) throws ParseException { // // Parse as selectors. We'll throw an exception if we encounter a regexp selector // Map<String, String> selectors = parseLabelsSelectors(str); Map<String, String> labels = new HashMap<String, String>(selectors.size() + initialCapacity); for (Entry<String, String> entry : selectors.entrySet()) { // // Check that selector is an exact match which would means // the syntax was label=value // if ('=' != entry.getValue().charAt(0)) { throw new ParseException(entry.getValue(), 0); } labels.put(entry.getKey(), entry.getValue().substring(1)); } return labels; }
From source file:hudson.model.Hudson.java
/** * Check if the given name is suitable as a name * for job, view, etc./*from w ww .j av a2s . c o m*/ * * @throws ParseException * if the given name is not good */ public static void checkGoodName(String name) throws ParseException { if (name == null || name.length() == 0) throw new ParseException(Messages.Hudson_NoName(), 0); for (int i = 0; i < name.length(); i++) { char ch = name.charAt(i); if (Character.isISOControl(ch)) { throw new ParseException(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)), i); } if ("?*/\\%!@#$^&|<>[]:;".indexOf(ch) != -1) throw new ParseException(Messages.Hudson_UnsafeChar(ch), i); } // looks good }