use of org.apache.commons.lang3.builder.ToStringStyleTest.Person in project commons-lang by apache.
the class SimpleToStringStyleTest method testPerson.
@Test
public void testPerson() {
final Person p = new Person();
p.name = "Jane Q. Public";
p.age = 47;
p.smoker = false;
assertEquals("Jane Q. Public,47,false", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).toString());
}
use of org.apache.commons.lang3.builder.ToStringStyleTest.Person in project DiscordSRV by Scarsz.
the class DiscordSRV method init.
public void init() {
// check if the person is trying to use the plugin without updating to ASM 5
try {
File specialSourceFile = new File("libraries/net/md-5/SpecialSource/1.7-SNAPSHOT/SpecialSource-1.7-SNAPSHOT.jar");
if (!specialSourceFile.exists())
specialSourceFile = new File("bin/net/md-5/SpecialSource/1.7-SNAPSHOT/SpecialSource-1.7-SNAPSHOT.jar");
if (specialSourceFile.exists() && DigestUtils.md5Hex(FileUtils.readFileToByteArray(specialSourceFile)).equalsIgnoreCase("096777a1b6098130d6c925f1c04050a3")) {
DiscordSRV.warning(LangUtil.InternalMessage.ASM_WARNING.toString().replace("{specialsourcefolder}", specialSourceFile.getParentFile().getPath()));
}
} catch (IOException e) {
e.printStackTrace();
}
// remove all event listeners from existing jda to prevent having multiple listeners when jda is recreated
if (jda != null)
jda.getRegisteredListeners().forEach(o -> jda.removeEventListener(o));
// make sure configuration file exists, save default ones if they don't
if (!configFile.exists()) {
LangUtil.saveConfig();
reloadConfig();
}
// make sure lang file exists, save default ones if they don't
if (!messagesFile.exists()) {
LangUtil.saveMessages();
LangUtil.reloadMessages();
}
ConfigUtil.migrate();
try {
getConfig();
} catch (IllegalArgumentException e) {
DiscordSRV.error(LangUtil.InternalMessage.INVALID_CONFIG + ": " + e.getMessage());
try {
new Yaml().load(FileUtils.readFileToString(getConfigFile(), Charset.forName("UTF-8")));
} catch (IOException io) {
DiscordSRV.error(io.getMessage());
}
return;
}
// update check
if (!getConfig().getBoolean("UpdateCheckDisabled")) {
updateIsAvailable = UpdateUtil.checkForUpdates();
// don't load other shit if the plugin was disabled by the update checker
if (!isEnabled())
return;
}
// cool kids club thank yous
if (!getConfig().getBoolean("CoolKidsClubThankYousDisabled")) {
String thankYou = HttpUtil.requestHttp("https://github.com/Scarsz/DiscordSRV/raw/randomaccessfiles/coolkidsclub").replace("\n", "");
if (thankYou.length() > 1)
DiscordSRV.info(LangUtil.InternalMessage.DONATOR_THANKS + ": " + thankYou);
}
// random phrases for debug handler
if (!getConfig().getBoolean("RandomPhrasesDisabled"))
Collections.addAll(randomPhrases, HttpUtil.requestHttp("https://raw.githubusercontent.com/Scarsz/DiscordSRV/randomaccessfiles/randomphrases").split("\n"));
// shutdown previously existing jda if plugin gets reloaded
if (jda != null)
try {
jda.shutdown();
jda = null;
} catch (Exception e) {
e.printStackTrace();
}
// set proxy just in case this JVM is fucking stupid
if (ProxySelector.getDefault() == null) {
ProxySelector.setDefault(new ProxySelector() {
private final List<Proxy> DIRECT_CONNECTION = Collections.unmodifiableList(Collections.singletonList(Proxy.NO_PROXY));
public void connectFailed(URI arg0, SocketAddress arg1, IOException arg2) {
}
public List<Proxy> select(URI uri) {
return DIRECT_CONNECTION;
}
});
}
// check log4j capabilities
boolean serverIsLog4jCapable = false;
try {
serverIsLog4jCapable = Class.forName("org.apache.logging.log4j.core.Logger") != null;
} catch (ClassNotFoundException e) {
error("Log4j classes are NOT available, console channel will not be attached");
}
// add log4j filter for JDA messages
if (serverIsLog4jCapable)
((org.apache.logging.log4j.core.Logger) org.apache.logging.log4j.LogManager.getRootLogger()).addFilter(new JdaFilter());
// log in to discord
try {
jda = new JDABuilder(AccountType.BOT).setAudioEnabled(false).setAutoReconnect(true).setBulkDeleteSplittingEnabled(false).setToken(getConfig().getString("BotToken")).addEventListener(new DiscordBanListener()).addEventListener(new DiscordChatListener()).addEventListener(new DiscordConsoleListener()).addEventListener(new DiscordDebugListener()).addEventListener(new DiscordAccountLinkListener()).buildAsync();
} catch (LoginException e) {
DiscordSRV.error(LangUtil.InternalMessage.FAILED_TO_CONNECT_TO_DISCORD + ": " + e.getMessage());
return;
} catch (Exception e) {
DiscordSRV.error("An unknown error occurred building JDA...");
e.printStackTrace();
return;
}
while (jda.getStatus() != JDA.Status.CONNECTED) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// game status
if (!getConfig().getString("DiscordGameStatus").isEmpty()) {
DiscordUtil.setGameStatus(getConfig().getString("DiscordGameStatus"));
}
// print the things the bot can see
for (Guild server : jda.getGuilds()) {
DiscordSRV.info(LangUtil.InternalMessage.FOUND_SERVER + " " + server);
for (TextChannel channel : server.getTextChannels()) DiscordSRV.info("- " + channel);
}
// show warning if bot wasn't in any guilds
if (jda.getGuilds().size() == 0) {
DiscordSRV.error(LangUtil.InternalMessage.BOT_NOT_IN_ANY_SERVERS);
return;
}
// set console channel
String consoleChannelId = getConfig().getString("DiscordConsoleChannelId");
if (consoleChannelId != null)
consoleChannel = DiscordUtil.getTextChannelById(consoleChannelId);
// see if console channel exists; if it does, tell user where it's been assigned & add console appender
if (serverIsLog4jCapable && consoleChannel != null) {
DiscordSRV.info(LangUtil.InternalMessage.CONSOLE_FORWARDING_ASSIGNED_TO_CHANNEL + " " + consoleChannel);
// attach appender to queue console messages
new ConsoleAppender();
// start console message queue worker thread
if (consoleMessageQueueWorker != null) {
if (consoleMessageQueueWorker.getState() == Thread.State.NEW) {
consoleMessageQueueWorker.start();
} else {
consoleMessageQueueWorker.interrupt();
consoleMessageQueueWorker = new ConsoleMessageQueueWorker();
consoleMessageQueueWorker.start();
}
} else {
consoleMessageQueueWorker = new ConsoleMessageQueueWorker();
consoleMessageQueueWorker.start();
}
} else {
DiscordSRV.info(LangUtil.InternalMessage.NOT_FORWARDING_CONSOLE_OUTPUT.toString());
}
// load channels
for (Map.Entry<String, Object> channelEntry : ((MemorySection) getConfig().get("Channels")).getValues(true).entrySet()) channels.put(channelEntry.getKey(), DiscordUtil.getTextChannelById((String) channelEntry.getValue()));
// warn if no channels have been linked
if (getMainTextChannel() == null)
DiscordSRV.warning(LangUtil.InternalMessage.NO_CHANNELS_LINKED);
if (getMainTextChannel() == null && consoleChannel == null)
DiscordSRV.error(LangUtil.InternalMessage.NO_CHANNELS_LINKED_NOR_CONSOLE);
// warn if the console channel is connected to a chat channel
if (getMainTextChannel() != null && consoleChannel != null && getMainTextChannel().getId().equals(consoleChannel.getId()))
DiscordSRV.warning(LangUtil.InternalMessage.CONSOLE_CHANNEL_ASSIGNED_TO_LINKED_CHANNEL);
// send server startup message
DiscordUtil.sendMessage(getMainTextChannel(), LangUtil.Message.SERVER_STARTUP_MESSAGE.toString(), 0, false);
// start channel topic updater
if (serverWatchdog != null) {
if (serverWatchdog.getState() == Thread.State.NEW) {
serverWatchdog.start();
} else {
serverWatchdog.interrupt();
serverWatchdog = new ServerWatchdog();
serverWatchdog.start();
}
} else {
serverWatchdog = new ServerWatchdog();
serverWatchdog.start();
}
// start lag (tps) monitor
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Lag(), 100L, 1L);
// cancellation detector
if (getConfig().getInt("DebugLevel") > 0) {
if (cancellationDetector != null) {
cancellationDetector.close();
cancellationDetector = null;
}
cancellationDetector = new CancellationDetector<>(AsyncPlayerChatEvent.class);
cancellationDetector.addListener((plugin, event) -> DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_CANCELLED_CHAT_EVENT.toString().replace("{plugin}", plugin.toString()).replace("{author}", event.getPlayer().getName()).replace("{message}", event.getMessage())));
DiscordSRV.info(LangUtil.InternalMessage.CHAT_CANCELLATION_DETECTOR_ENABLED);
}
// load account links
accountLinkManager = new AccountLinkManager();
// register events
Bukkit.getPluginManager().registerEvents(this, this);
new PlayerAchievementsListener();
try {
if (Class.forName("org.bukkit.advancement.Advancement") != null)
new PlayerAdvancementDoneListener();
} catch (ClassNotFoundException ignored) {
}
new PlayerBanListener();
new PlayerDeathListener();
new PlayerJoinLeaveListener();
// in-game chat events
if (PluginUtil.pluginHookIsEnabled("herochat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "HeroChat"));
getServer().getPluginManager().registerEvents(new HerochatHook(), this);
} else if (PluginUtil.pluginHookIsEnabled("legendchat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "LegendChat"));
getServer().getPluginManager().registerEvents(new LegendChatHook(), this);
} else if (PluginUtil.pluginHookIsEnabled("lunachat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "LunaChat"));
getServer().getPluginManager().registerEvents(new LunaChatHook(), this);
} else if (PluginUtil.checkIfPluginEnabled("towny") && PluginUtil.pluginHookIsEnabled("townychat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "TownyChat"));
getServer().getPluginManager().registerEvents(new TownyChatHook(), this);
} else if (PluginUtil.pluginHookIsEnabled("ultimatechat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "UltimateChat"));
getServer().getPluginManager().registerEvents(new UltimateChatHook(), this);
} else if (PluginUtil.pluginHookIsEnabled("venturechat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "VentureChat"));
getServer().getPluginManager().registerEvents(new VentureChatHook(), this);
} else {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOKS_NOT_ENABLED);
getServer().getPluginManager().registerEvents(new PlayerChatListener(), this);
}
// load user-defined colors
colors.clear();
for (Map.Entry<String, Object> colorEntry : ((MemorySection) getConfig().get("DiscordChatChannelColorTranslations")).getValues(true).entrySet()) colors.put(colorEntry.getKey().toUpperCase(), (String) colorEntry.getValue());
// load canned responses
responses.clear();
for (Map.Entry<String, Object> responseEntry : ((MemorySection) getConfig().get("DiscordCannedResponses")).getValues(true).entrySet()) responses.put(responseEntry.getKey(), (String) responseEntry.getValue());
// start server watchdog
if (channelTopicUpdater != null) {
if (channelTopicUpdater.getState() == Thread.State.NEW) {
channelTopicUpdater.start();
} else {
channelTopicUpdater.interrupt();
channelTopicUpdater = new ChannelTopicUpdater();
channelTopicUpdater.start();
}
} else {
channelTopicUpdater = new ChannelTopicUpdater();
channelTopicUpdater.start();
}
// enable metrics
if (!getConfig().getBoolean("MetricsDisabled")) {
try {
MCStats MCStats = new MCStats(this);
MCStats.start();
} catch (IOException e) {
DiscordSRV.warning("Unable to start metrics: " + e.getMessage());
}
BStats bStats = new BStats(this);
bStats.addCustomChart(new BStats.LambdaSimplePie("linked_channels", () -> String.valueOf(channels.size())));
bStats.addCustomChart(new BStats.LambdaSimplePie("console_channel_enabled", () -> String.valueOf(consoleChannel != null)));
bStats.addCustomChart(new BStats.LambdaSingleLineChart("messages_sent_to_discord", () -> metrics.get("messages_sent_to_discord")));
bStats.addCustomChart(new BStats.LambdaSingleLineChart("messages_sent_to_minecraft", () -> metrics.get("messages_sent_to_minecraft")));
bStats.addCustomChart(new BStats.LambdaSingleLineChart("console_commands_processed", () -> metrics.get("console_commands_processed")));
bStats.addCustomChart(new BStats.LambdaSimpleBarChart("hooked_plugins", () -> new HashMap<String, Integer>() {
{
if (hookedPlugins.size() == 0) {
put("none", 1);
} else {
for (String hookedPlugin : hookedPlugins) {
put(hookedPlugin.toLowerCase(), 1);
}
}
}
}));
bStats.addCustomChart(new BStats.LambdaSingleLineChart("minecraft-discord_account_links", () -> accountLinkManager.getLinkedAccounts().size()));
}
// dummy sync target to initialize class
GroupSynchronizationUtil.reSyncGroups(null);
// set ready status
if (jda.getStatus() == JDA.Status.CONNECTED)
isReady = true;
}
use of org.apache.commons.lang3.builder.ToStringStyleTest.Person in project uPortal by Jasig.
the class IdTokenFactory method createUserInfo.
public String createUserInfo(String username, Set<String> claimsToInclude, Set<String> groupsToInclude) {
final Date now = new Date();
final Date expires = new Date(now.getTime() + (timeoutSeconds * 1000L));
final JwtBuilder builder = Jwts.builder().setIssuer(issuer).setSubject(username).setAudience(issuer).setExpiration(expires).setIssuedAt(now);
final IPersonAttributes person = personAttributeDao.getPerson(username);
// Attribute mappings
mappings.stream().filter(mapping -> includeClaim(mapping.getClaimName(), claimsToInclude)).forEach(item -> {
final Object value = person.getAttributeValue(item.getAttributeName());
if (value != null) {
builder.claim(item.getClaimName(), item.getDataTypeConverter().convert(value));
}
});
// Groups
final List<String> groups = new ArrayList<>();
final IGroupMember groupMember = GroupService.getGroupMember(username, IPerson.class);
if (groupMember != null) {
final Set<IEntityGroup> ancestors = groupMember.getAncestorGroups();
for (IEntityGroup g : ancestors) {
if (includeGroup(g, groupsToInclude)) {
groups.add(g.getName());
}
}
}
if (!groups.isEmpty()) {
/*
* If a Claim is not returned, that Claim Name SHOULD be omitted from the JSON object
* representing the Claims; it SHOULD NOT be present with a null or empty string value.
*/
builder.claim("groups", groups);
}
// Default custom claims defined by uPortal.properties
customClaims.stream().filter(claimName -> includeClaim(claimName, claimsToInclude)).map(attributeName -> new CustomClaim(attributeName, person.getAttributeValues(attributeName))).filter(claim -> claim.getClaimValue() != null).forEach(claim -> builder.claim(claim.getClaimName(), claim.getClaimValue()));
final String rslt = builder.signWith(algorithmFactory.getAlgorithm(), signatureKey).compact();
logger.debug("Produced the following JWT for username='{}': {}", username, rslt);
return rslt;
}
use of org.apache.commons.lang3.builder.ToStringStyleTest.Person in project uPortal by Jasig.
the class ServerNameGuestChainingProfileMapper method getProfileFname.
@Override
public String getProfileFname(IPerson person, HttpServletRequest request) {
final StringBuilder fname = new StringBuilder(64);
if (person.isGuest()) {
final String serverName = authorizedServerNames.get(request.getServerName());
// If guest user
fname.append("guest" + ServerNameGuestChainingProfileMapper.SEPARATOR);
if (StringUtils.hasText(serverName)) {
// If use an authorized server name we add the guest prefix
fname.append(serverName);
fname.append(ServerNameGuestChainingProfileMapper.SEPARATOR);
}
}
boolean subFnameFound = false;
for (IProfileMapper mapper : subMappers) {
final String subFname = mapper.getProfileFname(person, request);
if (StringUtils.hasText(subFname)) {
fname.append(subFname);
subFnameFound = true;
break;
}
}
if (!subFnameFound) {
fname.append(this.defaultProfileName);
}
logger.debug("Profile fname: [{}].", fname.toString());
return fname.toString();
}
use of org.apache.commons.lang3.builder.ToStringStyleTest.Person in project alfresco-remote-api by Alfresco.
the class GroupsFilter method getGroupsByPersonId.
@Override
public CollectionWithPagingInfo<Group> getGroupsByPersonId(String requestedPersonId, Parameters parameters) {
// Canonicalize the person ID, performing -me- alias substitution.
final String personId = people.validatePerson(requestedPersonId);
// Non-admins can only access their own data
// TODO: this is also in PeopleImpl.update(personId,personInfo) - refactor?
boolean isAdmin = authorityService.hasAdminAuthority();
String currentUserId = AuthenticationUtil.getFullyAuthenticatedUser();
if (!isAdmin && !currentUserId.equalsIgnoreCase(personId)) {
// The user is not an admin user and is not attempting to retrieve *their own* details.
throw new PermissionDeniedException();
}
Query q = parameters.getQuery();
Boolean isRootParam = null;
String zoneFilter = null;
if (q != null) {
GroupsQueryWalker propertyWalker = new GroupsQueryWalker();
QueryHelper.walk(q, propertyWalker);
isRootParam = propertyWalker.getIsRoot();
List<String> zonesParam = propertyWalker.getZones();
if (zonesParam != null) {
validateListParam(zonesParam, ZONE, MAX_ZONES);
zoneFilter = zonesParam.get(0);
}
}
final List<String> includeParam = parameters.getInclude();
Paging paging = parameters.getPaging();
// Retrieve sort column. This is limited for now to sort column due to
// v0 api implementation. Should be improved in the future.
Pair<String, Boolean> sortProp = getGroupsSortProp(parameters);
// Get all the authorities for a user, including but not limited to, groups.
Set<String> userAuthorities = runAsSystem(() -> authorityService.getAuthoritiesForUser(personId));
final Set<String> rootAuthorities = getAllRootAuthorities(AuthorityType.GROUP);
// Filter, transform and sort the list of user authorities into
// a suitable list of AuthorityInfo objects.
final String finalZoneFilter = zoneFilter;
final Boolean finalIsRootParam = isRootParam;
List<AuthorityInfo> groupAuthorities = userAuthorities.stream().filter(a -> a.startsWith(AuthorityType.GROUP.getPrefixString())).filter(a -> isRootPredicate(finalIsRootParam, rootAuthorities, a)).filter(a -> zonePredicate(a, finalZoneFilter)).map(this::getAuthorityInfo).sorted(new AuthorityInfoComparator(sortProp.getFirst(), sortProp.getSecond())).collect(Collectors.toList());
PagingResults<AuthorityInfo> pagingResult = Util.wrapPagingResults(paging, groupAuthorities);
// Create response.
final List<AuthorityInfo> page = pagingResult.getPage();
int totalItems = pagingResult.getTotalResultCount().getFirst();
// Transform the page of results into Group objects
List<Group> groups = page.stream().map(authority -> getGroup(authority, includeParam, rootAuthorities)).collect(Collectors.toList());
return CollectionWithPagingInfo.asPaged(paging, groups, pagingResult.hasMoreItems(), totalItems);
}
Aggregations