Java Code Examples for com.google.common.primitives.Ints#tryParse()

The following examples show how to use com.google.common.primitives.Ints#tryParse() . 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: IPAddressRange.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new address range from its string representation. This can be either a CIDR or subnet notation.
 * <br/>
 * Examples:
 * <pre>
 * 192.168.1.1/24
 * 192.168.1.1/255.255.255.0
 * 2001:db8:abcd:0012::0/64
 * 2001:db8:abcd:0012::0/ffff:ffff:ffff:ffff::
 * </pre>
 *
 * @param string the string representation
 */
public IPAddressRange(String string) {
    String[] split = Objects.requireNonNull(string).split(RANGE_SEPARATOR, 2);

    this.address = new IPAddress(split[0]);

    if (split.length == 1) {
        this.prefix = this.address.getBitSize();
    } else {
        Integer sn = Ints.tryParse(split[1]);
        if (sn == null) {
            this.prefix = IPAddressRange.getPrefixForMask(new IPAddress(split[1]));
        } else {
            this.prefix = sn;
        }
    }
    init();
}
 
Example 2
Source File: SmartUriAdapter.java    From rya with Apache License 2.0 6 votes vote down vote up
private static IRI determineType(final String data) {
    if (Ints.tryParse(data) != null) {
        return XMLSchema.INTEGER;
    } else if (Doubles.tryParse(data) != null) {
        return XMLSchema.DOUBLE;
    } else if (Floats.tryParse(data) != null) {
        return XMLSchema.FLOAT;
    } else if (isShort(data)) {
        return XMLSchema.SHORT;
    } else if (Longs.tryParse(data) != null) {
        return XMLSchema.LONG;
    } if (Boolean.parseBoolean(data)) {
        return XMLSchema.BOOLEAN;
    } else if (isByte(data)) {
        return XMLSchema.BYTE;
    } else if (isDate(data)) {
        return XMLSchema.DATETIME;
    } else if (isUri(data)) {
        return XMLSchema.ANYURI;
    }

    return XMLSchema.STRING;
}
 
Example 3
Source File: PaginationCommand.java    From LagMonitor with MIT License 6 votes vote down vote up
private void onPageNumber(String subCommand, CommandSender sender, Pages pagination) {
    Integer page = Ints.tryParse(subCommand);
    if (page == null) {
        sendError(sender, "Unknown subcommand or not a valid page number");
    } else {
        if (page < 1) {
            sendError(sender, "Page number too small");
            return;
        } else if (page > pagination.getTotalPages(sender instanceof Player)) {
            sendError(sender, "Page number too high");
            return;
        }

        pagination.send(sender, page);
    }
}
 
Example 4
Source File: PaginationCommand.java    From LagMonitor with MIT License 6 votes vote down vote up
private void onPageNumber(String subCommand, CommandSender sender, Pages pagination) {
    Integer page = Ints.tryParse(subCommand);
    if (page == null) {
        sendError(sender, "Unknown subcommand or not a valid page number");
    } else {
        if (page < 1) {
            sendError(sender, "Page number too small");
            return;
        } else if (page > pagination.getTotalPages(sender instanceof Player)) {
            sendError(sender, "Page number too high");
            return;
        }

        pagination.send(sender, page);
    }
}
 
Example 5
Source File: SessionIdParser.java    From bundletool with Apache License 2.0 6 votes vote down vote up
private static int parseSessionIdFromOutput(String output) {
  int startIndex = output.indexOf("[");
  int endIndex = output.indexOf("]", startIndex);
  if (startIndex == -1 || endIndex == -1) {
    throw AdbOutputParseException.builder()
        .withInternalMessage("adb: failed to parse session id from output\nDetails:%s", output)
        .build();
  }
  Integer sessionId = Ints.tryParse(output.substring(startIndex + 1, endIndex));
  if (sessionId == null) {
    throw AdbOutputParseException.builder()
        .withInternalMessage("adb: session id should be integer\nDetails:%s", output)
        .build();
  }
  return sessionId;
}
 
