use of java.net.ProxySelector in project jdk8u_jdk by JetBrains.
the class B6563259 method main.
public static void main(String[] args) throws Exception {
System.setProperty("http.proxyHost", "myproxy");
System.setProperty("http.proxyPort", "8080");
System.setProperty("http.nonProxyHosts", "host1.*");
ProxySelector sel = ProxySelector.getDefault();
java.util.List<Proxy> l = sel.select(new URI("http://HOST1.sun.com/"));
if (l.get(0) != Proxy.NO_PROXY) {
throw new RuntimeException("ProxySelector returned the wrong proxy");
}
}
use of java.net.ProxySelector in project android_frameworks_base by crdroidandroid.
the class Proxy method getProxy.
/**
* Return the proxy object to be used for the URL given as parameter.
* @param ctx A Context used to get the settings for the proxy host.
* @param url A URL to be accessed. Used to evaluate exclusion list.
* @return Proxy (java.net) object containing the host name. If the
* user did not set a hostname it returns the default host.
* A null value means that no host is to be used.
* {@hide}
*/
public static final java.net.Proxy getProxy(Context ctx, String url) {
String host = "";
if ((url != null) && !isLocalHost(host)) {
URI uri = URI.create(url);
ProxySelector proxySelector = ProxySelector.getDefault();
List<java.net.Proxy> proxyList = proxySelector.select(uri);
if (proxyList.size() > 0) {
return proxyList.get(0);
}
}
return java.net.Proxy.NO_PROXY;
}
use of java.net.ProxySelector in project fabric8 by jboss-fuse.
the class DummyBatchingProgressMonitor method activateInternal.
private void activateInternal() throws Exception {
LOGGER.info("Starting up GitDataStore " + this);
// Call the bootstrap {@link DataStoreTemplate}
DataStoreTemplate template = runtimeProperties.get().removeRuntimeAttribute(DataStoreTemplate.class);
if (template != null) {
// Do the initial commit and set the root tag
Ref rootTag = getGit().getRepository().getRef(GitHelpers.ROOT_TAG);
if (rootTag == null) {
getGit().commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
getGit().tag().setName(GitHelpers.ROOT_TAG).setMessage("Tag the root commit").call();
}
LOGGER.debug("Running datastore bootstrap template: " + template);
template.doWith(this, dataStore.get());
}
// Setup proxy service
GitProxyService proxyService = gitProxyService.get();
defaultProxySelector = ProxySelector.getDefault();
// authenticator disabled, until properly tested it does not affect others, as Authenticator is static in the JVM
// Authenticator.setDefault(new FabricGitLocalHostAuthenticator(proxyService));
ProxySelector fabricProxySelector = new FabricGitLocalHostProxySelector(defaultProxySelector, proxyService);
ProxySelector.setDefault(fabricProxySelector);
LOGGER.debug("Setting up FabricProxySelector: {}", fabricProxySelector);
if (gitRemoteUrl != null) {
gitListener.runRemoteUrlChanged(gitRemoteUrl);
remoteUrl = gitRemoteUrl;
} else {
gitService.get().addGitListener(gitListener);
remoteUrl = gitService.get().getRemoteUrl();
if (remoteUrl != null) {
gitListener.runRemoteUrlChanged(remoteUrl);
}
}
// Get initial versions
getInitialVersions();
// poll logic in case of remote git repo
if (gitRemoteUrl != null) {
// i need this old logic in case of remote repos
LOGGER.info("Starting to pull from remote git repository every {} millis", gitRemotePollInterval);
threadPool.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
LockHandle writeLock = aquireWriteLock();
try {
LOGGER.trace("Performing timed pull");
doPullInternal();
LOGGER.debug("Performed timed pull from external git repo");
} catch (Throwable e) {
LOGGER.debug("Error during performed timed pull/push due " + e.getMessage(), e);
LOGGER.warn("Error during performed timed pull/push due " + e.getMessage() + ". This exception is ignored.");
} finally {
writeLock.unlock();
}
}
@Override
public String toString() {
return "TimedPushTask";
}
}, 1000, gitRemotePollInterval, TimeUnit.MILLISECONDS);
}
LOGGER.info("Using ZooKeeper SharedCount to react when master git repo is changed, so we can do a git pull to the local git repo.");
counter = new SharedCount(curator.get(), ZkPath.GIT_TRIGGER.getPath(), 0);
counter.addListener(new SharedCountListener() {
@Override
public void countHasChanged(final SharedCountReader sharedCountReader, final int value) throws Exception {
Runnable task = new Runnable() {
@Override
public void run() {
doPullInternal();
}
};
if (gitRandomFetchDelay == 0) {
LOGGER.debug("Watch counter updated to " + value + ", scheduling immediate pull");
threadPool.submit(task);
} else {
int delay = RND.nextInt(gitRandomFetchDelay) + 1;
LOGGER.debug("Watch counter updated to " + value + ", scheduling pull with random delay=" + delay + "s");
threadPool.schedule(task, delay, TimeUnit.SECONDS);
}
}
@Override
public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
switch(connectionState) {
case SUSPENDED:
case READ_ONLY:
case LOST:
// do nothing
break;
case CONNECTED:
case RECONNECTED:
LOGGER.info("Shared Counter (Re)connected, doing a pull");
doPullInternal();
break;
}
}
});
try {
counter.start();
} catch (KeeperException.NotReadOnlyException ex) {
// In read only mode the counter is not going to start.
// If the connection is reestablished the component will reactivate.
// We need to catch this error so that the component gets activated.
}
if (gitGcOnLoad) {
LockHandle writeLock = aquireWriteLock();
try {
GitOperation<Void> gitop = new GitOperation<Void>() {
public Void call(Git git, GitContext context) throws Exception {
long before = System.currentTimeMillis();
try {
git.gc().call();
LOGGER.debug("git gc took " + ((System.currentTimeMillis() - before)) + " ms.");
} catch (GitAPIException e) {
LOGGER.debug("git gc threw an exception!", e);
}
return null;
}
};
executeInternal(new GitContext(), null, gitop);
} finally {
writeLock.unlock();
}
}
// failing to activate the component
if (readWriteLock.isWriteLockedByCurrentThread() || readWriteLock.getWriteHoldCount() == 0) {
try {
// let's delegate to other thread in order to free MCF thread
// ENTESB-7843: there's a problem when jetty is configured with TLS and keystore location using
// profile: URI. while Jetty continues to be configured if profile:jetty.xml isn't available
// (and it isn't initially), it fails trying to access keystore via profile: URI.
// we should optimistically assume we can pull, but there's nothing wrong if we can't
// - we'll be able to pull later
threadPoolInitial.execute(new Runnable() {
@Override
public void run() {
doPullInternal(5);
}
});
} catch (IllegalStateException e) {
LOGGER.info("Another thread acquired write lock and GitDataStore can't pull from remote repository.");
}
} else {
LOGGER.info("Another thread is keeping git write lock. GitDataStore will continue activation.");
}
}
use of java.net.ProxySelector in project keystore-explorer by kaikramer.
the class PacProxySelector method loadPacScript.
private String loadPacScript(String pacUrl) throws PacProxyException {
URLConnection connection = null;
// Save existing default proxy selector...
ProxySelector defaultProxySelector = ProxySelector.getDefault();
try {
// ...and set use of no proxy selector. We don't want to try and use any proxy to get the the pac script
ProxySelector.setDefault(new NoProxySelector());
URL latestVersionUrl = new URL(pacUrl);
connection = latestVersionUrl.openConnection();
try (InputStreamReader isr = new InputStreamReader(connection.getInputStream());
StringWriter sw = new StringWriter()) {
CopyUtil.copy(isr, sw);
return sw.toString();
}
} catch (IOException ex) {
throw new PacProxyException(MessageFormat.format(res.getString("NoLoadPacScript.exception.message"), pacUrl), ex);
} finally {
// Restore saved default proxy selector
ProxySelector.setDefault(defaultProxySelector);
if ((connection != null) && (connection instanceof HttpURLConnection)) {
((HttpURLConnection) connection).disconnect();
}
}
}
use of java.net.ProxySelector 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;
}
Aggregations