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.ProcessService.java

/**
 * Get images origin directory.// w  ww .j  a  v  a2s  .c o  m
 *
 * @param useFallBack
 *            as boolean
 * @param process
 *            object
 * @return path
 */
public URI getImagesOriginDirectory(boolean useFallBack, Process process) {
    if (USE_ORIG_FOLDER) {
        URI dir = fileService.getProcessSubTypeURI(process, ProcessSubType.IMAGE, null);

        /* nur die _tif-Ordner anzeigen, die mit orig_ anfangen */
        FilenameFilter filterDirectory = new FileNameBeginsAndEndsWithFilter(DIRECTORY_PREFIX + "_",
                "_" + DIRECTORY_SUFFIX);
        URI origDirectory = null;
        List<URI> directories = fileService.getSubUris(filterDirectory, dir);
        for (URI directory : directories) {
            origDirectory = directory;
        }

        if (Objects.isNull(origDirectory) && useFallBack && !SUFFIX.isEmpty()) {
            List<URI> folderList = fileService.getSubUris(dir);
            for (URI folder : folderList) {
                if (folder.toString().endsWith(SUFFIX)) {
                    origDirectory = folder;
                    break;
                }
            }
        }

        origDirectory = getImageDirectory(useFallBack, dir, origDirectory);

        URI result = fileService.getProcessSubTypeURI(process, ProcessSubType.IMAGE, null);

        if (Objects.isNull(origDirectory)) {
            origDirectory = URI.create(result.toString() + DIRECTORY_PREFIX + "_"
                    + Helper.getNormalizedTitle(process.getTitle()) + "_" + DIRECTORY_SUFFIX);
        }

        return origDirectory;
    } else {
        return getImagesTifDirectory(useFallBack, process.getId(), process.getTitle(),
                process.getProcessBaseUri());
    }
}

From source file:org.dc.file.search.ui.DashboardForm.java

protected void fireEditingCanceled() {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
        if (listeners[i] == CellEditorListener.class) {
            // Lazily create the event:
            if (Objects.isNull(changeEvent)) {
                changeEvent = new ChangeEvent(this);
            }// w ww . j a va 2 s .  c o  m
            ((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent);
        }
    }
}

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

/**
 * Get process data directory./*ww w.j  a  v a  2s. co m*/
 *
 * @param process
 *            object
 * @return path
 */
public URI getProcessDataDirectory(Process process) {
    if (Objects.isNull(process.getProcessBaseUri())) {
        process.setProcessBaseUri(fileService.getProcessBaseUriForExistingProcess(process));
        try {
            save(process);
        } catch (DataException e) {
            logger.error(e.getMessage(), e);
            return URI.create("");
        }
    }
    return process.getProcessBaseUri();
}

From source file:org.sleuthkit.autopsy.timeline.db.EventDB.java

/**
 * mark any events with the given object and artifact ids as tagged, and
 * record the tag it self./*w ww .j  av a  2s.c  o m*/
 * <p>
 * NOTE: does not lock the db, must be called form inside a
 * DBLock.lock/unlock pair
 *
 * @param objectID   the obj_id that this tag applies to, the id of the
 *                   content that the artifact is derived from for artifact
 *                   tags
 * @param artifactID the artifact_id that this tag applies to, or null if
 *                   this is a content tag
 * @param tagged     true to mark the matching events tagged, false to mark
 *                   them as untagged
 *
 * @return the event ids that match the object/artifact pair
 *
 * @throws SQLException if there is an error marking the events as
 *                      (un)taggedS
 */
private Set<Long> markEventsTagged(long objectID, @Nullable Long artifactID, boolean tagged)
        throws SQLException {

    PreparedStatement selectStmt;
    if (Objects.isNull(artifactID)) {
        //"SELECT event_id FROM events WHERE file_id == ? AND artifact_id IS NULL"
        selectNonArtifactEventIDsByObjectIDStmt.clearParameters();
        selectNonArtifactEventIDsByObjectIDStmt.setLong(1, objectID);
        selectStmt = selectNonArtifactEventIDsByObjectIDStmt;
    } else {
        //"SELECT event_id FROM events WHERE file_id == ? AND artifact_id = ?"
        selectEventIDsBYObjectAndArtifactIDStmt.clearParameters();
        selectEventIDsBYObjectAndArtifactIDStmt.setLong(1, objectID);
        selectEventIDsBYObjectAndArtifactIDStmt.setLong(2, artifactID);
        selectStmt = selectEventIDsBYObjectAndArtifactIDStmt;
    }

    HashSet<Long> eventIDs = new HashSet<>();
    try (ResultSet executeQuery = selectStmt.executeQuery();) {
        while (executeQuery.next()) {
            eventIDs.add(executeQuery.getLong("event_id")); //NON-NLS
        }
    }

    //update tagged state for all event with selected ids
    try (Statement updateStatement = con.createStatement();) {
        updateStatement.executeUpdate("UPDATE events SET tagged = " + (tagged ? 1 : 0) //NON-NLS
                + " WHERE event_id IN (" + StringUtils.join(eventIDs, ",") + ")"); //NON-NLS
    }

    return eventIDs;
}