Example 6
Source File: HttpClient.java    From intercom-java with Apache License 2.0 6 votes vote down vote up
private <T> T throwException(int responseCode, ErrorCollection errors, HttpURLConnection conn) {
    // bind some well known response codes to exceptions
    if (responseCode == 403 || responseCode == 401) {
        throw new AuthorizationException(errors);
    } else if (responseCode == 429) {
        throw new RateLimitException(errors, Ints.tryParse(conn.getHeaderField(RATE_LIMIT_HEADER)),
                Ints.tryParse(conn.getHeaderField(RATE_LIMIT_REMAINING_HEADER)),
                Longs.tryParse(conn.getHeaderField(RATE_LIMIT_RESET_HEADER)));
    } else if (responseCode == 404) {
        throw new NotFoundException(errors);
    } else if (responseCode == 422) {
        throw new InvalidException(errors);
    } else if (responseCode == 400 || responseCode == 405 || responseCode == 406) {
        throw new ClientException(errors);
    } else if (responseCode == 500 || responseCode == 503) {
        throw new ServerException(errors);
    } else {
        throw new IntercomException(errors);
    }
}
 
Example 7
Source File: CassandraConfiguration.java    From cassandra-jdbc-driver with Apache License 2.0 6 votes vote down vote up
private void init() {
    int tentativePort = config.port;
    Splitter splitter = Splitter.on(':').trimResults().omitEmptyStrings().limit(2);
    StringBuilder sb = new StringBuilder();
    for (String host : Splitter.on(',').trimResults().omitEmptyStrings().split(
            config.hosts)) {
        List<String> h = splitter.splitToList(host);
        sb.append(h.get(0)).append(',');
        if (h.size() > 1 && tentativePort <= 0) {
            tentativePort = Ints.tryParse(h.get(1));
        }
    }

    config.hosts = sb.deleteCharAt(sb.length() - 1).toString();
    config.port = tentativePort;

    // update timeouts
    config.connectionTimeout = config.connectionTimeout * 1000;
    config.readTimeout = config.readTimeout * 1000;
}
 
Example 8
Source File: FullSwapTradeCsvPlugin.java    From Strata with Apache License 2.0 5 votes vote down vote up
private static Period parseInflationLag(Optional<String> strOpt, Currency currency) {
  if (!strOpt.isPresent()) {
    if (Currency.GBP.equals(currency)) {
      return Period.ofMonths(2);
    }
    return Period.ofMonths(3);
  }
  String str = strOpt.get();
  Integer months = Ints.tryParse(str);
  if (months != null) {
    return Period.ofMonths(months);
  }
  return Tenor.parse(str).getPeriod();
}
 
Example 9
Source File: PurgeCommand.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void executeCommand(CommandSender sender, List<String> arguments) {
    // Get the days parameter
    String daysStr = arguments.get(0);

    // Convert the days string to an integer value, and make sure it's valid
    Integer days = Ints.tryParse(daysStr);
    if (days == null) {
        sender.sendMessage(ChatColor.RED + "The value you've entered is invalid!");
        return;
    }

    // Validate the value
    if (days < MINIMUM_LAST_SEEN_DAYS) {
        sender.sendMessage(ChatColor.RED + "You can only purge data older than "
            + MINIMUM_LAST_SEEN_DAYS + " days");
        return;
    }

    // Create a calender instance to determine the date
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -days);
    long until = calendar.getTimeInMillis();

    // Run the purge
    purgeService.runPurge(sender, until);
}
 
Example 10
Source File: Bootstrap.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private static int getPort(final String[] args) {
    if (0 == args.length) {
        return DEFAULT_PORT;
    }
    Integer port = Ints.tryParse(args[0]);
    return port == null ? DEFAULT_PORT : port;
}
 
Example 11
Source File: StringUtils.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns true if the provided value with leading and trailing whitespace removed is an {@code
 * int} {@see isInteger} and is positive (greater than zero). Returns false if the parameter is
 * null, zero, negative, or cannot be parsed as an {@code int}.
 */
