Java Code Examples for java.text.ParseException

The following are top voted examples for showing how to use java.text.ParseException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: StringCutter.java   View source code 125 votes vote down vote up
public String next(String regexp) throws ParseException {
    trim();
    Pattern p = Pattern.compile(regexp);
    Matcher m = p.matcher(s);
    if(m.lookingAt()) {
        String r = m.group();
        s = s.substring(r.length());
        trim();
        return r;
    } else
        throw error();
}
 
Example 2
Project: MyFlightbookAndroid   File: Telemetry.java   View source code 5 votes vote down vote up
Date ParseUTCDate(String s) throws ParseException {
    if (m_pISODate == null) {
        m_pISODate = Pattern.compile("(\\d+)-(\\d+)-(\\d+)T? ?(\\d+):(\\d+):(\\d+\\.?\\d*)Z?", Pattern.CASE_INSENSITIVE);
    }
    Matcher m = m_pISODate.matcher(s);

    if (m.matches()) {
        int year = Integer.parseInt(m.group(1));
        int month = Integer.parseInt(m.group(2));
        int day = Integer.parseInt(m.group(3));
        int hour = Integer.parseInt(m.group(4));
        int minute = Integer.parseInt(m.group(5));
        double second = Double.parseDouble(m.group(6));

        GregorianCalendar gc = UTCDate.UTCCalendar();
        gc.set(year, month - 1, day, hour, minute, (int) second);
        return gc.getTime();
    }
    return new Date();
}
 
Example 3
Project: monarch   File: NumericQueryJUnitTest.java   View source code 5 votes vote down vote up
private Region createPartitionedRegion(String regionName) throws ParseException {
  Cache cache = CacheUtils.getCache();
  PartitionAttributesFactory prAttFactory = new PartitionAttributesFactory();
  AttributesFactory attributesFactory = new AttributesFactory();
  attributesFactory.setPartitionAttributes(prAttFactory.create());
  RegionAttributes regionAttributes = attributesFactory.create();
  return cache.createRegion(regionName, regionAttributes);
}
 
Example 4
Project: OpenDiabetes   File: UnderThresholdFilterTest.java   View source code 5 votes vote down vote up
@Test
public void testUnderThresholdFilterTest_GLUCOSE_125_00_CGM_CGM_AVAILABLE_CGM_TH() throws ParseException {

    UnderThresholdFilter instance = new UnderThresholdFilter(VaultEntryType.GLUCOSE_CGM, 125.00, FilterType.CGM_AVAILABLE, FilterType.CGM_TH);
    FilterResult result = instance.filter(data);

    List<VaultEntry> filteredData = new ArrayList<>();
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-09:59"), 118));
    //
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-10:29"), 110));
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-10:43"), 105));
    //
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-10:59"), 100));
    //
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-11:14"), 120));
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-11:29"), 103));

    List<Pair<Date, Date>> timeSeries = new ArrayList<>();
    timeSeries.add(new Pair<>(TestFunctions.creatNewDateToCheckFor("2016.04.18-09:59"), TestFunctions.creatNewDateToCheckFor("2016.04.18-09:59")));
    timeSeries.add(new Pair<>(TestFunctions.creatNewDateToCheckFor("2016.04.18-10:29"), TestFunctions.creatNewDateToCheckFor("2016.04.18-10:43")));
    timeSeries.add(new Pair<>(TestFunctions.creatNewDateToCheckFor("2016.04.18-10:59"), TestFunctions.creatNewDateToCheckFor("2016.04.18-10:59")));
    timeSeries.add(new Pair<>(TestFunctions.creatNewDateToCheckFor("2016.04.18-11:14"), TestFunctions.creatNewDateToCheckFor("2016.04.18-11:29")));
    FilterResult checkForThisResult = new FilterResult(filteredData, timeSeries);

    assertEquals(result.filteredData, checkForThisResult.filteredData);
    assertEquals(result.timeSeries, checkForThisResult.timeSeries);
    //assertEquals(result, checkForThisResult);
}
 