From source file:org.kitodo.production.forms.ProzesskopieForm.java

/**
 * Set images guessed./*  w w  w. j  a v  a 2s .  com*/
 *
 * @param imagesGuessed
 *            the imagesGuessed to set
 */
public void setImagesGuessed(Integer imagesGuessed) {
    if (Objects.isNull(imagesGuessed)) {
        imagesGuessed = 0;
    }
    this.guessedImages = imagesGuessed;
}

From source file:com.intuit.wasabi.assignment.impl.AssignmentsImpl.java

/**
 * This method creates an assignment object for NEW_ASSIGNMENT / NO_OPEN_BUCKETS.
 * <p>/*ww  w .  j a  v  a2s .c om*/
 * Note: it does not create entries in the database.
 *
 * @param experiment
 * @param userID
 * @param context
 * @param selectBucket
 * @param bucketList
 * @param date
 * @param segmentationProfile
 * @return new assignment object with status of either NEW_ASSIGNMENT or NO_OPEN_BUCKETS
 */
protected Assignment createAssignmentObject(Experiment experiment, User.ID userID, Context context,
        boolean selectBucket, BucketList bucketList, Date date, SegmentationProfile segmentationProfile) {

    Assignment.Builder builder = Assignment.newInstance(experiment.getID())
            .withExperimentLabel(getExperimentLabel(experiment.getID()))
            .withApplicationName(experiment.getApplicationName()).withUserID(userID).withContext(context);

    if (selectBucket) {
        Bucket assignedBucket;
        /*
        With the bucket state in effect, this part of the code could also result in
        the generation of a null assignment in cases where the selected bucket is CLOSED or EMPTY
        In CLOSED state, the current bucket assignments to the bucket are left as is and all the
        assignments to this bucket are made null going forward.
                
        In EMPTY state, the current bucket assignments are made null as well as all the future assignments
        to this bucket are made null.
                
        Retrieves buckets from Repository if personalization is not enabled and if skipBucketRetrieval is false
        Retrieves buckets from Assignment Decorator if personalization is enabled
        */
        BucketList bucketsExternal = getBucketList(experiment, userID, segmentationProfile, !Objects
                .isNull(bucketList) /* do not skip retrieving bucket from repository if bucketList is null */);
        if (Objects.isNull(bucketsExternal) || bucketsExternal.getBuckets().isEmpty()) {
            // if bucketlist obtained from Assignment Decorator is null; use the bucketlist passed into the method
            assignedBucket = selectBucket(bucketList.getBuckets());
        } else {
            //else use the bucketExternal obtained from the Assignment Decorator
            assignedBucket = selectBucket(bucketsExternal.getBuckets());
        }
        //check that at least one bucket was open
        if (!Objects.isNull(assignedBucket)) {
            //create the bucket with bucketlabel
            builder.withBucketLabel(assignedBucket.getLabel());
            builder.withPayload(getBucketPayload(experiment.getID(),
                    nonNull(assignedBucket.getLabel()) ? assignedBucket.getLabel().toString() : null));
        } else {
            return nullAssignment(userID, experiment.getApplicationName(), experiment.getID(),
                    Assignment.Status.NO_OPEN_BUCKETS);
        }

    } else {
        builder.withBucketLabel(null);
    }

    Assignment result = builder.withStatus(Assignment.Status.NEW_ASSIGNMENT)
            .withCreated(Optional.ofNullable(date).orElseGet(Date::new)).withCacheable(false).build();
    LOGGER.debug("result => {}", result);
    return result;
}

