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.filemanagement.locking.ImmutableReadFileManagement.java

/**
 * Removes a reference to the use of a file as a temporary copy. If no
 * reference is left, the user is logged out of the temporary copy. Then it
 * will also be checked if the copy can be deleted.
 *
 * @param originUri/* w  w  w .java  2s  . c  om*/
 *            URI to which the user requested the immutable read lock, that
 *            is, the URI of the original file
 * @param user
 *            user who held the lock
 */
void maybeRemoveReadFile(URI originUri, String user) {
    UserMapForURI userMapForURI = urisGivenToUsers.get(originUri);
    if (Objects.nonNull(userMapForURI)) {
        Pair<URI, AtomicInteger> copyUriWithCount = userMapForURI.get(user);
        if (copyUriWithCount.getValue().decrementAndGet() == 0) {
            userMapForURI.remove(user);
            if (userMapForURI.isEmpty()) {
                urisGivenToUsers.remove(originUri);
            }
            cleanUp(copyUriWithCount.getKey(), originUri);
        }
    }
}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {

    try {//w  w w . j ava  2 s. c  o  m
        final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer);

        String expandedUrl = formatter.format(url);
        String querystring = "";

        if (!params.isEmpty()) {

            querystring = params.entrySet().stream().map(
                    e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue()))
                    .collect(Collectors.joining("&"));

            expandedUrl = expandedUrl.concat("?").concat(querystring);
        }

        StringBuffer callDump = new StringBuffer();
        callDump.append("Performing RestCallOperation " + name).append("\n        ").append("URL: ")
                .append(expandedUrl);

        URL requestUrl = new URL(expandedUrl);

        HttpURLConnection httpURLConnection;
        if (truststorePath != null && expandedUrl.startsWith("https://")) {
            httpURLConnection = openSecureConnection(requestUrl);
        } else {
            httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
        }
        callDump.append("\n        ").append("Method: " + method);

        callDump.append("\n        ").append("Connection timeout: " + connectionTimeout);
        callDump.append("\n        ").append("Read timeout: " + readTimeout);

        httpURLConnection.setRequestMethod(method);
        httpURLConnection.setConnectTimeout(connectionTimeout);
        httpURLConnection.setReadTimeout(readTimeout);

        for (Entry<String, String> header : headers.entrySet()) {
            String k = formatter.format(header.getKey());
            String v = formatter.format(header.getValue());
            httpURLConnection.setRequestProperty(k, v);
            callDump.append("\n        ").append("Header: " + k + "=" + v);
            if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) {
                body = querystring;
            }

        }

        if (sendGVBufferObject && gvBuffer.getObject() != null) {
            byte[] requestData;
            if (gvBuffer.getObject() instanceof byte[]) {
                requestData = (byte[]) gvBuffer.getObject();
            } else {
                requestData = gvBuffer.getObject().toString().getBytes();

            }
            httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length));
            callDump.append("\n        ").append("Content-Length: " + requestData.length);
            callDump.append("\n        ").append("Request body: binary");
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(requestData);

            dataOutputStream.flush();
            dataOutputStream.close();

        } else if (Objects.nonNull(body) && body.length() > 0) {

            String expandedBody = formatter.format(body);
            callDump.append("\n        ").append("Request body: " + expandedBody);
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
            outputStreamWriter.write(expandedBody);
            outputStreamWriter.flush();
            outputStreamWriter.close();

        }

        httpURLConnection.connect();

        InputStream responseStream = null;

        try {
            httpURLConnection.getResponseCode();
            responseStream = httpURLConnection.getInputStream();
        } catch (IOException connectionFail) {
            responseStream = httpURLConnection.getErrorStream();
        }

        for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) {
            if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) {
                gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()),
                        header.getValue().stream().collect(Collectors.joining(";")));
            }
        }

        if (responseStream != null) {

            byte[] responseData = IOUtils.toByteArray(responseStream);
            String responseContentType = Optional
                    .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse("");

            if (responseContentType.startsWith("application/json")
                    || responseContentType.startsWith("application/javascript")) {
                gvBuffer.setObject(new String(responseData, "UTF-8"));
            } else {
                gvBuffer.setObject(responseData);
            }

        } else { // No content
            gvBuffer.setObject(null);
        }

        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode()));
        gvBuffer.setProperty(RESPONSE_MESSAGE,
                Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL"));

        httpURLConnection.disconnect();

    } catch (Exception exc) {
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    }
    return gvBuffer;
}

From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java

