Java Code Examples for java.util.Optional#of()

The following examples show how to use java.util.Optional#of() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BluetoothServer.java    From ShootOFF with GNU General Public License v3.0 7 votes vote down vote up
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();
	}
}
 
Example 2
Source File: PrincipalUserMatchRule.java    From presto with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 3
Source File: GraphApi.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: IndexingItemBuilder.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 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)));
    }
  }
}
 
Example 5
Source File: BsqStateService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
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();
}
 
Example 6
Source File: BigQueryConfig.java    From presto with Apache License 2.0 5 votes vote down vote up
@Config("bigquery.credentials-file")
@ConfigDescription("The path to the JSON credentials file")
public BigQueryConfig setCredentialsFile(String credentialsFile)
{
    this.credentialsFile = Optional.of(credentialsFile);
    return this;
}
 
Example 7
Source File: UnifiedModelReader.java    From openAGV with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<PlantModelCreationTO> deserialize(File file)
    throws IOException {
  requireNonNull(file, "file");

  PlantModelCreationTO plantModel = modelParser.readModel(file);
  return Optional.of(plantModel);
}
 
Example 8
Source File: UaMethodLoader.java    From ua-server-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 9
Source File: ServerChangeSplashEventImpl.java    From Javacord with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 10
Source File: TypedMap.java    From swage with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 11
Source File: SortedUniqueSet.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public Optional<T> get(String key) {
    final T value = items.get(key);
    if (value != null) {
        return Optional.of(value);
    } else {
        return Optional.empty();
    }
}
 
Example 12
Source File: AuditAwareImpl.java    From Spring-Boot-2.0-Projects with MIT License 5 votes vote down vote up
@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());
}
 
Example 13
Source File: WebUserQueries.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
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();
        }
    };
}
 
Example 14
Source File: MockInvoker.java    From vespa with Apache License 2.0 4 votes vote down vote up
protected MockInvoker(int key, Coverage coverage) {
    super(Optional.of(new Node(key, "?", 0)));
    this.coverage = coverage;
}
 
Example 15
Source File: TestSocketFlowFileServerProtocol.java    From nifi with Apache License 2.0 4 votes vote down vote up
@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());
        }
    }
}
 
Example 16
Source File: ContentBlockPressurePlate.java    From customstuff4 with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected Optional<Item> createItem()
{
    return Optional.of(new ItemBlock(block, this));
}
 
Example 17
Source File: FlowableToRSPublisherTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 4 votes vote down vote up
@Override
protected Optional<Flowable> createInstanceEmittingASingleValueAsynchronously(String value) {
    return Optional.of(
            Flowable.just(value).delay(DELAY, TimeUnit.MILLISECONDS).observeOn(Schedulers.io()));
}
 
Example 18
Source File: RaftApplication.java    From barge with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 19
Source File: TestReplicasClient.java    From hbase with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<RegionObserver> getRegionObserver() {
  return Optional.of(this);
}
 
Example 20
Source File: HBaseTableSchema.java    From flink with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}