From source file:com.intuit.wasabi.assignment.impl.AssignmentsImpl.java

/**
 * Returns a bucketList depending on whether it is a personalization experiment or not.
 * Retrieves buckets from Assignment Decorator if personalization is enabled
 * Retrieves buckets from Repository if personalization is not enabled and if skipBucketRetrieval is false
 *
 * @param experiment          Experiment
 * @param userID              UserId/*from   www .  j a v  a 2s.  c  om*/
 * @param segmentationProfile The segmentation profile
 * @param skipBucketRetrieval If false, retrieves buckets from Repository
 * @return BucketList
 */
protected BucketList getBucketList(Experiment experiment, User.ID userID,
        SegmentationProfile segmentationProfile, Boolean skipBucketRetrieval) {

    BucketList bucketList = null;
    Boolean isPersonalizationEnabled = experiment.getIsPersonalizationEnabled();
    if (isPersonalizationEnabled) {
        try {
            bucketList = assignmentDecorator.getBucketList(experiment, userID, segmentationProfile);
        } catch (BucketDistributionNotFetchableException e) {
            LOGGER.error("Error obtaining the Bucket List from {} for user_id {}, for experiment: {} due to {}",
                    assignmentDecorator.getClass().getSimpleName(), userID, experiment.getLabel().toString(),
                    e);
        } finally {
            //TODO: add some metrics on how often this fails
            // Logic behind the below step is to ensure the following:
            // In the case of batch assignments, when response from Assignment Decorator fails, we skip doing a back end call to cassandra
            // This is consistent with the different manner in which generateAssignment method is used for single and batch assignment calls.
            if ((Objects.isNull(bucketList) || bucketList.getBuckets().isEmpty()) && !skipBucketRetrieval) {
                bucketList = getBucketList(experiment.getID());
            }
        }
    } else {
        if (!skipBucketRetrieval) {
            bucketList = getBucketList(experiment.getID());
        }
    }
    return bucketList;
}

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

/**
 * DMS-Export to a desired location.//from   w w  w. j ava 2 s  .  com
 *
 * @param process
 *            object
 * @param exportWithImages
 *            true or false
 * @param exportFullText
 *            true or false
 * @return true or false
 */

public boolean startDmsExport(Process process, boolean exportWithImages, boolean exportFullText)
        throws IOException {
    LegacyPrefsHelper preferences = ServiceManager.getRulesetService().getPreferences(process.getRuleset());
    String atsPpnBand = Helper.getNormalizedTitle(process.getTitle());

    // read document
    LegacyMetsModsDigitalDocumentHelper gdzfile = readDocument(preferences, process);
    if (Objects.isNull(gdzfile)) {
        return false;
    }

    trimAllMetadata(gdzfile.getDigitalDocument().getLogicalDocStruct());

    // validate metadata
    if (ConfigCore.getBooleanParameterOrDefaultValue(ParameterCore.USE_META_DATA_VALIDATION)
            && !ServiceManager.getMetadataValidationService().validate(gdzfile, preferences, process)) {
        return false;
    }

    Project project = process.getProject();

    // prepare place for save and download
    URI targetDirectory = new File(project.getDmsImportImagesPath()).toURI();
    URI userHome = targetDirectory;

    // if necessary, create an operation folder
    if (project.isDmsImportCreateProcessFolder()) {
        targetDirectory = userHome.resolve(File.separator + Helper.getNormalizedTitle(process.getTitle()));
        boolean created = createOperationDirectory(userHome, process);
        if (!created) {
            return false;
        }
    }

    try {
        if (exportWithImages) {
            downloadImages(process, userHome, atsPpnBand, DIRECTORY_SUFFIX);
            downloadFullText(process, userHome, atsPpnBand);
        } else if (exportFullText) {
            downloadFullText(process, userHome, atsPpnBand);
        }
        directoryDownload(process, targetDirectory);
    } catch (RuntimeException e) {
        Helper.setErrorMessage(ERROR_EXPORT, new Object[] { process.getTitle() }, logger, e);
        return false;
    }

    /*
     * zum Schluss Datei an gewnschten Ort exportieren entweder direkt in den
     * Import-Ordner oder ins Benutzerhome anschliessend den Import-Thread starten
     */
    if (project.isUseDmsImport()) {
        if (MetadataFormat
                .findFileFormatsHelperByName(project.getFileFormatDmsExport()) == MetadataFormat.METS) {
            // if METS, then write by writeMetsFile...
            writeMetsFile(process, userHome + File.separator + atsPpnBand + ".xml", gdzfile, false);
        } else {
            // ...if not, just write a Fileformat
            gdzfile.write(userHome + File.separator + atsPpnBand + ".xml");
        }

        // if necessary, METS and RDF should be written in the export
        if (MetadataFormat
                .findFileFormatsHelperByName(project.getFileFormatDmsExport()) == MetadataFormat.METS_AND_RDF) {
            writeMetsFile(process, userHome + File.separator + atsPpnBand + ".mets.xml", gdzfile, false);
        }

        Helper.setMessage(process.getTitle() + ": ", "DMS-Export started");

        if (!ConfigCore.getBooleanParameterOrDefaultValue(ParameterCore.EXPORT_WITHOUT_TIME_LIMIT)
                && project.isDmsImportCreateProcessFolder()) {
            // again remove success folder
            File successFile = new File(project.getDmsImportSuccessPath() + File.separator
                    + Helper.getNormalizedTitle(process.getTitle()));
            fileService.delete(successFile.toURI());
        }
    }
    return true;
}

