Search in sources :

Example 51 with Objects

use of java.util.Objects in project jgnash by ccavanaugh.

the class Engine method emptyTrash.

/**
     * Empty the trash if any objects are older than the defined time.
     */
private void emptyTrash() {
    if (backGroundCounter.incrementAndGet() == 1) {
        messageBus.fireEvent(new Message(MessageChannel.SYSTEM, ChannelEvent.BACKGROUND_PROCESS_STARTED, Engine.this));
    }
    dataLock.writeLock().lock();
    try {
        logger.info("Checking for trash");
        final List<TrashObject> trash = getTrashDAO().getTrashObjects();
        /* always sort by the timestamp of the trash object to prevent
             * foreign key removal exceptions when multiple related accounts
             * or objects are removed */
        Collections.sort(trash);
        if (trash.isEmpty()) {
            logger.info("No trash was found");
        }
        trash.stream().filter(o -> ChronoUnit.MILLIS.between(o.getDate(), LocalDateTime.now()) >= MAXIMUM_TRASH_AGE).forEach(o -> getTrashDAO().remove(o));
    } finally {
        dataLock.writeLock().unlock();
        if (backGroundCounter.decrementAndGet() == 0) {
            messageBus.fireEvent(new Message(MessageChannel.SYSTEM, ChannelEvent.BACKGROUND_PROCESS_STOPPED, Engine.this));
        }
    }
}
Also used : EngineDAO(jgnash.engine.dao.EngineDAO) CurrencyUpdateFactory(jgnash.net.currency.CurrencyUpdateFactory) ScheduledFuture(java.util.concurrent.ScheduledFuture) UpdateFactory(jgnash.net.security.UpdateFactory) TimeoutException(java.util.concurrent.TimeoutException) LockManager(jgnash.engine.concurrent.LockManager) MessageBus(jgnash.engine.message.MessageBus) BigDecimal(java.math.BigDecimal) Nullable(jgnash.util.Nullable) Future(java.util.concurrent.Future) Budget(jgnash.engine.budget.Budget) MessageProperty(jgnash.engine.message.MessageProperty) RecurringIterator(jgnash.engine.recurring.RecurringIterator) MessageChannel(jgnash.engine.message.MessageChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DefaultDaemonThreadFactory(jgnash.util.DefaultDaemonThreadFactory) Path(java.nio.file.Path) AttachmentManager(jgnash.engine.attachment.AttachmentManager) NotNull(jgnash.util.NotNull) CancellationException(java.util.concurrent.CancellationException) Collection(java.util.Collection) Set(java.util.Set) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) PendingReminder(jgnash.engine.recurring.PendingReminder) Objects(java.util.Objects) BudgetGoal(jgnash.engine.budget.BudgetGoal) List(java.util.List) LocalDate(java.time.LocalDate) Optional(java.util.Optional) Handler(java.util.logging.Handler) Message(jgnash.engine.message.Message) ConfigDAO(jgnash.engine.dao.ConfigDAO) TrashDAO(jgnash.engine.dao.TrashDAO) LocalDateTime(java.time.LocalDateTime) ResourceUtils(jgnash.util.ResourceUtils) MonthlyReminder(jgnash.engine.recurring.MonthlyReminder) Callable(java.util.concurrent.Callable) CommodityDAO(jgnash.engine.dao.CommodityDAO) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ChannelEvent(jgnash.engine.message.ChannelEvent) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) ResourceBundle(java.util.ResourceBundle) ExecutorService(java.util.concurrent.ExecutorService) DateUtils(jgnash.time.DateUtils) IOException(java.io.IOException) AccountDAO(jgnash.engine.dao.AccountDAO) TransactionDAO(jgnash.engine.dao.TransactionDAO) Reminder(jgnash.engine.recurring.Reminder) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ChronoUnit(java.time.temporal.ChronoUnit) DayOfWeek(java.time.DayOfWeek) BudgetDAO(jgnash.engine.dao.BudgetDAO) Collections(java.util.Collections) CollectionUtils(jgnash.util.CollectionUtils) RecurringDAO(jgnash.engine.dao.RecurringDAO) Message(jgnash.engine.message.Message)

Example 52 with Objects

use of java.util.Objects in project jgnash by ccavanaugh.

the class TableViewManager method getCalculatedColumnWidth.

/**
     * Determines the preferred width of the column including contents.
     *
     * @param column {@code TableColumn} to measure content
     * @return preferred width
     */
