在本文中,我们将为您详细介绍OSX上的bash–`date`命令没有ISO8601`-I’选项?的相关知识,并且为您解答关于没有.bash_profile的疑问,此外,我们还会提供一些关于bash–如
在本文中,我们将为您详细介绍OS X上的bash – `date`命令没有ISO 8601`-I’选项?的相关知识,并且为您解答关于没有.bash_profile的疑问,此外,我们还会提供一些关于bash – 如何将命令结果传递给 – 选项? (没有空格)、bash – 安装make命令没有make(mac os 10.5)、com.fasterxml.jackson.databind.util.ISO8601DateFormat的实例源码、com.fasterxml.jackson.databind.util.ISO8601Utils的实例源码的有用信息。
本文目录一览:- OS X上的bash – `date`命令没有ISO 8601`-I’选项?(没有.bash_profile)
- bash – 如何将命令结果传递给 – 选项? (没有空格)
- bash – 安装make命令没有make(mac os 10.5)
- com.fasterxml.jackson.databind.util.ISO8601DateFormat的实例源码
- com.fasterxml.jackson.databind.util.ISO8601Utils的实例源码
OS X上的bash – `date`命令没有ISO 8601`-I’选项?(没有.bash_profile)
http://ss64.com/bash/date.html
但这似乎并不适用于我的Mac:
$ date -I date: illegal option -- I usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
事实上,man日期没有列出这个选项。
任何人知道为什么这是,或任何其他(容易)的方式,我打印日期的ISO 8601格式?谢谢!
date "+%Y-%m-%d"
或者对于完全ISO-8601 compliant date,请使用以下格式之一:
date -u +"%Y-%m-%dT%H:%M:%sZ"
输出:
2011-08-27T23:22:37Z
要么
date +%Y-%m-%dT%H:%M:%s%z
输出:
2011-08-27T15:22:37-0800
bash – 如何将命令结果传递给 – 选项? (没有空格)
grep -n '*' file.txt | head -n1 | awk -F\: '{print $1-1;}'
它告诉我前一行,它首先找到星号.
现在我想让以前的行管道:
head -n<that prevIoUs line number>
Head需要紧跟-n参数后面的数字,不带空格,例如:
head -n4
我怎样才能做到这一点?它只是不接受添加
| head -n
在命令集的末尾.
我的搜索没有结果.谢谢!
解决方法
head -n`grep -n '*' file.txt | head -n1 | awk -F\: '{print $1-1;}'` file.txt
或者可能在多行上类似:
LINENO=`grep -n '*' file.txt | head -n1 | awk -F\: '{print $1-1;}'` head -n${LINENO} file.txt
bash – 安装make命令没有make(mac os 10.5)
(我知道您可以通过安装 Xcode和Mac OS附带的开发人员工具来完成,但是我不希望人们去找到他们的mac os安装dvds以使用该脚本.)
它甚至不需要做,我只是寻找一个实用程序,您可以轻松地下载脚本(使用ftp或curl),并用于编译源代码.
If you need to build GNU Make and have no other make program to use,
you can use the shell script build.sh instead. To do this,first run
configure
as described in INSTALL. Then,instead of typingmake
to
build the program,typesh build.sh
. This should compile the program
in the current directory. Then you will have a Make program that you can
use for./make install
,or whatever else.
是的,他们想到了这个问题!
com.fasterxml.jackson.databind.util.ISO8601DateFormat的实例源码
private <T> T patch(UriTemplate template,Object body,final Class<T> modelClass) throws IOException,InterruptedException { HttpURLConnection connection = (HttpURLConnection) new URL(template.expand()).openConnection(); withAuthentication(connection); setRequestMethodViaJreBugWorkaround(connection,"PATCH"); byte[] bytes; if (body != null) { bytes = mapper.writer(new ISO8601DateFormat()).writeValueAsBytes(body); connection.setRequestProperty("Content-Type","application/json"); connection.setRequestProperty("Content-Length",Integer.toString(bytes.length)); connection.setDoOutput(true); } else { bytes = null; connection.setDoOutput(false); } connection.setDoInput(true); try { connection.connect(); if (bytes != null) { try (OutputStream os = connection.getoutputStream()) { os.write(bytes); } } int status = connection.getResponseCode(); if (status / 100 == 2) { if (Void.class.equals(modelClass)) { return null; } try (InputStream is = connection.getInputStream()) { return mapper.readerFor(modelClass).readValue(is); } } throw new IOException("HTTP " + status + "/" + connection.getResponseMessage()); } finally { connection.disconnect(); } }
@Override public final void run(MatchingServiceAdapterConfiguration configuration,Environment environment) { IdaSamlBootstrap.bootstrap(); environment.getobjectMapper().setDateFormat(new ISO8601DateFormat()); environment.jersey().register(LocalMetadataResource.class); environment.jersey().register(MatchingServiceResource.class); environment.jersey().register(UnkNownUserAttributeQueryResource.class); environment.jersey().register(SamloverSoapExceptionMapper.class); environment.jersey().register(ExceptionExceptionMapper.class); MatchingServiceAdapterHealthCheck healthCheck = new MatchingServiceAdapterHealthCheck(); environment.healthChecks().register(healthCheck.getName(),healthCheck); }
@Inject public CreateCerberusBackupOperation(CerberusAdminClientFactory cerberusAdminClientFactory,ConfigStore configStore,MetricsService metricsService,EnvironmentMetadata environmentMetadata) { objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNowN_PROPERTIES); objectMapper.enable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS); objectMapper.setDateFormat(new ISO8601DateFormat()); this.configStore = configStore; this.metricsService = metricsService; this.environmentMetadata = environmentMetadata; cerberusAdminClient = cerberusAdminClientFactory.createCerberusAdminClient( configStore.getCerberusBaseUrl()); }
@Test public void testGenerateRequest() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); objectMapper.setDateFormat(new ISO8601DateFormat()); BausparBerechnungsAnfrage berechnungsdaten = new BausparBerechnungsAnfrage(); berechnungsdaten.setBausparsummeInEuro(new BigDecimal("100000")); berechnungsdaten.setBerechnungsZiel(BerechnungsZiel.SPARBEITRAG); SparBeitrag sparBeitrag = new SparBeitrag(); sparBeitrag.setBeitrag(new BigDecimal("100")); sparBeitrag.setZahlungAb(LocalDate.Now()); sparBeitrag.setZahlungBis(LocalDate.Now().plusYears(10)); sparBeitrag.setZahlungsrhythmus(Zahlungsrhythmus.MONATLICH); berechnungsdaten.setSparBeitraege(asList(sparBeitrag)); System.out.println(objectMapper.writeValueAsstring(berechnungsdaten)); }
private List<Drop> parseResponse(String responseBody) { try { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setDateFormat(new ISO8601DateFormat()); ArrayNode eventNodes = (ArrayNode) objectMapper.readTree(responseBody); List<Drop> drops = new ArrayList<>(); for (JsonNode eventNode : eventNodes) { String type = eventNode.get("type").asText(); if ("PushEvent".equals(type)) { parsePushEvent(eventNode,objectMapper) .forEach(drops::add); } } return drops; } catch (IOException e) { throw new RuntimeException("Could not parse github api result: " + responseBody,e); } }
public void test_() throws Exception { JSONSerializer ser = new JSONSerializer(new SerializeConfig()); ser.setDateFormat(new ISO8601DateFormat()); Assert.assertEquals(null,ser.getDateFormatPattern()); ser.close(); }
private RestObjectMapper() { // swagger中要求date使用ISO8601格式传递,这里与之做了功能绑定,这在cse中是没有问题的 setDateFormat(new ISO8601DateFormat()); getFactory().disable(Feature.AUTO_CLOSE_SOURCE); disable(DeserializationFeature.FAIL_ON_UNKNowN_PROPERTIES); disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); }
@Override public final void run(StubEventSinkConfiguration configuration,Environment environment) { environment.getobjectMapper().setDateFormat(new ISO8601DateFormat()); StubEventSinkHealthCheck healthCheck = new StubEventSinkHealthCheck(); environment.healthChecks().register(healthCheck.getName(),healthCheck); environment.jersey().register(EventSinkHubEventResource.class); environment.jersey().register(EventSinkHubEventTestResource.class); }
@Override public void run(PolicyConfiguration configuration,Environment environment) throws Exception { environment.getobjectMapper().setDateFormat(new ISO8601DateFormat()); registerResources(configuration,environment); registerExceptionMappers(environment); environment.jersey().register(SessionIdpathParamLoggingFilter.class); }
@Override public final void run(SamlEngineConfiguration configuration,Environment environment) { IdaSamlBootstrap.bootstrap(); environment.getobjectMapper().registerModule(new GuavaModule()); environment.getobjectMapper().setDateFormat(new ISO8601DateFormat()); // register resources registerResources(environment,configuration); // register exception mappers environment.jersey().register(SamlEngineExceptionMapper.class); environment.servlets().addFilter("Logging SessionId registration Filter",SessionIdQueryParamLoggingFilter.class).addMappingForUrlPatterns(EnumSet.allOf(dispatcherType.class),true,"/*"); }
@Override public void run(SamlSoapProxyConfiguration configuration,Environment environment) throws Exception { IdaSamlBootstrap.bootstrap(); environment.getobjectMapper().setDateFormat(new ISO8601DateFormat()); registerResources(environment); environment.servlets().addFilter("Logging SessionId registration Filter","/*"); }
private <T> T post(UriTemplate template,InterruptedException { HttpURLConnection connection = (HttpURLConnection) new URL(template.expand()).openConnection(); withAuthentication(connection); connection.setRequestMethod("POST"); byte[] bytes; if (body != null) { bytes = mapper.writer(new ISO8601DateFormat()).writeValueAsBytes(body); connection.setRequestProperty("Content-Type",Integer.toString(bytes.length)); connection.setDoOutput(true); } else { bytes = null; connection.setDoOutput(false); } connection.setDoInput(!Void.class.equals(modelClass)); try { connection.connect(); if (bytes != null) { try (OutputStream os = connection.getoutputStream()) { os.write(bytes); } } int status = connection.getResponseCode(); if (status / 100 == 2) { if (Void.class.equals(modelClass)) { return null; } try (InputStream is = connection.getInputStream()) { return mapper.readerFor(modelClass).readValue(is); } } throw new IOException( "HTTP " + status + "/" + connection.getResponseMessage() + "\n" + (bytes != null ? new String(bytes,StandardCharsets.UTF_8) : "")); } finally { connection.disconnect(); } }
public MessageUtils() { xmlMapper = new ExtendedXmlMapper(); xmlMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); xmlMapper.setDateFormat(new ISO8601DateFormat()); xmlMapper.registerModule(new JaxbAnnotationModule()); xmlMapper.setSerializationInclusion(Include.NON_NULL); }
@Override public void initialize(Bootstrap<VerifyServiceProviderConfiguration> bootstrap) { // Enable variable substitution with environment variables bootstrap.setConfigurationSourceProvider( new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),new EnvironmentvariableSubstitutor(false) ) ); IdaSamlBootstrap.bootstrap(); bootstrap.getobjectMapper().setDateFormat(ISO8601DateFormat.getInstance()); }
@Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.setDateFormat(new ISO8601DateFormat()); mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); mapper.configure(DeserializationFeature.FAIL_ON_UNKNowN_PROPERTIES,false); return mapper; }
@Before public void init() throws JsonParseException,JsonMappingException,UnsupportedEncodingException,IOException { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.setDateFormat(new ISO8601DateFormat()); Envelope envelope = mapper.readValue(MediaEventTest.MEDIA_EVENT.getBytes("UTF-8"),Envelope.class); mediaEvent = envelope.getData().get(0); }
/** * Create and configure the {@link ObjectMapper} used for serializing and deserializing * JSON requests and responses. * * @return a configured {@link ObjectMapper} */ public static ObjectMapper buildobjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setDateFormat(new ISO8601DateFormat()); objectMapper.setPropertyNamingStrategy(new PropertyNamingStrategy.SnakeCaseStrategy()); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNowN_PROPERTIES,false); objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING,true); objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING,true); configureCredentialDetailTypeMapping(objectMapper); return objectMapper; }
@Override public Long deserialize(JsonParser parser,DeserializationContext context) throws IOException { String value = StringDeserializer.instance.deserialize(parser,context); try { return Double.valueOf(value).longValue(); } catch (NumberFormatException e1) { try { DateFormat dateFormat = new ISO8601DateFormat(); return dateFormat.parse(value).getTime(); } catch (ParseException e2) { return 0L; } } }
public JbrickJacksonConfigurator() { // Serializzazione date in formato ISO-8601: YYYY-MM-DDThh:mm:ss.sss+hhmm // v. http://stackoverflow.com/a/5234682/1178235 // v. http://wiki.fasterxml.com/JacksonFAQDateHandling mapper.setDateFormat(new ISO8601DateFormat()); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNowN_PROPERTIES,false); // Registrazione del modulo dei serializzatori personalizzati mapper.registerModule(new zefiroModule()); }
/** * Creating mapper for serialize/deserialize data to JSON. */ @NotNull public static ObjectMapper createMapper() { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.setDateFormat(new ISO8601DateFormat()); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; }
public ToJson() { mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.setDateFormat(new ISO8601DateFormat()); // Adding custom writer dynamically List<WorkflowBundleWriter> writers = io.getWriters(); writers.add(jsonWriter); io.setWriters(writers); }
public JsonExport() { mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.setDateFormat(new ISO8601DateFormat()); // Adding custom writer dynamically List<WorkflowBundleWriter> writers = io.getWriters(); writers.add(jsonWriter); io.setWriters(writers); }
public static DateFormat newUtcFormatter() { TimeZone tz = TimeZone.getTimeZone("UTC"); ISO8601DateFormat df = new ISO8601DateFormat(); df.setTimeZone(tz); return df; }
private static long parseTimeStrToMilli(String timeStr) throws ParseException { StringBuilder sb = new StringBuilder(timeStr); int snipStart = sb.indexOf("."); int snipEnd = sb.indexOf("+"); if (snipEnd == -1) snipEnd = sb.indexOf("Z"); if (snipEnd == -1) snipEnd = sb.length(); String microsstring="0.0"; if (snipStart != -1) { microsstring = "0"+sb.substring(snipStart,snipEnd); sb.delete(snipStart,snipEnd); timeStr = sb.toString(); } SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX"); SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ISO8601DateFormat formatter3 = new ISO8601DateFormat(); Date dt = null; try{ dt = formatter1.parse(timeStr); }catch (Exception e){ try{ dt = formatter2.parse(timeStr); }catch (Exception e2){ dt = formatter3.parse(timeStr); } } long timeMillis = dt.getTime(); long millis = (long) (Double.parseDouble(microsstring)*1000); long time = timeMillis + millis; return time; }
private static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new ISO8601DateFormat()); mapper.configure(DeserializationFeature.FAIL_ON_UNKNowN_PROPERTIES,false); mapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME,true); return mapper; }
public JsonResponseWriter() { this.mapper = new ObjectMapper(); this.mapper.registerModule(new ObjectIdJsonModule()); this.mapper.registerModule(new Jodamodule()); this.mapper.registerModule(new JsonorgModule()); this.mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNowN_PROPERTIES,false); this.mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERscoreS); this.mapper.setSerializationInclusion(Include.NON_NULL); this.mapper.setDateFormat(new ISO8601DateFormat()); }
public void testSchemaCreation() { try { Schema schema = new SchemaBuilderjson(jsonSchema).getSchema(); assertTrue(((DateTimeIndex) schema.getFieldindex("dateTime")).getDateFormat() instanceof ISO8601DateFormat); } catch (SchemaConfigurationError e) { assertTrue(false); } }
public AbraidJsonObjectMapper() { super(); this.registerModule(new Jodamodule()); DateFormat dateFormat = ISO8601DateFormat.getDateTimeInstance(); dateFormat.setTimeZone(TimeZone.getTimeZone(UTC)); this.setDateFormat(dateFormat); this.configure(MapperFeature.DEFAULT_VIEW_INCLUSION,true); this.setSerializationInclusion(JsonInclude.Include.NON_NULL); }
@Test public void shouldReturnSecondsInDateTime() throws ParseException { Person p = new Person(); p.set("name","john","last_name","doe").saveIt(); p.refresh(); String json = p.toJson(true); System.out.println(json); @SuppressWarnings("unchecked") Map<String,String> map = JsonHelper.toMap(json); Date d = new ISO8601DateFormat().parse(map.get("created_at")); // difference between date in Json and in original model instance should be less than 1000 milliseconds a(Math.abs(d.getTime() - p.getTimestamp("created_at").getTime()) < 1000L).shouldBeTrue(); }
public static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.disable(DeserializationFeature.FAIL_ON_UNKNowN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.setDateFormat(new ISO8601DateFormat()); return mapper; }
@Override public void run(ConfigConfiguration configuration,Environment environment) throws Exception { environment.getobjectMapper().setDateFormat(new ISO8601DateFormat()); registerResources(environment); environment.servlets().addFilter("Logging SessionId registration Filter","/*"); }
@Before public void init() throws JsonParseException,IOException { if (savedTenant == null) { Tenant tenant = new Tenant.Builder() .withId("test-tid") .withName("test") .build(); savedTenant = tenantRepository.save(tenant); } if (mongoOrg == null) { Org org = new Org.Builder() .withSourcedId("org-id") .withName("org") .build(); mongoOrg = new MongoOrg.Builder() .withOrg(org) .withTenantId(savedTenant.getId()) .withApiKey(UUID.randomUUID().toString()) .withApiSecret(UUID.randomUUID().toString()) .build(); mongoOrgRepository.save(mongoOrg); } if (event == null || mediaEvent == null) { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.setDateFormat(new ISO8601DateFormat()); Envelope envelope = mapper.readValue(MediaEventTest.MEDIA_EVENT.getBytes("UTF-8"),Envelope.class); mediaEvent = envelope.getData().get(0); Envelope envelope1 = mapper.readValue(MinimalEventTest.MINIMAL_VIEWED_EVENT.getBytes("UTF-8"),Envelope.class); event = envelope1.getData().get(0); } }
@Before public void setUpJsonParsing() throws Exception { objectMapper = JsonUtils.buildobjectMapper(); testDate = new ISO8601DateFormat().parse(TEST_DATE_STRING); }
@Before public void setUp() throws Exception { objectMapper = Jackson.newObjectMapper().setDateFormat(ISO8601DateFormat.getDateInstance()); }
@Before public void setUp() throws Exception { objectMapper = Jackson.newObjectMapper().setDateFormat(ISO8601DateFormat.getDateInstance()); }
public ChronosMapper() { this.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false) .registerModule(new Jodamodule()) .setDateFormat(new ISO8601DateFormat()); }
public HarEntryBuilder withStartedDateTime(Date startedDateTime) { this.startedDateTime = new ISO8601DateFormat().format(startedDateTime); return this; }
public HarPageBuilder withStartedDateTime(Date startedDateTime) { this.startedDateTime = new ISO8601DateFormat().format(startedDateTime); return this; }
/** * Dumps JVM metrics for this process. * @param incidentId incident id */ public static void dumpVmMetrics(String incidentId) { PrintWriter writer = null; try { String dumpFile = EventUtil.getDumpPathPrefix() + "/" + INC_DUMP_FILE_NAME + incidentId + INC_DUMP_FILE_EXT; final OutputStream outStream = new GZIPOutputStream(new FileOutputStream(dumpFile)); writer = new PrintWriter(outStream,true); final VirtualMachineMetrics vm = VirtualMachineMetrics.getInstance(); writer.print("\n\n\n--------------------------- METRICS " + "---------------------------\n\n"); writer.flush(); JsonFactory jf = new JsonFactory(); jf.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); ObjectMapper mapper = new ObjectMapper(jf); mapper.registerModule(new Jodamodule()); mapper.setDateFormat(new ISO8601DateFormat()); mapper.configure(SerializationFeature.INDENT_OUTPUT,true); MetricsServlet metrics = new MetricsServlet(Clock.defaultClock(),vm,Metrics.defaultRegistry(),jf,true); final JsonGenerator json = jf.createGenerator(outStream,JsonEncoding.UTF8); json.useDefaultPrettyPrinter(); json.writeStartObject(); // JVM metrics writeVmMetrics(json,vm); // Components metrics metrics.writeRegularMetrics(json,// json generator null,// class prefix false); // include full samples json.writeEndobject(); json.close(); logger.debug("Creating full thread dump in dump file {}",dumpFile); // Thread dump next.... writer.print("\n\n\n--------------------------- THREAD DUMP " + "---------------------------\n\n"); writer.flush(); vm.threadDump(outStream); logger.debug("Dump file {} is created.",dumpFile); } catch(Exception exc) { logger.error( "Unable to write dump file,exception: {}",exc.getMessage()); } finally { if (writer != null) { writer.close(); } } }
public static Date getStashCreationTimeStamp(String stashStartTime) throws ParseException { return new ISO8601DateFormat().parse(stashStartTime); }
com.fasterxml.jackson.databind.util.ISO8601Utils的实例源码
@Test public void testGetValueCookiesDate() throws Exception { Date date = new Date(); String strDate = ISO8601Utils.format(date); Cookie[] cookies = new Cookie[] {new Cookie("c1",strDate)}; new Expectations() { { request.getCookies(); result = cookies; } }; CookieProcessor processor = createProcessor("c1",Date.class); Object value = processor.getValue(request); Assert.assertEquals(strDate,ISO8601Utils.format((Date) value)); }
@Override public Date parse(String source,ParsePosition pos) { // index must be set to other than 0,I would swear this requirement is // not there in some version of jdk 6. String toParse = source; if( !toParse.toupperCase().contains("T") ) { toParse = toParse + "T00:00:00Z"; } try { return ISO8601Utils.parse(toParse,pos); } catch (ParseException e) { throw new RuntimeException(e); } }
public void assertDate(JsonNode dateNode,Object time) { Date parsed = ISO8601Utils.parse(dateNode.textValue()); long timeMillis; if( time instanceof String ) { timeMillis = ISO8601Utils.parse((String) time).getTime(); } else if( time instanceof Date ) { timeMillis = ((Date) time).getTime(); } else { timeMillis = ((Number) time).longValue(); } if( timeMillis / 1000 != parsed.getTime() / 1000 ) { Assert.assertEquals(dateNode.textValue(),ISO8601Utils.format(new Date(timeMillis),true,TimeZone.getTimeZone("America/Chicago"))); } }
@SuppressWarnings("deprecation") @Override public MockResponse createResponse(MockRequest request) { Optional<String> targetKey = getobjectKey(request); Optional<Bucket> targetBucket = getBucket(request); Optional<S3Object> source = getSourceFromHeader(request); if (request.utils().areAllPresent(targetKey,targetBucket,source)) { S3Object copy = SerializationUtils.clone(source.get()); copy.setKey(targetKey.get()); targetBucket.get().getobjects().add(copy); } return new MockResponse( successBody("copyObject","<LastModified>" + ISO8601Utils.format(new Date()) + "</LastModified>\n" + " <ETag>" + UUID.randomUUID().toString() + "</ETag>")); }
@Override public Date parse(String source,ParsePosition pos) { // index must be set to other than 0,I would swear this requirement is not there in // some version of jdk 6. //pos.setIndex(source.length()); try { return ISO8601Utils.parse(source,pos); } catch (Exception e) { for (DateFormat dateFormat : formats) { try { return dateFormat.parse(source); } catch (ParseException e1) { // do notin' } } throw new RuntimeException(e); } }
/** * <p>parseDate.</p> * * @param value a {@link java.lang.String} object. * @param pos a {@link java.text.ParsePosition} object. * @return a {@link java.util.Date} object. */ public static Date parseDate(String value,ParsePosition pos) { Long timestamp = parseTimestamp(value); if (timestamp != null) { return new Date(timestamp); } if (value.contains(" ")) { value = value.replace(" ","+"); } if (!(value.contains("-") || value.contains("+")) && !value.endsWith("Z")) { value += SYS_TZ; } try { return ISO8601Utils.parse(value,pos); } catch (ParseException e) { throw new ExtractorException(e); } }
/** * <p> * Parses the ISO-8601 date from the image JSON. * </p> * <p> * Handles the bug in the NASA JSON where not all timestamps comply with ISO-8601 (some are missing the 'Z' for UTC * time at the end of the timestamp). * </p> * Uses Jackson ISO8601Utils to convert the timestamp. * * @param image * JSON representation of the image * @return Java Date object containing the creation time stamp */ protected static Date getTimestamp(final JsonNode image) { Date date = null; String iso8601 = image.get(IMAGE_TIME_KEY).get(CREATION_TIME_STAMP_KEY).asText(); try { date = ISO8601Utils.parse(iso8601); } catch (final IllegalArgumentException e) { // Don't like this,but not all times have the Z at the end for // ISO-8601 if (iso8601.charat(iso8601.length() - 1) != 'Z') { iso8601 = iso8601 + "Z"; date = ISO8601Utils.parse(iso8601); } else { throw e; } } return date; }
public ObjectNode toJsonShallow(final FileStore.File file) throws RepositoryException { final ObjectNode json = JsonNodeFactory.instance.objectNode(); json.put("id",file.getIdentifier()); json.put("name",file.getName()); json.put("path",file.getPath()); json.put("mime",file.getMimeType()); json.put("sha512",file.getDigest()); json.put("type","file"); json.put("parent",file.getParent().getIdentifier()); json.put("accessLevel",file.getAccessLevel().toString()); json.put("modified",ISO8601Utils.format( file.getModificationTime().getTime(),TimeZone.getDefault())); return json; }
@Test public void testGetValuenormalDate() throws Exception { Date date = new Date(); String strDate = ISO8601Utils.format(date); new Expectations() { { request.getHeader("h1"); result = strDate; } }; HeaderProcessor processor = createProcessor("h1",ISO8601Utils.format((Date) value)); }
@Test public void testSetValueDate() throws Exception { Date date = new Date(); String strDate = ISO8601Utils.format(date); createClientRequest(); HeaderProcessor processor = createProcessor("h1",Date.class); processor.setValue(clientRequest,date); Assert.assertEquals(strDate,headers.get("h1")); }
@Test public void testSetValueDate() throws Exception { Date date = new Date(); String strDate = ISO8601Utils.format(date); createClientRequest(); CookieProcessor processor = createProcessor("h1",cookies.get("h1")); }
@Test public void testGetValuenormalDate() throws Exception { Date date = new Date(); String strDate = ISO8601Utils.format(date); new Expectations() { { request.getParameter("name"); result = strDate; } }; ParamValueProcessor processor = createProcessor("name",ISO8601Utils.format((Date) value)); }
@JsonCreator public Token(@JsonProperty("appId") String appId,@JsonProperty("secret") String secret,@JsonProperty("creator") User creator,@JsonProperty("creationTime") String creationTimeAsText) throws ParseException { this(requireNonNull(appId,"appId"),requireNonNull(secret,"secret"),requireNonNull(creator,"creator"),ISO8601Utils.parse(requireNonNull(creationTimeAsText,"creationTimeAsText"),new ParsePosition(0)),creationTimeAsText); }
@JsonProperty public String creationTime() { if (creationTimeAsText == null) { creationTimeAsText = ISO8601Utils.format(creationTime); } return creationTimeAsText; }
@Override public StringBuffer format(Date date,StringBuffer toAppendTo,FieldPosition fieldPosition) { String value = ISO8601Utils.format(date,CurrentTimeZone.get()); toAppendTo.append(value); return toAppendTo; }
public static ObjectNode history(String userId,Date date,String event,String state,String msg,String step,String toStep,String stepName,String toStepName) { ObjectNode hevent = mapper.createObjectNode(); hevent.with("user").put("id",userId); hevent.put("date",ISO8601Utils.format(date)); hevent.put("type",event); hevent.put("state",state); hevent.put("comment",msg); hevent.put("step",step); hevent.put("toStep",toStep); hevent.put("stepName",stepName); hevent.put("toStepName",toStepName); return hevent; }
public static ObjectNode statusMsg(char type,String message,String userId,Date date) { String typestr; switch( type ) { case 'a': typestr = "accept"; break; case 'r': typestr = "reject"; break; case 's': typestr = "submit"; break; case 'c': typestr = "comment"; break; default: throw new Error("Unsupported type: " + type); } ObjectNode msg = mapper.createObjectNode(); msg.put("type",typestr); msg.put("message",message); msg.put("date",ISO8601Utils.format(date)); msg.with("user").put("id",userId); return msg; }
public static ObjectNode importTaskStatus(String uuid,char status,Date started,Date due,Collection<String> accepted) { ObjectNode ns = importStatus(uuid,status); ns.put("started",ISO8601Utils.format(started)); ns.put("due",due != null ? ISO8601Utils.format(due) : null); ArrayNode users = ns.withArray("acceptedUsers"); for( String user : accepted ) { users.add(user); } return ns; }
private void assertInWaitingOrder(JsonNode jsonNode) throws Exception { Date first = new Date(0l); // 1970 JsonNode results = jsonNode.get("results"); assertTrue(results.size() > 1,"Must have at least 2 results"); for( JsonNode result : results ) { JsonNode dateNode = result.get("startDate"); Date started = ISO8601Utils.parse(dateNode.asText()); assertTrue(started.after(first) || started.equals(first),"Results were not sorted by waiting date"); first = started; } }
/** * Delete connections to all connected banks for given session ID. * * @param sessionId Session ID. * @param sessionPublicKey A public key of this session,obtained by calling {@link ExpressstatementClient#initExpressstatement()}. * @return OK response with session ID in case everything works as expected. * @throws ErrorException ErrorException In case error occurs,for example with signature validation. * @see DeleteConnectionResponse */ public DeleteConnectionResponse deleteallConnections(String sessionId,String sessionPublicKey) throws ErrorException { DeleteConnectionRequest requestObject = new DeleteConnectionRequest(); requestObject.setSessionId(sessionId); requestObject.setAppKey(configuration.getApplicationAppKey()); requestObject.setTimestamp(ISO8601Utils.format(new Date())); requestObject.setNonce(ExpressstatementSignature.generateNonce()); return httpPost("/api/statement/delete",requestObject,DeleteConnectionResponse.class,sessionPublicKey); }
/** Parses an ISO 8601 date+time string into a Java Date object. */ public static Date parseTimestamp(@Nullable String string) { Date date = null; try { if (string != null) { date = ISO8601Utils.parse(string,new ParsePosition(0)); } } catch (ParseException e) { throw Throwables.propagate(e); } return date; }
public static Date parseDate(String s) { if (s != null) { try { return ISO8601Utils.parse(s,new ParsePosition(0)); } catch (ParseException e) { return null; } } return null; }
@Override public String toJson() { final StringBuilder json = new StringBuilder("{"); if (data != null) { json.append("\"timestamp\":\"").append(ISO8601Utils.format(timestamp,defaultTimeZone)).append("\",\"responseTime\":").append(responseTime); if (!data.isEmpty()) { json.append(',').append(jsonifyMap("data",data)); } json.append(',').append(jsonifyCollection("thresholds",thresholds)); } json.append('}'); return json.toString(); }
@Override public String toJson() { final StringBuilder json = new StringBuilder(); if (status == null) { json.append("null"); } else { json.append('{'); if (timestamp != null) { json.append("\"timestamp\":\"").append(ISO8601Utils.format(timestamp,"); } json.append("\"status\":\"").append(status).append("\",\"description\":\"").append(description).append("\"}"); } return json.toString(); }
public static Date parseDate(String date) { try { return ISO8601Utils.parse(date,new ParsePosition(0)); } catch (ParseException e) { throw new IllegalStateException(e); } }
public static Date parseDate(String date) { Date d = null; try { d = ISO8601Utils.parse(date,new ParsePosition(0)); } catch (ParseException e) { throw new IllegalStateException(e); } return d; }
@Override public StringBuffer format(Date date,StringBuffer stringbuffer,FieldPosition fieldposition) { String s = ISO8601Utils.format(date,true); stringbuffer.append(s); return stringbuffer; }
public ObjectNode toJson(final Notification notification) { final ObjectNode json = Json.newObject(); json.put("id",notification.getId()); json.put("message",notification.getMessage()); json.put("read",notification.isRead()); json.put("timestamp",ISO8601Utils.format( notification.getCreated(),TimeZone.getDefault())); return json; }
@SubjectPresent public Result versionList(final String fileId) { return fileBasedResult(fileId,new FileOp() { @Override public final Result apply(final Session session,final FileStore.File file) throws RepositoryException { final ArrayNode json = JsonNodeFactory.instance.arrayNode(); for (FileStore.File version : file.getVersions()) { final User author = version.getAuthor(); final ObjectNode versionInfo = Json.newObject(); versionInfo.put("id",version.getIdentifier()); versionInfo.put("name",version.getName()); if (author != null) { final ObjectNode authorInfo = Json.newObject(); authorInfo.put("id",author.getId()); authorInfo.put("name",author.getName()); authorInfo.put("email",author.getEmail()); versionInfo.put("author",authorInfo); } versionInfo.put("timestamp",ISO8601Utils.format( version.getModificationTime().getTime(),false,TimeZone.getDefault())); json.add(versionInfo); } return ok(json).as("application/json; charset=utf-8"); } }); }
@Test public void testNotification() { final JsonBuilder jb = new JsonBuilder(); final String randomId = UUID.randomUUID().toString(); final Notification notification = new Notification() { @Override public String getId() { return randomId; } @Override public Date getCreated() { return new Date(0); } }; notification.setMessage("Test message."); // Get JSON final ObjectNode json = jb.toJson(notification); assertthat(json.get("id")).isNotNull(); assertthat(json.get("id").asText()).isEqualTo(notification.getId()); assertthat(json.get("read")).isNotNull(); assertthat(json.get("read").asBoolean()).isEqualTo(false); assertthat(json.get("message")).isNotNull(); assertthat(json.get("message").asText()) .isEqualTo(notification.getMessage()); assertthat(json.get("timestamp")).isNotNull(); assertthat(json.get("timestamp").asText()).isEqualTo( ISO8601Utils.format(notification.getCreated(),TimeZone.getDefault())); }
/** * @throws ParseException */ private RequestMetric request(String requestStart,long requestDuration,String url,String resource,String method,String apiOrgId,String apiId,String apiVersion,String planId,String clientOrgId,String clientId,String clientVersion,String contractId,String user,int responseCode,String responseMessage,boolean failure,int failureCode,String failureReason,boolean error,String errorMessage,long bytesuploaded,long bytesDownloaded) throws ParseException { Date start = ISO8601Utils.parse(requestStart,new ParsePosition(0)); RequestMetric rval = new RequestMetric(); rval.setRequestStart(start); rval.setRequestEnd(new Date(start.getTime() + requestDuration)); rval.setApiStart(start); rval.setApiEnd(rval.getRequestEnd()); rval.setApiDuration(requestDuration); rval.setUrl(url); rval.setResource(resource); rval.setMethod(method); rval.setApiOrgId(apiOrgId); rval.setApiId(apiId); rval.setApiVersion(apiVersion); rval.setPlanId(planId); rval.setClientOrgId(clientOrgId); rval.setClientId(clientId); rval.setClientVersion(clientVersion); rval.setContractId(contractId); rval.setUser(user); rval.setResponseCode(responseCode); rval.setResponseMessage(responseMessage); rval.setFailure(failure); rval.setFailureCode(failureCode); rval.setFailureReason(failureReason); rval.setError(error); rval.setErrorMessage(errorMessage); rval.setBytesuploaded(bytesuploaded); rval.setBytesDownloaded(bytesDownloaded); return rval; }
@Override public StringBuffer format(Date date,FieldPosition fieldPosition) { String value = ISO8601Utils.format(date,true); toAppendTo.append(value); return toAppendTo; }
@Override public StringBuffer format(Date date,true); toAppendTo.append(value); return toAppendTo; }
@Override public StringBuffer format(Date date,true); toAppendTo.append(value); return toAppendTo; }
@Override public StringBuffer format(Date date,true); toAppendTo.append(value); return toAppendTo; }
@Override public StringBuffer format(Date date,true); toAppendTo.append(value); return toAppendTo; }
@Override public StringBuffer format(Date date,FieldPosition fieldPosition) { String value = ISO8601Utils.format(date,true); toAppendTo.append(value); return toAppendTo; }
@Override public StringBuffer format(Date date,true); toAppendTo.append(value); return toAppendTo; }
@Override public StringBuffer format(Date date,true); toAppendTo.append(value); return toAppendTo; }
关于OS X上的bash – `date`命令没有ISO 8601`-I’选项?和没有.bash_profile的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于bash – 如何将命令结果传递给 – 选项? (没有空格)、bash – 安装make命令没有make(mac os 10.5)、com.fasterxml.jackson.databind.util.ISO8601DateFormat的实例源码、com.fasterxml.jackson.databind.util.ISO8601Utils的实例源码等相关知识的信息别忘了在本站进行查找喔。
本文标签: