Example usage for java.util Objects isNull

List of usage examples for java.util Objects isNull

Introduction

In this page you can find the example usage for java.util Objects isNull.

Prototype

public static boolean isNull(Object obj) 

Source Link

Document

Returns true if the provided reference is null otherwise returns false .

Usage

From source file:org.kitodo.production.services.data.BatchService.java

/**
 * The function contains() returns true if the title (if set) or the
 * id-based label contain the specified sequence of char values.
 *
 * @param sequence/*w w  w. j  a va 2s .  c  om*/
 *            the sequence to search for
 * @return true if the title or label contain s, false otherwise
 */
public boolean contains(Batch batch, CharSequence sequence) {
    return Objects.isNull(sequence) || Objects.nonNull(batch.getTitle()) && batch.getTitle().contains(sequence)
            || getNumericLabel(batch).contains(sequence);
}

From source file:org.kitodo.production.metadata.copier.MetadataPathSelector.java

/**
 * The function findAll() returns all concrete metadata selectors the
 * potentially generic metadata selector expression resolves to.
 *
 * @param logicalNode// w  w  w. j av a2s .co  m
 *            Node of the logical document structure to work on
 * @return all metadata selectors the expression resolves to
 *
 * @see MetadataSelector#findAll(LegacyDocStructHelperInterface)
 */
@Override
protected Iterable<MetadataSelector> findAll(LegacyDocStructHelperInterface logicalNode) {
    LinkedList<MetadataSelector> result = new LinkedList<>();
    List<LegacyDocStructHelperInterface> children = logicalNode.getAllChildren();
    if (Objects.isNull(children)) {
        children = Collections.emptyList();
    }
    int lastChild = children.size() - 1;
    int count = 0;
    for (LegacyDocStructHelperInterface child : children) {
        if (typeCheck(child) && indexCheck(count, lastChild)) {
            for (MetadataSelector cms : selector.findAll(child)) {
                result.add(new MetadataPathSelector(ANY_METADATA_TYPE_SYMBOL, count, cms));
            }
        }
        count++;
    }
    return result;
}

From source file:org.geowebcache.storage.BlobStore.java

/**
 * If the given layer is cached, remove 
 * @param layer//from w  w  w. j ava2  s  . c  o  m
 * @throws StorageException
 */
public default boolean purgeOrphans(TileLayer layer) throws StorageException {
    // TODO maybe do purging based on gridset and format
    try {
        final List<ParameterFilter> parameterFilters = layer.getParameterFilters();

        // Given known parameter mapping, figures out if the parameters need to be purged
        final Function<Map<String, String>, Boolean> parametersNeedPurge = parameters -> {
            return parameters.size() != parameterFilters.size() || // Should have the same number of parameters as the layer has filters
            parameterFilters.stream().allMatch(pfilter -> { // Do all the parameter filters on the layer consider their parameter legal
                final String key = pfilter.getKey();
                final String value = parameters.get(key);
                if (Objects.isNull(value)) {
                    return true; // No parameter for this filter so purge
                }
                return !pfilter.isFilteredValue(value); // purge if it's not a filtered value
            });
        };

        return getParametersMapping(layer.getName()).entrySet().stream().filter(parameterMapping -> {
            return parameterMapping.getValue().map(parametersNeedPurge).orElse(true); // Don't have the original values so purge
        }).map(Map.Entry::getKey) // The parameter id
                .map(id -> {
                    try {
                        return this.deleteByParametersId(layer.getName(), id);
                    } catch (StorageException e) {
                        throw new UncheckedIOException(e);
                    }
                }).reduce((x, y) -> x || y) // OR results without short circuiting
                .orElse(false);
    } catch (UncheckedIOException ex) {
        if (ex.getCause() instanceof StorageException) {
            throw (StorageException) ex.getCause();
        } else {
            throw ex;
        }
    }
}