Example 5
Project: directory-ldap-api   File: ACIItemParserTest.java   View source code 5 votes vote down vote up
@Test
public void testOrderOfMainACIComponentsDoesNotMatterButMissingsMatter() throws Exception
{
    String spec = "{   itemOrUserFirst userFirst:  { userClasses {  allUsers  , name { \"ou=people,cn=ersin\" }, "
        + "subtree {{ base \"ou=system\" }, { base \"ou=ORGANIZATIONUNIT\","
        + "minimum  1, maximum   2 } } }  , "
        + "userPermissions { { protectedItems{ entry  , attributeType { cn  , ou }  , attributeValue {x=y,m=n,k=l} , "
        + "rangeOfValues (cn=ErsinEr) }  , grantsAndDenials { grantBrowse } } } }, "
        + " identificationTag \"id2\"   , precedence 14 }   ";

    try
    {
        parser.parse( spec );
        fail( "testOrderOfMainACIComponentsDoesNotMatterButMissingsMatter() should not have run this line." );
    }
    catch ( ParseException e )
    {
        assertNotNull( e );
    }
}
 
Example 6
Project: OpenDA   File: RtcToolsRuntimeConfigFile.java   View source code 5 votes vote down vote up
public void initialize(File workingDirectory, String[] arguments)
{
	if(arguments.length != 1 && arguments.length != 2 ) {
		throw new RuntimeException(usageString);
	}
	String inputFileName = arguments[0];
	this.outputFileName = inputFileName;
	if (arguments.length > 1) {
		this.outputFileName = arguments[1];
	}

	this.workingDirectory = workingDirectory;
	configTree = new ConfigTree(workingDirectory, inputFileName);
	String startDateString = configTree.getAsString(CONFIG_TREE_ELEMENT_STARTDATE, "");
	String startTimeString = configTree.getAsString(CONFIG_TREE_ELEMENT_STARTTIME, "");
	String endDateString = configTree.getAsString(CONFIG_TREE_ELEMENT_ENDDATE, "");
	String endTimeString = configTree.getAsString(CONFIG_TREE_ELEMENT_ENDTIME, "");

	String startString = startDateString + " " + startTimeString;
	String endString = endDateString + " " + endTimeString;
	double mjdStartTime;
	double mjdEndTime;
	try {
		mjdStartTime = TimeUtils.date2Mjd(startString);
		mjdEndTime = TimeUtils.date2Mjd(endString);
	} catch (ParseException e) {
		throw new RuntimeException("Could not parse start/end date time in file " + new File(workingDirectory, inputFileName));
	}
	exchangeItems = new HashMap<>();
	exchangeItems.put(PROPERTY_STARTTIME, new Flow1DTimeInfoExchangeItem(Flow1DTimeInfoExchangeItem.PropertyId.StartTime, mjdStartTime));
	exchangeItems.put(PROPERTY_STOPTIME, new Flow1DTimeInfoExchangeItem(Flow1DTimeInfoExchangeItem.PropertyId.StopTime, mjdEndTime));
}
 
Example 7
Project: ditb   File: PerfDataGenerator.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws IOException, ParseException {
  if (args.length < 4) {
    StringBuilder sb = new StringBuilder();
    sb.append("current parameters: ");
    for (String one : args) {
      sb.append(one).append(",");
    }
    usage();
    return;
  }
  new PerfDataGenerator(args[0], Integer.valueOf(args[1]), Integer.valueOf(args[2]),
      Integer.valueOf(args[3])).work();
}
 
Example 8
Project: uroborosql   File: DateTimeApiParameterMapperTest.java   View source code 5 votes vote down vote up
@Test
public void testOffsetTime() throws ParseException {
	DateTimeApiParameterMapper mapper = new DateTimeApiParameterMapper();
	assertThat(mapper.toJdbc(OffsetTime.from(createDateTime("2000/01/01 10:10:10.010")), null, null),
			instanceOf(java.sql.Time.class));
	assertThat(mapper.toJdbc(OffsetTime.from(createDateTime("2000/01/01 10:10:10.010")), null, null),
			is(createTime("10:10:10.010")));
}
 