private double getCalculatedColumnWidth(final TableColumnBase<S, ?> column) {
    double maxWidth = 0;
    /* Collect all the unique cell items and remove null*/
    final Set<Object> cellItems = new HashSet<>();
    for (int i = 0; i < tableView.getItems().size(); i++) {
        cellItems.add(column.getCellData(i));
    }
    cellItems.remove(null);
    if (cellItems.size() > 0) {
        // don't try if there is no data or the stream function will throw an error
        final OptionalDouble max = cellItems.parallelStream().filter(Objects::nonNull).mapToDouble(o -> {
            final Format format = columnFormatFactory.get().call(column);
            return JavaFXUtils.getDisplayedTextWidth(format != null ? format.format(o) : o.toString(), column.getStyle());
        }).max();
        maxWidth = max.isPresent() ? max.getAsDouble() : 0;
    }
    //noinspection SuspiciousMethodCalls
    maxWidth = Math.max(maxWidth, Math.max(column.getMinWidth(), minimumColumnWidthFactory.get().call(tableView.getColumns().indexOf(column))));
    // header text width
    maxWidth = Math.max(maxWidth, JavaFXUtils.getDisplayedTextWidth(column.getText(), column.getStyle()) * BOLD_MULTIPLIER);
    return Math.ceil(maxWidth + COLUMN_PADDING);
}
Also used : Format(java.text.Format) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) OptionalDouble(java.util.OptionalDouble) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) TableColumn(javafx.scene.control.TableColumn) EncodeDecode(jgnash.util.EncodeDecode) HashSet(java.util.HashSet) TableView(javafx.scene.control.TableView) Callback(javafx.util.Callback) ObjectProperty(javafx.beans.property.ObjectProperty) NotNull(jgnash.util.NotNull) Set(java.util.Set) Logger(java.util.logging.Logger) Preferences(java.util.prefs.Preferences) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) BooleanProperty(javafx.beans.property.BooleanProperty) SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) TableColumnBase(javafx.scene.control.TableColumnBase) SimpleObjectProperty(javafx.beans.property.SimpleObjectProperty) ObservableValue(javafx.beans.value.ObservableValue) ChangeListener(javafx.beans.value.ChangeListener) Format(java.text.Format) Objects(java.util.Objects) OptionalDouble(java.util.OptionalDouble) HashSet(java.util.HashSet)

Example 53 with Objects

use of java.util.Objects in project ddf by codice.

the class ValidateCommand method getMetacardsFromCatalog.

private List<Metacard> getMetacardsFromCatalog() throws Exception {
    List<Metacard> results = new ArrayList<>();
    QueryImpl query = new QueryImpl(getFilter());
    ThreadContext.bind(Security.getInstance().getSystemSubject());
    SourceResponse response = getCatalog().query(new QueryRequestImpl(query));
    List<Result> resultList = response.getResults();
    if (resultList != null) {
        results.addAll(resultList.stream().map(Result::getMetacard).filter(Objects::nonNull).collect(Collectors.toList()));
    }
    return results;
}
Also used : Metacard(ddf.catalog.data.Metacard) QueryImpl(ddf.catalog.operation.impl.QueryImpl) SourceResponse(ddf.catalog.operation.SourceResponse) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) ArrayList(java.util.ArrayList) Objects(java.util.Objects) Result(ddf.catalog.data.Result)

Example 54 with Objects

use of java.util.Objects in project ddf by codice.

the class CqlResult method countMatches.

private void countMatches(Set<SearchTerm> searchTerms, Metacard mc) {
    List<String> textAttributes = mc.getMetacardType().getAttributeDescriptors().stream().filter(CqlResult::isTextAttribute).filter(Objects::nonNull).map(descriptor -> mc.getAttribute(descriptor.getName())).filter(Objects::nonNull).map(attribute -> Optional.ofNullable(attribute.getValue())).filter(Optional::isPresent).map(Optional::get).map(Object::toString).collect(Collectors.toList());
    List<SearchTerm> terms = searchTerms.stream().filter(term -> !"*".equals(term.getTerm())).collect(Collectors.toList());
    int totalTokens = 0;
    for (String value : textAttributes) {
        BufferedReader reader = new BufferedReader(new StringReader(value.toLowerCase()));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                String[] tokens = line.split("[\\s\\p{Punct}]+");
                for (String token : tokens) {
                    totalTokens++;
                    for (SearchTerm term : terms) {
                        if (term.match(token)) {
                            matches.put(term.getTerm(), matches.getOrDefault(term.getTerm(), 0) + 1);
                        }
                    }
                }
            }
        } catch (IOException e) {
            LOGGER.debug("Unable to read line", e);
        }
        matches.put("*", totalTokens);
    }
}
Also used : ValidationRule(org.locationtech.spatial4j.context.jts.ValidationRule) ShapeReader(org.locationtech.spatial4j.io.ShapeReader) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) FilterAdapter(ddf.catalog.filter.FilterAdapter) StringUtils(org.apache.commons.lang3.StringUtils) AttributeType(ddf.catalog.data.AttributeType) Action(ddf.action.Action) DistanceUtils(org.locationtech.spatial4j.distance.DistanceUtils) ImmutableList(com.google.common.collect.ImmutableList) Metacard(ddf.catalog.data.Metacard) Map(java.util.Map) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) QueryRequest(ddf.catalog.operation.QueryRequest) ParseException(java.text.ParseException) Result(ddf.catalog.data.Result) DateTimeFormat(org.joda.time.format.DateTimeFormat) JtsSpatialContextFactory(org.locationtech.spatial4j.context.jts.JtsSpatialContextFactory) Logger(org.slf4j.Logger) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) PropertyJsonMetacardTransformer(ddf.catalog.transformer.metacard.propertyjson.PropertyJsonMetacardTransformer) WktQueryDelegate(org.codice.ddf.catalog.ui.query.delegate.WktQueryDelegate) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) ImmutableMap(com.google.common.collect.ImmutableMap) DateTime(org.joda.time.DateTime) Set(java.util.Set) IOException(java.io.IOException) Shape(org.locationtech.spatial4j.shape.Shape) Collectors(java.util.stream.Collectors) SpatialContextFactory(org.locationtech.spatial4j.context.SpatialContextFactory) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Objects(java.util.Objects) Query(ddf.catalog.operation.Query) List(java.util.List) Attribute(ddf.catalog.data.Attribute) StringReader(java.io.StringReader) SearchTerm(org.codice.ddf.catalog.ui.query.delegate.SearchTerm) Optional(java.util.Optional) ActionRegistry(ddf.action.ActionRegistry) BufferedReader(java.io.BufferedReader) SpatialContext(org.locationtech.spatial4j.context.SpatialContext) Optional(java.util.Optional) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) IOException(java.io.IOException) SearchTerm(org.codice.ddf.catalog.ui.query.delegate.SearchTerm)