From source file:org.eclipse.winery.repository.rest.resources.entitytemplates.artifacttemplates.FilesResource.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//from   www . j  a  va  2s.c om
public Response copySourceToFiles(@ApiParam(value = "if data contains a non-empty array than only the files"
        + " whose names are included are copied ", required = true) ArtifactResourcesApiData data) {
    if (Objects.isNull(this.destinationDir)) {
        return Response.status(Status.BAD_REQUEST).build();
    }
    List<String> artifactList = data.getArtifactNames();
    for (RepositoryFileReference ref : RepositoryFactory.getRepository().getContainedFiles(this.fileDir)) {
        if (artifactList == null || artifactList.contains(ref.getFileName())) {
            try (InputStream inputStream = RepositoryFactory.getRepository().newInputStream(ref)) {
                String fileName = ref.getFileName();
                String subDirectory = ref.getSubDirectory().map(s -> s.toString()).orElse("");
                this.destinationDir.putFile(fileName, subDirectory, inputStream);
            } catch (IOException e) {
                LOGGER.debug("The artifact source " + ref.getFileName()
                        + " could not be copied to the files directory.", e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }
    }
    return Response.status(Status.CREATED).build();
}

From source file:com.github.rutledgepaulv.qbuilders.visitors.PredicateVisitor.java

private Predicate<T> doesNotExist(ComparisonNode node) {
    return t -> resolveSingleField(t, node.getField().asKey(), node, (one, two) -> Objects.isNull(one));
}

From source file:org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.java

/**
 * Extract attached resource id optional.
 *
 * @param heatFileName              the heat file name
 * @param heatOrchestrationTemplate the heat orchestration template
 * @param context                   the context
 * @param propertyValue             the property value
 * @return the optional//  ww  w  .  ja  v a2 s .  c o m
 */
public static Optional<AttachedResourceId> extractAttachedResourceId(String heatFileName,
        HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context, Object propertyValue) {

    Object entity;
    Object translatedId;

    if (Objects.isNull(propertyValue)) {
        return Optional.empty();
    }

    ResourceReferenceType referenceType = ResourceReferenceType.OTHER;
    if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
        Map<String, Object> propMap = (Map) propertyValue;
        Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
        entity = entry.getValue();
        String key = entry.getKey();
        switch (key) {
        case "get_resource":
            referenceType = ResourceReferenceType.GET_RESOURCE;
            break;
        case "get_param":
            referenceType = ResourceReferenceType.GET_PARAM;
            break;
        case "get_attr":
            referenceType = ResourceReferenceType.GET_ATTR;
            break;
        default:
        }
        translatedId = TranslatorHeatToToscaFunctionConverter.getToscaFunction(entry.getKey(), entry.getValue(),
                heatFileName, heatOrchestrationTemplate, null, context);
        if (translatedId instanceof String
                && !TranslatorHeatToToscaFunctionConverter.isResourceSupported((String) translatedId)) {
            translatedId = null;
        }

    } else {
        translatedId = propertyValue;
        entity = propertyValue;
    }

    return Optional.of(new AttachedResourceId(translatedId, entity, referenceType));
}

From source file:com.mac.holdempoker.app.impl.util.HandMatrix.java

/**
 * FLUSH/*ww w  .j  a v a2 s  . com*/
 *
 * @return
 */
private HandRank eHandRank() {
    Entry<Suit, Rank[]> flush = getFlushEntry();
    if (Objects.isNull(flush)) {
        return null;
    }
    Rank[] ranks = flush.getValue();
    Arrays.sort(ranks, rc);
    CollectionUtils.reverseArray(ranks);

    List<Card> cards = new ArrayList();
    for (int i = 0; i < 13; i++) {
        Rank r = ranks[i];
        if (Objects.nonNull(r) && cards.size() < 5) {
            cards.add(makeCard(flush.getKey(), r));
        }
    }
    Collections.sort(cards, this);
    return new SimpleHandRank(HandType.FLUSH, cards.toArray(new Card[5]));
}

From source file:de.speexx.jira.jan.command.issuequery.CsvCreator.java

void printHeader(final List<FieldNamePath> currentFieldNames, final List<FieldName> historyFieldNames,
        final TemporalChangeOutput temporalOutput) {
    assert !Objects.isNull(currentFieldNames);
    assert !Objects.isNull(historyFieldNames);
    assert !Objects.isNull(temporalOutput);

    final List<String> headerNames = new ArrayList<>();
    currentFieldNames.stream().map(FieldNamePath::asString)
            .map(name -> name.replaceAll(FieldNamePath.DELIMITER, FIELDNAMEPATH_DELIMITER_REPALCEMENT))
            .forEach(name -> headerNames.add(name));
    historyFieldNames.stream().map(FieldName::asString).forEach(name -> {
        headerNames.add(HOSTORICAL_FROM_PREFIX + name);
        if (temporalOutput != NONE) {
            if (temporalOutput == BOTH || temporalOutput == TIME) {
                headerNames.add(HOSTORICAL_CHANGE_DATETIME_PREFIX + name);
            }/*w w  w .  j a v a2 s .co  m*/
            if (temporalOutput == BOTH || temporalOutput == DURATION) {
                headerNames.add(HOSTORICAL_DURATION_PREFIX + name);
            }
        }
        headerNames.add(HOSTORICAL_TO_PREFIX + name);
    });
    try {
        final CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8),
                RFC4180);
        csvPrinter.printRecord(headerNames.toArray());
        csvPrinter.flush();
    } catch (final IOException e) {
        throw new JiraAnalyzeException(e);
    }
}