Example 9
Project: Reer   File: IvyXmlModuleDescriptorParser.java   View source code 5 votes vote down vote up
private void extendsStarted(Attributes attributes) throws ParseException {
    String parentOrganisation = attributes.getValue("organisation");
    String parentModule = attributes.getValue("module");
    String parentRevision = attributes.getValue("revision");
    String location = elvis(attributes.getValue("location"), "../ivy.xml");

    String extendType = elvis(attributes.getValue("extendType"), "all").toLowerCase();
    List<String> extendTypes = Arrays.asList(extendType.split(","));

    ModuleDescriptor parent;
    try {
        LOGGER.debug("Trying to parse included ivy file :{}", location);
        parent = parseOtherIvyFileOnFileSystem(location);
        if (parent != null) {
            //verify that the parsed descriptor is the correct parent module.
            ModuleId expected = IvyUtil.createModuleId(parentOrganisation, parentModule);
            ModuleId pid = parent.getModuleRevisionId().getModuleId();
            if (!expected.equals(pid)) {
                LOGGER.warn("Ignoring parent Ivy file {}; expected {} but found {}", location, expected, pid);
                parent = null;
            }
        }

        // if the included ivy file is not found on file system, tries to resolve using
        // repositories
        if (parent == null) {
            LOGGER.debug("Trying to parse included ivy file by asking repository for module :{}#{};{}",
                parentOrganisation, parentModule, parentRevision);
            parent = parseOtherIvyFile(parentOrganisation, parentModule, parentRevision);
        }
    } catch(Exception e) {
        throw (ParseException) new ParseException("Unable to parse included ivy file for " + parentOrganisation + "#" + parentModule + ";" + parentRevision, 0).initCause(e);
    }

    if (parent == null) {
        throw new ParseException("Unable to parse included ivy file for " + parentOrganisation + "#" + parentModule + ";" + parentRevision, 0);
    }

    mergeWithOtherModuleDescriptor(extendTypes, parent);
}
 
Example 10
Project: ralasafe   File: SimpleValue.java   View source code 5 votes vote down vote up
public Object getValue(User user, Map context) {
	if (type.equals(STRING)) {
		return value;
	} else if (type.equals(INTEGER)) {
		return new Integer(value);
	} else if (type.equals(FLOAT)) {
		return new Float(value);
	} else if (type.equals(BOOLEAN)) {
		return new Boolean(value);
	} else if (type.equals(DATETIME)) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return format.parse(value);
		} catch (ParseException e) {
			log.error( "", e );
			throw new RalasafeException(e);
		}
	} else {
		String msg="Not supported value type '" + type + "'.";
		log.error( msg );
		throw new RalasafeException(msg);
	}
}
 
Example 11
Project: Pluto-Android   File: StringUtils.java   View source code 5 votes vote down vote up
/**
 * 将字符串转位年月日
 * 
 * @param sdate
 * @return
 */
public static Date toDate2(String sdate) {
	try {
		return dateFormater2.get().parse(sdate);
	} catch (ParseException e) {
		return null;
	}
}
 
