Java Code Examples for joptsimple.internal.Strings

The following examples show how to use joptsimple.internal.Strings. These examples are extracted from open source projects. 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 Project: plugins   Source File: ClueScrollPlugin.java    License: 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 2
Source Project: OpenPeripheral   Source File: DocUtils.java    License: 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 3
Source Project: ForgeHax   Source File: MethodTransformer.java    License: 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 4
Source Project: ForgeHax   Source File: FastMethod.java    License: 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 5
Source Project: ForgeHax   Source File: FastField.java    License: 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 Project: ForgeHax   Source File: AutoReply.java    License: MIT License 6 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 7
Source Project: ForgeHax   Source File: ChatIdentifierService.java    License: 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 8
Source Project: incubator-pinot   Source File: BaseNotificationContent.java    License: 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 9
Source Project: incubator-gobblin   Source File: HttpDataNode.java    License: 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 10
Source Project: ForgeHax   Source File: BaseMod.java    License: 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 11
Source Project: runelite   Source File: ClueScrollPlugin.java    License: 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 12
Source Project: runelite   Source File: ClockManager.java    License: 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 13
Source Project: runelite   Source File: ClockManager.java    License: 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 Project: Visage   Source File: VisageHandler.java    License: 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 15
Source Project: plugins   Source File: SlayerPlugin.java    License: 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 16
Source Project: incubator-gobblin   Source File: HiveDataNode.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param metastoreUri hive metastore URI
 * @return true if the scheme is "thrift" and authority is not empty.
 */
public boolean isMetastoreUriValid(URI metastoreUri) {
  String scheme = metastoreUri.getScheme();
  if (!scheme.equals("thrift")) {
    return false;
  }
  //Ensure that the authority is not empty
  if (com.google.common.base.Strings.isNullOrEmpty(metastoreUri.getAuthority())) {
    return false;
  }
  return true;
}
 
Example 17
Source Project: plugins   Source File: ShaderTest.java    License: GNU General Public License v3.0 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 18
Source Project: plugins   Source File: NotesManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
void loadNotes()
{
	final String configJson = configManager.getConfiguration(NotesConfig.CONFIG_GROUP, NotesConfig.NOTES);

	notes = null;
	if (!Strings.isNullOrEmpty(configJson))
	{
		final Gson gson = new Gson();
		notes = gson.fromJson(configJson, new TypeToken<ArrayList<String>>() {}.getType());
	}

	if (notes == null)
	{
		notes = new ArrayList<>();
		notes.add("");
	}

	// migrate from legacy single tab notes
	if (!config.notesData().isEmpty())
	{
		log.info("Adding tab for legacy note data");
		notes.add(0, config.notesData());

		if (notes.size() == 2 && notes.get(1).equals(""))
		{
			// remove the default empty note page
			notes.remove(1);
		}
	}
}
 
Example 19
@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 20
Source Project: plugins   Source File: ClockManager.java    License: GNU General Public License v3.0 5 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 21
Source Project: plugins   Source File: ClockManager.java    License: GNU General Public License v3.0 5 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 22
Source Project: plugins   Source File: EmojiPlugin.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Nullable
String updateMessage(final String message)
{
	final String[] messageWords = WHITESPACE_REGEXP.split(message);

	boolean editedMessage = false;
	for (int i = 0; i < messageWords.length; i++)
	{
		// Remove tags except for <lt> and <gt>
		final String trigger = Text.removeFormattingTags(messageWords[i]);
		final Emoji emoji = Emoji.getEmoji(trigger);

		if (emoji == null)
		{
			continue;
		}

		final int emojiId = modIconsStart + emoji.ordinal();

		messageWords[i] = messageWords[i].replace(trigger, "<img=" + emojiId + ">");
		editedMessage = true;
	}

	// If we haven't edited the message any, don't update it.
	if (!editedMessage)
	{
		return null;
	}

	return Strings.join(messageWords, " ");
}
 
Example 23
@SubscribeEvent
public static void itemToolTipEvent(ItemTooltipEvent event) {
    if (twosList == null || twosList.length < 1 || event.getToolTip().isEmpty())
        return;
    boolean isPotion = event.getItemStack().getItem() instanceof ItemPotion || event.getItemStack().getItem() instanceof ItemArrow;

    for (int i = 0; i < event.getToolTip().size(); i++) {
        String toolTip = event.getToolTip().get(i);
        String lowerTip = toolTip.toLowerCase();
        boolean relocateReset = false;
        if (lowerTip.endsWith("§r")) {
            lowerTip = lowerTip.substring(0, lowerTip.length() - 2);
            toolTip = toolTip.substring(0, toolTip.length() - 2);
            relocateReset = true;
        }
        for (String to : twosList) {
            String boogaloo = null;
            if (isPotion && TIMER_PATTERN.matcher(lowerTip).find()) {
                String potionName = lowerTip.substring(0, lowerTip.indexOf('(') - 1);
                if (potionName.endsWith(to)) {
                    int index = toolTip.indexOf('(') - 1;
                    String beforeTimer = toolTip.substring(0, index);
                    String timer = toolTip.substring(index);
                    boogaloo = I18n.format("tooltip.community_mod.electric", beforeTimer) + timer;
                }
            }
            if (lowerTip.endsWith(to)) {
                boogaloo = I18n.format("tooltip.community_mod.electric", toolTip);
                if (relocateReset)
                    boogaloo += "§r";
            }
            if (!Strings.isNullOrEmpty(boogaloo))
                event.getToolTip().set(i, boogaloo);
        }
    }
}
 