From source file:org.kitodo.production.helper.tasks.CreateNewspaperProcessesTask.java

/**
 * The function run() is the main function of this task (which is a thread).
 *
 * <p>//from www  . java  2 s.  c  o m
 * It will create a new process for each entry from the field processes?.
 * </p>
 *
 * <p>
 * Therefore it makes use of
 * CreateNewProcessProcessor.newProcessFromTemplate() to once again load a
 * ProzesskopieForm from Hibernate for each process to create, sets the
 * required fields accordingly, then triggers the calculation of the process
 * title and finally initiates the process creation one by one. The
 * statusProgress variable is being updated to show the operator how far the
 * task has proceeded.
 * </p>
 *
 * @see java.lang.Thread#run()
 */
@Override
public void run() {
    String currentTitle = null;
    try {
        while (nextProcessToCreate < numberOfProcesses) {
            List<IndividualIssue> issues = processes.get(nextProcessToCreate);
            if (!issues.isEmpty()) {
                ProzesskopieForm newProcess = CreateNewProcessProcessor
                        .newProcessFromTemplate(pattern.getTemplate().getTitle());
                newProcess.setDigitalCollections(pattern.getDigitalCollections());
                newProcess.setDocType(pattern.getDocType());
                newProcess.setAdditionalFields(pattern.getAdditionalFields());

                TitleGenerator titleGenerator = new TitleGenerator(newProcess.getAtstsl(),
                        newProcess.getAdditionalFields());
                try {
                    currentTitle = titleGenerator.generateTitle(newProcess.getTitleDefinition(),
                            issues.get(0).getGenericFields());
                } catch (ProcessGenerationException e) {
                    setException(new ProcessCreationException(
                            "Couldnt create process title for issue " + issues.get(0).toString(), e));
                    return;
                }
                setWorkDetail(currentTitle);

                if (Objects.isNull(newProcess.getFileformat())) {
                    newProcess.createNewFileformat();
                }
                createLogicalStructure(newProcess, issues, StringUtils.join(description, "\n\n"));

                if (isInterrupted()) {
                    return;
                }
                boolean created = newProcess.createProcess();
                if (!created) {
                    throw new ProcessCreationException(Helper.getLastMessage().replaceFirst(":\\?*$", ""));
                }
                addToBatches(newProcess.getProzessKopie(), issues, currentTitle);
            }
            nextProcessToCreate++;
            setProgress((100 * nextProcessToCreate) / (numberOfProcesses + 2));
            if (isInterrupted()) {
                return;
            }
        }
        flushLogisticsBatch(currentTitle);
        setProgress(((100 * nextProcessToCreate) + 1) / (numberOfProcesses + 2));
        saveFullBatch(currentTitle);
        setProgress(100);
    } catch (DataException | RuntimeException e) {
        String message = Objects.nonNull(currentTitle)
                ? Helper.getTranslation("createNewspaperProcessesTask.MetadataNotAllowedException",
                        currentTitle)
                : e.getClass().getSimpleName();
        setException(new ProcessCreationException(message + ": " + e.getMessage(), e));
    }
}

From source file:org.kitodo.production.metadata.copier.MetadataPathSelector.java

/**
 * Returns the value of the metadata named by the path used to construct the
 * metadata selector, or null if either the path or the metadata at the end
 * of the path arent available. This works recursively, by calling itself
 * on the subnode, if found, or returning null otherwise.
 *
 * @see MetadataSelector#findIn(LegacyDocStructHelperInterface)
 */// w w w  . j  ava2  s. com
@Override
protected String findIn(LegacyDocStructHelperInterface superNode) {
    LegacyDocStructHelperInterface subNode = getSubnode(superNode);
    if (Objects.isNull(subNode)) {
        return null;
    } else {
        return selector.findIn(subNode);
    }
}