Example usage for java.util Objects nonNull

List of usage examples for java.util Objects nonNull

Introduction

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

Prototype

public static boolean nonNull(Object obj) 

Source Link

Document

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

Usage

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

private Map<String, Integer> getCalculationForProgress(List<Task> tasksBean, List<TaskDTO> tasksDTO) {
    List<TaskStatus> taskStatuses = new ArrayList<>();

    if (Objects.nonNull(tasksBean)) {
        for (Task task : tasksBean) {
            taskStatuses.add(task.getProcessingStatus());
        }//from  w  w w.  j av a 2s .c o  m
    } else {
        for (TaskDTO task : tasksDTO) {
            taskStatuses.add(task.getProcessingStatus());
        }
    }
    return calculationForProgress(taskStatuses);
}

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

/**
 * Download docket for given process.//from  ww w  .  j a  v  a2  s.c  o m
 *
 * @param process
 *            object
 * @throws IOException
 *             when xslt file could not be loaded, or write to output failed
 */
public void downloadDocket(Process process) throws IOException {
    logger.debug("generate docket for process with id {}", process.getId());
    URI rootPath = Paths.get(ConfigCore.getParameter(ParameterCore.DIR_XSLT)).toUri();
    URI xsltFile;
    if (Objects.nonNull(process.getDocket())) {
        xsltFile = ServiceManager.getFileService().createResource(rootPath, process.getDocket().getFile());
        if (!fileService.fileExist(xsltFile)) {
            Helper.setErrorMessage("docketMissing");
        }
    } else {
        xsltFile = ServiceManager.getFileService().createResource(rootPath, "docket.xsl");
    }
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {
        // write run note to servlet output stream
        DocketInterface module = initialiseDocketModule();

        File file = module.generateDocket(getDocketData(process), xsltFile);
        writeToOutputStream(facesContext, file, Helper.getNormalizedTitle(process.getTitle()) + ".pdf");
        Files.deleteIfExists(file.toPath());
    }
}

From source file:org.kitodo.production.metadata.MetadataProcessor.java

/**
 * Gets logicalTopstruct of digital document as full expanded TreeNode
 * structure./*  www.  j a  v a 2s  .c  om*/
 *
 * @return The TreeNote.
 */
public TreeNode getTreeNodes() {
    TreeNode root = new DefaultTreeNode("root", null);
    IncludedStructuralElement includedStructuralElement = this.gdzfile.getWorkpiece().getRootElement();
    List<IncludedStructuralElement> children = Objects.nonNull(includedStructuralElement)
            ? includedStructuralElement.getChildren()
            : null;
    TreeNode visibleRoot = new DefaultTreeNode(this.gdzfile.getWorkpiece().getRootElement(), root);
    if (this.selectedTreeNode == null) {
        visibleRoot.setSelected(true);
    } else {
        if (this.selectedTreeNode.equals(visibleRoot)) {
            visibleRoot.setSelected(true);
        }
    }

    if (children != null) {
        TreeNode primeFacesTreeNode = convertIncludedStructuralElementToPrimeFacesTreeNode(children,
                visibleRoot);
        if (Objects.nonNull(primeFacesTreeNode)) {
            visibleRoot.getChildren().add(primeFacesTreeNode);
        }
    }
    return setExpandingAll(root, true);
}

From source file:org.kitodo.production.metadata.MetadataProcessor.java

private TreeNode convertIncludedStructuralElementToPrimeFacesTreeNode(List<IncludedStructuralElement> elements,
        TreeNode parentTreeNode) {
    TreeNode treeNode = null;//from ww  w . j  a  v a  2s . c  o  m

    for (IncludedStructuralElement element : elements) {

        treeNode = new DefaultTreeNode(element, parentTreeNode);
        if (this.selectedTreeNode != null && Objects.equals(this.selectedTreeNode.getData(), element)) {
            treeNode.setSelected(true);
        }
        List<IncludedStructuralElement> children = element.getChildren();
        Collection<View> pages = element.getViews();
        if (Objects.nonNull(children)) {
            convertIncludedStructuralElementToPrimeFacesTreeNode(children, treeNode);
        }
        if (Objects.nonNull(pages)) {
            convertViewToPrimeFacesTreeNode(pages, treeNode);
        }
    }
    return treeNode;
}

From source file:org.openecomp.sdc.vendorsoftwareproduct.impl.VendorSoftwareProductManagerImpl.java

private ComponentArtifactEntity setValuesForComponentArtifactEntityUpload(String vspId, Version version,
        String filename, String componentId, String artifactId, boolean isTrap, byte[] uploadedFileData) {
    ComponentArtifactEntity componentArtifactEntity = new ComponentArtifactEntity();

    componentArtifactEntity.setVspId(vspId);
    componentArtifactEntity.setVersion(version);
    componentArtifactEntity.setComponentId(componentId);
    componentArtifactEntity.setId(artifactId);
    componentArtifactEntity.setType(ComponentArtifactType.getComponentArtifactType(isTrap));
    componentArtifactEntity.setArtifactName(filename);

    if (Objects.nonNull(uploadedFileData)) {
        componentArtifactEntity.setArtifact(ByteBuffer.wrap(uploadedFileData));
    }/* ww w . j av a2s  .c o  m*/

    return componentArtifactEntity;
}

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

/**
 * Run through all metadata and children of given docStruct to trim the strings
 * calls itself recursively.//from   w  w w  .ja v a  2 s  . c om
 *
 * @param docStruct
 *            metadata to be trimmed
 */