/**
 * @see com.qpark.eip.core.model.analysis.report.DataProviderModelAnalysis#getElement(java.lang.String)
 *///from ww  w . j  av a  2s.  co  m
@Override
@Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public Optional<ElementType> getElement(final String elementId) {
    return this.getElementTypesById(this.getLastModelVersion(), Arrays.asList(elementId)).stream()
            .filter(e -> Objects.nonNull(e)).findFirst();
}

From source file:org.kitodo.export.ExportDms.java

private boolean executeDataCopierProcess(LegacyMetsModsDigitalDocumentHelper gdzfile, Process process) {
    try {//  w w w .  ja  v a 2s.c om
        String rules = ConfigCore.getParameter(ParameterCore.COPY_DATA_ON_EXPORT);
        if (Objects.nonNull(rules) && !executeDataCopierProcess(gdzfile, process, rules)) {
            return false;
        }
    } catch (NoSuchElementException e) {
        logger.catching(Level.TRACE, e);
        // no configuration simply means here is nothing to do
    }
    return true;
}

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>//w w w . j a  v a  2 s.  c  om
 * 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:it.greenvulcano.configuration.BaseConfigurationManager.java

@Override
public void deploy(String name) throws XMLConfigException, FileNotFoundException {

    Path configurationArchivePath = getConfigurationPath(name);

    Path current = Paths.get(XMLConfig.getBaseConfigPath());
    Path staging = current.getParent().resolve("deploy");
    Path destination = current.getParent().resolve(name);

    if (LOCK.tryLock()) {

        if (Files.exists(configurationArchivePath) && !Files.isDirectory(configurationArchivePath)) {

            try {

                ZipInputStream configurationArchive = new ZipInputStream(
                        Files.newInputStream(configurationArchivePath, StandardOpenOption.READ));

                LOG.debug("Starting deploy of configuration " + name);
                ZipEntry zipEntry = null;

                for (Path cfgFile : Files.walk(current).collect(Collectors.toSet())) {

                    if (!Files.isDirectory(cfgFile)) {

                        Path target = staging.resolve(current.relativize(cfgFile));
                        Files.createDirectories(target);

                        Files.copy(cfgFile, target, StandardCopyOption.REPLACE_EXISTING);
                    }// w ww. ja  v  a 2s . co m

                }

                LOG.debug("Staging new config " + name);

                while ((zipEntry = configurationArchive.getNextEntry()) != null) {

                    Path entryPath = staging.resolve(zipEntry.getName());

                    LOG.debug("Adding resource: " + entryPath);
                    if (zipEntry.isDirectory()) {
                        entryPath.toFile().mkdirs();
                    } else {

                        Path parent = entryPath.getParent();
                        if (!Files.exists(parent)) {
                            Files.createDirectories(parent);
                        }

                        Files.copy(configurationArchive, entryPath, StandardCopyOption.REPLACE_EXISTING);
                    }

                }

                //**** Deleting old config dir
                LOG.debug("Removing old config: " + current);
                Files.walk(current, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(java.nio.file.Path::toFile).forEach(File::delete);

                LOG.debug("Deploy new config " + name + " in path " + destination);
                Files.move(staging, destination, StandardCopyOption.ATOMIC_MOVE);

                setXMLConfigBasePath(destination.toString());
                LOG.debug("Deploy complete");
                deployListeners.forEach(l -> l.onDeploy(destination));

            } catch (Exception e) {

                if (Objects.nonNull(staging) && Files.exists(staging)) {
                    LOG.error("Deploy failed, rollback to previous configuration", e);
                    try {
                        Files.walk(staging, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                                .map(java.nio.file.Path::toFile).forEach(File::delete);

                        setXMLConfigBasePath(current.toString());
                    } catch (IOException | InvalidSyntaxException rollbackException) {
                        LOG.error("Failed to delete old configuration", e);
                    }
                } else {
                    LOG.error("Deploy failed", e);
                }

                throw new XMLConfigException("Deploy failed", e);
            } finally {
                LOCK.unlock();
            }
        } else {
            throw new FileNotFoundException(configurationArchivePath.toString());
        }
    } else {
        throw new IllegalStateException("A deploy is already in progress");
    }

}

From source file:com.epam.dlab.auth.dao.LdapUserDAO.java

private void addUserAttributes(String username, UserInfo ui, LdapConnection ldapConnection)
        throws IOException, LdapException {
    Map<String, Object> usersAttributes = searchUsersAttributes(username, ldapConnection);
    usersAttributes.entrySet().stream().filter(e -> Objects.nonNull(e.getValue()))
            .forEach(attribute -> addAttribute(ui, attribute));
}

From source file:ca.watier.echechess.services.GameService.java

private boolean isNotAllowedToJoinGame(Side side, GenericGameHandler gameFromUuid) {
    boolean allowObservers = gameFromUuid.isAllowObservers();
    boolean allowOtherToJoin = gameFromUuid.isAllowOtherToJoin();

    return (!allowOtherToJoin && !allowObservers)
            || (allowOtherToJoin && !allowObservers && Side.OBSERVER.equals(side))
            || (!allowOtherToJoin && (Side.BLACK.equals(side) || Side.WHITE.equals(side)))
            || (allowOtherToJoin && !allowObservers && Objects.nonNull(gameFromUuid.getPlayerWhite())
                    && Objects.nonNull(gameFromUuid.getPlayerBlack()));
}

From source file:org.openecomp.sdc.validation.impl.validators.EcompGuideLineValidator.java

private void validateNovaServerResourceNetworkUniqueRole(String fileName, String resourceId,
        HeatOrchestrationTemplate heatOrchestrationTemplate, GlobalValidationContext globalValidationContext) {

    String network;/*  ww w.  j a  v a  2 s.co m*/
    String role;
    Map<String, String> uniqueResourcePortNetworkRole = new HashMap<>();

    Object propertyNetworkValue = heatOrchestrationTemplate.getResources().get(resourceId).getProperties()
            .get("networks");
    if (propertyNetworkValue != null && propertyNetworkValue instanceof List) {
        List<String> portResourceIdList = getNovaNetworkPortResourceList(fileName, (List) propertyNetworkValue,
                globalValidationContext);
        for (String portResourceId : portResourceIdList) {
            Resource portResource = heatOrchestrationTemplate.getResources().get(portResourceId);
            if (portResource != null && portResource.getType()
                    .equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) {
                Map portNetwork = getPortNetwork(fileName, resourceId, portResource, globalValidationContext);
                if (Objects.nonNull(portNetwork)) {
                    network = (String) portNetwork.get("get_param");
                    if (Objects.nonNull(network)) {
                        role = getNetworkRole(network);
                        if (role != null && uniqueResourcePortNetworkRole.containsKey(role)) {
                            globalValidationContext.addMessage(fileName, ErrorLevel.WARNING,
                                    ErrorMessagesFormatBuilder.getErrorWithParameters(
                                            Messages.RESOURCE_CONNECTED_TO_TWO_EXTERNAL_NETWORKS_WITH_SAME_ROLE
                                                    .getErrorMessage(),
                                            resourceId, role));
                        } else {
                            uniqueResourcePortNetworkRole.put(role, portResourceId);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.winery.accountability.AccountabilityManagerImpl.java

protected List<FileProvenanceElement> getHistoryOfSingleFile(List<ModelProvenanceElement> historyElements,
        String fileId, AuthorizationInfo authorizationInfo) {
    List<FileProvenanceElement> history = new ArrayList<>();

    if (Objects.nonNull(historyElements) && historyElements.size() > 0) {
        for (ModelProvenanceElement modelProvenanceElement : historyElements) {
            if (Objects.nonNull(modelProvenanceElement.getFingerprint())) {
                ManifestContents manifestContents = new RecoveringManifestParser()
                        .parse(modelProvenanceElement.getFingerprint());

                for (String name : manifestContents.getSectionNames()) {
                    if (name.equals(fileId)) {
                        modelProvenanceElement.setAuthorizedFlag(authorizationInfo);
                        modelProvenanceElement.setAuthorName(authorizationInfo
                                .getRealWorldIdentity(modelProvenanceElement.getAuthorAddress())
                                .orElseGet(String::new));

                        FileProvenanceElement currentFile = new FileProvenanceElement(modelProvenanceElement);
                        currentFile.setAddressInImmutableStorage(manifestContents.getAttributesForSection(name)
                                .get(TOSCAMetaFileAttributes.IMMUTABLE_ADDRESS));
                        currentFile.setFileHash(TOSCAMetaFileAttributes.HASH + "-" + manifestContents
                                .getAttributesForSection(name).get(TOSCAMetaFileAttributes.HASH));
                        currentFile.setFileName(fileId);
                        history.add(currentFile);

                        break;
                    }//ww w  .  j  a  v a 2 s.  c o m
                }
            }
        }
    }

    if (history.size() > 0)
        return history;

    return null;
}