From source file:com.qpark.maven.plugin.modelanalysis.Report.java

private static String getString(final String s) {
    String value = s;//from   w w  w .  ja  v a 2s.  com
    if (Objects.isNull(s)) {
        value = "missing";
    } else {
        value = value.replaceAll("\\n", "<br/>");
    }
    return value;
}

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

/**
 * write MetsFile to given Path.//from ww  w .  ja v a 2  s  .  c  o  m
 *
 * @param process
 *            the Process to use
 * @param targetFileName
 *            the filename where the metsfile should be written
 * @param gdzfile
 *            the FileFormat-Object to use for Mets-Writing
 */
protected boolean writeMetsFile(Process process, String targetFileName,
        LegacyMetsModsDigitalDocumentHelper gdzfile, boolean writeLocalFilegroup) throws IOException {
    LegacyPrefsHelper preferences = ServiceManager.getRulesetService().getPreferences(process.getRuleset());
    LegacyMetsModsDigitalDocumentHelper mm = new LegacyMetsModsDigitalDocumentHelper(preferences.getRuleset());
    mm.setWriteLocal(writeLocalFilegroup);
    URI imageFolderPath = fileService.getImagesDirectory(process);
    File imageFolder = new File(imageFolderPath);
    /*
     * before creating mets file, change relative path to absolute -
     */
    LegacyMetsModsDigitalDocumentHelper dd = gdzfile.getDigitalDocument();
    if (Objects.isNull(dd.getFileSet())) {
        Helper.setErrorMessage(process.getTitle() + ": digital document does not contain images; aborting");
        return false;
    }

    /*
     * get the topstruct element of the digital document depending on anchor
     * property
     */
    LegacyDocStructHelperInterface topElement = dd.getLogicalDocStruct();
    if (preferences.getDocStrctTypeByName(topElement.getDocStructType().getName()).getAnchorClass() != null) {
        if (Objects.isNull(topElement.getAllChildren()) || topElement.getAllChildren().isEmpty()) {
            throw new IllegalStateException(process.getTitle()
                    + ": the topstruct element is marked as anchor, but does not have any children for "
                    + "physical docstrucs");
        } else {
            topElement = topElement.getAllChildren().get(0);
        }
    }

    /*
     * if the top element does not have any image related, set them all
     */
    if (Objects.isNull(topElement.getAllToReferences("logical_physical"))
            || topElement.getAllToReferences("logical_physical").isEmpty()) {
        if (Objects.nonNull(dd.getPhysicalDocStruct())
                && Objects.nonNull(dd.getPhysicalDocStruct().getAllChildren())) {
            Helper.setMessage(process.getTitle()
                    + ": topstruct element does not have any referenced images yet; temporarily adding them "
                    + "for mets file creation");
            for (LegacyDocStructHelperInterface mySeitenDocStruct : dd.getPhysicalDocStruct()
                    .getAllChildren()) {
                topElement.addReferenceTo(mySeitenDocStruct, "logical_physical");
            }
        } else {
            Helper.setErrorMessage(
                    process.getTitle() + ": could not find any referenced images, export aborted");
            return false;
        }
    }

    for (LegacyContentFileHelper cf : dd.getFileSet().getAllFiles()) {
        String location = cf.getLocation();
        // If the file's location string shoes no sign of any protocol,
        // use the file protocol.
        if (!location.contains("://")) {
            location = "file://" + location;
        }
        String url = new URL(location).getFile();
        File f = new File(!url.startsWith(imageFolder.toURI().toURL().getPath()) ? imageFolder : null, url);
        cf.setLocation(f.toURI().toString());
    }

    mm.setDigitalDocument(dd);

    /*
     * wenn Filegroups definiert wurden, werden diese jetzt in die Metsstruktur
     * bernommen
     */
    // Replace all paths with the given VariableReplacer, also the file
    // group paths!
    Project project = process.getProject();
    VariableReplacer variables = new VariableReplacer(mm.getDigitalDocument(), preferences, process, null);
    List<Folder> folders = project.getFolders();
    for (Folder folder : folders) {
        // check if source files exists
        if (folder.getLinkingMode().equals(LinkingMode.EXISTING)) {
            URI folderUri = new File(folder.getRelativePath()).toURI();
            if (fileService.fileExist(folderUri)
                    && !ServiceManager.getFileService().getSubUris(folderUri).isEmpty()) {
                throw new UnsupportedOperationException("Dead code pending removal");
            }
        } else if (!folder.getLinkingMode().equals(LinkingMode.NO)) {
            throw new UnsupportedOperationException("Dead code pending removal");
        }
    }

    // Replace rights and digiprov entries.
    mm.setRightsOwner(variables.replace(project.getMetsRightsOwner()));
    mm.setRightsOwnerLogo(variables.replace(project.getMetsRightsOwnerLogo()));
    mm.setRightsOwnerSiteURL(variables.replace(project.getMetsRightsOwnerSite()));
    mm.setRightsOwnerContact(variables.replace(project.getMetsRightsOwnerMail()));
    mm.setDigiprovPresentation(variables.replace(project.getMetsDigiprovPresentation()));
    mm.setDigiprovReference(variables.replace(project.getMetsDigiprovReference()));
    mm.setDigiprovPresentationAnchor(variables.replace(project.getMetsDigiprovPresentationAnchor()));
    mm.setDigiprovReferenceAnchor(variables.replace(project.getMetsDigiprovReferenceAnchor()));

    mm.setPurlUrl(variables.replace(project.getMetsPurl()));
    mm.setContentIDs(variables.replace(project.getMetsContentIDs()));

    // Set mets pointers. MetsPointerPathAnchor or mptrAnchorUrl is the
    // pointer used to point to the superordinate (anchor) file, that is
    // representing a virtual? group such as a series. Several anchors
    // pointer paths can be defined/ since it is possible to define several
    // levels of superordinate structures (such as the complete edition of
    // a daily newspaper, one year ouf of that edition, )
    String anchorPointersToReplace = project.getMetsPointerPath();
    mm.setMptrUrl(null);
    for (String anchorPointerToReplace : anchorPointersToReplace.split(Project.ANCHOR_SEPARATOR)) {
        String anchorPointer = variables.replace(anchorPointerToReplace);
        mm.setMptrUrl(anchorPointer);
    }

    // metsPointerPathAnchor or mptrAnchorUrl is the pointer used to point
    // from the (lowest) superordinate (anchor) file to the lowest level
    // file (the non-anchor file).
    String anchor = project.getMetsPointerPathAnchor();
    String pointer = variables.replace(anchor);
    mm.setMptrAnchorUrl(pointer);

    try {
        // TODO andere Dateigruppen nicht mit image Namen ersetzen
        List<URI> images = getDataFiles(process);
        List<String> imageStrings = new ArrayList<>();
        for (URI image : images) {
            imageStrings.add(image.getPath());
        }
        int sizeOfPagination = dd.getPhysicalDocStruct().getAllChildren().size();
        int sizeOfImages = images.size();
        if (sizeOfPagination == sizeOfImages) {
            dd.overrideContentFiles(imageStrings);
        } else {
            Helper.setErrorMessage("imagePaginationError", new Object[] { sizeOfPagination, sizeOfImages });
            return false;
        }
    } catch (IndexOutOfBoundsException | InvalidImagesException e) {
        logger.error(e.getMessage(), e);
    }
    mm.write(targetFileName);
    Helper.setMessage(process.getTitle() + ": ", "exportFinished");
    return true;
}