Example usage for com.google.common.primitives Ints tryParse

List of usage examples for com.google.common.primitives Ints tryParse

Introduction

In this page you can find the example usage for com.google.common.primitives Ints tryParse.

Prototype

@Beta
@Nullable
@CheckForNull
public static Integer tryParse(String string) 

Source Link

Document

Parses the specified string as a signed decimal integer value.

Usage

From source file:org.graylog.plugins.beats.ConsolePrinter.java

public static void main(String[] args) {
    String hostname = "127.0.0.1";
    int port = 5044;
    if (args.length >= 2) {
        hostname = args[0];//from w w w.  jav a  2s  .  co m
        port = firstNonNull(Ints.tryParse(args[1]), 5044);
    }
    if (args.length >= 1) {
        port = firstNonNull(Ints.tryParse(args[1]), 5044);
    }

    final ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());
    final ServerBootstrap b = new ServerBootstrap(factory);
    b.getPipeline().addLast("beats-frame-decoder", new BeatsFrameDecoder());
    b.getPipeline().addLast("beats-codec", new BeatsCodecHandler());
    b.getPipeline().addLast("logging", new LoggingHandler());
    System.out.println("Starting listener on " + hostname + ":" + port);
    b.bind(new InetSocketAddress(hostname, port));
}

From source file:com.homeadvisor.kafdrop.util.JmxUtils.java

public static int getJmxPort(final Environment environment) {
    Optional<Integer> jmxPort = Optional.empty();

    final Properties managementProperties = Agent.getManagementProperties();
    if (managementProperties != null) {
        final String portProperty = managementProperties.getProperty(JMX_PORT_PROPERTY);
        if (portProperty != null) {
            final Optional<Integer> port = Optional.ofNullable(Ints.tryParse(portProperty));
            jmxPort = port;//from  w  w w  .  java  2 s. c o m
        }
    }
    return jmxPort.orElse(0);
}

From source file:io.motown.domain.api.chargingstation.TransactionIdFactory.java

/**
 * Creates {@code NumberedTransactionId} or {@code UUIDTransactionId} by inspecting the provided transactionId String.
 * @param transactionIdString   the String to create into a TransactionId
 * @param chargingStationId     the chargingstation id
 * @param protocol              the protocol identifier
 * @return a {@code TransactionId}/*from   w w  w  . j  av a2  s.c o  m*/
 * @throws NullPointerException in case transactionIdString is null.
 * @throws IllegalArgumentException in case no {@code TransactionId} could be created.
 */
public static TransactionId createTransactionId(String transactionIdString, ChargingStationId chargingStationId,
        String protocol) {
    return Ints.tryParse(checkNotNull(transactionIdString)) != null
            ? new NumberedTransactionId(chargingStationId, protocol, Ints.tryParse(transactionIdString))
            : new UuidTransactionId(UUID.fromString(transactionIdString));
}

From source file:com.google.gerrit.server.query.account.AccountPredicates.java

static Predicate<AccountState> defaultPredicate(String query) {
    // Adapt the capacity of this list when adding more default predicates.
    List<Predicate<AccountState>> preds = Lists.newArrayListWithCapacity(3);
    Integer id = Ints.tryParse(query);
    if (id != null) {
        preds.add(id(new Account.Id(id)));
    }/*  ww  w. ja v a  2 s .  c o m*/
    preds.add(equalsName(query));
    preds.add(username(query));
    // Adapt the capacity of the "predicates" list when adding more default
    // predicates.
    return Predicate.or(preds);
}

From source file:com.brighttag.agathon.security.Netmask.java

public static @Nullable Netmask fromCidr(String cidr) {
    String[] parts = cidr.split("/");
    if (parts.length == 2 && InetAddresses.isInetAddress(parts[0])) {
        Integer prefixLength = Ints.tryParse(parts[1]);
        if (prefixLength != null) {
            return new Netmask(parts[0], prefixLength);
        }//w ww  .  j av a  2  s  . co m
    }
    return null;
}

From source file:com.google.errorprone.refaster.testdata.TryTemplateExample.java

int foo(String str) {
    int result;
    result = MoreObjects.firstNonNull(Ints.tryParse(str), 0);
    return result;
}

From source file:org.midonet.cluster.data.neutron.RuleProtocol.java

