Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

In this page you can find the example usage for java.util Optional ifPresent.

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

From source file:org.apache.tinkerpop.gremlin.structure.util.batch.BatchGraph.java

@Override
public Vertex addVertex(final Object... keyValues) {
    final Object id = ElementHelper.getIdValue(keyValues)
            .orElseThrow(() -> new IllegalArgumentException("Vertex id value cannot be null"));
    if (!incrementalLoading && retrieveFromCache(id) != null)
        throw new IllegalArgumentException("Vertex id already exists");
    nextElement();/*from ww w.ja v a  2  s. co  m*/

    // if the vertexIdKey is not the T.id then append it as a name/value pair.  this will overwrite what
    // is present in that field already
    final Object[] keysVals = T.id.getAccessor().equals(vertexIdKey) ? keyValues
            : ElementHelper.upsert(keyValues, vertexIdKey, id);

    // if the graph doesn't support vertex ids or the vertex id is not the T.id then remove that key
    // value pair as it will foul up insertion (i.e. an exception for graphs that don't support it and the
    // id will become the value of the vertex id which might not be expected.
    final Optional<Object[]> kvs = this.baseSupportsSuppliedVertexId && T.id.getAccessor().equals(vertexIdKey)
            ? Optional.ofNullable(keyValues)
            : ElementHelper.remove(T.id, keysVals);

    Vertex currentVertex;
    if (!incrementalLoading)
        currentVertex = kvs.isPresent() ? baseGraph.addVertex(kvs.get()) : baseGraph.addVertex();
    else {
        final Traversal<Vertex, Vertex> traversal = baseGraph.V().has(vertexIdKey, id);
        if (traversal.hasNext()) {
            final Vertex v = traversal.next();
            if (traversal.hasNext())
                throw new IllegalStateException(
                        String.format("There is more than one vertex identified by %s=%s", vertexIdKey, id));

            // let the caller decide how to handle conflict
            kvs.ifPresent(keyvals -> existingVertexStrategy.accept(v, keyvals));
            currentVertex = v;
        } else
            currentVertex = kvs.isPresent() ? baseGraph.addVertex(kvs.get()) : baseGraph.addVertex();
    }

    cache.set(currentVertex, id);

    return new BatchVertex(id);
}

From source file:org.ballerinalang.composer.service.ballerina.parser.service.BallerinaParserService.java

/**
 * Validates a given ballerina input.//from  w  ww. ja v a 2s.c om
 *
 * @param bFileRequest - Object which holds data about Ballerina content.
 * @return List of errors if any
 */
private synchronized JsonObject validateAndParse(BFile bFileRequest)
        throws InvocationTargetException, IllegalAccessException {
    final String fileName = bFileRequest.getFileName();
    final String content = bFileRequest.getContent();

    String programDir = "";
    java.nio.file.Path filePath;
    if (UNTITLED_BAL.equals(fileName)) {
        filePath = LSCompiler.createAndGetTempFile(UNTITLED_BAL);
    } else {
        filePath = Paths.get(bFileRequest.getFilePath(), bFileRequest.getFileName());
    }

    BallerinaFile bFile;
    ExtendedWorkspaceDocumentManagerImpl documentManager = ExtendedWorkspaceDocumentManagerImpl.getInstance();
    Optional<Lock> lock = documentManager.lockFile(filePath);
    documentManager.enableExplicitMode(filePath);
    try {
        bFile = LSCompiler.compileContent(content, filePath, CompilerPhase.CODE_ANALYZE, documentManager, true);
    } finally {
        documentManager.disableExplicitMode();
        lock.ifPresent(Lock::unlock);
    }
    programDir = (bFile.isBallerinaProject()) ? LSCompiler.getSourceRoot(filePath) : "";

    final BLangPackage model = bFile.getBLangPackage();
    final List<Diagnostic> diagnostics = bFile.getDiagnostics();

    ErrorCategory errorCategory = ErrorCategory.NONE;
    if (!diagnostics.isEmpty()) {
        if (model == null || model.symbol == null) {
            errorCategory = ErrorCategory.SYNTAX;
        } else {
            errorCategory = ErrorCategory.SEMANTIC;
        }
    }
    JsonArray errors = new JsonArray();
    final String errorCategoryName = errorCategory.name();
    diagnostics.forEach(diagnostic -> {

        JsonObject error = new JsonObject();
        Diagnostic.DiagnosticPosition position = diagnostic.getPosition();
        if (position != null) {
            if (!diagnostic.getSource().getCompilationUnitName().equals(fileName)) {
                return;
            }

            error.addProperty("row", position.getStartLine());
            error.addProperty("column", position.getStartColumn());
            error.addProperty("type", "error");
            error.addProperty("category", errorCategoryName);
        } else {
            // position == null means it's a bug in core side.
            error.addProperty("category", ErrorCategory.RUNTIME.name());
        }

        error.addProperty("text", diagnostic.getMessage());
        errors.add(error);
    });
    JsonObject result = new JsonObject();
    result.add("errors", errors);

    JsonElement diagnosticsJson = GSON.toJsonTree(diagnostics);
    result.add("diagnostics", diagnosticsJson);

    if (model != null && model.symbol != null && bFileRequest.needTree()) {
        BLangCompilationUnit compilationUnit = model.getCompilationUnits().stream()
                .filter(compUnit -> fileName.equals(compUnit.getName())).findFirst().get();
        JsonElement modelElement = generateJSON(compilationUnit, new HashMap<>());
        result.add("model", modelElement);
    }

    final Map<String, ModelPackage> modelPackage = new HashMap<>();
    ParserUtils.loadPackageMap("Current Package", bFile.getBLangPackage(), modelPackage);
    Optional<ModelPackage> packageInfoJson = modelPackage.values().stream().findFirst();
    if (packageInfoJson.isPresent() && bFileRequest.needPackageInfo()) {
        JsonElement packageInfo = GSON.toJsonTree(packageInfoJson.get());
        result.add("packageInfo", packageInfo);
    }
    result.addProperty("programDirPath", programDir);
    return result;
}