public static boolean isPositiveInt(final String value) {
  if (value == null) {
    return false;
  }
  final Integer intValue = Ints.tryParse(value.trim());
  return intValue != null && intValue > 0;
}
 
Example 12
Source File: LumongoQueryParser.java    From lumongo with Apache License 2.0 5 votes vote down vote up
@Override
protected Query newTermQuery(org.apache.lucene.index.Term term) {
	String field = term.field();
	String text = term.text();

	FieldConfig.FieldType fieldType = indexConfig.getFieldTypeForIndexField(field);
	if (IndexConfigUtil.isNumericOrDateFieldType(fieldType)) {
		if (IndexConfigUtil.isDateFieldType(fieldType)) {
			return getNumericOrDateRange(field, text, text, true, true);
		}
		else {
			if (IndexConfigUtil.isNumericIntFieldType(fieldType) && Ints.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericLongFieldType(fieldType) && Longs.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericFloatFieldType(fieldType) && Floats.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericDoubleFieldType(fieldType) && Doubles.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
		}
		return new MatchNoDocsQuery(field + " expects numeric");
	}

	return super.newTermQuery(term);
}
 
Example 13
Source File: LogCatMessageParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parse a list of strings into {@link LogCatMessage} objects. This method
 * maintains state from previous calls regarding the last seen header of
 * logcat messages.
 * @param lines list of raw strings obtained from logcat -v long
 * @param device device from which these log messages have been received
 * @return list of LogMessage objects parsed from the input
 */
@NonNull
public List<LogCatMessage> processLogLines(String[] lines, IDevice device) {
    List<LogCatMessage> messages = new ArrayList<LogCatMessage>(lines.length);

    for (String line : lines) {
        if (line.isEmpty()) {
            continue;
        }

        Matcher matcher = sLogHeaderPattern.matcher(line);
        if (matcher.matches()) {
            mCurTime = matcher.group(1);
            mCurPid = matcher.group(2);
            mCurTid = matcher.group(3);
            mCurLogLevel = LogLevel.getByLetterString(matcher.group(4));
            mCurTag = matcher.group(5).trim();

            /* LogLevel doesn't support messages with severity "F". Log.wtf() is supposed
             * to generate "A", but generates "F". */
            if (mCurLogLevel == null && matcher.group(4).equals("F")) {
                mCurLogLevel = LogLevel.ASSERT;
            }
        } else {
            String pkgName = ""; //$NON-NLS-1$
            Integer pid = Ints.tryParse(mCurPid);
            if (pid != null && device != null) {
                pkgName = device.getClientName(pid);
            }
            LogCatMessage m = new LogCatMessage(mCurLogLevel, mCurPid, mCurTid,
                    pkgName, mCurTag, mCurTime, line);
            messages.add(m);
        }
    }

    return messages;
}
 
Example 14
Source File: BeforeConstant.java    From Mixin with MIT License 5 votes vote down vote up
public BeforeConstant(InjectionPointData data) {
    super(data);
    
    String strNullValue = data.get("nullValue", null);
    Boolean empty = strNullValue != null ? Boolean.parseBoolean(strNullValue) : null;
    
    this.ordinal = data.getOrdinal();
    this.nullValue = empty != null && empty.booleanValue();
    this.intValue = Ints.tryParse(data.get("intValue", ""));
    this.floatValue = Floats.tryParse(data.get("floatValue", ""));
    this.longValue = Longs.tryParse(data.get("longValue", ""));
    this.doubleValue = Doubles.tryParse(data.get("doubleValue", ""));
    this.stringValue = data.get("stringValue", null);
    String strClassValue = data.get("classValue", null);
    this.typeValue = strClassValue != null ? Type.getObjectType(strClassValue.replace('.', '/')) : null;
    
    this.matchByType = this.validateDiscriminator(data.getContext(), "V", empty, "in @At(\"CONSTANT\") args");
    if ("V".equals(this.matchByType)) {
        throw new InvalidInjectionException(data.getContext(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args");
    }
    
    List<Condition> conditions = new ArrayList<Condition>();
    String strConditions = data.get("expandZeroConditions", "").toLowerCase(Locale.ROOT);
    for (Condition condition : Condition.values()) {
        if (strConditions.contains(condition.name().toLowerCase(Locale.ROOT))) {
            conditions.add(condition);
        }
    }
    
    this.expandOpcodes = this.parseExpandOpcodes(conditions);
    this.expand = this.expandOpcodes.length > 0;
    
    this.log = data.get("log", false);
}
 
Example 15
Source File: CassandraCqlStmtConfiguration.java    From cassandra-jdbc-driver with Apache License 2.0 5 votes vote down vote up
public CassandraCqlStmtConfiguration(CassandraConfiguration connectionConfig, CassandraStatementType stmtType,
                                     Map<String, String> stmtOptions) {
    this.connectionConfig = connectionConfig;
    this.stmtType = stmtType;

    Properties options = new Properties();
    if (stmtOptions != null) {
        options.putAll(stmtOptions);
    }

    CassandraEnums.ConsistencyLevel preferredCL = connectionConfig.getConsistencyLevel();
    if (stmtType.isQuery()) {
        preferredCL = connectionConfig.getReadConsistencyLevel();
    } else if (stmtType.isUpdate()) {
        preferredCL = connectionConfig.getWriteConsistencyLevel();
    }

    consistencyLevel = options.getProperty(KEY_CONSISTENCY_LEVEL, preferredCL.name()).trim().toUpperCase();
    // TODO better to check if there's IF condition in the update CQL before doing so
    serialConsistencyLevel = stmtType.isUpdate()
            && (preferredCL == CassandraEnums.ConsistencyLevel.LOCAL_SERIAL
            || preferredCL == CassandraEnums.ConsistencyLevel.SERIAL) ? preferredCL.name() : null;

    String value = options.getProperty(KEY_FETCH_SIZE);
    // -1 implies using the one defined in Statement / PreparedStatement
    fetchSize = Strings.isNullOrEmpty(value) ? -1 : Ints.tryParse(value);
    noLimit = Boolean.valueOf(options.getProperty(KEY_NO_LIMIT, null));
    noWait = Boolean.valueOf(options.getProperty(KEY_NO_WAIT, null));
    tracing = Boolean.valueOf(options.getProperty(KEY_TRACING, String.valueOf(connectionConfig.isTracingEnabled())));
    value = options.getProperty(KEY_READ_TIMEOUT);
    // convert second to millisecond
    readTimeout = Strings.isNullOrEmpty(value) ? connectionConfig.getReadTimeout() : Ints.tryParse(value) * 1000;
    replaceNullValue = Boolean.valueOf(options.getProperty(KEY_REPLACE_NULL_VALUE, null));
    sqlParser = Boolean.valueOf(options.getProperty(KEY_SQL_PARSER, String.valueOf(connectionConfig.isSqlFriendly())));
}
 
Example 16
Source File: MockImageBase.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * This resizes the picture according to
 * 1. height and width value of the div tag enclosing the img tag
 * 2. scaling mode. 0 - Scale proportionally, 1 - Scale to fit
 *    which correspond to the choices in ScalingChoicePropertyEditor
 *
 * This should be called whenever a property affecting the size is changed
 */
private void resizeImage() {
  if (image.getUrl().equals(getIconImage().getUrl())) {
    unclipImage();
    return;
  }

  String width = getElement().getStyle().getWidth();
  String height = getElement().getStyle().getHeight();

  // the situation right after refreshing the page
  if (width.isEmpty() || height.isEmpty()) {
    return;
  }

  int frameWidth = Ints.tryParse(width.substring(0, width.indexOf("px")));
  int frameHeight = Ints.tryParse(height.substring(0, height.indexOf("px")));

  if (scalingMode.equals("0")) {
    float ratio = Math.min(frameWidth / (float) getPreferredWidth(),
        frameHeight / (float) getPreferredHeight());
    int scaledWidth = Double.valueOf(getPreferredWidth() * ratio).intValue();
    int scaledHeight = Double.valueOf(getPreferredHeight() * ratio).intValue();
    image.setSize(scaledWidth + "px", scaledHeight + "px");

  } else if (scalingMode.equals("1")) {
    image.setSize("100%", "100%");

  } else {
    throw new IllegalStateException("Illegal scaling mode: " + scalingMode);
  }
}
 
Example 17
Source File: StsInterpreter.java    From theta with Apache License 2.0 5 votes vote down vote up
private Object evalAtom(final SAtom satom) {
	final String symbol = satom.getAtom();
	final Integer integer = Ints.tryParse(symbol);
	if (integer != null) {
		return integer;
	} else {
		final Object value = env.eval(symbol);
		return value;
	}
}
 
Example 18
Source File: StatusBarsOverlay.java    From plugins with GNU General Public License v3.0 4 votes vote down vote up
public int getRestoreValue(String skill)
{
	final MenuEntry[] menu = client.getMenuEntries();
	final int menuSize = menu.length;
	final MenuEntry entry = menuSize > 0 ? menu[menuSize - 1] : null;
	int restoreValue = 0;

	if (entry != null && entry.getParam1() == WidgetInfo.INVENTORY.getId())
	{
		final Effect change = itemStatService.getItemStatChanges(entry.getIdentifier());

		if (change != null)
		{
			final StatsChanges statsChanges = change.calculate(client);

			for (final StatChange c : statsChanges.getStatChanges())
			{
				//final String strVar = c.getTheoretical(); this was erroring
				final String strVar = String.valueOf(c.getTheoretical());

				if (Strings.isNullOrEmpty(strVar))
				{
					continue;
				}

				final Integer value = Ints.tryParse(strVar.startsWith("+") ? strVar.substring(1) : strVar);

				if (value == null)
				{
					continue;
				}

				if (c.getStat().getName().equals(skill))
				{
					restoreValue = value;
				}

				if (restoreValue != 0)
				{
					break;
				}
			}
		}
	}

	return restoreValue;
}
 
Example 19
Source File: WorkspaceSharedPool.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Inject
public WorkspaceSharedPool(
    @Named("che.workspace.pool.type") String poolType,
    @Named("che.workspace.pool.exact_size") @Nullable String exactSizeProp,
    @Named("che.workspace.pool.cores_multiplier") @Nullable String coresMultiplierProp,
    ExecutorServiceWrapper wrapper) {

  ThreadFactory factory =
      new ThreadFactoryBuilder()
          .setNameFormat("WorkspaceSharedPool-%d")
          .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance())
          .setDaemon(false)
          .build();
  switch (poolType.toLowerCase()) {
    case "cached":
      executor =
          wrapper.wrap(
              Executors.newCachedThreadPool(factory), WorkspaceSharedPool.class.getName());
      break;
    case "fixed":
      Integer exactSize = exactSizeProp == null ? null : Ints.tryParse(exactSizeProp);
      int size;
      if (exactSize != null && exactSize > 0) {
        size = exactSize;
      } else {
        size = Runtime.getRuntime().availableProcessors();
        Integer coresMultiplier =
            coresMultiplierProp == null ? null : Ints.tryParse(coresMultiplierProp);
        if (coresMultiplier != null && coresMultiplier > 0) {
          size *= coresMultiplier;
        }
      }
      executor =
          wrapper.wrap(
              Executors.newFixedThreadPool(size, factory), WorkspaceSharedPool.class.getName());
      break;
    default:
      throw new IllegalArgumentException(
          "The type of the pool '" + poolType + "' is not supported");
  }
}
 
Example 20
Source File: ExtendedCommunity.java    From batfish with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static ExtendedCommunity parse(String communityStr) {
  String[] parts = communityStr.trim().split(":");
  checkArgument(parts.length == 3, "Invalid extended community string: %s", communityStr);
  long gaLong;
  long laLong;
  String subType = parts[0].toLowerCase();
  String globalAdministrator = parts[1].toLowerCase();
  String localAdministrator = parts[2].toLowerCase();

  // Try to figure out type/subtype first
  Byte typeByte = null;
  byte subTypeByte;
  // Special values
  if (subType.equals("target")) {
    subTypeByte = 0x02;
  } else if (subType.equals("origin")) {
    subTypeByte = 0x03;
  } else {
    // They type/subtype is a literal integer
    Integer intVal = Ints.tryParse(subType);
    if (intVal != null && intVal <= 0xFFFF && intVal >= 0) {
      subTypeByte = (byte) (intVal & 0xFF);
      typeByte = (byte) ((intVal & 0xFF00) >> 8);
    } else {
      throw new IllegalArgumentException(
          String.format("Invalid extended community type: %s", communityStr));
    }
  }
  // Local administrator, can only be a number
  laLong = Long.parseUnsignedLong(localAdministrator);
  // Global administrator, is complicated. Try a bunch of combinations
  String[] gaParts = globalAdministrator.split("\\.");
  if (gaParts.length == 4) { // Dotted IP address notation
    // type 0x01, 1-byte subtype, 4-byte ip address, 2-byte number la
    typeByte = firstNonNull(typeByte, (byte) 0x01);
    // Ip.parse() ensures IP is valid
    gaLong = Ip.parse(globalAdministrator).asLong();
    checkArgument(laLong <= 0xFFFFL, "Invalid local administrator value %s", localAdministrator);
  } else if (gaParts.length == 2) { // Dotted AS notation
    // type 0x02, 1-byte subtype, 2-byte.2-byte dotted as, 2-byte number la
    typeByte = firstNonNull(typeByte, (byte) 0x02);
    int hi = Integer.parseUnsignedInt(gaParts[0]);
    int lo = Integer.parseUnsignedInt(gaParts[1]);
    checkArgument(
        hi <= 0xFFFF && lo <= 0xFFFF,
        "Invalid global administrator value %s",
        globalAdministrator);
    gaLong = ((long) hi) << 16 | lo;
    checkArgument(laLong <= 0xFFFFL, "Invalid local administrator value %s", localAdministrator);
  } else { // Regular numbers, almost
    if (globalAdministrator.endsWith("l")) { // e.g., 123L, a shorthand for forcing 4-byte GA.
      // type 0x02, 1-byte subtype, 4-byte number ga, 2-byte number la
      typeByte = firstNonNull(typeByte, (byte) 0x02);
      // Strip the "L" and convert to long
      gaLong =
          Long.parseUnsignedLong(
              globalAdministrator.substring(0, globalAdministrator.length() - 1));
      checkArgument(
          gaLong <= 0xFFFFFFFFL, "Invalid global administrator value %s", globalAdministrator);
      checkArgument(
          laLong <= 0xFFFFL, "Invalid local administrator value %s", localAdministrator);
    } else { // No type hint, try both variants with 2-byte GA preferred
      // Try for 2-byte ga, unless the number is too big, in which case it is a 4-byte ga.
      gaLong = Long.parseUnsignedLong(globalAdministrator);
      if (gaLong <= 0xFFFFL) {
        checkArgument(
            laLong <= 0xFFFFFFFFL, "Invalid local administrator value %s", localAdministrator);
        // type 0x00, 1-byte subtype, 2-byte number ga, 4-byte number la
        typeByte = firstNonNull(typeByte, (byte) 0x00);
      } else {
        // type 0x02, 1-byte subtype, 4-byte number ga, 2-byte number la
        checkArgument(
            gaLong <= 0xFFFFFFFFL, "Invalid global administrator value %s", globalAdministrator);
        checkArgument(
            laLong <= 0xFFFFL, "Invalid local administrator value %s", localAdministrator);
        typeByte = firstNonNull(typeByte, (byte) 0x02);
      }
    }
  }
  return of((int) typeByte << 8 | (int) subTypeByte, gaLong, laLong);
}