@JsonCreator
public static RuleProtocol forValue(String v) {
    if (v == null)
        return null;

    Integer num = Ints.tryParse(v);
    if (num != null) {
        return forNumValue(num.byteValue());
    } else {//w  w w  . j  av  a 2s .  c  o  m
        return forStrValue(v);
    }
}

From source file:com.google.gerrit.server.mail.receive.MetadataParser.java

public static MailMetadata parse(MailMessage m) {
    MailMetadata metadata = new MailMetadata();
    // Find author
    metadata.author = m.from().getEmail();

    // Check email headers for X-Gerrit-<Name>
    for (String header : m.additionalHeaders()) {
        if (header.startsWith(toHeaderWithDelimiter(MetadataName.CHANGE_ID))) {
            metadata.changeId = header.substring(toHeaderWithDelimiter(MetadataName.CHANGE_ID).length());
        } else if (header.startsWith(toHeaderWithDelimiter(MetadataName.PATCH_SET))) {
            String ps = header.substring(toHeaderWithDelimiter(MetadataName.PATCH_SET).length());
            metadata.patchSet = Ints.tryParse(ps);
        } else if (header.startsWith(toHeaderWithDelimiter(MetadataName.TIMESTAMP))) {
            String ts = header.substring(toHeaderWithDelimiter(MetadataName.TIMESTAMP).length()).trim();
            try {
                metadata.timestamp = Timestamp.from(MailUtil.rfcDateformatter.parse(ts, Instant::from));
            } catch (DateTimeParseException e) {
                log.error("Mail: Error while parsing timestamp from header of message " + m.id(), e);
            }//from  w  w w. ja  va 2  s . c o m
        } else if (header.startsWith(toHeaderWithDelimiter(MetadataName.MESSAGE_TYPE))) {
            metadata.messageType = header.substring(toHeaderWithDelimiter(MetadataName.MESSAGE_TYPE).length());
        }
    }
    if (metadata.hasRequiredFields()) {
        return metadata;
    }

    // If the required fields were not yet found, continue to parse the text
    if (!Strings.isNullOrEmpty(m.textContent())) {
        String[] lines = m.textContent().replace("\r\n", "\n").split("\n");
        extractFooters(lines, metadata, m);
        if (metadata.hasRequiredFields()) {
            return metadata;
        }
    }

    // If the required fields were not yet found, continue to parse the HTML
    // HTML footer are contained inside a <div> tag
    if (!Strings.isNullOrEmpty(m.htmlContent())) {
        String[] lines = m.htmlContent().replace("\r\n", "\n").split("</div>");
        extractFooters(lines, metadata, m);
        if (metadata.hasRequiredFields()) {
            return metadata;
        }
    }

    return metadata;
}

From source file:com.google.gerrit.server.account.HashedPassword.java

/**
 * decodes a hashed password encoded with {@link #encode}.
 *
 * @throws DecoderException if input is malformed.
 *//*  w  ww. java 2  s .c  o  m*/
public static HashedPassword decode(String encoded) throws DecoderException {
    if (!encoded.startsWith(ALGORITHM_PREFIX)) {
        throw new DecoderException("unrecognized algorithm");
    }

    String[] fields = encoded.split(":");
    if (fields.length != 4) {
        throw new DecoderException("want 4 fields");
    }

    Integer cost = Ints.tryParse(fields[1]);
    if (cost == null) {
        throw new DecoderException("cost parse failed");
    }

    if (!(cost >= 4 && cost < 32)) {
        throw new DecoderException("cost should be 4..31 inclusive, got " + cost);
    }

    byte[] salt = codec.decode(fields[2]);
    if (salt.length != 16) {
        throw new DecoderException("salt should be 16 bytes, got " + salt.length);
    }
    return new HashedPassword(codec.decode(fields[3]), salt, cost);
}

From source file:com.google.gerrit.pgm.init.HANAInitializer.java

@Override
public void initConfig(Section databaseSection) {
    final String defInstanceNumber = "00";
    databaseSection.string("Server hostname", "hostname", "localhost");
    databaseSection.string("Instance number", "instance", defInstanceNumber, false);
    String instance = databaseSection.get("instance");
    Integer instanceNumber = Ints.tryParse(instance);
    if (instanceNumber == null || instanceNumber < 0 || instanceNumber > 99) {
        instanceIsInvalid();/*from  w w w .jav a 2  s . co m*/
    }
    databaseSection.string("Database username", "username", username());
    databaseSection.password("username", "password");
}