Example 24
Source Project: LiquidBounce   Source File: Plugins.java    License: GNU General Public License v3.0 5 votes vote down vote up
@EventTarget
public void onPacket(PacketEvent event) {
    if(event.getPacket() instanceof S3APacketTabComplete) {
        final S3APacketTabComplete s3APacketTabComplete = (S3APacketTabComplete) event.getPacket();

        final List<String> plugins = new ArrayList<>();
        final String[] commands = s3APacketTabComplete.func_149630_c();

        for(final String command1 : commands) {
            final String[] command = command1.split(":");

            if(command.length > 1) {
                final String pluginName = command[0].replace("/", "");

                if(!plugins.contains(pluginName))
                    plugins.add(pluginName);
            }
        }

        Collections.sort(plugins);

        if(!plugins.isEmpty())
            ClientUtils.displayChatMessage("§aPlugins §7(§8" + plugins.size() + "§7): §c" + Strings.join(plugins.toArray(new String[0]), "§7, §c"));
        else
            ClientUtils.displayChatMessage("§cNo plugins found.");
        setState(false);
        tickTimer.reset();
    }
}
 
Example 25
Source Project: incubator-gobblin   Source File: SqlDataNode.java    License: Apache License 2.0 5 votes vote down vote up
public SqlDataNode(Config nodeProps) throws DataNodeCreationException {
  super(nodeProps);
  try {
    this.hostName = ConfigUtils.getString(nodeProps, SQL_HOSTNAME, "");
    this.port = ConfigUtils.getInt(nodeProps, SQL_PORT, 0);
    this.jdbcDriver = ConfigUtils.getString(nodeProps, SQL_DRIVER, "");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(hostName), SQL_HOSTNAME + " cannot be null or empty.");
    Preconditions.checkArgument(port != 0, SQL_PORT + " cannot be empty.");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(jdbcDriver), SQL_DRIVER + " cannot be null or empty.");
  } catch (Exception e) {
    throw new DataNodeCreationException(e);
  }
}
 
Example 26
Source Project: ic   Source File: EventDeserializer.java    License: MIT License 5 votes vote down vote up
/**
 * 如果事件不包含类型信息,则返回空字符串
 */
private String parseType(String type, String event) {
    String result = Strings.EMPTY;
    if (type != null) {
        result = type;
    } else if (event != null) {
        result = event;
    }
    return result;
}
 
Example 27
Source Project: newblog   Source File: JmxPortCheck.java    License: Apache License 2.0 5 votes vote down vote up
public static String check() {
    String ipAndPorts = Config.getProperty("jmx_ip_port");
    if (!Strings.isNullOrEmpty(ipAndPorts)) {
        String[] strings = ipAndPorts.split(",");
        for (String string : strings) {
            String[] str = string.split(":");
            if (getURL(str[0], Integer.parseInt(str[1]))) {
                return string;
            }
        }
    }
    return null;
}
 
Example 28
Source Project: ForgeHax   Source File: ASMClassBuilder.java    License: MIT License 5 votes vote down vote up
public ASMClassBuilder setSrgClassName(String srgInternalClassName) {
  srgName =
    !Strings.isNullOrEmpty(srgInternalClassName)
      ? Type.getObjectType(srgInternalClassName)
      : null;
  return this;
}
 
Example 29
Source Project: incubator-pinot   Source File: BaseNotificationContent.java    License: Apache License 2.0 5 votes vote down vote up
public AnomalyReportEntity(String anomalyId, String anomalyURL, String baselineVal, String currentVal, String lift,
    boolean positiveLift, Double swi, List<String> dimensions, String duration, String feedback, String function,
    String funcDescription, String metric, String startTime, String endTime, String timezone, String issueType,
    String anomalyType, String properties) {
  this.anomalyId = anomalyId;
  this.anomalyURL = anomalyURL;
  this.baselineVal = baselineVal;
  this.currentVal = currentVal;
  this.dimensions = dimensions;
  this.duration = duration;
  this.feedback = feedback;
  this.function = function;
  this.funcDescription = funcDescription;
  this.swi = "";
  if (swi != null) {
    this.swi = String.format(PERCENTAGE_FORMAT, swi * 100);
  }
  if (baselineVal.equals("-")) {
    this.lift = Strings.EMPTY;
  } else {
    this.lift = lift;
  }
  this.positiveLift = positiveLift;
  this.metric = metric;
  this.startDateTime = startTime;
  this.endTime = endTime;
  this.timezone = timezone;
  this.issueType = issueType;
  this.anomalyType = anomalyType;
  this.properties = properties;
}
 
Example 30
Source Project: ForgeHax   Source File: FirstTimeRunningService.java    License: 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;
}