joptsimple.internal.Strings Java Examples

The following examples show how to use joptsimple.internal.Strings. 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: AutoReply.java    From ForgeHax with MIT License 7 votes vote down vote up
@SubscribeEvent
public void onClientChat(ClientChatReceivedEvent event) {
  String message = (event.getMessage().getUnformattedText());
  if (message.matches(search.get()) && !message.startsWith(MC.getSession().getUsername())) {
    String append;
    switch (mode.get().toUpperCase()) {
      case "REPLY":
        append = "/r ";
        break;
      case "CHAT":
      default:
        append = Strings.EMPTY;
        break;
    }
    getLocalPlayer().sendChatMessage(append + reply.get());
  }
}
 
Example #2
Source File: BaseMod.java    From ForgeHax with MIT License 6 votes vote down vote up
private void writeChildren(
    StringBuilder builder, Command command, final boolean deep, final String append) {
  command
      .getChildren()
      .forEach(
          child -> {
            boolean invalid = Strings.isNullOrEmpty(append);
            if (!invalid) {
              builder.append(append);
              builder.append(' ');
            }
            builder.append(child.getPrintText());
            builder.append('\n');
            if (deep) {
              String app = invalid ? Strings.EMPTY : append;
              writeChildren(builder, child, deep, app + ">");
            }
          });
}
 
Example #3
Source File: ClueScrollPlugin.java    From plugins with GNU General Public License v3.0 6 votes vote down vote up
@Subscribe
public void onCommandExecuted(CommandExecuted commandExecuted)
{
	if (commandExecuted.getCommand().equals("clue"))
	{
		String text = Strings.join(commandExecuted.getArguments(), " ");

		if (text.isEmpty())
		{
			resetClue(true);
		}
		else
		{
			ClueScroll clueScroll = findClueScroll(text);
			log.debug("Found clue scroll for '{}': {}", text, clueScroll);
			updateClue(clueScroll);
		}
	}
}
 
Example #4
Source File: ChatIdentifierService.java    From ForgeHax with MIT License 6 votes vote down vote up
private static boolean extract(
    String message, Pattern[] patterns, BiConsumer<GameProfile, String> callback) {
  for (Pattern pattern : patterns) {
    Matcher matcher = pattern.matcher(message);
    if (matcher.find()) {
      final String messageSender = matcher.group(1);
      final String messageOnly = matcher.group(2);
      if (!Strings.isNullOrEmpty(messageSender)) {
        for (NetworkPlayerInfo data : getLocalPlayer().connection.getPlayerInfoMap()) {
          if (
              String.CASE_INSENSITIVE_ORDER
                  .compare(messageSender, data.getGameProfile().getName())
                  == 0) {
            callback.accept(data.getGameProfile(), messageOnly);
            return true;
          }
        }
      }
    }
  }
  return false;
}
 
Example #5
Source File: FastField.java    From ForgeHax with MIT License 6 votes vote down vote up
@Override
protected Field lookup() throws Exception {
  for (State state : State.values()) {
    String n = name.getByState(state);
    if (!Strings.isNullOrEmpty(n)) {
      try {
        Field f = insideClass.getDeclaredField(n);
        f.setAccessible(true);
        if (stripFinal) {
          Field modifiersField = Field.class.getDeclaredField("modifiers");
          modifiersField.setAccessible(true);
          modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
        }
        return f;
      } catch (Exception e) {
      }
    }
  }
  return null;
}
 
Example #6
Source File: DocUtils.java    From OpenPeripheral with MIT License 6 votes vote down vote up
public static String createPeripheralHelpText(Class<? extends Object> cls, String type, IMethodMap methods) {
	StringBuilder builder = new StringBuilder();
	builder.append("----OpenPeripheral doc----\n");
	builder.append("Peripheral type: ");
	builder.append(type);
	builder.append("\n\n");

	final String docText = DOC_TEXT_CACHE.getOrCreate(cls);
	if (!Strings.isNullOrEmpty(docText)) {
		builder.append(docText);
		builder.append("\n\n");
	}

	builder.append("---Methods---\n");

	listMethods(builder, methods);

	return builder.toString();
}
 