Example 12
Project: YiZhi   File: DateUtils.java   View source code 5 votes vote down vote up
public static Date str2date(String str, String format) {
    Date date = null;
    try {
        if (str != null) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            date = sdf.parse(str);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}
 
Example 13
Project: java-coap   File: LinkFormatTest.java   View source code 5 votes vote down vote up
@Test
public void testSingle() throws ParseException {
    LinkFormat lf = new LinkFormat("/power");
    lf.setObservable(Boolean.TRUE);
    lf.setResourceType("rt-test", "rt-test2");
    lf.setInterfaceDescription("if-test");
    lf.setMaximumSize(123);
    lf.setResourceInstance("ri-test");
    lf.setExport(Boolean.TRUE);
    lf.setMedia("text/plain");
    lf.setTitle("my title");
    lf.setType("example type");
    lf.setAnchor("/test/anch");
    lf.setContentType((short) 12);
    lf.setOAutobservable(true);

    LinkFormat lf2 = LinkFormatBuilder.parse(lf.toString());

    assertEquals(lf, lf2);
    assertEquals(lf.getUri(), lf2.getUri());
    assertEquals(lf.getContentType(), lf2.getContentType());
    assertEquals(lf.getResourceTypeArray(), lf2.getResourceTypeArray());
    assertEquals(lf.getInterfaceDescriptionArray(), lf2.getInterfaceDescriptionArray());
    assertEquals(lf.isObservable(), lf2.isObservable());
    assertEquals(lf.getMaxSize(), lf2.getMaxSize());
    assertEquals(lf.getResourceInstance(), lf2.getResourceInstance());
    assertEquals(lf.getExport(), lf2.getExport());
    assertEquals(lf.getMedia(), lf2.getMedia());
    assertEquals(lf.getTitle(), lf2.getTitle());
    assertEquals(lf.getType(), lf2.getType());
    assertEquals(lf.getAnchor(), lf2.getAnchor());
    assertEquals(lf.getParam("href"), lf.getUri());
}
 
Example 14
Project: BiglyBT   File: DERUTCTime.java   View source code 5 votes vote down vote up
/**
 * The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were
 * never encoded. When you're creating one of these objects from scratch, that's
 * what you want to use, otherwise we'll try to deal with whatever gets read from
 * the input stream... (this is why the input format is different from the getTime()
 * method output).
 * <p>
 *
 * @param time the time string.
 */
public DERUTCTime(
    String  time)
{
    this.time = time;
    try
    {
        this.getDate();
    }
    catch (ParseException e)
    {
        throw new IllegalArgumentException("invalid date string: " + e.getMessage());
    }
}
 
Example 15
Project: ChronoBike   File: DateUtil.java   View source code 5 votes vote down vote up
public static Date formatDate(String csDate, String csFormat, boolean strict)
{
	Date date = null;

	if (csDate != null && csFormat != null && csFormat.length() > 0) 
	{
		try 
		{
			SimpleDateFormat formatter = new SimpleDateFormat(csFormat);
			formatter.setLenient(false);
			date = formatter.parse(csDate);
			if (strict) 
			{
				if (csFormat.length() != csDate.length()) 
				{
					date = null;
				}
			}
		} 
		catch (ParseException e) 
		{
		}
	}
	return date;
}
 
Example 16
Project: CalendarFX   File: IcalSchema.java   View source code 5 votes vote down vote up
public void applyParamSchema(
        String rule, String name, String value, IcalObject out)
        throws ParseException {
    // all elements are allowed extension parameters
    if (EXTENSION_PARAM_NAME_RE.matcher(name).find()) {
        out.getExtParams().put(name, value);
        return;
    }
    // if not an extension, apply the rule
    ruleStack.add(rule);
    try {
        (paramRules.get(rule)).apply(this, name, value, out);
    } finally {
        ruleStack.remove(ruleStack.get(ruleStack.size() - 1));
    }
}
 
Example 17
Project: teamcity-kubernetes-plugin   File: KubeCloudInstanceImpl.java   View source code 5 votes vote down vote up
@NotNull
@Override
public Date getStartedTime() {
    final PodStatus podStatus = myApiConnector.getPodStatus(myPod.getMetadata().getName());
    if(podStatus == null) return myCreationTime;
    try {
        final List<PodCondition> podConditions = podStatus.getConditions();
        if (podConditions != null && !podConditions.isEmpty()) {
            for (PodCondition podCondition : podConditions) {
                if (PodConditionType.valueOf(podCondition.getType()) == PodConditionType.Ready)
                    return myPodTransitionTimeFormat.parse(podCondition.getLastTransitionTime());
            }
        }
        String startTime = podStatus.getStartTime();
        return !StringUtil.isEmpty(startTime) ? myPodStartTimeFormat.parse(startTime) : myCreationTime;
    } catch (ParseException e) {
        throw new KubeCloudException("Failed to get instance start date", e);
    }
}
 
Example 18
Project: spr   File: SqlUpdates.java   View source code 5 votes vote down vote up
public static boolean updateDocumentos(Documentos documentos, String usuarioResponsable)throws ParseException{
	try {
		Connection conect = ConnectionConfiguration.conectar();
		String query = "update documentos set ";
		PreparedStatement update = null;
		
		String startDate = documentos.getFecha();
	    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
	    java.util.Date date = sdf1.parse(startDate);
		java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());

		if (documentos.getNombre() != "") 		{	query += "nombre= ?, ";			}
		if (documentos.getDescripcion() != "") 	{	query += "descripcion= ?, ";	}
		if (documentos.getFecha() !="") 		{	query += "fecha_valides= ?, ";	}
		
		query += "usuario_responsable= ?, ";
		query = query.substring(0, query.length() - 2);
		query += " where id = ? ";

		int cantCampos = 0;
		update = conect.prepareStatement(query);
		if (documentos.getNombre() != "") 		{	cantCampos++;update.setString(cantCampos, documentos.getNombre());}
		if (documentos.getDescripcion() != "")	{	cantCampos++;update.setString(cantCampos, documentos.getDescripcion());}
		if (documentos.getFecha() !="") 		{	cantCampos++;update.setDate(cantCampos, sqlStartDate);}
		
		cantCampos++;
		update.setString(cantCampos, usuarioResponsable);
		cantCampos++;
		update.setInt(cantCampos, documentos.getId());

		update.execute();
		conect.close();
		return true;
	} catch (SQLException e){e.printStackTrace();
			return false;
	}
}
 