private void trimAllMetadata(LegacyDocStructHelperInterface docStruct) {
    // trim all metadata values
    if (Objects.nonNull(docStruct.getAllMetadata())) {
        for (LegacyMetadataHelper md : docStruct.getAllMetadata()) {
            if (Objects.nonNull(md.getValue())) {
                md.setStringValue(md.getValue().trim());
            }
        }
    }

    // run through all children of docStruct
    if (Objects.nonNull(docStruct.getAllChildren())) {
        for (LegacyDocStructHelperInterface child : docStruct.getAllChildren()) {
            trimAllMetadata(child);
        }
    }
}

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

/**
 * write MetsFile to given Path./* w w w.  j  a  va 2s  . c  om*/
 *
 * @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;
}

From source file:org.kitodo.production.metadata.MetadataProcessor.java

/**
 * Convert the TIFF images of the current process to PNG images for the metadata web frontend and
 * copy them to them to the webapps/images/[processID]/fullsize/ folder.
 *//*from ww w .  ja va  2 s  .  co  m*/
private void convertImages() {
    if (Objects.nonNull(this.currentTifFolder)) {
        try {
            ensureDirectoryExists(Paths.get(fullsizePath));

            // first, convert tiff images to pngs
            for (URI tiffPath : this.imageHelper.getImageFiles(this.currentTifFolder)) {
                String targetPath = fullsizePath + FilenameUtils.removeExtension(tiffPath.toString()) + ".png";

                File fullsizeFile = new File(targetPath);
                if (fullsizeFile.exists()) {
                    continue;
                }

                URI tiffURI = Paths
                        .get(ConfigCore.getKitodoDataDirectory() + this.currentTifFolder + tiffPath.toString())
                        .toUri();

                logger.info("Reading {}", tiffURI);
                BufferedImage inputImage = ImageIO.read(tiffURI.toURL());

                logger.info("Writing {}", targetPath);
                ImageIO.write(inputImage, "png", new File(targetPath));
                numberOfConvertedImages++;
                // FIXME: this call to the update function does not work!
                updateComponent(metadataEditorComponents);
            }

            // then, create thumbnails from the converted images
            generateThumbnails();

            updateComponent(metadataEditorComponents);
        } catch (MalformedURLException e) {
            Helper.setErrorMessage("ERROR: URL malformed!", logger, e);
        } catch (IOException e) {
            Helper.setErrorMessage("ERROR: IOException!", logger, e);
        }
    }
}

From source file:org.kitodo.production.metadata.MetadataProcessor.java

private List<LegacyDocStructHelperInterface> getStructureElements(LegacyDocStructHelperInterface docStruct) {
    List<LegacyDocStructHelperInterface> docStructElements = new LinkedList<>();
    if (Objects.nonNull(docStruct)) {
        docStructElements.add(docStruct);
        if (Objects.nonNull(docStruct.getAllChildren())) {
            for (LegacyDocStructHelperInterface element : docStruct.getAllChildren()) {
                if (Objects.nonNull(element)) {
                    if (Objects.isNull(element.getAllChildren()) || element.getAllChildren().isEmpty()) {
                        docStructElements.add(element);
                    } else {
                        docStructElements.addAll(getStructureElements(element));
                    }//from  w w  w  .  j ava 2 s  .  co  m
                }
            }
        }
    }
    return docStructElements;
}

From source file:org.kitodo.production.metadata.MetadataProcessor.java

/**
 * Event listener for drag drop event.//from w  w  w.j  ava2  s  .c om
 *
 * @param dragDropEvent
 *            the event that triggers this listener
 */
public void onPageDrop(DragDropEvent dragDropEvent) {
    String dragId = dragDropEvent.getDragId();
    String dropId = dragDropEvent.getDropId();

    String[] dragIDComponents = dragId.split(":");
    String[] dropIDComponents = dropId.split(":");

    int sourceStructureElementIndex;
    int pageIndex;

    int targetStructureElementIndex = Integer.parseInt(dropIDComponents[2]);
    LegacyDocStructHelperInterface targetDocStruct = getAllStructureElements().get(targetStructureElementIndex);

    if (dragIDComponents[1].equals("structuredPages")) {
        sourceStructureElementIndex = Integer.parseInt(dragIDComponents[2]);
        pageIndex = Integer.parseInt(dragIDComponents[4]);

        LegacyDocStructHelperInterface sourceDocStruct = getAllStructureElements()
                .get(sourceStructureElementIndex);

        List<String> docStructPages = getPagesAssignedToDocStruct(sourceDocStruct);

        String pagePath = docStructPages.get(pageIndex);

        if (Objects.nonNull(sourceDocStruct.getAllToReferences("logical_physical"))) {
            for (LegacyReferenceHelper reference : sourceDocStruct.getAllToReferences("logical_physical")) {

                if (FilenameUtils.getBaseName(pagePath)
                        .equals(FilenameUtils.removeExtension(reference.getTarget().getImageName()))) {
                    // Remove page reference from source doc struct
                    sourceDocStruct.removeReferenceTo(reference.getTarget());

                    // Add page reference to target doc struct
                    targetDocStruct.addReferenceTo(reference.getTarget(), "logical_physical");

                    determinePagesStructure(sourceDocStruct);
                    determinePagesStructure(targetDocStruct);

                    break;
                }
            }
        }
    }
}