List of usage examples for com.google.common.collect ImmutableList subList
@Override public ImmutableList<E> subList(int fromIndex, int toIndex)
From source file:dagger2.internal.codegen.BindingGraphValidator.java
private void reportCycle(DependencyRequest request, Deque<ResolvedRequest> path, final ValidationReport.Builder<BindingGraph> reportBuilder) { ImmutableList<DependencyRequest> pathElements = ImmutableList.<DependencyRequest>builder().add(request) .addAll(Iterables.transform(path, REQUEST_FROM_RESOLVED_REQUEST)).build(); ImmutableList<String> printableDependencyPath = FluentIterable.from(pathElements) .transform(dependencyRequestFormatter).filter(Predicates.not(Predicates.equalTo(""))).toList() .reverse();//w ww . j a v a 2s. c o m DependencyRequest rootRequest = path.getLast().request(); TypeElement componentType = MoreElements.asType(rootRequest.requestElement().getEnclosingElement()); // TODO(cgruber): Restructure to provide a hint for the start and end of the cycle. reportBuilder .addItem( String.format(ErrorMessages.CONTAINS_DEPENDENCY_CYCLE_FORMAT, componentType.getQualifiedName(), rootRequest.requestElement().getSimpleName(), Joiner.on("\n") .join(printableDependencyPath.subList(1, printableDependencyPath.size()))), rootRequest.requestElement()); }
From source file:com.google.errorprone.refaster.BlockTemplate.java
private Choice<List<BlockTemplateMatch>> matchesStartingAtBeginning(final JCBlock block, final int offset, final ImmutableList<? extends StatementTree> statements, final Context context) { if (statements.isEmpty()) { return Choice.none(); }/* ww w.ja v a2s.c o m*/ final JCStatement firstStatement = (JCStatement) statements.get(0); Choice<UnifierWithUnconsumedStatements> choice = Choice .of(UnifierWithUnconsumedStatements.create(new Unifier(context), statements)); for (UStatement templateStatement : templateStatements()) { choice = choice.thenChoose(templateStatement); } return choice.thenChoose(new Function<UnifierWithUnconsumedStatements, Choice<List<BlockTemplateMatch>>>() { @Override public Choice<List<BlockTemplateMatch>> apply(UnifierWithUnconsumedStatements state) { Unifier unifier = state.unifier(); Inliner inliner = unifier.createInliner(); try { Optional<Unifier> checkedUnifier = typecheck(unifier, inliner, new Warner(firstStatement), expectedTypes(inliner), actualTypes(inliner)); if (checkedUnifier.isPresent()) { int consumedStatements = statements.size() - state.unconsumedStatements().size(); BlockTemplateMatch match = new BlockTemplateMatch(block, checkedUnifier.get(), offset, offset + consumedStatements); return matchesStartingAnywhere(block, offset + consumedStatements, statements.subList(consumedStatements, statements.size()), context) .transform(prepend(match)); } } catch (CouldNotResolveImportException e) { // fall through } return Choice.none(); } }); }
From source file:org.apache.calcite.materialize.Lattice.java
private Lattice(CalciteSchema rootSchema, ImmutableList<Node> nodes, boolean auto, boolean algorithm, long algorithmMaxMillis, LatticeStatisticProvider statisticProvider, Double rowCountEstimate, ImmutableList<Column> columns, ImmutableList<Measure> defaultMeasures, ImmutableList<Tile> tiles) { this.rootSchema = rootSchema; this.nodes = Preconditions.checkNotNull(nodes); this.columns = Preconditions.checkNotNull(columns); this.auto = auto; this.algorithm = algorithm; this.algorithmMaxMillis = algorithmMaxMillis; this.statisticProvider = Preconditions.checkNotNull(statisticProvider); this.defaultMeasures = Preconditions.checkNotNull(defaultMeasures); this.tiles = Preconditions.checkNotNull(tiles); // Validate that nodes form a tree; each node except the first references // a predecessor. for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); if (i == 0) { assert node.parent == null; } else {//from w w w . ja v a2s .c om assert nodes.subList(0, i).contains(node.parent); } } List<String> nameList = Lists.newArrayList(); for (Column column : columns) { nameList.add(column.alias); } uniqueColumnNames = ImmutableList .copyOf(SqlValidatorUtil.uniquify(Lists.transform(columns, GET_ALIAS), true)); if (rowCountEstimate == null) { // We could improve this when we fix // [CALCITE-429] Add statistics SPI for lattice optimization algorithm rowCountEstimate = 1000d; } Preconditions.checkArgument(rowCountEstimate > 0d); this.rowCountEstimate = rowCountEstimate; }
From source file:com.techcavern.pircbotz.InputParser.java
/** * This method is called by the PircBotX when a numeric response * is received from the IRC server. We use this method to * allow PircBotX to process various responses from the server * before then passing them on to the onServerResponse method. * <p>//www . j ava2 s.com * Note that this method is private and should not appear in any * of the javadoc generated documentation. * * @param code The three-digit numerical code for the response. * @param response The full response from the IRC server. */ public void processServerResponse(int code, String rawResponse, List<String> parsedResponseOrig) { ImmutableList<String> parsedResponse = ImmutableList.copyOf(parsedResponseOrig); //Parsed response format: Everything after code //eg: Response 321 Channel :Users Name gives us [Channel, Users Name] if (code == RPL_LISTSTART) { //EXAMPLE: 321 Channel :Users Name (actual text) //A channel list is about to be sent channelListBuilder = ImmutableList.builder(); channelListRunning = true; } else if (code == RPL_LIST) { //This is part of a full channel listing as part of /LIST //EXAMPLE: 322 lordquackstar #xomb 12 :xomb exokernel project @ www.xomb.org String channel = parsedResponse.get(1); int userCount = Utils.tryParseInt(parsedResponse.get(2), -1); String topic = parsedResponse.get(3); channelListBuilder.add(new ChannelListEntry(channel, userCount, topic)); } else if (code == RPL_LISTEND) { //EXAMPLE: 323 :End of /LIST //End of channel list, dispatch event configuration.getListenerManager() .dispatchEvent(new ChannelInfoEvent<PircBotZ>(bot, channelListBuilder.build())); channelListBuilder = null; channelListRunning = false; } else if (code == RPL_TOPIC) { //EXAMPLE: 332 PircBotX #aChannel :I'm some random topic //This is topic about a channel we've just joined. From /JOIN or /TOPIC Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); String topic = parsedResponse.get(2); channel.setTopic(topic); } else if (code == RPL_TOPICINFO) { //EXAMPLE: 333 PircBotX #aChannel ISetTopic 1564842512 //This is information on the topic of the channel we've just joined. From /JOIN or /TOPIC Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); User setBy = bot.getUserChannelDao().getUser(parsedResponse.get(2)); long date = Utils.tryParseLong(parsedResponse.get(3), -1); channel.setTopicTimestamp(date * 1000); channel.setTopicSetter(setBy.getNick()); configuration.getListenerManager().dispatchEvent( new TopicEvent<PircBotZ>(bot, channel, null, channel.getTopic(), setBy, date, false)); } else if (code == RPL_WHOREPLY) { //EXAMPLE: 352 PircBotX #aChannel ~someName 74.56.56.56.my.Hostmask wolfe.freenode.net someNick H :0 Full Name //Part of a WHO reply on information on individual users Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); //Setup user User curUser = bot.getUserChannelDao().createUser(parsedResponse.get(5)); curUser.setLogin(parsedResponse.get(2)); curUser.setHostmask(parsedResponse.get(3)); curUser.setServer(parsedResponse.get(4)); curUser.setNick(parsedResponse.get(5)); processUserStatus(channel, curUser, parsedResponse.get(6)); //Extra parsing needed since tokenizer stopped at : String rawEnding = parsedResponse.get(7); int rawEndingSpaceIndex = rawEnding.indexOf(' '); if (rawEndingSpaceIndex == -1) { //parsedResponse data is trimmed, so if the index == -1, then there was no real name given and the space separating hops from real name was trimmed. curUser.setHops(Integer.parseInt(rawEnding)); curUser.setRealName(""); } else { //parsedResponse data contains a real name curUser.setHops(Integer.parseInt(rawEnding.substring(0, rawEndingSpaceIndex))); curUser.setRealName(rawEnding.substring(rawEndingSpaceIndex + 1)); } //Associate with channel bot.getUserChannelDao().addUserToChannel(curUser, channel); } else if (code == RPL_ENDOFWHO) { //EXAMPLE: 315 PircBotX #aChannel :End of /WHO list //End of the WHO reply Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); configuration.getListenerManager().dispatchEvent( new UserListEvent<PircBotZ>(bot, channel, bot.getUserChannelDao().getUsers(channel))); } else if (code == RPL_CHANNELMODEIS) { //EXAMPLE: 324 PircBotX #aChannel +cnt //Full channel mode (In response to MODE <channel>) Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); ImmutableList<String> modeParsed = parsedResponse.subList(2, parsedResponse.size()); String mode = StringUtils.join(modeParsed, ' '); channel.setMode(mode, modeParsed); configuration.getListenerManager() .dispatchEvent(new ModeEvent<PircBotZ>(bot, channel, null, mode, modeParsed)); } else if (code == 329) { //EXAMPLE: 329 lordquackstar #botters 1199140245 //Tells when channel was created. From /JOIN Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); int createDate = Utils.tryParseInt(parsedResponse.get(2), -1); //Set in channel channel.setCreateTimestamp(createDate); } else if (code == RPL_MOTDSTART) //Example: 375 PircBotX :- wolfe.freenode.net Message of the Day - //Motd is starting, reset the StringBuilder motdBuilder = new StringBuilder(); else if (code == RPL_MOTD) //Example: 372 PircBotX :- Welcome to wolfe.freenode.net in Manchester, England, Uk! Thanks to //This is part of the MOTD, add a new line motdBuilder.append(CharMatcher.WHITESPACE.trimFrom(parsedResponse.get(1).substring(1))).append("\n"); else if (code == RPL_ENDOFMOTD) { //Example: PircBotX :End of /MOTD command. //End of MOTD, clean it and dispatch MotdEvent ServerInfo serverInfo = bot.getServerInfo(); serverInfo.setMotd(motdBuilder.toString().trim()); motdBuilder = null; configuration.getListenerManager().dispatchEvent(new MotdEvent<PircBotZ>(bot, serverInfo.getMotd())); } else if (code == 4 || code == 5) { //Example: 004 PircBotX sendak.freenode.net ircd-seven-1.1.3 DOQRSZaghilopswz CFILMPQbcefgijklmnopqrstvz bkloveqjfI //Server info line, remove ending comment and let ServerInfo class parse it int endCommentIndex = rawResponse.lastIndexOf(" :"); if (endCommentIndex > 1) { String endComment = rawResponse.substring(endCommentIndex + 2); int lastIndex = parsedResponseOrig.size() - 1; if (endComment.equals(parsedResponseOrig.get(lastIndex))) parsedResponseOrig.remove(lastIndex); } bot.getServerInfo().parse(code, parsedResponseOrig); } else if (code == RPL_WHOISUSER) { //Example: 311 TheLQ Plazma ~Plazma freenode/staff/plazma * :Plazma Rooolz! //New whois is starting String whoisNick = parsedResponse.get(1); WhoisEvent.Builder<PircBotZ> builder = new WhoisEvent.Builder<PircBotZ>(); builder.setNick(whoisNick); builder.setLogin(parsedResponse.get(2)); builder.setHostname(parsedResponse.get(3)); builder.setRealname(parsedResponse.get(5)); whoisBuilder.put(whoisNick, builder); } else if (code == RPL_AWAY) //Example: 301 PircBotXUser TheLQ_ :I'm away, sorry bot.getUserChannelDao().getUser(parsedResponse.get(1)).setAwayMessage(parsedResponse.get(2)); else if (code == RPL_WHOISCHANNELS) { //Example: 319 TheLQ Plazma :+#freenode //Channel list from whois. Re-tokenize since they're after the : String whoisNick = parsedResponse.get(1); ImmutableList<String> parsedChannels = ImmutableList.copyOf(Utils.tokenizeLine(parsedResponse.get(2))); whoisBuilder.get(whoisNick).setChannels(parsedChannels); } else if (code == RPL_WHOISSERVER) { //Server info from whois //312 TheLQ Plazma leguin.freenode.net :Ume?, SE, EU String whoisNick = parsedResponse.get(1); whoisBuilder.get(whoisNick).setServer(parsedResponse.get(2)); whoisBuilder.get(whoisNick).setServerInfo(parsedResponse.get(3)); } else if (code == RPL_WHOISIDLE) { //Idle time from whois //317 TheLQ md_5 6077 1347373349 :seconds idle, signon time String whoisNick = parsedResponse.get(1); whoisBuilder.get(whoisNick).setIdleSeconds(Long.parseLong(parsedResponse.get(2))); whoisBuilder.get(whoisNick).setSignOnTime(Long.parseLong(parsedResponse.get(3))); } else if (code == 330) { //RPL_WHOISACCOUNT: Extra Whois info //330 TheLQ Utoxin Utoxin :is logged in as //Make sure we set registered as to the nick, not to the note after the colon String registeredNick = ""; if (!rawResponse.endsWith(":" + parsedResponse.get(2))) registeredNick = parsedResponse.get(2); whoisBuilder.get(parsedResponse.get(1)).setRegisteredAs(registeredNick); } else if (code == 307) { //If shown, tells us that the user is registered with nickserv //307 TheLQ TheLQ-PircBotX :has identified for this nick whoisBuilder.get(parsedResponse.get(1)).setRegisteredAs(""); } else if (code == RPL_ENDOFWHOIS) { //End of whois //318 TheLQ Plazma :End of /WHOIS list. String whoisNick = parsedResponse.get(1); try { configuration.getListenerManager().dispatchEvent(whoisBuilder.get(whoisNick).generateEvent(bot)); whoisBuilder.remove(whoisNick); } catch (NullPointerException e) { WhoisEvent.Builder<PircBotZ> builder = new WhoisEvent.Builder<PircBotZ>(); configuration.getListenerManager().dispatchEvent(builder.generateEvent(bot)); } } configuration.getListenerManager() .dispatchEvent(new ServerResponseEvent<PircBotZ>(bot, code, rawResponse, parsedResponse)); }
From source file:com.google.devtools.build.lib.syntax.BaseFunction.java
/** * Process the caller-provided arguments into an array suitable for the callee (this function). */// w w w . ja v a 2 s . c om public Object[] processArguments(List<Object> args, @Nullable Map<String, Object> kwargs, @Nullable Location loc, @Nullable Environment env) throws EvalException { Object[] arguments = new Object[getArgArraySize()]; // extract function signature FunctionSignature sig = signature.getSignature(); FunctionSignature.Shape shape = sig.getShape(); ImmutableList<String> names = sig.getNames(); List<Object> defaultValues = signature.getDefaultValues(); // Note that this variable will be adjusted down if there are extra positionals, // after these extra positionals are dumped into starParam. int numPositionalArgs = args.size(); int numMandatoryPositionalParams = shape.getMandatoryPositionals(); int numOptionalPositionalParams = shape.getOptionalPositionals(); int numMandatoryNamedOnlyParams = shape.getMandatoryNamedOnly(); int numOptionalNamedOnlyParams = shape.getOptionalNamedOnly(); boolean hasStarParam = shape.hasStarArg(); boolean hasKwParam = shape.hasKwArg(); int numPositionalParams = numMandatoryPositionalParams + numOptionalPositionalParams; int numNamedOnlyParams = numMandatoryNamedOnlyParams + numOptionalNamedOnlyParams; int numNamedParams = numPositionalParams + numNamedOnlyParams; int kwParamIndex = names.size() - 1; // only valid if hasKwParam // (1) handle positional arguments if (hasStarParam) { // Nota Bene: we collect extra positional arguments in a (tuple,) rather than a [list], // and this is actually the same as in Python. int starParamIndex = numNamedParams; if (numPositionalArgs > numPositionalParams) { arguments[starParamIndex] = Tuple.copyOf(args.subList(numPositionalParams, numPositionalArgs)); numPositionalArgs = numPositionalParams; // clip numPositionalArgs } else { arguments[starParamIndex] = Tuple.empty(); } } else if (numPositionalArgs > numPositionalParams) { throw new EvalException(loc, numPositionalParams > 0 ? "too many (" + numPositionalArgs + ") positional arguments in call to " + this : this + " does not accept positional arguments, but got " + numPositionalArgs); } for (int i = 0; i < numPositionalArgs; i++) { arguments[i] = args.get(i); } // (2) handle keyword arguments if (kwargs == null || kwargs.isEmpty()) { // Easy case (2a): there are no keyword arguments. // All arguments were positional, so check we had enough to fill all mandatory positionals. if (numPositionalArgs < numMandatoryPositionalParams) { throw new EvalException(loc, String.format("insufficient arguments received by %s (got %s, expected at least %s)", this, numPositionalArgs, numMandatoryPositionalParams)); } // We had no named argument, so fail if there were mandatory named-only parameters if (numMandatoryNamedOnlyParams > 0) { throw new EvalException(loc, String.format("missing mandatory keyword arguments in call to %s", this)); } // Fill in defaults for missing optional parameters, that were conveniently grouped together, // thanks to the absence of mandatory named-only parameters as checked above. if (defaultValues != null) { int j = numPositionalArgs - numMandatoryPositionalParams; int endOptionalParams = numPositionalParams + numOptionalNamedOnlyParams; for (int i = numPositionalArgs; i < endOptionalParams; i++) { arguments[i] = defaultValues.get(j++); } } // If there's a kwParam, it's empty. if (hasKwParam) { // TODO(bazel-team): create a fresh mutable dict, like Python does arguments[kwParamIndex] = SkylarkDict.of(env); } } else if (hasKwParam && numNamedParams == 0) { // Easy case (2b): there are no named parameters, but there is a **kwParam. // Therefore all keyword arguments go directly to the kwParam. // Note that *starParam and **kwParam themselves don't count as named. // Also note that no named parameters means no mandatory parameters that weren't passed, // and no missing optional parameters for which to use a default. Thus, no loops. // NB: not 2a means kwarg isn't null arguments[kwParamIndex] = SkylarkDict.copyOf(env, kwargs); } else { // Hard general case (2c): some keyword arguments may correspond to named parameters SkylarkDict<String, Object> kwArg = hasKwParam ? SkylarkDict.<String, Object>of(env) : SkylarkDict.<String, Object>empty(); // For nicer stabler error messages, start by checking against // an argument being provided both as positional argument and as keyword argument. ArrayList<String> bothPosKey = new ArrayList<>(); for (int i = 0; i < numPositionalArgs; i++) { String name = names.get(i); if (kwargs.containsKey(name)) { bothPosKey.add(name); } } if (!bothPosKey.isEmpty()) { throw new EvalException(loc, String.format("argument%s '%s' passed both by position and by name in call to %s", (bothPosKey.size() > 1 ? "s" : ""), Joiner.on("', '").join(bothPosKey), this)); } // Accept the arguments that were passed. for (Map.Entry<String, Object> entry : kwargs.entrySet()) { String keyword = entry.getKey(); Object value = entry.getValue(); int pos = names.indexOf(keyword); // the list should be short, so linear scan is OK. if (0 <= pos && pos < numNamedParams) { arguments[pos] = value; } else { if (!hasKwParam) { List<String> unexpected = Ordering.natural().sortedCopy(Sets.difference(kwargs.keySet(), ImmutableSet.copyOf(names.subList(0, numNamedParams)))); throw new EvalException(loc, String.format("unexpected keyword%s '%s' in call to %s", unexpected.size() > 1 ? "s" : "", Joiner.on("', '").join(unexpected), this)); } if (kwArg.containsKey(keyword)) { throw new EvalException(loc, String.format("%s got multiple values for keyword argument '%s'", this, keyword)); } kwArg.put(keyword, value, loc, env); } } if (hasKwParam) { // TODO(bazel-team): create a fresh mutable dict, like Python does arguments[kwParamIndex] = SkylarkDict.copyOf(env, kwArg); } // Check that all mandatory parameters were filled in general case 2c. // Note: it's possible that numPositionalArgs > numMandatoryPositionalParams but that's OK. for (int i = numPositionalArgs; i < numMandatoryPositionalParams; i++) { if (arguments[i] == null) { throw new EvalException(loc, String.format( "missing mandatory positional argument '%s' while calling %s", names.get(i), this)); } } int endMandatoryNamedOnlyParams = numPositionalParams + numMandatoryNamedOnlyParams; for (int i = numPositionalParams; i < endMandatoryNamedOnlyParams; i++) { if (arguments[i] == null) { throw new EvalException(loc, String.format( "missing mandatory named-only argument '%s' while calling %s", names.get(i), this)); } } // Get defaults for those parameters that weren't passed. if (defaultValues != null) { for (int i = Math.max(numPositionalArgs, numMandatoryPositionalParams); i < numPositionalParams; i++) { if (arguments[i] == null) { arguments[i] = defaultValues.get(i - numMandatoryPositionalParams); } } int numMandatoryParams = numMandatoryPositionalParams + numMandatoryNamedOnlyParams; for (int i = numMandatoryParams + numOptionalPositionalParams; i < numNamedParams; i++) { if (arguments[i] == null) { arguments[i] = defaultValues.get(i - numMandatoryParams); } } } } // End of general case 2c for argument passing. return arguments; }
From source file:org.pircbotx.InputParser.java
/** * This method is called by the PircBotX when a numeric response is received * from the IRC server. We use this method to allow PircBotX to process * various responses from the server before then passing them on to the * onServerResponse method.// ww w . jav a2s . c o m * <p> * Note that this method is private and should not appear in any of the * javadoc generated documentation. * * @param code The three-digit numerical code for the response. */ public void processServerResponse(int code, String rawResponse, List<String> parsedResponseOrig) { ImmutableList<String> parsedResponse = ImmutableList.copyOf(parsedResponseOrig); //Parsed response format: Everything after code if (code == 433) { //EXAMPLE: * AnAlreadyUsedName :Nickname already in use //Nickname in use, rename String usedNick = parsedResponseOrig.get(1); boolean autoNickChange = configuration.isAutoNickChange(); String autoNewNick = null; if (autoNickChange) { nickSuffix++; autoNewNick = configuration.getName() + nickSuffix; bot.sendIRC().changeNick(autoNewNick); bot.setNick(autoNewNick); bot.getUserChannelDao().renameUser(bot.getUserChannelDao().getUser(usedNick), autoNewNick); } configuration.getListenerManager() .dispatchEvent(new NickAlreadyInUseEvent(bot, usedNick, autoNewNick, autoNickChange)); } else if (code == RPL_LISTSTART) { //EXAMPLE: 321 Channel :Users Name (actual text) //A channel list is about to be sent channelListBuilder = ImmutableList.builder(); channelListRunning = true; } else if (code == RPL_LIST) { //This is part of a full channel listing as part of /LIST //EXAMPLE: 322 lordquackstar #xomb 12 :xomb exokernel project @ www.xomb.org String channel = parsedResponse.get(1); int userCount = Utils.tryParseInt(parsedResponse.get(2), -1); String topic = parsedResponse.get(3); channelListBuilder.add(new ChannelListEntry(channel, userCount, topic)); } else if (code == RPL_LISTEND) { //EXAMPLE: 323 :End of /LIST //End of channel list, dispatch event configuration.getListenerManager().dispatchEvent(new ChannelInfoEvent(bot, channelListBuilder.build())); channelListBuilder = null; channelListRunning = false; } else if (code == RPL_TOPIC) { //EXAMPLE: 332 PircBotX #aChannel :I'm some random topic //This is topic about a channel we've just joined. From /JOIN or /TOPIC Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); String topic = parsedResponse.get(2); channel.setTopic(topic); } else if (code == RPL_TOPICINFO) { //EXAMPLE: 333 PircBotX #aChannel ISetTopic 1564842512 //This is information on the topic of the channel we've just joined. From /JOIN or /TOPIC Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); UserHostmask setBy = configuration.getBotFactory().createUserHostmask(bot, parsedResponse.get(2)); long date = Utils.tryParseLong(parsedResponse.get(3), -1); channel.setTopicTimestamp(date * 1000); channel.setTopicSetter(setBy); configuration.getListenerManager() .dispatchEvent(new TopicEvent(bot, channel, null, channel.getTopic(), setBy, date, false)); } else if (code == RPL_WHOREPLY) { //EXAMPLE: 352 PircBotX #aChannel ~someName 74.56.56.56.my.Hostmask wolfe.freenode.net someNick H :0 Full Name //Part of a WHO reply on information on individual users Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); //Setup user UserHostmask curUserHostmask = bot.getConfiguration().getBotFactory().createUserHostmask(bot, null, parsedResponse.get(5), parsedResponse.get(2), parsedResponse.get(3)); User curUser = (bot.getUserChannelDao().containsUser(curUserHostmask)) ? bot.getUserChannelDao().getUser(curUserHostmask) : bot.getUserChannelDao().createUser(curUserHostmask); curUser.setServer(parsedResponse.get(4)); processUserStatus(channel, curUser, parsedResponse.get(6)); //Extra parsing needed since tokenizer stopped at : String rawEnding = parsedResponse.get(7); int rawEndingSpaceIndex = rawEnding.indexOf(' '); if (rawEndingSpaceIndex == -1) { //parsedResponse data is trimmed, so if the index == -1, then there was no real name given and the space separating hops from real name was trimmed. curUser.setHops(Integer.parseInt(rawEnding)); curUser.setRealName(""); } else { //parsedResponse data contains a real name curUser.setHops(Integer.parseInt(rawEnding.substring(0, rawEndingSpaceIndex))); curUser.setRealName(rawEnding.substring(rawEndingSpaceIndex + 1)); } //Associate with channel bot.getUserChannelDao().addUserToChannel(curUser, channel); } else if (code == RPL_ENDOFWHO) { //EXAMPLE: 315 PircBotX #aChannel :End of /WHO list //End of the WHO reply Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); configuration.getListenerManager().dispatchEvent( new UserListEvent(bot, channel, bot.getUserChannelDao().getUsers(channel), true)); } else if (code == RPL_CHANNELMODEIS) { //EXAMPLE: 324 PircBotX #aChannel +cnt //Full channel mode (In response to MODE <channel>) Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); ImmutableList<String> modeParsed = parsedResponse.subList(2, parsedResponse.size()); String mode = StringUtils.join(modeParsed, ' '); channel.setMode(mode, modeParsed); configuration.getListenerManager() .dispatchEvent(new ModeEvent(bot, channel, null, null, mode, modeParsed)); } else if (code == 329) { //EXAMPLE: 329 lordquackstar #botters 1199140245 //Tells when channel was created. From /JOIN Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); int createDate = Utils.tryParseInt(parsedResponse.get(2), -1); //Set in channel channel.setCreateTimestamp(createDate); } else if (code == RPL_MOTDSTART) //Example: 375 PircBotX :- wolfe.freenode.net Message of the Day - //Motd is starting, reset the StringBuilder motdBuilder = new StringBuilder(); else if (code == RPL_MOTD) //Example: 372 PircBotX :- Welcome to wolfe.freenode.net in Manchester, England, Uk! Thanks to //This is part of the MOTD, add a new line motdBuilder.append(CharMatcher.WHITESPACE.trimFrom(parsedResponse.get(1).substring(1))).append("\n"); else if (code == RPL_ENDOFMOTD) { //Example: PircBotX :End of /MOTD command. //End of MOTD, clean it and dispatch MotdEvent ServerInfo serverInfo = bot.getServerInfo(); serverInfo.setMotd(motdBuilder.toString().trim()); motdBuilder = null; configuration.getListenerManager().dispatchEvent(new MotdEvent(bot, serverInfo.getMotd())); } else if (code == 4 || code == 5) { //Example: 004 PircBotX sendak.freenode.net ircd-seven-1.1.3 DOQRSZaghilopswz CFILMPQbcefgijklmnopqrstvz bkloveqjfI //Server info line, remove ending comment and let ServerInfo class parse it int endCommentIndex = rawResponse.lastIndexOf(" :"); if (endCommentIndex > 1) { String endComment = rawResponse.substring(endCommentIndex + 2); int lastIndex = parsedResponseOrig.size() - 1; if (endComment.equals(parsedResponseOrig.get(lastIndex))) parsedResponseOrig.remove(lastIndex); } bot.getServerInfo().parse(code, parsedResponseOrig); } else if (code == RPL_WHOISUSER) { //Example: 311 TheLQ Plazma ~Plazma freenode/staff/plazma * :Plazma Rooolz! //New whois is starting String whoisNick = parsedResponse.get(1); WhoisEvent.Builder builder = WhoisEvent.builder(); builder.nick(whoisNick); builder.login(parsedResponse.get(2)); builder.hostname(parsedResponse.get(3)); builder.realname(parsedResponse.get(5)); whoisBuilder.put(whoisNick, builder); } else if (code == RPL_AWAY) { //Example: 301 PircBotXUser TheLQ_ :I'm away, sorry //Can be sent during whois String nick = parsedResponse.get(1); String awayMessage = parsedResponse.get(2); if (bot.getUserChannelDao().containsUser(nick)) bot.getUserChannelDao().getUser(nick).setAwayMessage(awayMessage); if (whoisBuilder.containsKey(nick)) whoisBuilder.get(nick).awayMessage(awayMessage); } else if (code == RPL_WHOISCHANNELS) { //Example: 319 TheLQ Plazma :+#freenode //Channel list from whois. Re-tokenize since they're after the : String whoisNick = parsedResponse.get(1); ImmutableList<String> parsedChannels = ImmutableList.copyOf(Utils.tokenizeLine(parsedResponse.get(2))); whoisBuilder.get(whoisNick).channels(parsedChannels); } else if (code == RPL_WHOISSERVER) { //Server info from whois //312 TheLQ Plazma leguin.freenode.net :Ume?, SE, EU String whoisNick = parsedResponse.get(1); whoisBuilder.get(whoisNick).server(parsedResponse.get(2)); whoisBuilder.get(whoisNick).serverInfo(parsedResponse.get(3)); } else if (code == RPL_WHOISIDLE) { //Idle time from whois //317 TheLQ md_5 6077 1347373349 :seconds idle, signon time String whoisNick = parsedResponse.get(1); whoisBuilder.get(whoisNick).idleSeconds(Long.parseLong(parsedResponse.get(2))); whoisBuilder.get(whoisNick).signOnTime(Long.parseLong(parsedResponse.get(3))); } else if (code == 330) { //RPL_WHOISACCOUNT: Extra Whois info //330 TheLQ Utoxin Utoxin :is logged in as //Make sure we set registered as to the nick, not to the note after the colon String registeredNick = ""; if (!rawResponse.endsWith(":" + parsedResponse.get(2))) registeredNick = parsedResponse.get(2); whoisBuilder.get(parsedResponse.get(1)).registeredAs(registeredNick); } else if (code == 307) //If shown, tells us that the user is registered with nickserv //307 TheLQ TheLQ-PircBotX :has identified for this nick whoisBuilder.get(parsedResponse.get(1)).registeredAs(""); else if (code == RPL_ENDOFWHOIS) { //End of whois //318 TheLQ Plazma :End of /WHOIS list. String whoisNick = parsedResponse.get(1); WhoisEvent.Builder builder; if (whoisBuilder.containsKey(whoisNick)) { builder = whoisBuilder.get(whoisNick); builder.exists(true); } else { builder = WhoisEvent.builder(); builder.nick(whoisNick); builder.exists(false); } configuration.getListenerManager().dispatchEvent(builder.generateEvent(bot)); whoisBuilder.remove(whoisNick); } else if (code == 367) { //Ban list entry //367 TheLQ #aChannel *!*@test1.host TheLQ!~quackstar@some.host 1415143822 Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); UserHostmask recipient = bot.getConfiguration().getBotFactory().createUserHostmask(bot, parsedResponse.get(2)); UserHostmask source = bot.getConfiguration().getBotFactory().createUserHostmask(bot, parsedResponse.get(3)); long time = Long.parseLong(parsedResponse.get(4)); banListBuilder.put(channel, new BanListEvent.Entry(recipient, source, time)); log.debug("Adding entry"); } else if (code == 368) { //Ban list is finished //368 TheLQ #aChannel :End of Channel Ban List Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); ImmutableList<BanListEvent.Entry> entries = ImmutableList.copyOf(banListBuilder.removeAll(channel)); log.debug("Dispatching event"); configuration.getListenerManager().dispatchEvent(new BanListEvent(bot, channel, entries)); } else if (code == 353) { //NAMES response //353 PircBotXUser = #aChannel :aUser1 aUser2 for (String curUser : StringUtils.split(parsedResponse.get(3))) { //Siphon off any levels this user has String nick = curUser; List<UserLevel> levels = Lists.newArrayList(); UserLevel parsedLevel; while ((parsedLevel = UserLevel.fromSymbol(nick.charAt(0))) != null) { nick = nick.substring(1); levels.add(parsedLevel); } User user; if (!bot.getUserChannelDao().containsUser(nick)) //Create user with nick only user = bot.getUserChannelDao().createUser(new UserHostmask(bot, nick)); else user = bot.getUserChannelDao().getUser(nick); Channel chan = bot.getUserChannelDao().getChannel(parsedResponse.get(2)); bot.getUserChannelDao().addUserToChannel(user, chan); //Now that the user is created, add them to the appropiate levels for (UserLevel curLevel : levels) { bot.getUserChannelDao().addUserToLevel(curLevel, user, chan); } } } else if (code == 366) { //NAMES response finished //366 PircBotXUser #aChannel :End of /NAMES list. Channel channel = bot.getUserChannelDao().getChannel(parsedResponse.get(1)); configuration.getListenerManager().dispatchEvent( new UserListEvent(bot, channel, bot.getUserChannelDao().getUsers(channel), false)); } configuration.getListenerManager() .dispatchEvent(new ServerResponseEvent(bot, code, rawResponse, parsedResponse)); }