Example 19
Project: arquillian-reporter   File: TestSuiteReportTest.java   View source code 5 votes vote down vote up
@Test
public void testNewTestSuiteReportShouldContainStartDate() throws ParseException {
    new DateChecker() {
        @Override
        public String getDateFromReport() {
            return new TestSuiteReport().getExecutionStartTime();
        }
    }.assertThatDateWasCorrectlyCreated();
}
 
Example 20
Project: rulesservice   File: DateTimeDeserializer.java   View source code 5 votes vote down vote up
@Override
public LocalDateTime deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
    String datetime = element.getAsString();

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    format.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        Date result = format.parse(datetime);
        return result.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    } catch (ParseException exp) {
        System.err.println("Failed to parse Date:"+ exp);
        return null;
    }
 }
 
Example 21
Project: directory-ldap-api   File: AttributeUtils.java   View source code 5 votes vote down vote up
/**
 * Parse attribute's options :
 * 
 * options = *( ';' option )
 * option = 1*keychar
 * keychar = 'a'-z' | 'A'-'Z' / '0'-'9' / '-'
 */
private static void parseOptions( char[] str, Position pos ) throws ParseException
{
    while ( Strings.isCharASCII( str, pos.start, ';' ) )
    {
        pos.start++;

        // We have an option
        if ( !Chars.isAlphaDigitMinus( str, pos.start ) )
        {
            // We must have at least one keychar
            throw new ParseException( I18n.err( I18n.ERR_04343 ), pos.start );
        }

        pos.start++;

        while ( Chars.isAlphaDigitMinus( str, pos.start ) )
        {
            pos.start++;
        }
    }
}
 
Example 22
Project: Cryptocurrency-Java-Wrappers   File: Time.java   View source code 5 votes vote down vote up
/**
 * Returns a UNIX timestamp of time specified
 * @param year Year
 * @param month Month
 * @param day Day
 * @param hour Hour
 * @param minute Minute
 * @param timeZone Timezone; e.g. "UTC-5:00"
 * @return Time in UNIX timestamp
 */
public static long unixTimestamp(int year, int month, int day, int hour, int minute, String timeZone) {

	long timeNumber = (year * 100000000L) + (month * 1000000) + (day * 10000) + (hour * 100) + (minute);
	String timeString = Long.toString(timeNumber);
	long unixTime = 0L;

	dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));

	try {
		unixTime = dateFormat.parse(timeString).getTime();
		unixTime /= 1000L;
	} catch(ParseException pe) {
		pe.printStackTrace();
	}

	return unixTime;

}
 