From source file:org.ballerinalang.langserver.command.testgen.template.AbstractTestTemplate.java

/**
 * Returns a conflict free name./*from w  ww  . ja va 2s.c  o  m*/
 *
 * @param name variable name
 * @return suggested name
 */
protected String getSafeName(String name) {
    List<String> names = builtTestFile.getGlobalVariables().stream().map(variable -> variable.name.value)
            .collect(Collectors.toList());
    Optional<BLangTestablePackage> testablePkg = builtTestFile.testablePkgs.stream().findAny();
    testablePkg.ifPresent(pkg -> names.addAll(pkg.getGlobalVariables().stream()
            .map(variable -> variable.name.value).collect(Collectors.toList())));
    names.addAll(builtTestFile.getFunctions().stream().map(function -> function.name.value)
            .collect(Collectors.toList()));
    testablePkg.ifPresent(pkg -> names.addAll(
            pkg.getFunctions().stream().map(function -> function.name.value).collect(Collectors.toList())));
    names.addAll(builtTestFile.getServices().stream().map(service -> service.name.value)
            .collect(Collectors.toList()));
    testablePkg.ifPresent(pkg -> names.addAll(
            pkg.getServices().stream().map(service -> service.name.value).collect(Collectors.toList())));
    return getSafeName(name, names);
}

From source file:org.ballerinalang.langserver.command.testgen.template.RootTemplate.java

public RootTemplate(String fileName, BLangPackage builtTestFile,
        BiConsumer<Integer, Integer> focusLineAcceptor) {
    super(builtTestFile, focusLineAcceptor);
    builtTestFile.getServices().forEach(service -> {
        String owner = service.listenerType.tsymbol.owner.name.value;
        String serviceTypeName = service.listenerType.tsymbol.name.value;

        Optional<BLangTypeInit> optionalServiceInit = TestGenerator.getServiceInit(builtTestFile, service);
        optionalServiceInit.ifPresent(init -> {
            if ("http".equals(owner)) {
                switch (serviceTypeName) {
                case "Listener":
                    httpServices.add(new ImmutablePair<>(service, init));
                    break;
                case "WebSocketListener":
                    httpWSServices.add(new ImmutablePair<>(service, init));
                    break;
                default:
                    // do nothing
                }//  www. j  av  a  2 s .c  o m
            }
        });
    });
    builtTestFile.getFunctions().stream().filter(func -> fileName.equals(func.pos.src.cUnitName))
            .forEach(functions::add);
}

From source file:org.ballerinalang.langserver.command.testgen.TestGenerator.java