Example #7
Source File: FastMethod.java    From ForgeHax with MIT License 6 votes vote down vote up
@Override
protected Method lookup() throws Exception {
  Objects.requireNonNull(parameters);
  for (State state : State.values()) {
    String n = name.getByState(state);
    if (!Strings.isNullOrEmpty(n)) {
      try {
        Method m = insideClass.getDeclaredMethod(n, parameters);
        m.setAccessible(true);
        return m;
      } catch (Exception e) {
      }
    }
  }
  return null;
}
 
Example #8
Source File: HttpDataNode.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
public HttpDataNode(Config nodeProps) throws DataNode.DataNodeCreationException {
  super(nodeProps);
  try {
    this.httpDomain = ConfigUtils.getString(nodeProps, FlowGraphConfigurationKeys.DATA_NODE_HTTP_DOMAIN_KEY, "");
    // Authentication details and credentials should reside in the Gobblin job payload
    this.authenticationType = ConfigUtils.getString(
        nodeProps, FlowGraphConfigurationKeys.DATA_NODE_HTTP_AUTHENTICATION_TYPE_KEY, "");

    Preconditions.checkArgument(!Strings.isNullOrEmpty(httpDomain),
        FlowGraphConfigurationKeys.DATA_NODE_HTTP_DOMAIN_KEY + " cannot be null or empty.");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(authenticationType),
        FlowGraphConfigurationKeys.DATA_NODE_HTTP_AUTHENTICATION_TYPE_KEY + " cannot be null or empty.");
  } catch (Exception e) {
    throw new DataNode.DataNodeCreationException(e);
  }
}
 
Example #9
Source File: VisageHandler.java    From Visage with MIT License 6 votes vote down vote up
private void write(HttpServletResponse response, List<String> missed, byte[] png, String renderer) throws IOException {
	if (rendererHeader) {
		response.setHeader("X-Visage-Renderer", renderer);
	}
	response.setContentType("image/png");
	response.setContentLength(png.length);
	if (cacheHeader) {
		if (missed.isEmpty()) {
			response.setHeader("X-Visage-Cache-Miss", "none");
		} else {
			response.setHeader("X-Visage-Cache-Miss", Strings.join(missed, ", "));
		}
	}
	response.getOutputStream().write(png);
	response.getOutputStream().flush();
	response.setStatus(200);
	response.flushBuffer();
}
 
Example #10
Source File: ClueScrollPlugin.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Subscribe
public void onCommandExecuted(CommandExecuted commandExecuted)
{
	if (developerMode && commandExecuted.getCommand().equals("clue"))
	{
		String text = Strings.join(commandExecuted.getArguments(), " ");

		if (text.isEmpty())
		{
			resetClue(true);
		}
		else
		{
			ClueScroll clueScroll = findClueScroll(text);
			log.debug("Found clue scroll for '{}': {}", text, clueScroll);
			updateClue(clueScroll);
		}
	}
}
 
Example #11
Source File: BaseNotificationContent.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * The lift value for an SLA anomaly is delay from the configured sla. (Ex: 2 days & 3 hours)
 */
protected static String getFormattedSLALiftValue(MergedAnomalyResultDTO anomaly) {
  if (!anomaly.getType().equals(AnomalyType.DATA_SLA)
      || anomaly.getProperties() == null || anomaly.getProperties().isEmpty()
      || !anomaly.getProperties().containsKey("sla")
      || !anomaly.getProperties().containsKey("datasetLastRefreshTime")) {
    return Strings.EMPTY;
  }

  long delayInMillis = anomaly.getEndTime() - Long.parseLong(anomaly.getProperties().get("datasetLastRefreshTime"));
  long days = TimeUnit.MILLISECONDS.toDays(delayInMillis);
  long hours = TimeUnit.MILLISECONDS.toHours(delayInMillis) % TimeUnit.DAYS.toHours(1);
  long minutes = TimeUnit.MILLISECONDS.toMinutes(delayInMillis) % TimeUnit.HOURS.toMinutes(1);

  String liftValue;
  if (days > 0) {
    liftValue = String.format("%d days & %d hours", days, hours);
  } else if (hours > 0) {
    liftValue = String.format("%d hours & %d mins", hours, minutes);
  } else {
    liftValue = String.format("%d mins", minutes);
  }

  return liftValue;
}
 
