java.util.Optional#of ( )源码实例Demo

下面列出了java.util.Optional#of ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: presto   文件: PrincipalUserMatchRule.java
public Optional<Boolean> match(String principal, String user)
{
    Matcher matcher = principalRegex.matcher(principal);

    if (!matcher.matches()) {
        return Optional.empty();
    }

    if (userRegex.isPresent()) {
        if (userRegex.get().matcher(user).matches()) {
            return Optional.of(allow);
        }
    }

    if (principalToUserSubstitution.isPresent()) {
        String userExtraction = matcher.replaceAll(principalToUserSubstitution.get());
        if (user.equals(userExtraction)) {
            return Optional.of(allow);
        }
    }

    return Optional.empty();
}
 
源代码2 项目: bisq-core   文件: BsqStateService.java
public Optional<byte[]> getLockupHash(TxOutput txOutput) {
    Optional<Tx> lockupTx = Optional.empty();
    String txId = txOutput.getTxId();
    if (txOutput.getTxOutputType() == TxOutputType.LOCKUP) {
        lockupTx = getTx(txId);
    } else if (isUnlockTxOutputAndLockTimeNotOver(txOutput)) {
        if (getTx(txId).isPresent()) {
            Tx unlockTx = getTx(txId).get();
            lockupTx = getTx(unlockTx.getTxInputs().get(0).getConnectedTxOutputTxId());
        }
    }
    if (lockupTx.isPresent()) {
        byte[] opReturnData = lockupTx.get().getLastTxOutput().getOpReturnData();
        if (opReturnData != null)
            return Optional.of(BondingConsensus.getHashFromOpReturnData(opReturnData));
    }
    return Optional.empty();
}
 
源代码3 项目: ShootOFF   文件: BluetoothServer.java
private Optional<String> getLocalAddress() {
	try {
		final LocalDevice localDevice = LocalDevice.getLocalDevice();

		// Insert colons into the address because android needs them
		final StringBuilder addressBuilder = new StringBuilder();
		final String originalAddress = localDevice.getBluetoothAddress();
		for (int i = 0; i < originalAddress.length(); i++) {
			addressBuilder.append(originalAddress.charAt(i));
			if (i > 0 && i < originalAddress.length() - 1 && i % 2 != 0) addressBuilder.append(':');
		}

		return Optional.of(addressBuilder.toString());
	} catch (BluetoothStateException e) {
		logger.error("Failed to access local bluetooth device to fetch its address. Ensure the "
				+ "system's bluetooth service is started with \"sudo systemctl start bluetooth\" "
				+ "and the bluetooth stack is on in the system settings", e);
		return Optional.empty();
	}
}
 
源代码4 项目: connector-sdk   文件: IndexingItemBuilder.java
/**
 * Constructs a {@link FieldOrValue} instance for the given {@code configKey},
 * trying first the given field and if that is not does not exist,
 * or has an empty value, the given default value.
 *
 * @param configKey a configuration key prefix, for example, {@code "itemMetadata.title"}
 * @param field the key to lookup from {@link IndexingItemBuilder#setValues}
 * @param value the default value
 * @param parser a configuration {@link Parser} of the appropriate type, for example,
 *     {@code String} or {@code DateTime}
 */
private static <T> Optional<FieldOrValue<T>> fieldOrValue(String configKey, String field,
    String value, Configuration.Parser<T> parser) {
  if (field.isEmpty()) {
    if (value.isEmpty()) {
      return Optional.empty();
    } else {
      logger.log(Level.CONFIG, "{0} = {1}", new Object[] { dotValue(configKey), value });
      return Optional.of(FieldOrValue.withValue(parser.parse(value)));
    }
  } else {
    logger.log(Level.CONFIG, "{0} = {1}", new Object[] { dotField(configKey), field });
    if (value.isEmpty()) {
      return Optional.of(FieldOrValue.withField(field));
    } else {
      logger.log(Level.CONFIG, "{0} = {1}", new Object[] { dotValue(configKey), value });
      return Optional.of(new FieldOrValue<>(field, parser.parse(value)));
    }
  }
}
 
