List of usage examples for org.joda.time.format ISODateTimeFormat dateTimeNoMillis
public static DateTimeFormatter dateTimeNoMillis()
From source file:com.alfaariss.oa.authentication.remote.saml2.idp.storage.config.IDPConfigStorage.java
License:Open Source License
/** * @see com.alfaariss.oa.engine.idp.storage.configuration.AbstractConfigurationStorage#createIDP(com.alfaariss.oa.api.configuration.IConfigurationManager, org.w3c.dom.Element) *//*w ww . j a va2 s .c om*/ @Override protected IIDP createIDP(IConfigurationManager configManager, Element config) throws OAException { SAML2IDP saml2IDP = null; try { String sID = configManager.getParam(config, "id"); if (sID == null) { _oLogger.error("No 'id' item found in 'organization' section in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } byte[] baSourceID = generateSHA1(sID); String sFriendlyName = configManager.getParam(config, "friendlyname"); if (sFriendlyName == null) { _oLogger.error("No 'friendlyname' item found in 'organization' section in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } String sDateLastModified = configManager.getParam(config, "lastmodified"); Date dLastModified = null; if (sDateLastModified != null) { // Convert to java.util.Date try { DateTime dt = ISODateTimeFormat.dateTimeNoMillis().parseDateTime(sDateLastModified); dLastModified = dt.toDate(); } catch (IllegalArgumentException iae) { _oLogger.info( "Invalid 'lastmodified' timestamp provided: " + sDateLastModified + "; ignoring."); dLastModified = null; } } String sMetadataURL = null; int iMetadataURLTimeout = -1; String sMetadataFile = null; Element eMetadata = configManager.getSection(config, "metadata"); if (eMetadata == null) { _oLogger.warn( "No optional 'metadata' section found in configuration for organization with id: " + sID); } else { Element eHttp = configManager.getSection(eMetadata, "http"); if (eHttp == null) { _oLogger.warn( "No optional 'http' section in 'metadata' section found in configuration for organization with id: " + sID); } else { sMetadataURL = configManager.getParam(eHttp, "url"); if (sMetadataURL == null) { _oLogger.error( "No 'url' item in 'http' section found in configuration for organization with id: " + sID); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } URL urlTarget = null; try { urlTarget = new URL(sMetadataURL); } catch (MalformedURLException e) { _oLogger.error( "Invalid 'url' item in 'http' section found in configuration: " + sMetadataURL, e); throw new OAException(SystemErrors.ERROR_INIT); } StringBuffer sbInfo = new StringBuffer("Organization '"); sbInfo.append(sID); sbInfo.append("' uses metadata from url: "); sbInfo.append(sMetadataURL); _oLogger.info(sbInfo.toString()); try { URLConnection urlConnection = urlTarget.openConnection(); urlConnection.setConnectTimeout(3000); urlConnection.setReadTimeout(3000); urlConnection.connect(); } catch (IOException e) { _oLogger.warn("Could not connect to 'url' item in 'http' section found in configuration: " + sMetadataURL, e); } String sTimeout = configManager.getParam(eHttp, "timeout"); if (sTimeout != null) { try { iMetadataURLTimeout = Integer.parseInt(sTimeout); } catch (NumberFormatException e) { _oLogger.error( "Invalid 'timeout' item in 'http' section found in configuration (must be a number): " + sTimeout, e); throw new OAException(SystemErrors.ERROR_INIT); } if (iMetadataURLTimeout < 0) { _oLogger.error( "Invalid 'timeout' item in 'http' section found in configuration: " + sTimeout); throw new OAException(SystemErrors.ERROR_INIT); } } } sMetadataFile = configManager.getParam(eMetadata, "file"); if (sMetadataFile == null) { _oLogger.warn( "No optional 'file' item in 'metadata' section found in configuration for organization with id: " + sID); } else { // Translate the path sMetadataFile = PathTranslator.getInstance().map(sMetadataFile); File fMetadata = new File(sMetadataFile); if (!fMetadata.exists()) { _oLogger.error("Configured metadata 'file' doesn't exist: " + sMetadataFile); throw new OAException(SystemErrors.ERROR_INIT); } StringBuffer sbInfo = new StringBuffer("Organization '"); sbInfo.append(sID); sbInfo.append("' uses metadata in file: "); sbInfo.append(sMetadataFile); _oLogger.info(sbInfo.toString()); } } Boolean boolACSIndex = new Boolean(true); String sACSIndex = configManager.getParam(config, "acs_index"); if (sACSIndex != null) { if (sACSIndex.equalsIgnoreCase("FALSE")) boolACSIndex = new Boolean(false); else if (!sACSIndex.equalsIgnoreCase("TRUE")) { _oLogger.error("Invalid 'acs_index' item value found in configuration: " + sACSIndex); throw new OAException(SystemErrors.ERROR_INIT); } } Boolean boolScoping = new Boolean(true); String sScoping = configManager.getParam(config, "scoping"); if (sScoping != null) { if (sScoping.equalsIgnoreCase("FALSE")) boolScoping = new Boolean(false); else if (!sScoping.equalsIgnoreCase("TRUE")) { _oLogger.error("Invalid 'scoping' item value found in configuration: " + sScoping); throw new OAException(SystemErrors.ERROR_INIT); } } Boolean boolNameIDPolicy = new Boolean(true); String sNameIDFormat = null; Boolean boolAllowCreate = null; Element eNameIDPolicy = configManager.getSection(config, "nameidpolicy"); if (eNameIDPolicy != null) { String sNameIDPolicyEnabled = configManager.getParam(eNameIDPolicy, "enabled"); if (sNameIDPolicyEnabled != null) { if (sNameIDPolicyEnabled.equalsIgnoreCase("FALSE")) boolNameIDPolicy = new Boolean(false); else if (!sNameIDPolicyEnabled.equalsIgnoreCase("TRUE")) { _oLogger.error( "Invalid 'enabled' item value in 'nameidpolicy' section found in configuration: " + sNameIDPolicyEnabled); throw new OAException(SystemErrors.ERROR_INIT); } } if (boolNameIDPolicy) { String sAllowCreate = configManager.getParam(eNameIDPolicy, "allow_create"); if (sAllowCreate != null) { if (sAllowCreate.equalsIgnoreCase("TRUE")) boolAllowCreate = new Boolean(true); else if (sAllowCreate.equalsIgnoreCase("FALSE")) boolAllowCreate = new Boolean(false); else { _oLogger.error( "Invalid 'allow_create' item value found in configuration: " + sAllowCreate); throw new OAException(SystemErrors.ERROR_INIT); } } sNameIDFormat = configManager.getParam(eNameIDPolicy, "nameidformat"); } } Boolean boolAvoidSubjectConfirmation = new Boolean(false); // default: don't avoid String sAvoidSC = configManager.getParam(config, "avoid_subjectconfirmation"); if (sAvoidSC != null) { if (sAvoidSC.equalsIgnoreCase("TRUE")) boolAvoidSubjectConfirmation = new Boolean(true); else if (!sAvoidSC.equalsIgnoreCase("FALSE")) { _oLogger.error( "Invalid 'avoid_subjectconfirmation' item value found in configuration: " + sAvoidSC); throw new OAException(SystemErrors.ERROR_INIT); } } Boolean boolDisableSSOForIDP = new Boolean(false); // default: don't disable String sDisableSSO = configManager.getParam(config, "disable_sso"); if (sDisableSSO != null) { if (sDisableSSO.equalsIgnoreCase("TRUE")) boolDisableSSOForIDP = new Boolean(true); else if (!sDisableSSO.equalsIgnoreCase("FALSE")) { _oLogger.error("Invalid 'disable_sso' item value found in configuration: " + sDisableSSO); throw new OAException(SystemErrors.ERROR_INIT); } } saml2IDP = new SAML2IDP(sID, baSourceID, sFriendlyName, sMetadataFile, sMetadataURL, iMetadataURLTimeout, boolACSIndex, boolAllowCreate, boolScoping, boolNameIDPolicy, sNameIDFormat, boolAvoidSubjectConfirmation, boolDisableSSOForIDP, dLastModified, _sMPMId); } catch (OAException e) { throw e; } catch (Exception e) { _oLogger.fatal("Internal error while reading organization configuration", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return saml2IDP; }
From source file:com.alfaariss.oa.engine.requestor.configuration.ConfigurationPool.java
License:Open Source License
private Requestor createRequestor(IConfigurationManager oConfigurationManager, Element eConfig) throws RequestorException { Requestor oRequestor = null;/*from w ww .j ava 2 s . com*/ try { String sID = oConfigurationManager.getParam(eConfig, "id"); if (sID == null) { _logger.error("No 'id' item in 'requestor' section found in configuration"); throw new RequestorException(SystemErrors.ERROR_CONFIG_READ); } String sEnabled = oConfigurationManager.getParam(eConfig, "enabled"); boolean bEnabled = true; if (sEnabled != null) { if (sEnabled.equalsIgnoreCase("FALSE")) bEnabled = false; else if (!sEnabled.equalsIgnoreCase("TRUE")) { _logger.error("Unknown value in 'enabled' configuration item: " + sEnabled); throw new RequestorException(SystemErrors.ERROR_CONFIG_READ); } } if (!bEnabled) { StringBuffer sbInfo = new StringBuffer("Requestor with id '"); sbInfo.append(sID); sbInfo.append("' is disabled"); _logger.info(sbInfo.toString()); return null; } String sFriendlyName = oConfigurationManager.getParam(eConfig, "friendlyname"); if (sFriendlyName == null) { _logger.error("No 'friendlyname' item in 'requestor' section found in configuration"); throw new RequestorException(SystemErrors.ERROR_CONFIG_READ); } Element eProperties = oConfigurationManager.getSection(eConfig, "properties"); Properties properties = null; if (eProperties == null) { _logger.info("No 'properties' section found, no extended properties found for requestor: " + sID); properties = new Properties(); } else { properties = readExtendedProperties(oConfigurationManager, eProperties); } String sDateLastModified = oConfigurationManager.getParam(eConfig, "lastmodified"); Date dLastModified = null; if (sDateLastModified != null) { // Convert to java.util.Date try { DateTime dt = ISODateTimeFormat.dateTimeNoMillis().parseDateTime(sDateLastModified); dLastModified = dt.toDate(); } catch (IllegalArgumentException iae) { _logger.info("Invalid 'lastmodified' timestamp provided: " + sDateLastModified + "; ignoring."); dLastModified = null; } } oRequestor = new Requestor(sID, sFriendlyName, bEnabled, properties, dLastModified); _logger.info("Found: " + oRequestor); } catch (RequestorException e) { throw e; } catch (Exception e) { _logger.fatal("Internal error during pool object update", e); throw new RequestorException(SystemErrors.ERROR_INTERNAL, e); } return oRequestor; }
From source file:com.alfaariss.oa.util.saml2.SAML2Requestor.java
License:Open Source License
/** * Constructor.// www . j a v a 2 s .c om * * @param configurationManager The config manager. * @param config Configuration section. * @param bSigning Default signing boolean. * @param sMPMId The name of the MetadataProviderManager that manages the MetadataProvider * for this SAML2Requestor * @throws OAException If creation fails. */ public SAML2Requestor(IConfigurationManager configurationManager, Element config, boolean bSigning, String sMPMId) throws OAException { try { _sID = configurationManager.getParam(config, "id"); if (_sID == null) { _logger.error("No 'id' item found in 'requestor' section in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } _bSigning = false; String sSigning = configurationManager.getParam(config, "signing"); if (sSigning == null) { _logger.warn("No optional 'signing' item found in configuration for requestor with id: " + _sID); _bSigning = bSigning; } else { if (sSigning.equalsIgnoreCase("TRUE")) { _bSigning = true; } else { if (!sSigning.equalsIgnoreCase("FALSE")) { _logger.error( "Invalid 'signing' item found in configuration (must be true or false) for requestor with id: " + _sID); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } } } _logger.info("Using signing enabled: " + _bSigning); String sDateLastModified = configurationManager.getParam(config, "lastmodified"); _dLastModified = null; if (sDateLastModified != null) { // Convert to java.util.Date try { DateTime dt = ISODateTimeFormat.dateTimeNoMillis().parseDateTime(sDateLastModified); _dLastModified = dt.toDate(); } catch (IllegalArgumentException iae) { _logger.warn("Invalid 'lastmodified' timestamp provided: " + sDateLastModified + "; ignoring."); _dLastModified = null; } } // Keep reference to the MetadataProviderManager _sMPMId = sMPMId; // Do some integrity checking: IMetadataProviderManager oMPM = MdMgrManager.getInstance().getMetadataProviderManager(_sMPMId); if (oMPM == null) _logger.warn("The MetadataProviderManager '" + _sMPMId + "' does not (yet?) exist!"); // Initialize MetadataProviderConfig _oMetadataProviderConfig = getMetadataConfigFromConfig(configurationManager, config); // Initialize upon construction, as last modification date will not change initMetadataProvider(); } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Internal error while reading requestors configuration", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } }
From source file:com.animedetour.android.model.transformer.ApiEventTransformer.java
License:Open Source License
@Override public Pair<ApiEvent, DateTime> reverseTransform(Event data) { return new Pair<>( new ApiEvent(data.getId(), data.getName(), ISODateTimeFormat.dateTimeNoMillis().print(data.getStart()), ISODateTimeFormat.dateTimeNoMillis().print(data.getEnd()), data.getCategory(), data.getTags(), data.getRoom(), data.getHosts(), data.getDescription(), data.getBanner()), data.getFetched());//from w w w. jav a 2s . c o m }
From source file:com.digi.android.wva.fragments.ChartFragment.java
License:Mozilla Public License
/** * Repaints the chart view onto the screen. This is done by * removing the chart view from the layout, calling repaint(), * and putting the view back into the layout. */*from ww w .j av a 2 s . c o m*/ * <p>This method is protected, rather than private, due to a bug between JaCoCo and * the Android build tools which causes the instrumented bytecode to be invalid when this * method is private: * http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode * </p> */ protected void redrawChart() { // super.getView() should return NoSaveStateFrameLayout, which // extends FrameLayout, which extends ViewGroup ViewGroup l = (ViewGroup) super.getView(); if (mChart == null) { mChart = ChartFactory.getCombinedXYChartView(getActivity(), mDataset, mRenderer, new String[] { LineChart.TYPE, LineChart.TYPE }); mChart.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SeriesSelection sel = mChart.getCurrentSeriesAndPoint(); if (sel == null) return; String series = "SERIES"; switch (sel.getSeriesIndex()) { case 0: series = "Vehicle Speed"; break; case 1: series = "Engine RPM"; break; } String time = ISODateTimeFormat.dateTimeNoMillis().print((long) sel.getXValue()); Toast.makeText(getActivity(), series + " (" + time + "): " + sel.getValue(), Toast.LENGTH_SHORT) .show(); } }); } if (l != null) { // Ensure that the chart is removed from all views. try { if (mChart.getParent() != null) { //noinspection ConstantConditions ((ViewGroup) mChart.getParent()).removeAllViews(); } } catch (Exception e) { e.printStackTrace(); } l.removeAllViews(); mChart.repaint(); l.addView(mChart); } else { // If the getView() result is null, something's up, like // the activity has been backgrounded. Log.d(TAG, "redrawChart -- l is null"); } }
From source file:com.digi.android.wva.model.LogEvent.java
License:Mozilla Public License
/** * Create a new LogEvent.// ww w . j av a 2s. c o m * * <p>If the timestamp passed in is null, the current time will be used.</p> * @param message message of the event * @param timestamp timestamp of the event * @param alarm true if the event is to record that an alarm went off */ public LogEvent(String message, String timestamp, boolean alarm) { if (TextUtils.isEmpty(timestamp)) { timestamp = ISODateTimeFormat.dateTimeNoMillis().print(DateTime.now()); } this.message = message; this.timestamp = timestamp; isAlarm = alarm; }
From source file:com.digitalpebble.stormcrawler.elasticsearch.persistence.AggregationSpout.java
License:Apache License
@Override protected void populateBuffer() { if (lastDate == null) { lastDate = new Date(); }//from w ww . j ava 2 s. c o m String formattedLastDate = ISODateTimeFormat.dateTimeNoMillis().print(lastDate.getTime()); LOG.info("{} Populating buffer with nextFetchDate <= {}", logIdprefix, formattedLastDate); QueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("nextFetchDate").lte(formattedLastDate); SearchRequestBuilder srb = client.prepareSearch(indexName).setTypes(docType) .setSearchType(SearchType.QUERY_THEN_FETCH).setQuery(rangeQueryBuilder).setFrom(0).setSize(0) .setExplain(false); TermsAggregationBuilder aggregations = AggregationBuilders.terms("partition").field(partitionField) .size(maxBucketNum); TopHitsAggregationBuilder tophits = AggregationBuilders.topHits("docs").size(maxURLsPerBucket) .explain(false); // sort within a bucket if (StringUtils.isNotBlank(bucketSortField)) { FieldSortBuilder sorter = SortBuilders.fieldSort(bucketSortField).order(SortOrder.ASC); tophits.sort(sorter); } aggregations.subAggregation(tophits); // sort between buckets if (StringUtils.isNotBlank(totalSortField)) { MinAggregationBuilder minBuilder = AggregationBuilders.min("top_hit").field(totalSortField); aggregations.subAggregation(minBuilder); aggregations.order(Terms.Order.aggregation("top_hit", true)); } if (sample) { DiversifiedAggregationBuilder sab = new DiversifiedAggregationBuilder("sample"); sab.field(partitionField).maxDocsPerValue(maxURLsPerBucket); sab.shardSize(maxURLsPerBucket * maxBucketNum); sab.subAggregation(aggregations); srb.addAggregation(sab); } else { srb.addAggregation(aggregations); } // https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-preference.html // _shards:2,3 if (shardID != -1) { srb.setPreference("_shards:" + shardID); } // dump query to log LOG.debug("{} ES query {}", logIdprefix, srb.toString()); timeStartESQuery = System.currentTimeMillis(); isInESQuery.set(true); srb.execute(this); }
From source file:com.digitalpebble.stormcrawler.elasticsearch.persistence.CollapsingSpout.java
License:Apache License
@Override protected void populateBuffer() { // not used yet or returned empty results if (lastDate == null) { lastDate = new Date(); lastStartOffset = 0;//from www . j av a 2s.co m } // been running same query for too long and paging deep? else if (maxStartOffset != -1 && lastStartOffset > maxStartOffset) { LOG.info("Reached max start offset {}", lastStartOffset); lastStartOffset = 0; } String formattedLastDate = ISODateTimeFormat.dateTimeNoMillis().print(lastDate.getTime()); LOG.info("{} Populating buffer with nextFetchDate <= {}", logIdprefix, formattedLastDate); QueryBuilder queryBuilder = QueryBuilders.rangeQuery("nextFetchDate").lte(formattedLastDate); SearchRequestBuilder srb = client.prepareSearch(indexName).setTypes(docType) .setSearchType(SearchType.QUERY_THEN_FETCH).setQuery(queryBuilder).setFrom(lastStartOffset) .setSize(maxBucketNum).setExplain(false); // https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-preference.html // _shards:2,3 if (shardID != -1) { srb.setPreference("_shards:" + shardID); } if (StringUtils.isNotBlank(totalSortField)) { FieldSortBuilder sorter = SortBuilders.fieldSort(totalSortField).order(SortOrder.ASC); srb.addSort(sorter); } CollapseBuilder collapse = new CollapseBuilder(partitionField); srb.setCollapse(collapse); // group expansion -> sends sub queries for each bucket if (maxURLsPerBucket > 1) { InnerHitBuilder ihb = new InnerHitBuilder(); ihb.setSize(maxURLsPerBucket); ihb.setName("urls_per_bucket"); // sort within a bucket if (StringUtils.isNotBlank(bucketSortField)) { List<SortBuilder<?>> sorts = new LinkedList<>(); FieldSortBuilder bucketsorter = SortBuilders.fieldSort(bucketSortField).order(SortOrder.ASC); sorts.add(bucketsorter); ihb.setSorts(sorts); } collapse.setInnerHits(ihb); } // dump query to log LOG.debug("{} ES query {}", logIdprefix, srb.toString()); timeStartESQuery = System.currentTimeMillis(); isInESQuery.set(true); srb.execute(this); }
From source file:com.enitalk.configs.DateCache.java
@Bean(name = "skipCache") public LoadingCache<String, ConcurrentSkipListSet<DateTime>> datesMap() { CacheBuilder<Object, Object> ccc = CacheBuilder.newBuilder(); ccc.expireAfterWrite(2, TimeUnit.MINUTES); LoadingCache<String, ConcurrentSkipListSet<DateTime>> cache = ccc .build(new CacheLoader<String, ConcurrentSkipListSet<DateTime>>() { @Override// ww w . j a v a2s .c o m public ConcurrentSkipListSet<DateTime> load(String key) throws Exception { try { HashMap teachers = mongo.findOne(Query.query(Criteria.where("i").is(key)), HashMap.class, "teachers"); ObjectNode teacherJson = jackson.convertValue(teachers, ObjectNode.class); String timeZone = teacherJson.at("/calendar/timeZone").asText(); NavigableSet<DateTime> set = days(teacherJson.path("schedule"), timeZone, teacherJson); DateTimeZone dzz = DateTimeZone.forID(timeZone); DateTimeFormatter df = ISODateTimeFormat.dateTimeNoMillis().withZone(dzz); byte[] events = calendar.busyEvents(jackson.createObjectNode().put("id", key)); JsonNode evs = jackson.readTree(events); Iterator<JsonNode> its = evs.iterator(); TreeSet<DateTime> dates = new TreeSet<>(); while (its.hasNext()) { String date = its.next().asText(); DateTime av = df.parseDateTime(date).toDateTime(DateTimeZone.UTC); dates.add(av); } set.removeAll(dates); logger.info("Dates for i {} {}", key, set); return new ConcurrentSkipListSet<>(set); } catch (Exception e) { logger.error(ExceptionUtils.getFullStackTrace(e)); } return null; } }); return cache; }
From source file:com.example.bigquery.QueryParametersSample.java
License:Apache License
private static void runTimestamp() throws InterruptedException { BigQuery bigquery = new BigQueryOptions.DefaultBigqueryFactory() .create(BigQueryOptions.getDefaultInstance()); DateTime timestamp = new DateTime(2016, 12, 7, 8, 0, 0, DateTimeZone.UTC); String queryString = "SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);"; QueryRequest queryRequest = QueryRequest.newBuilder(queryString) .addNamedParameter("ts_value", QueryParameterValue.timestamp( // Timestamp takes microseconds since 1970-01-01T00:00:00 UTC timestamp.getMillis() * 1000)) // Standard SQL syntax is required for parameterized queries. // See: https://cloud.google.com/bigquery/sql-reference/ .setUseLegacySql(false).build(); // Execute the query. QueryResponse response = bigquery.query(queryRequest); // Wait for the job to finish (if the query takes more than 10 seconds to complete). while (!response.jobCompleted()) { Thread.sleep(1000);/*w w w . ja v a 2 s . c o m*/ response = bigquery.getQueryResults(response.getJobId()); } if (response.hasErrors()) { throw new RuntimeException(response.getExecutionErrors().stream().<String>map(err -> err.getMessage()) .collect(Collectors.joining("\n"))); } QueryResult result = response.getResult(); Iterator<List<FieldValue>> iter = result.iterateAll(); DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis().withZoneUTC(); while (iter.hasNext()) { List<FieldValue> row = iter.next(); System.out.printf("%s\n", formatter.print(new DateTime( // Timestamp values are returned in microseconds since 1970-01-01T00:00:00 UTC, // but org.joda.time.DateTime constructor accepts times in milliseconds. row.get(0).getTimestampValue() / 1000, DateTimeZone.UTC))); } }