Example #12
Source File: MethodTransformer.java    From ForgeHax with MIT License 6 votes vote down vote up
@Override
public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("MethodTransformer [");
  builder.append(getMethod() != null ? getMethod().toString() : "null");
  builder.append("] ");
  if (tasks.isEmpty()) {
    builder.append("No transform tasks");
  } else {
    builder.append("Found ");
    builder.append(tasks.size());
    builder.append(" transform tasks: ");
    Iterator<TaskElement> it = tasks.iterator();
    while (it.hasNext()) {
      TaskElement next = it.next();
      String desc = next.getMethod().getDeclaredAnnotation(Inject.class).description();
      if (!Strings.isNullOrEmpty(desc)) {
        builder.append(desc);
      }
      if (it.hasNext()) {
        builder.append(", ");
      }
    }
  }
  return builder.toString();
}
 
Example #13
Source File: ClockManager.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void loadStopwatches()
{
	final String stopwatchesJson = configManager.getConfiguration(TimeTrackingConfig.CONFIG_GROUP, TimeTrackingConfig.STOPWATCHES);

	if (!Strings.isNullOrEmpty(stopwatchesJson))
	{
		final Gson gson = new Gson();
		final List<Stopwatch> stopwatches = gson.fromJson(stopwatchesJson, new TypeToken<ArrayList<Stopwatch>>()
		{
		}.getType());

		this.stopwatches.clear();
		this.stopwatches.addAll(stopwatches);
		SwingUtilities.invokeLater(clockTabPanel::rebuild);
	}
}
 
Example #14
Source File: ClockManager.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void loadTimers()
{
	final String timersJson = configManager.getConfiguration(TimeTrackingConfig.CONFIG_GROUP, TimeTrackingConfig.TIMERS);

	if (!Strings.isNullOrEmpty(timersJson))
	{
		final Gson gson = new Gson();
		final List<Timer> timers = gson.fromJson(timersJson, new TypeToken<ArrayList<Timer>>()
		{
		}.getType());

		this.timers.clear();
		this.timers.addAll(timers);
		SwingUtilities.invokeLater(clockTabPanel::rebuild);
	}
}
 
Example #15
Source File: KafkaRpcPluginThread.java    From opentsdb-rpc-kafka with Apache License 2.0 5 votes vote down vote up
String getPrefix(final String metric) {
  if (Strings.isNullOrEmpty(metric)) {
    return DEFAULT_COUNTER_ID;
  }
  
  int idx = metric.indexOf(".");
  if (idx < 1) {
    return DEFAULT_COUNTER_ID;
  }
  return metric.substring(0, idx);
}
 
Example #16
Source File: SlayerPlugin.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
private void addCounter()
{
	if (!config.showInfobox() || counter != null || currentTask == null || Strings.isNullOrEmpty(currentTask.getTaskName()))
	{
		return;
	}

	Task task = Task.getTask(currentTask.getTaskName());
	AsyncBufferedImage taskImg = getImageForTask(task);
	String taskTooltip = ColorUtil.wrapWithColorTag("%s", new Color(255, 119, 0)) + "</br>";

	if (currentTask.getTaskLocation() != null && !currentTask.getTaskLocation().isEmpty())
	{
		taskTooltip += currentTask.getTaskLocation() + "</br>";
	}

	taskTooltip += ColorUtil.wrapWithColorTag("Pts:", Color.YELLOW)
		+ " %s</br>"
		+ ColorUtil.wrapWithColorTag("Streak:", Color.YELLOW)
		+ " %s";

	if (currentTask.getInitialAmount() > 0)
	{
		taskTooltip += "</br>"
			+ ColorUtil.wrapWithColorTag("Start:", Color.YELLOW)
			+ " " + currentTask.getInitialAmount();
	}

	counter = new TaskCounter(taskImg, this, currentTask.getAmount());
	counter.setTooltip(String.format(taskTooltip, capsString(currentTask.getTaskName()), points, streak));

	infoBoxManager.addInfoBox(counter);
}
 