Example 55 with Objects

use of java.util.Objects in project ddf by codice.

the class Associated method putAssociations.

public void putAssociations(String id, Collection<Edge> edges) throws UnsupportedQueryException, SourceUnavailableException, FederationException, IngestException {
    Collection<Edge> oldEdges = getAssociations(id);
    List<String> ids = Stream.concat(oldEdges.stream(), edges.stream()).flatMap(e -> Stream.of(e.child, e.parent)).filter(Objects::nonNull).map(m -> m.get(Metacard.ID)).filter(Objects::nonNull).map(Object::toString).distinct().collect(Collectors.toList());
    Map<String, Metacard> metacards = util.getMetacards(ids, getNonrestrictedTagsFilter()).entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getMetacard()));
    Map<String, Metacard> changedMetacards = new HashMap<>();
    Set<Edge> oldEdgeSet = new HashSet<>(oldEdges);
    Set<Edge> newEdgeSet = new HashSet<>(edges);
    Set<Edge> oldDiff = Sets.difference(oldEdgeSet, newEdgeSet);
    Set<Edge> newDiff = Sets.difference(newEdgeSet, oldEdgeSet);
    for (Edge edge : oldDiff) {
        removeEdge(edge, metacards, changedMetacards);
    }
    for (Edge edge : newDiff) {
        addEdge(edge, metacards, changedMetacards);
    }
    if (changedMetacards.isEmpty()) {
        return;
    }
    catalogFramework.update(new UpdateRequestImpl(changedMetacards.keySet().toArray(new String[0]), new ArrayList<>(changedMetacards.values())));
}
Also used : QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) CatalogFramework(ddf.catalog.CatalogFramework) UpdateRequestImpl(ddf.catalog.operation.impl.UpdateRequestImpl) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) MetacardVersion(ddf.catalog.core.versioning.MetacardVersion) SortBy(org.opengis.filter.sort.SortBy) EndpointUtil(org.codice.ddf.catalog.ui.util.EndpointUtil) Metacard(ddf.catalog.data.Metacard) Map(java.util.Map) HashCodeBuilder(org.apache.commons.lang3.builder.HashCodeBuilder) Result(ddf.catalog.data.Result) EqualsBuilder(org.apache.commons.lang3.builder.EqualsBuilder) QueryImpl(ddf.catalog.operation.impl.QueryImpl) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) IngestException(ddf.catalog.source.IngestException) DeletedMetacard(ddf.catalog.core.versioning.DeletedMetacard) Set(java.util.Set) FederationException(ddf.catalog.federation.FederationException) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) QueryResponse(ddf.catalog.operation.QueryResponse) List(java.util.List) Stream(java.util.stream.Stream) Attribute(ddf.catalog.data.Attribute) Optional(java.util.Optional) Filter(org.opengis.filter.Filter) Collections(java.util.Collections) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Metacard(ddf.catalog.data.Metacard) DeletedMetacard(ddf.catalog.core.versioning.DeletedMetacard) UpdateRequestImpl(ddf.catalog.operation.impl.UpdateRequestImpl) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Aggregations

Objects (java.util.Objects)55 List (java.util.List)29 Map (java.util.Map)24 Collectors (java.util.stream.Collectors)22 ArrayList (java.util.ArrayList)20 Set (java.util.Set)19 Optional (java.util.Optional)16 IOException (java.io.IOException)15 HashMap (java.util.HashMap)14 Collections (java.util.Collections)13 HashSet (java.util.HashSet)10 ImmutableSet (com.google.common.collect.ImmutableSet)9 Result (ddf.catalog.data.Result)9 Stream (java.util.stream.Stream)9 Metacard (ddf.catalog.data.Metacard)8 TimeUnit (java.util.concurrent.TimeUnit)8 LoggerFactory (org.slf4j.LoggerFactory)8 QueryImpl (ddf.catalog.operation.impl.QueryImpl)7 Path (java.nio.file.Path)7 Logger (org.slf4j.Logger)7