Example 23
Project: MyFlightbookAndroid   File: FlightProperty.java   View source code 5 votes vote down vote up
private void FromCursor(Cursor c) {
    _id = c.getInt(c.getColumnIndex("_id"));
    idProp = c.getInt(c.getColumnIndex("idProp"));
    idFlight = c.getInt(c.getColumnIndex("idFlight"));
    idPropType = c.getInt(c.getColumnIndex("idPropType"));
    intValue = c.getInt(c.getColumnIndex("IntValue"));
    boolValue = (intValue != 0);
    decValue = c.getDouble(c.getColumnIndex("DecValue"));
    try {
        dateValue = df.parse(c.getString(c.getColumnIndex("DateValue")));
    } catch (ParseException e) {
        dateValue = null;
    }
    stringValue = c.getString(c.getColumnIndex("StringValue"));
}
 
Example 24
Project: Hydrograph   File: DateFuncitonsTest.java   View source code 5 votes vote down vote up
@Test
public void itShouldReturnDayOfYear() throws ParseException{
    String dateInString = "2011-02-01";
    Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateInString);
    Integer dayOfYear =  DateFunctions.getDayOfYear(date);
    Assert.assertEquals(dayOfYear,new Integer(32));
}
 
Example 25
Project: excel-utils   File: ConvertUtils.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Object convertIfNeccesary(Object obj, Class<?> type,String dateFormat) throws ParseException {
	if(type.equals(obj.getClass())){
		return obj;
	}
	if(String.class.equals(type)){
		if(Date.class.isAssignableFrom(obj.getClass())){
			SimpleDateFormat format = getDateFormat(dateFormat);
			return format.format((Date)obj);
		}
		return obj.toString();
	}
	if(Number.class.isAssignableFrom(type)){
		if(Number.class.isAssignableFrom(obj.getClass())){
			return NumberUtils.convertNumberToTargetClass((Number)obj, (Class<Number>)type);
		}else if(String.class.equals(obj.getClass())){
			return NumberUtils.parseNumber(obj.toString(), (Class<Number>)type);
		}
	}
	if(ClassUtils.isBaseNumberType(type)){//基本类型之中的数字类型
		return NumberUtils.convertNumberToTargetClass((Number)obj, ClassUtils.getNumberWrapClass(type));
	}
	if(char.class.equals(type) || Character.class.equals(type)){
		if(obj.toString().length() > 0 ){
			return new Character(obj.toString().charAt(0));				
		}
		return null;
	}
	if(String.class.equals(obj.getClass())){
		if(Date.class.equals(type)){	
			SimpleDateFormat simpleDateFormat = getDateFormat(dateFormat);
			return simpleDateFormat.parse(obj.toString());
		}
		if(Boolean.class.equals(type)){
			return Boolean.parseBoolean(obj.toString());
		}
	}
	return null;
}
 
Example 26
Project: ibm-cos-sdk-java   File: DateUtilsTest.java   View source code 5 votes vote down vote up
@Test
public void parseIso8601Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    String alternative = DateUtils.iso8601DateFormat.print(date.getTime());
    assertEquals(formatted, alternative);

    Date expectedDate = sdf.parse(formatted);
    Date actualDate = DateUtils.parseISO8601Date(formatted);
    assertEquals(expectedDate, actualDate);
}
 
Example 27
Project: Sanxing   File: MyDuration.java   View source code 5 votes vote down vote up
public static long durationFromNowtoB(String B)
{
    //need format of B is yyyy-MM-dd HH:mm:ss
    long diff=0;
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try
    {
        Date nowDate=new Date();
        Date endDate=df.parse(B);
        diff = endDate.getTime() - nowDate.getTime();//这样得到的差值是微秒级别
    }
    catch(ParseException e)
    {
        e.printStackTrace();
    }
    return diff;
}
 