Example #17
Source File: Command.java    From ForgeHax with MIT License 5 votes vote down vote up
protected boolean processChildren(@Nonnull String[] args)
    throws CommandExecuteException, NullPointerException {
  if (args.length > 0) {
    final String lookup = (args[0] != null ? args[0] : Strings.EMPTY).toLowerCase();
    Command child = getChild(lookup);
    if (child != null) { // perfect match, use this
      child.run(CommandHelper.forward(args));
      return true;
    } else { // no match found, try and infer
      List<Command> results =
          children
              .stream()
              .filter(cmd -> cmd.getName().toLowerCase().startsWith(lookup))
              .collect(Collectors.toList());
      
      if (results.size() == 1) { // if found 1 result, use that
        results.get(0).run(CommandHelper.forward(args));
        return true;
      } else if (results.size() > 1) {
        throw new CommandExecuteException(
            String.format(
                "Ambiguous command \"%s\": %s",
                lookup,
                results.stream().map(Command::getName).collect(Collectors.joining(", "))));
      }
    }
  }
  return false;
}
 
Example #18
Source File: DiskRegion.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private boolean hasSameCompressor(final RegionAttributes<?,?> ra) {
  Compressor raCompressor = ra.getCompressor();
  if (raCompressor == null) {
    return Strings.isNullOrEmpty(getCompressorClassName()) ? true : false;
  }
  return raCompressor.getClass().getName().equals(getCompressorClassName());
}
 
Example #19
Source File: ConsoleIO.java    From ForgeHax with MIT License 5 votes vote down vote up
public static void write(String msg, Style style) {
  String tab = Strings.repeat('>', Math.max(getOrCreate().get(), MIN_INDENT)) + " ";
  if (style == null) {
    Helper.printMessageNaked(tab, msg); // TODO: use a non-chat console
  } else {
    Helper.printMessageNaked(tab, msg, style); // TODO: use a non-chat console
  }
}
 
Example #20
Source File: BlockEntry.java    From ForgeHax with MIT License 5 votes vote down vote up
public BlockEntry(Block block, int meta, boolean check) throws BlockDoesNotExistException {
  meta = Math.max(meta, 0);
  if (check) {
    BlockOptionHelper.requiresValidBlock(block, meta);
  }
  this.block = block;
  this.meta = BlockOptionHelper.getAllBlocks(block).size() > 1 ? meta : -1;
  this.uniqueId = getResourceName() + (isMetadata() ? ("::" + getMetadata()) : Strings.EMPTY);
}
 
Example #21
Source File: BlockEntry.java    From ForgeHax with MIT License 5 votes vote down vote up
public String getPrettyName() {
  return block != null
      ? ((block.getRegistryName() != null
      ? block.getRegistryName().getResourcePath()
      : block.toString())
      + (isMetadata() ? ":" + meta : Strings.EMPTY))
      : Strings.EMPTY;
}
 
Example #22
Source File: FirstTimeRunningService.java    From ForgeHax with MIT License 5 votes vote down vote up
private static final String getOnceFileVersion() {
  if (Files.exists(STARTUP_ONCE)) {
    try {
      return new String(Files.readAllBytes(STARTUP_ONCE));
    } catch (Throwable t) {
    }
  }
  return Strings.EMPTY;
}
 
Example #23
Source File: SpamEntry.java    From ForgeHax with MIT License 5 votes vote down vote up
public String next() {
  if (!messages.isEmpty()) {
    switch (type) {
      case RANDOM:
        return messages.get(ThreadLocalRandom.current().nextInt(messages.size()));
      case SEQUENTIAL:
        return messages.get((nextIndex++ % messages.size()));
    }
  }
  return Strings.EMPTY;
}
 
Example #24
Source File: SlayerPlugin.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void addCounter()
{
	if (!config.showInfobox() || counter != null || Strings.isNullOrEmpty(taskName))
	{
		return;
	}

	Task task = Task.getTask(taskName);
	int itemSpriteId = ItemID.ENCHANTED_GEM;
	if (task != null)
	{
		itemSpriteId = task.getItemSpriteId();
	}

	BufferedImage taskImg = itemManager.getImage(itemSpriteId);
	String taskTooltip = ColorUtil.wrapWithColorTag("%s", new Color(255, 119, 0)) + "</br>";

	if (taskLocation != null && !taskLocation.isEmpty())
	{
		taskTooltip += taskLocation + "</br>";
	}

	taskTooltip += ColorUtil.wrapWithColorTag("Pts:", Color.YELLOW)
		+ " %s</br>"
		+ ColorUtil.wrapWithColorTag("Streak:", Color.YELLOW)
		+ " %s";

	if (initialAmount > 0)
	{
		taskTooltip += "</br>"
			+ ColorUtil.wrapWithColorTag("Start:", Color.YELLOW)
			+ " " + initialAmount;
	}

	counter = new TaskCounter(taskImg, this, amount);
	counter.setTooltip(String.format(taskTooltip, capsString(taskName), config.points(), config.streak()));

	infoBoxManager.addInfoBox(counter);
}
 