源代码5 项目: SciGraph   文件: GraphApi.java
public Optional<Node> getNode(String id, Optional<String> lblHint) {
  String iriResolved = curieUtil.getIri(id).orElse(id);
  Optional<Node> node = Optional.empty();
  if (lblHint.isPresent()) {
    Label hintLabel = Label.label(lblHint.get());
    Node hit = graphDb.findNode(hintLabel, NodeProperties.IRI, iriResolved);
    if (hit != null) {
      node = Optional.of(hit);
    }
  } else {
    String startQuery =
        "MATCH (n {" + NodeProperties.IRI + ": \"" + iriResolved + "\"}) RETURN n";
    Result res = cypherUtil.execute(startQuery);
    if (res.hasNext()) {
      node = Optional.of((Node) res.next().get("n"));
    }
  }

  return node;
}
 
源代码6 项目: Plan   文件: WebUserQueries.java
public static Query<Optional<User>> fetchUser(UUID linkedToUUID) {
    String sql = SELECT + '*' + FROM + SecurityTable.TABLE_NAME +
            LEFT_JOIN + UsersTable.TABLE_NAME + " on " + SecurityTable.LINKED_TO + "=" + UsersTable.USER_UUID +
            WHERE + SecurityTable.LINKED_TO + "=? LIMIT 1";
    return new QueryStatement<Optional<User>>(sql) {
        @Override
        public void prepare(PreparedStatement statement) throws SQLException {
            if (linkedToUUID == null) {
                statement.setNull(1, Types.VARCHAR);
            } else {
                statement.setString(1, linkedToUUID.toString());
            }
        }

        @Override
        public Optional<User> processResults(ResultSet set) throws SQLException {
            if (set.next()) {
                String username = set.getString(SecurityTable.USERNAME);
                String linkedTo = set.getString(UsersTable.USER_NAME);
                String passwordHash = set.getString(SecurityTable.SALT_PASSWORD_HASH);
                int permissionLevel = set.getInt(SecurityTable.PERMISSION_LEVEL);
                List<String> permissions = WebUser.getPermissionsForLevel(permissionLevel);
                return Optional.of(new User(username, linkedTo != null ? linkedTo : "console", linkedToUUID, passwordHash, permissionLevel, permissions));
            }
            return Optional.empty();
        }
    };
}
 
源代码7 项目: presto   文件: BigQueryConfig.java
@Config("bigquery.credentials-file")
@ConfigDescription("The path to the JSON credentials file")
public BigQueryConfig setCredentialsFile(String credentialsFile)
{
    this.credentialsFile = Optional.of(credentialsFile);
    return this;
}
 
源代码8 项目: openAGV   文件: UnifiedModelReader.java
@Override
public Optional<PlantModelCreationTO> deserialize(File file)
    throws IOException {
  requireNonNull(file, "file");

  PlantModelCreationTO plantModel = modelParser.readModel(file);
  return Optional.of(plantModel);
}
 
源代码9 项目: ua-server-sdk   文件: UaMethodLoader.java
private void buildNode20() {
    UaMethodNode node = new UaMethodNode(this.nodeManager, NodeId.parse("ns=0;i=12749"), new QualifiedName(0, "SetSubscriptionDurable"), new LocalizedText("en", "SetSubscriptionDurable"), Optional.empty(), Optional.of(UInteger.valueOf(0L)), Optional.of(UInteger.valueOf(0L)), true, true);
    node.addReference(new Reference(NodeId.parse("ns=0;i=12749"), NodeId.parse("ns=0;i=47"), ExpandedNodeId.parse("svr=0;i=2253"), NodeClass.Object, false));
    node.addReference(new Reference(NodeId.parse("ns=0;i=12749"), NodeId.parse("ns=0;i=46"), ExpandedNodeId.parse("svr=0;i=12750"), NodeClass.Variable, true));
    node.addReference(new Reference(NodeId.parse("ns=0;i=12749"), NodeId.parse("ns=0;i=46"), ExpandedNodeId.parse("svr=0;i=12751"), NodeClass.Variable, true));
    node.addReference(new Reference(NodeId.parse("ns=0;i=12749"), NodeId.parse("ns=0;i=47"), ExpandedNodeId.parse("svr=0;i=2253"), NodeClass.Object, false));
    node.addReference(new Reference(NodeId.parse("ns=0;i=12749"), NodeId.parse("ns=0;i=46"), ExpandedNodeId.parse("svr=0;i=12750"), NodeClass.Variable, true));
    node.addReference(new Reference(NodeId.parse("ns=0;i=12749"), NodeId.parse("ns=0;i=46"), ExpandedNodeId.parse("svr=0;i=12751"), NodeClass.Variable, true));
    this.nodeManager.addNode(node);
}
 