private static RootTemplate getRootTemplate(String fileName, Pair<BLangNode, Object> nodes,
        BLangPackage builtTestFile, BiConsumer<Integer, Integer> focusLineAcceptor)
        throws TestGeneratorException {

    BLangNode bLangNode = nodes.getLeft();
    Object otherNode = nodes.getRight();

    if (bLangNode == null && otherNode == null) {
        throw new TestGeneratorException("Target test construct not found!");
    }// ww  w .  j  a v a2s.c om

    if (bLangNode instanceof BLangFunction) {
        // A function
        return RootTemplate.fromFunction((BLangFunction) bLangNode, builtTestFile, focusLineAcceptor);

    } else if (bLangNode instanceof BLangService || hasServiceConstructor(bLangNode)) {
        // A Service
        BLangService service;
        if (bLangNode instanceof BLangService) {
            // is a service eg. service {};
            service = (BLangService) bLangNode;
        } else {
            // is a service variable eg. service a = service {};
            service = ((BLangServiceConstructorExpr) (((BLangSimpleVariable) bLangNode).expr)).serviceNode;
        }

        String owner = (service.listenerType != null) ? service.listenerType.tsymbol.owner.name.value : null;
        String serviceTypeName = (service.listenerType != null) ? service.listenerType.tsymbol.name.value
                : null;
        Optional<BLangTypeInit> optionalServiceInit = getServiceInit(builtTestFile, service);
        RootTemplate[] t = { null };
        // Has ServiceInit
        optionalServiceInit.ifPresent(init -> {
            if ("http".equals(owner)) {
                switch (serviceTypeName) {
                case "Listener":
                    t[0] = RootTemplate.fromHttpService(service, init, builtTestFile, focusLineAcceptor);
                    break;
                case "WebSocketListener":
                    t[0] = RootTemplate.fromHttpWSService(service, init, builtTestFile, focusLineAcceptor);
                    break;
                default:
                    // do nothing
                }
            }
        });
        // Return service
        if (t[0] == null) {
            if (hasServiceConstructor(bLangNode)) {
                throw new TestGeneratorException("Services assigned to the variables are not supported!");
            }
            throw new TestGeneratorException(owner + ":" + serviceTypeName + " services are not supported!");
        }
        return t[0];
    }
    // Whole file
    return new RootTemplate(fileName, builtTestFile, focusLineAcceptor);
}

From source file:org.ballerinalang.net.http.HttpUtil.java

public static void checkAndObserveHttpRequest(Context context, HttpCarbonMessage message) {
    Optional<ObserverContext> observerContext = ObserveUtils.getObserverContextOfCurrentFrame(context);
    observerContext.ifPresent(ctx -> {
        HttpUtil.injectHeaders(message, ObserveUtils.getContextProperties(ctx));
        ctx.addTag(TAG_KEY_HTTP_METHOD, String.valueOf(message.getProperty(HttpConstants.HTTP_METHOD)));
        ctx.addTag(TAG_KEY_HTTP_URL, String.valueOf(message.getProperty(HttpConstants.TO)));
        ctx.addTag(TAG_KEY_PEER_ADDRESS,
                message.getProperty(PROPERTY_HTTP_HOST) + ":" + message.getProperty(PROPERTY_HTTP_PORT));
        // Add HTTP Status Code tag. The HTTP status code will be set using the response message.
        // Sometimes the HTTP status code will not be set due to errors etc. Therefore, it's very important to set
        // some value to HTTP Status Code to make sure that tags will not change depending on various
        // circumstances.
        // HTTP Status code must be a number.
        ctx.addTag(TAG_KEY_HTTP_STATUS_CODE, Integer.toString(0));
    });//from w  ww.  j  a  va2  s. c o  m
}

From source file:org.ballerinalang.test.observability.tracing.TracingTestCase.java

@Test
public void testObservePackageUserTraceTrue() throws Exception {
    final String service = "http://localhost:9092/echoService/";
    HttpClientRequest.doGet(service + "resourceOne");
    Thread.sleep(1000);/*from w w w  . j  a v  a 2 s.c o  m*/
    Type type = new TypeToken<List<BMockSpan>>() {
    }.getType();
    String data = HttpClientRequest.doGet(service + "getMockTracers").getData();
    PrintStream out = System.out;
    out.println(data);
    List<BMockSpan> mockSpans = new Gson().fromJson(data, type);

    Assert.assertEquals(mockSpans.size(), 32, "Mismatch in number of spans reported.");

    Assert.assertEquals(mockSpans.stream().filter(bMockSpan -> bMockSpan.getParentId() == 0).count(), 6,
            "Mismatch in number of root spans.");

    Optional<BMockSpan> uSpanTwo = mockSpans.stream()
            .filter(bMockSpan -> bMockSpan.getOperationName().equals("uSpanFour")).findFirst();

    Assert.assertTrue(uSpanTwo.isPresent());
    uSpanTwo.ifPresent(bMockSpan -> {
        Assert.assertEquals(bMockSpan.getTags().get("Allowed"), "Successful", "Tag not found");
        Assert.assertNull(bMockSpan.getTags().get("Disallowed"), "Unexpected tag found");
    });
}