Example 28
Project: Calendouer   File: CalendouerActivity.java   View source code 5 votes vote down vote up
boolean needUpdateWeather() {
    int frequency = Integer.parseInt(settingPref.getString("update_frequency", "2"));

    String lastWeatherUpdate = sharedPref.getString("update_datetime", "");
    if (!lastWeatherUpdate.equals("")) {
        try {
            Date lastUpdateDate = df_ymd_hms.parse(lastWeatherUpdate);
            return new Date().getTime() - lastUpdateDate.getTime() > frequency * 60 * 60 * 1000;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    } else {
        return true;
    }
}
 
Example 29
Project: iosched-reader   File: TimeUtils.java   View source code 5 votes vote down vote up
public static Date parseTimestamp(String timestamp) {
    for (SimpleDateFormat format : ACCEPTED_TIMESTAMP_FORMATS) {
        // TODO: We shouldn't be forcing the time zone when parsing dates.
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        try {
            return format.parse(timestamp);
        } catch (ParseException ex) {
            continue;
        }
    }

    // All attempts to parse have failed
    return null;
}
 
Example 30
Project: spring-spreadsheet   File: ExcelStreamerTest.java   View source code 5 votes vote down vote up
@Test
public void testSimpleObject_checkThatDocumentIsAValidZipFile() throws ParseException, IOException {
    final List<SpreadsheetStreamerTest.ObjectExampleDTO> data = Arrays.asList(
            new SpreadsheetStreamerTest.ObjectExampleDTO("field 1", 2, createDate(), true),
            new SpreadsheetStreamerTest.ObjectExampleDTO("field 1 2", 23, createDate(), false)
    );

    byte[] bytes = excelStreamer.toByteArray(spreadsheetConverter.convert(data));
    assertThat(bytes, isActuallyAnExcelFile());
}
 
Example 31
Project: mpay24-java   File: TestPaymentStatus.java   View source code 5 votes vote down vote up
@Test
public void testPaymentStatusUsingTransactionId() throws PaymentException, ParseException {
	String tid = getRandomTransactionId();
	Payment payment = mpay24.payment(getTestPaymentRequest(tid, 1l), getVisaTestData());
	Payment paymentStatus = mpay24.paymentDetails(tid);
	assertNotNull(paymentStatus);
	assertEquals("BILLED", paymentStatus.getState().toString());
	assertEquals("EUR", paymentStatus.getCurrency());
	assertEquals(new BigDecimal(100l), paymentStatus.getAmount());
	assertEquals("CC", paymentStatus.getPaymentType().toString());
	assertNotNull(paymentStatus.getmPayTid());
	assertEquals(tid, paymentStatus.getTransactionId());

}
 
Example 32
Project: openjdk-jdk10   File: NFS4StringPrep.java   View source code 5 votes vote down vote up
private static byte[] prepare(byte[] src, StringPrep prep)
            throws ParseException, UnsupportedEncodingException{
    String s = new String(src, "UTF-8");
    UCharacterIterator iter =  UCharacterIterator.getInstance(s);
    StringBuffer out = prep.prepare(iter,StringPrep.DEFAULT);
    return out.toString().getBytes("UTF-8");
}
 
Example 33
Project: seldon-core   File: TimeUtils.java   View source code 5 votes vote down vote up
@Override
public void merge(JsonElement json, Builder builder) throws InvalidProtocolBufferException {
    try {
        Timestamp value = Timestamps.parse(json.getAsString());
        builder.mergeFrom(value.toByteString());
      } catch (ParseException e) {
        throw new InvalidProtocolBufferException("Failed to parse timestamp: " + json);
      }
}
 
Example 34
Project: lams   File: CronTriggerSupport.java   View source code 5 votes vote down vote up
public static OperableTrigger newTrigger(Map<String, Object> attrMap) throws ParseException {
    CronTriggerImpl result = new CronTriggerImpl();
    result.setCronExpression((String) attrMap.get("cronExpression"));
    if(attrMap.containsKey("timeZone")) {
        result.setTimeZone(TimeZone.getTimeZone((String)attrMap.get("timeZone")));
    }
    TriggerSupport.initializeTrigger(result, attrMap);
    return result;
}
 
Example 35
Project: SOS-The-Healthcare-Companion   File: ReadingTools.java   View source code 5 votes vote down vote up
/**
 * A convenient method for parsing reading value based on user's locale
 *
 * @param reading reading number String
 * @return reading Number
 */
@Nullable
public static Number parseReading(String reading) {
    if (reading == null)
        return null;
    NumberFormat numberFormat = NumberFormat.getInstance();
    try {
        return numberFormat.parse(reading);
    } catch (ParseException e) {
        return null;
    }
}
 
Example 36
Project: safecharge-java   File: RequestUtils.java   View source code 5 votes vote down vote up
/**
 * This method is used to calculate the clientRequestId parameter of a request.
 *
 * @param timestamp the timestamp to generate clientRequestId from. It should be in "yyyyMMddHHmmss" format
 * @return the clientRequestId or -1 if it can't be calculated
 */
public static String calculateClientRequestId(String timestamp) {
    try {
        return String.valueOf(sdf.parse(timestamp)
                .getTime());
    } catch (ParseException e) {
        return "-1";
    }
}
 
Example 37
Project: civify-app   File: IssueAdapterTest.java   View source code 5 votes vote down vote up
@Test
public void testInvalidEditIssue() throws InterruptedException, ParseException {
    Issue editedIssue = setUpEditedIssue();
    JsonObject edited = mGson.toJsonTree(editedIssue).getAsJsonObject();
    MockResponse mockResponse = new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_BAD_REQUEST);
    mMockWebServer.enqueue(mockResponse);
    IssueSimpleCallback mockCallback = mock(IssueSimpleCallback.class);

    UserAdapter.setCurrentUser(mUser);

    mIssueAdapter.editIssue("issue-auth-token", edited, mockCallback);

    // Test mockCallback.onFailure() is called
    verify(mockCallback, timeout(1000)).onFailure();
}
 
