Search in sources :

Example 41 with StringUtils.join

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;
}
Also used : Plane(com.willwinder.universalgcodesender.gcode.util.Plane) UnitUtils(com.willwinder.universalgcodesender.model.UnitUtils) Iterables(com.google.common.collect.Iterables) UNKNOWN(com.willwinder.universalgcodesender.gcode.util.Code.UNKNOWN) java.util(java.util) Stats(com.willwinder.universalgcodesender.gcode.processors.Stats) Code(com.willwinder.universalgcodesender.gcode.util.Code) Position(com.willwinder.universalgcodesender.model.Position) Motion(com.willwinder.universalgcodesender.gcode.util.Code.ModalGroup.Motion) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) CommandProcessor(com.willwinder.universalgcodesender.gcode.processors.CommandProcessor) PointSegment(com.willwinder.universalgcodesender.types.PointSegment) Localization(com.willwinder.universalgcodesender.i18n.Localization) GcodeParserException(com.willwinder.universalgcodesender.gcode.util.GcodeParserException) PlaneFormatter(com.willwinder.universalgcodesender.gcode.util.PlaneFormatter) Code(com.willwinder.universalgcodesender.gcode.util.Code) GcodeParserException(com.willwinder.universalgcodesender.gcode.util.GcodeParserException)

Example 42 with StringUtils.join

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()));
}
Also used : Settings(ml.duncte123.skybot.Settings) HelpEmbeds(ml.duncte123.skybot.utils.HelpEmbeds) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Command(ml.duncte123.skybot.objects.command.Command) GuildSettingsUtils(ml.duncte123.skybot.utils.GuildSettingsUtils) MessageUtils(ml.duncte123.skybot.utils.MessageUtils) Pattern(java.util.regex.Pattern) StringUtils(org.apache.commons.lang3.StringUtils) AirUtils(ml.duncte123.skybot.utils.AirUtils) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) Command(ml.duncte123.skybot.objects.command.Command)

Example 43 with StringUtils.join

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");
    }
}
Also used : DateTimeZone(org.joda.time.DateTimeZone) DataAccessException(org.springframework.dao.DataAccessException) InconsistentStateException(org.zalando.nakadi.exceptions.runtime.InconsistentStateException) NoSubscriptionException(org.zalando.nakadi.exceptions.runtime.NoSubscriptionException) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Subscription(org.zalando.nakadi.domain.Subscription) StringUtils(org.apache.commons.lang3.StringUtils) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) UUIDGenerator(org.zalando.nakadi.util.UUIDGenerator) SQLException(java.sql.SQLException) MessageFormat.format(java.text.MessageFormat.format) Lists(com.google.common.collect.Lists) Sets.newTreeSet(com.google.common.collect.Sets.newTreeSet) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) ResultSet(java.sql.ResultSet) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DateTime(org.joda.time.DateTime) Set(java.util.Set) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Profile(org.springframework.context.annotation.Profile) Collectors(java.util.stream.Collectors) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) Component(org.springframework.stereotype.Component) List(java.util.List) SubscriptionBase(org.zalando.nakadi.domain.SubscriptionBase) RowMapper(org.springframework.jdbc.core.RowMapper) NoSuchSubscriptionException(org.zalando.nakadi.exceptions.NoSuchSubscriptionException) DuplicatedSubscriptionException(org.zalando.nakadi.exceptions.runtime.DuplicatedSubscriptionException) HashGenerator(org.zalando.nakadi.util.HashGenerator) Optional(java.util.Optional) RepositoryProblemException(org.zalando.nakadi.exceptions.runtime.RepositoryProblemException) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) DataAccessException(org.springframework.dao.DataAccessException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException)

Example 44 with StringUtils.join

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());
}
Also used : GuardianSequenceBuilder(com.ichorpowered.guardian.sequence.GuardianSequenceBuilder) Summary(com.ichorpowered.guardianapi.detection.report.Summary) ContentKeys(com.ichorpowered.guardianapi.content.ContentKeys) Keys(org.spongepowered.api.data.key.Keys) StringUtils(org.apache.commons.lang3.StringUtils) GuardianValue(com.ichorpowered.guardian.util.item.mutable.GuardianValue) Origin(com.ichorpowered.guardianapi.event.origin.Origin) GuardianCaptureRegistry(com.ichorpowered.guardian.sequence.capture.GuardianCaptureRegistry) SequenceReport(com.ichorpowered.guardian.sequence.SequenceReport) Nonnull(javax.annotation.Nonnull) ConditionType(com.abilityapi.sequenceapi.action.condition.ConditionType) Location(org.spongepowered.api.world.Location) GuardianSequence(com.ichorpowered.guardian.sequence.GuardianSequence) Event(org.spongepowered.api.event.Event) InvalidControlCapture(com.ichorpowered.guardian.common.capture.player.InvalidControlCapture) Set(java.util.Set) SequenceContext(com.abilityapi.sequenceapi.SequenceContext) Sets(com.google.common.collect.Sets) Check(com.ichorpowered.guardianapi.detection.check.Check) GuardianPlayerEntry(com.ichorpowered.guardian.entry.GuardianPlayerEntry) Detection(com.ichorpowered.guardianapi.detection.Detection) CommonContextKeys(com.ichorpowered.guardian.sequence.context.CommonContextKeys) CaptureContainer(com.ichorpowered.guardianapi.detection.capture.CaptureContainer) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) SequenceBlueprint(com.abilityapi.sequenceapi.SequenceBlueprint) Collections(java.util.Collections) MoveEntityEvent(org.spongepowered.api.event.entity.MoveEntityEvent) Player(org.spongepowered.api.entity.living.player.Player) MoveEntityEvent(org.spongepowered.api.event.entity.MoveEntityEvent) Set(java.util.Set) InvalidControlCapture(com.ichorpowered.guardian.common.capture.player.InvalidControlCapture) Optional(java.util.Optional) SequenceReport(com.ichorpowered.guardian.sequence.SequenceReport) GuardianPlayerEntry(com.ichorpowered.guardian.entry.GuardianPlayerEntry) CaptureContainer(com.ichorpowered.guardianapi.detection.capture.CaptureContainer) Summary(com.ichorpowered.guardianapi.detection.report.Summary) GuardianSequenceBuilder(com.ichorpowered.guardian.sequence.GuardianSequenceBuilder) GuardianCaptureRegistry(com.ichorpowered.guardian.sequence.capture.GuardianCaptureRegistry) Nonnull(javax.annotation.Nonnull)

Example 45 with StringUtils.join

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;
}
Also used : JSONObject(org.json.JSONObject) StopWatch(org.apache.commons.lang3.time.StopWatch)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)34 List (java.util.List)30 Collectors (java.util.stream.Collectors)23 ArrayList (java.util.ArrayList)21 Map (java.util.Map)17 HashMap (java.util.HashMap)15 Set (java.util.Set)14 Logger (org.slf4j.Logger)14 LoggerFactory (org.slf4j.LoggerFactory)14 IOException (java.io.IOException)13 HashSet (java.util.HashSet)11 Arrays (java.util.Arrays)10 Collections (java.util.Collections)10 Date (java.util.Date)9 File (java.io.File)6 StopWatch (org.apache.commons.lang3.time.StopWatch)6 InputStream (java.io.InputStream)5 java.util (java.util)5 Pair (org.apache.commons.lang3.tuple.Pair)5 Path (java.nio.file.Path)4