源代码10 项目: Javacord   文件: ServerChangeSplashEventImpl.java
/**
 * Gets the splash for the given hash.
 *
 * @param splashHash The hash of the splash.
 * @return The splash with the given hash.
 */
private Optional<Icon> getSplash(String splashHash) {
    if (splashHash == null) {
        return Optional.empty();
    }
    try {
        return Optional.of(new IconImpl(getApi(), new URL(
                "https://" + Javacord.DISCORD_CDN_DOMAIN + "/splashs/" + getServer().getIdAsString()
                        + "/" + splashHash + ".png")));
    } catch (MalformedURLException e) {
        logger.warn("Seems like the url of the splash is malformed! Please contact the developer!", e);
        return Optional.empty();
    }
}
 
源代码11 项目: swage   文件: TypedMap.java
/**
 * Returns an Optional containing the value stored for the given key, or
 * empty if the key does not have a value mapped.
 * @param key Key to retrieve data for
 * @param <T> Type of the data
 * @return Optional containing value stored under the given key, or empty if nothing exists for the key
 */
public default <T> Optional<T> getOptional(Key<T> key) {
    T value = get(key);
    if (value == null) {
        return Optional.empty();
    }
    return Optional.of(value);
}
 
源代码12 项目: scheduling   文件: SortedUniqueSet.java
public Optional<T> get(String key) {
    final T value = items.get(key);
    if (value != null) {
        return Optional.of(value);
    } else {
        return Optional.empty();
    }
}
 
源代码13 项目: Spring-Boot-2.0-Projects   文件: AuditAwareImpl.java
@Override
public Optional<String> getCurrentAuditor() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null || !authentication.isAuthenticated()) {
        return Optional.empty();
    }

    return Optional.of(((User) authentication.getPrincipal()).getUsername());
}
 
源代码14 项目: vespa   文件: MockInvoker.java
protected MockInvoker(int key, Coverage coverage) {
    super(Optional.of(new Node(key, "?", 0)));
    this.coverage = coverage;
}
 