Example #25
Source File: ShaderTest.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testShaders() throws Exception
{
	String verifier = System.getProperty("glslang.path");
	Assume.assumeFalse("glslang.path is not set", Strings.isNullOrEmpty(verifier));

	Template[] templates = {
		new Template()
			.addInclude(GpuPlugin.class)
			.add(key ->
		{
			if ("version_header".equals(key))
			{
				return GpuPlugin.WINDOWS_VERSION_HEADER;
			}
			return null;
		}),
	};

	Shader[] shaders = {
		GpuPlugin.PROGRAM,
		GpuPlugin.COMPUTE_PROGRAM,
		GpuPlugin.SMALL_COMPUTE_PROGRAM,
		GpuPlugin.UNORDERED_COMPUTE_PROGRAM,
		GpuPlugin.UI_PROGRAM,
	};

	for (Template t : templates)
	{
		for (Shader s : shaders)
		{
			verify(t, s);
		}
	}
}
 
Example #26
Source File: PlayerInfoHelper.java    From ForgeHax with MIT License 5 votes vote down vote up
private static PlayerInfo register(String name) throws IOException {
  if (Strings.isNullOrEmpty(name) || name.length() > MAX_NAME_LENGTH) {
    return null;
  }
  PlayerInfo info = new PlayerInfo(name);
  NAME_TO_INFO.put(info.getName().toLowerCase(), info);
  UUID_TO_INFO.put(info.getId(), info);
  return info;
}
 
Example #27
Source File: WildcardMatchLoaderTest.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test(timeout = 1000)
public void testExplosive()
{
	String name = "archer" + Strings.repeat('e', 50000) + "s ring";
	WildcardMatchLoader loader = new WildcardMatchLoader(Arrays.asList(name + "* < 100"));
	assertTrue(loader.load(new NamedQuantity(name, 50)));
	assertFalse(loader.load(new NamedQuantity(name, 150)));
}
 
Example #28
Source File: DiskRegion.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private boolean hasSameCompressor(final RegionAttributes<?,?> ra) {
  Compressor raCompressor = ra.getCompressor();
  if (raCompressor == null) {
    return Strings.isNullOrEmpty(getCompressorClassName()) ? true : false;
  }
  return raCompressor.getClass().getName().equals(getCompressorClassName());
}
 
Example #29
Source File: SpamService.java    From ForgeHax with MIT License 5 votes vote down vote up
@SubscribeEvent
public void onTick(LocalPlayerUpdateEvent event) {
  if (!SENDING.isEmpty() && System.currentTimeMillis() > nextSendMs) {
    SENDING
        .stream()
        .filter(
            msg -> {
              if (!Strings.isNullOrEmpty(msg.getType())) {
                long time = customDelays.getOrDefault(msg.getType(), new AtomicLong(0)).get();
                return System.currentTimeMillis() > time;
              } else {
                return true;
              }
            })
        .sorted()
        .findFirst()
        .ifPresent(
            msg -> {
              getLocalPlayer().sendChatMessage(msg.getMessage());
              customDelays
                  .computeIfAbsent(msg.getType(), t -> new AtomicLong(0L))
                  .set(System.currentTimeMillis() + msg.getDelay());
              nextSendMs = System.currentTimeMillis() + delay.get();
              SENDING.remove(msg);
            });
  }
}
 
Example #30
Source File: HiveDataNode.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor. A HiveDataNode must have hive.metastore.uri property specified in addition to a node Id and fs.uri.
 */
public HiveDataNode(Config nodeProps) throws DataNodeCreationException {
  super(nodeProps);
  try {
    this.metastoreUri = ConfigUtils.getString(nodeProps, METASTORE_URI_KEY, "");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(this.metastoreUri), "hive.metastore.uri cannot be null or empty.");

    //Validate the srcFsUri and destFsUri of the DataNode.
    if (!isMetastoreUriValid(new URI(this.metastoreUri))) {
      throw new IOException("Invalid hive metastore URI " + this.metastoreUri);
    }
  } catch (Exception e) {
    throw new DataNodeCreationException(e);
  }
}