Example 38
Project: LightSIP   File: MultipartMimeContentImpl.java   View source code 5 votes vote down vote up
private ContentImpl parseBodyPart(String bodyPart) throws ParseException {
  String headers[] = null;
  String bodyContent;
  
  // if a empty line starts the body it means no headers are present
  if (bodyPart.startsWith("\n") || bodyPart.startsWith("\r\n")) {
    bodyContent = bodyPart;
  } else {
    // limit the number of crlf (new lines) we split on, only split the header from
    // the body and don't split on any crlf in the body  
    String[] nextPartSplit = bodyPart.split("\r?\n\r?\n", 2);

    bodyContent = bodyPart;
    
    if (nextPartSplit.length == 2) {
      // since we aren't completely sure the data is a header let's test the first one
      String potentialHeaders[] = nextPartSplit[0].split("\r?\n");
      if (potentialHeaders[0].indexOf(":") > 0) {
        headers = potentialHeaders;
        bodyContent = nextPartSplit[1];
      }
    }
  }
  
  ContentImpl content = new ContentImpl(bodyContent);
  if (headers != null) {
    for (String partHeader : headers) {
      Header header = headerFactory.createHeader(partHeader);
      if (header instanceof ContentTypeHeader) {
        content.setContentTypeHeader((ContentTypeHeader) header);
      } else if (header instanceof ContentDispositionHeader) {
        content.setContentDispositionHeader((ContentDispositionHeader) header);
      } else {
        content.addExtensionHeader(header);
      }
    }
  }
  return content;
}
 
Example 39
Project: ttc2017smartGrids   File: ISO8601DateConverter.java   View source code 5 votes vote down vote up
public Date convert(String value) {
  try {
    return DATE_FORMAT.parse(value);
  } catch (ParseException pe) {
    throw new ParameterException(getErrorString(value, String.format("an ISO-8601 formatted date (%s)", DATE_FORMAT.toPattern())));
  }
}
 
Example 40
Project: DateTimePicker   File: DatePickerSpinnerDelegate.java   View source code 5 votes vote down vote up
/**
 * Parses the given <code>date</code> and in case of success sets the result
 * to the <code>outDate</code>.
 *
 * @return True if the date was parsed.
 */
private boolean parseDate(String date, Calendar outDate) {
    try {
        outDate.setTime(mDateFormat.parse(date));
        return true;
    } catch (ParseException e) {
        e.printStackTrace();
        return false;
    }
}