源代码15 项目: nifi   文件: TestSocketFlowFileServerProtocol.java
@Test
public void testSendPeerListCluster() throws Exception {
    final SocketFlowFileServerProtocol protocol = getDefaultSocketFlowFileServerProtocol();
    final List<NodeInformation> nodeInfoList = new ArrayList<>();
    final ClusterNodeInformation clusterNodeInformation = new ClusterNodeInformation();
    clusterNodeInformation.setNodeInformation(nodeInfoList);
    final Optional<ClusterNodeInformation> clusterNodeInfo = Optional.of(clusterNodeInformation);

    for (int i = 0; i < 3; i++) {
        final String siteToSiteHostname = String.format("node%d.example.com", i);
        final Integer siteToSitePort = 8081;
        final Integer siteToSiteHttpPort = null;
        final int apiPort = 8080;
        final boolean isSiteToSiteSecure = true;
        final int numOfQueuedFlowFiles = 100 + i;
        final NodeInformation nodeInformation = new NodeInformation(siteToSiteHostname, siteToSitePort, siteToSiteHttpPort,
                apiPort, isSiteToSiteSecure, numOfQueuedFlowFiles);
        nodeInfoList.add(nodeInformation);
    }

    final NodeInformation self = nodeInfoList.get(0);

    final HandshakeProperties handshakeProperties = new HandshakeProperties();
    handshakeProperties.setCommsIdentifier("communication-identifier");
    handshakeProperties.setTransitUriPrefix("uri-prefix");

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final Peer peer = getDefaultPeer(handshakeProperties, outputStream);

    protocol.handshake(peer);
    protocol.sendPeerList(peer, clusterNodeInfo, self);

    try (final DataInputStream dis = new DataInputStream(new ByteArrayInputStream(outputStream.toByteArray()))) {
        final Response handshakeResponse = Response.read(dis);
        assertEquals(ResponseCode.PROPERTIES_OK, handshakeResponse.getCode());

        final int numPeers = dis.readInt();
        assertEquals(nodeInfoList.size(), numPeers);

        for (int i = 0; i < nodeInfoList.size(); i++) {
            final NodeInformation node = nodeInfoList.get(i);
            assertEquals(node.getSiteToSiteHostname(), dis.readUTF());
            assertEquals(node.getSiteToSitePort().intValue(), dis.readInt());
            assertEquals(node.isSiteToSiteSecure(), dis.readBoolean());
            assertEquals(node.getTotalFlowFiles(), dis.readInt());
        }
    }
}
 
源代码16 项目: customstuff4   文件: ContentBlockPressurePlate.java
@Override
protected Optional<Item> createItem()
{
    return Optional.of(new ItemBlock(block, this));
}
 
@Override
protected Optional<Flowable> createInstanceEmittingASingleValueAsynchronously(String value) {
    return Optional.of(
            Flowable.just(value).delay(DELAY, TimeUnit.MILLISECONDS).observeOn(Schedulers.io()));
}
 
源代码18 项目: barge   文件: RaftApplication.java
public ResourceConfig makeResourceConfig() {
  ClusterConfig clusterConfig = HttpClusterConfig.from(new HttpReplica(uris[serverIndex]),
    remotes());

  if (!logDir.exists() && !logDir.mkdirs())
    logger.warn("failed to create directories for storing logs, bad things will happen");

  StateMachine stateMachine = new StateMachine() {
    int i = 0;

    @Override
    public Object applyOperation(@Nonnull ByteBuffer entry) {
      return i++;
    }
  };

  final JaxRsRaftModule raftModule = new JaxRsRaftModule(clusterConfig, logDir, stateMachine, 1500, transitionListeners, protocolListeners);

  injector = Optional.of(Guice.createInjector(raftModule));

  ResourceConfig resourceConfig = new ResourceConfig();

  Binder binder = new AbstractBinder() {
    @Override
    protected void configure() {
      bindFactory(new Factory<Raft>() {
            @Override
            public Raft provide() {
              return injector.get().getInstance(Raft.class);
            }

            @Override
            public void dispose(Raft raft) {
            }
          }).to(Raft.class);
      
      bindFactory(new Factory<ClusterConfig>() {
        @Override public ClusterConfig provide() {
          return injector.get().getInstance(ClusterConfig.class);
        }

        @Override public void dispose(ClusterConfig instance) {
        }
      }).to(ClusterConfig.class);
    }
  };

  resourceConfig.register(BargeResource.class);
  resourceConfig.register(Jackson.customJacksonProvider());
  resourceConfig.register(binder);

  return resourceConfig;
}
 
源代码19 项目: hbase   文件: TestReplicasClient.java
@Override
public Optional<RegionObserver> getRegionObserver() {
  return Optional.of(this);
}
 
源代码20 项目: flink   文件: HBaseTableSchema.java
/**
 * Returns optional value of row key name.
 * The row key name is the field name in hbase schema which can be queried in Flink SQL.
 */
public Optional<String> getRowKeyName() {
	return rowKeyInfo == null ? Optional.empty() : Optional.of(rowKeyInfo.rowKeyName);
}