use of org.apache.commons.lang3.StringUtils.join in project Universal-G-Code-Sender by winder.
the class GcodeParser method processCommand.
/**
* Process commend given an initial state. This method will not modify its
* input parameters.
*
* @param includeNonMotionStates Create gcode meta responses even if there is no motion, for example "F100" will not
* return a GcodeMeta entry unless this flag is set to true.
*/
public static List<GcodeMeta> processCommand(String command, int line, final GcodeState inputState, boolean includeNonMotionStates) throws GcodeParserException {
List<String> args = GcodePreprocessorUtils.splitCommand(command);
if (args.isEmpty())
return null;
// Initialize with original state
GcodeState state = inputState.copy();
state.commandNumber = line;
// handle M codes.
// codes = GcodePreprocessorUtils.parseCodes(args, 'M');
// handleMCode(for each codes);
List<String> fCodes = GcodePreprocessorUtils.parseCodes(args, 'F');
if (!fCodes.isEmpty()) {
try {
state.speed = Double.parseDouble(Iterables.getOnlyElement(fCodes));
} catch (IllegalArgumentException e) {
throw new GcodeParserException("Multiple F-codes on one line.");
}
}
List<String> sCodes = GcodePreprocessorUtils.parseCodes(args, 'S');
if (!sCodes.isEmpty()) {
try {
state.spindleSpeed = Double.parseDouble(Iterables.getOnlyElement(sCodes));
} catch (IllegalArgumentException e) {
throw new GcodeParserException("Multiple S-codes on one line.");
}
}
// Gather G codes.
Set<Code> gCodes = GcodePreprocessorUtils.getGCodes(args);
boolean hasAxisWords = GcodePreprocessorUtils.hasAxisWords(args);
// Error to mix group 1 (Motion) and certain group 0 (NonModal) codes (G10, G28, G30, G92)
Collection<Code> motionCodes = gCodes.stream().filter(c -> c.consumesMotion()).collect(Collectors.toList());
// 1 motion code per line.
if (motionCodes.size() > 1) {
throw new GcodeParserException(Localization.getString("parser.gcode.multiple-axis-commands") + ": " + StringUtils.join(motionCodes, ", "));
}
// If there are axis words and nothing to use them, add the currentMotionMode.
if (hasAxisWords && motionCodes.isEmpty() && state.currentMotionMode != null) {
gCodes.add(state.currentMotionMode);
}
// Apply each code to the state.
List<GcodeMeta> results = new ArrayList<>();
for (Code i : gCodes) {
if (i == UNKNOWN) {
logger.warning("An unknown gcode command was detected in: " + command);
} else {
GcodeMeta meta = handleGCode(i, args, line, state, hasAxisWords);
meta.command = command;
// Commands like 'G21' don't return a point segment.
if (meta.point != null) {
meta.point.setSpeed(state.speed);
}
results.add(meta);
}
}
// Return updated state / command.
if (results.isEmpty() && includeNonMotionStates) {
GcodeMeta meta = new GcodeMeta();
meta.state = state;
meta.command = command;
meta.code = state.currentMotionMode;
return Collections.singletonList(meta);
}
return results;
}
use of org.apache.commons.lang3.StringUtils.join in project SkyBot by duncte123.
the class HelpCommand method executeCommand.
@SuppressWarnings("NullableProblems")
@Override
public void executeCommand(String invoke, String[] args, GuildMessageReceivedEvent event) {
if (args.length > 0) {
String toSearch = StringUtils.join(args, " ").toLowerCase().replaceFirst("(" + Pattern.quote(Settings.PREFIX) + "|" + Pattern.quote(Settings.OTHER_PREFIX) + "|" + Pattern.quote(getSettings(event.getGuild()).getCustomPrefix()) + ")", "");
for (Command cmd : AirUtils.COMMAND_MANAGER.getCommands()) {
if (cmd.getName().equals(toSearch)) {
MessageUtils.sendMsg(event, "Command help for `" + cmd.getName() + "` :\n" + cmd.help(cmd.getName()) + (cmd.getAliases().length > 0 ? "\nAliases: " + StringUtils.join(cmd.getAliases(), ", ") : ""));
return;
} else {
for (String alias : cmd.getAliases()) {
if (alias.equals(toSearch)) {
MessageUtils.sendMsg(event, "Command help for `" + cmd.getName() + "` :\n" + cmd.help(alias) + (cmd.getAliases().length > 0 ? "\nAliases: " + StringUtils.join(cmd.getAliases(), ", ") : ""));
return;
}
}
}
}
MessageUtils.sendMsg(event, "That command could not be found, try " + PREFIX + "help for a list of commands");
return;
}
event.getAuthor().openPrivateChannel().queue(pc -> pc.sendMessage(HelpEmbeds.getCommandListWithPrefix(GuildSettingsUtils.getGuild(event.getGuild()).getCustomPrefix())).queue(msg -> MessageUtils.sendMsg(event, event.getMember().getAsMention() + " check your DM's"), // When sending fails, send to the channel
err -> MessageUtils.sendMsg(event, (new MessageBuilder()).append("Message could not be delivered to dm's and has been send in this channel.").setEmbed(HelpEmbeds.getCommandListWithPrefix(GuildSettingsUtils.getGuild(event.getGuild()).getCustomPrefix())).build())), err -> MessageUtils.sendMsg(event, "ERROR: " + err.getMessage()));
}
use of org.apache.commons.lang3.StringUtils.join in project nakadi by zalando.
the class SubscriptionDbRepository method listSubscriptions.
public List<Subscription> listSubscriptions(final Set<String> eventTypes, final Optional<String> owningApplication, final int offset, final int limit) throws ServiceUnavailableException {
final StringBuilder queryBuilder = new StringBuilder("SELECT s_subscription_object FROM zn_data.subscription ");
final List<String> clauses = Lists.newArrayList();
final List<Object> params = Lists.newArrayList();
owningApplication.ifPresent(owningApp -> {
clauses.add(" s_subscription_object->>'owning_application' = ? ");
params.add(owningApp);
});
if (!eventTypes.isEmpty()) {
final String clause = eventTypes.stream().map(et -> " s_subscription_object->'event_types' @> ?::jsonb").collect(Collectors.joining(" AND "));
clauses.add(clause);
eventTypes.stream().map(et -> format("\"{0}\"", et)).forEach(params::add);
}
if (!clauses.isEmpty()) {
queryBuilder.append(" WHERE ");
queryBuilder.append(StringUtils.join(clauses, " AND "));
}
queryBuilder.append(" ORDER BY s_subscription_object->>'created_at' DESC LIMIT ? OFFSET ? ");
params.add(limit);
params.add(offset);
try {
return jdbcTemplate.query(queryBuilder.toString(), params.toArray(), rowMapper);
} catch (final DataAccessException e) {
LOG.error("Database error when listing subscriptions", e);
throw new ServiceUnavailableException("Error occurred when running database request");
}
}
use of org.apache.commons.lang3.StringUtils.join in project guardian by ichorpowered.
the class InvalidCheck method getSequence.
@Nonnull
@Override
public SequenceBlueprint<Event> getSequence(final Detection detection) {
final Double analysisTime = detection.getContentContainer().get(ContentKeys.ANALYSIS_TIME).orElse(GuardianValue.empty()).getDirect().orElse(0d) / 0.05;
final Double minimumTickRate = detection.getContentContainer().get(ContentKeys.ANALYSIS_MINIMUM_TICK).orElse(GuardianValue.empty()).getDirect().orElse(0d) / 0.05;
final Double maximumTickRate = detection.getContentContainer().get(ContentKeys.ANALYSIS_MAXIMUM_TICK).orElse(GuardianValue.empty()).getDirect().orElse(0d) / 0.05;
return new GuardianSequenceBuilder().capture(new InvalidControlCapture(detection.getPlugin(), detection)).observe(MoveEntityEvent.class).observe(MoveEntityEvent.class).delay(analysisTime.intValue()).expire(maximumTickRate.intValue()).condition(sequenceContext -> {
final GuardianPlayerEntry<Player> entityEntry = sequenceContext.get(CommonContextKeys.ENTITY_ENTRY);
final Summary summary = sequenceContext.get(CommonContextKeys.SUMMARY);
final GuardianCaptureRegistry captureRegistry = sequenceContext.get(CommonContextKeys.CAPTURE_REGISTRY);
final long lastActionTime = sequenceContext.get(CommonContextKeys.LAST_ACTION_TIME);
summary.set(SequenceReport.class, new SequenceReport(false, Origin.source(sequenceContext.getRoot()).owner(entityEntry).build()));
if (!entityEntry.getEntity(Player.class).isPresent())
return false;
final Player player = entityEntry.getEntity(Player.class).get();
/*
* Capture Collection
*/
final CaptureContainer captureContainer = captureRegistry.getContainer();
Optional<Location> initial = captureContainer.get(GuardianSequence.INITIAL_LOCATION);
Optional<Set<String>> invalidControls = captureContainer.get(InvalidControlCapture.INVALID_CONTROLS);
if (!initial.isPresent() || !invalidControls.isPresent())
return false;
long current = System.currentTimeMillis();
// Finds the average between now and the last action.
double averageClockRate = ((current - lastActionTime) / 1000) / 0.05;
if (averageClockRate < minimumTickRate) {
detection.getLogger().warn("The server may be overloaded. A check could not be completed.");
return false;
} else if (averageClockRate > maximumTickRate) {
return false;
}
if (invalidControls.get().isEmpty() || player.get(Keys.VEHICLE).isPresent())
return false;
// ------------------------- DEBUG -----------------------------
System.out.println(player.getName() + " has been caught using invalid movement hacks.");
// -------------------------------------------------------------
SequenceReport report = new SequenceReport(true, Origin.source(sequenceContext.getRoot()).owner(entityEntry).build());
report.put("type", "InvalidControlCapture Movement");
report.put("information", Collections.singletonList("Received invalid controls of " + StringUtils.join((Set<String>) invalidControls.get(), ", ") + "."));
report.put("initial_location", initial.get());
report.put("final_location", player.getLocation());
report.put("severity", 1d);
summary.set(SequenceReport.class, report);
return true;
}, ConditionType.NORMAL).build(SequenceContext.builder().owner(detection).root(this).build());
}
use of org.apache.commons.lang3.StringUtils.join in project dcos-commons by mesosphere.
the class CmdExecutor method runCmd.
private static JSONObject runCmd(List<String> cmd) throws Exception {
ProcessBuilder builder = new ProcessBuilder(cmd);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Process process = builder.start();
int exitCode = process.waitFor();
stopWatch.stop();
String stdout = streamToString(process.getInputStream());
String stderr = streamToString(process.getErrorStream());
log.warn(String.format("stdout:%n%s", stdout));
log.warn(String.format("stderr:%n%s", stderr));
String message = createOutputMessage(stdout, stderr);
if (exitCode == 0) {
log.info(String.format("Command succeeded in %dms: %s", stopWatch.getTime(), StringUtils.join(cmd, " ")));
} else {
log.warn(String.format("Command failed with code=%d in %dms: %s", exitCode, stopWatch.getTime(), StringUtils.join(cmd, " ")));
log.warn(String.format("stdout:%n%s", stdout));
log.warn(String.format("stderr:%n%s", stderr));
}
JSONObject obj = new JSONObject();
obj.put("message", message);
return obj;
}
Aggregations