From source file:org.cloudfoundry.identity.uaa.oauth.AccessController.java

private List<Map<String, String>> getScopes(ArrayList<String> scopes) {

    List<Map<String, String>> result = new ArrayList<Map<String, String>>();
    for (String scope : scopes) {
        HashMap<String, String> map = new HashMap<String, String>();
        String code = SCOPE_PREFIX + scope;
        map.put("code", code);

        Optional<ScimGroup> group = groupProvisioning.query(String.format("displayName eq \"%s\"", scope))
                .stream().findFirst();//from  w  w  w  . j  ava 2  s  . c  o  m
        group.ifPresent(g -> {
            String description = g.getDescription();
            if (StringUtils.hasText(description)) {
                map.put("text", description);
            }
        });
        map.putIfAbsent("text", scope);

        result.add(map);
    }
    Collections.sort(result, (map1, map2) -> {
        String code1 = map1.get("code");
        String code2 = map2.get("code");
        int i;
        if (0 != (i = codeIsPasswordOrOpenId(code2) - codeIsPasswordOrOpenId(code1))) {
            return i;
        }
        return code1.compareTo(code2);
    });
    return result;
}

From source file:org.codice.ddf.configuration.migration.ImportMigrationEntryImpl.java

@Override
public boolean restore(BiThrowingConsumer<MigrationReport, Optional<InputStream>, IOException> consumer) {
    Validate.notNull(consumer, "invalid null consumer");
    if (restored == null) {
        this.restored = false; // until proven otherwise
        Optional<InputStream> is = Optional.empty();

        try {//from ww w  . jav a  2 s  .c  o m
            is = getInputStream(true);
            final Optional<InputStream> fis = is;

            this.restored = getReport().wasIOSuccessful(() -> consumer.accept(getReport(), fis));
        } catch (IOException e) {
            getReport().record(new MigrationException(Messages.IMPORT_PATH_COPY_ERROR, path,
                    context.getPathUtils().getDDFHome(), e));
        } finally {
            is.ifPresent(IOUtils::closeQuietly); // we do not care if we cannot close it
        }
    }
    return restored;
}

From source file:org.codice.ddf.configuration.migration.ImportMigrationManagerImplTest.java

private ZipEntry getMetadataZipEntry(ZipFile zip, Optional<String> version, Optional<String> productVersion)
        throws IOException {
    final StringBuilder sb = new StringBuilder();

    sb.append("{\"dummy\":\"dummy");
    version.ifPresent(
            v -> sb.append("\",\"").append(MigrationContextImpl.METADATA_VERSION).append("\":\"").append(v));
    productVersion.ifPresent(v -> sb.append("\",\"").append(MigrationContextImpl.METADATA_PRODUCT_VERSION)
            .append("\":\"").append(v));
    sb.append("\",\"").append(MigrationContextImpl.METADATA_MIGRATABLES).append("\":{");
    boolean first = true;

    for (final Migratable m : migratables) {
        if (first) {
            first = false;/*from  w ww .ja v  a2 s.c o m*/
        } else {
            sb.append(",");
        }
        sb.append("\"").append(m.getId()).append("\":{\"").append(MigrationContextImpl.METADATA_VERSION)
                .append("\":\"").append(m.getVersion()).append("\",\"")
                .append(MigrationContextImpl.METADATA_TITLE).append("\":\"").append(m.getTitle())
                .append("\",\"").append(MigrationContextImpl.METADATA_DESCRIPTION).append("\":\"")
                .append(m.getDescription()).append("\",\"").append(MigrationContextImpl.METADATA_ORGANIZATION)
                .append("\":\"").append(m.getOrganization()).append("\"}");
    }
    sb.append("\"}");
    final ZipEntry ze = Mockito.mock(ZipEntry.class);

    Mockito.when(ze.getName()).thenReturn(MigrationContextImpl.METADATA_FILENAME.toString());
    Mockito.when(ze.isDirectory()).thenReturn(false);
    // use answer to ensure we create a new stream each time if called multiple times
    Mockito.doAnswer(
            AdditionalAnswers.answer(zea -> new ByteArrayInputStream(sb.toString().getBytes(Charsets.UTF_8))))
            .when(zip).getInputStream(ze);
    return ze;
}