Search in sources :

Example 51 with Authenticator

use of java.net.Authenticator in project java by wavefrontHQ.

the class AbstractAgent method start.

/**
 * Entry-point for the application.
 *
 * @param args Command-line parameters passed on to JCommander to configure the daemon.
 */
public void start(String[] args) throws IOException {
    try {
        // read build information and print version.
        props = ResourceBundle.getBundle("build");
        logger.info("Starting proxy version " + props.getString("build.version"));
        logger.info("Arguments: " + Joiner.on(", ").join(args));
        JCommander jCommander = new JCommander(this, args);
        if (help) {
            jCommander.setProgramName(this.getClass().getCanonicalName());
            jCommander.usage();
            System.exit(0);
        }
        if (unparsed_params != null) {
            logger.info("Unparsed arguments: " + Joiner.on(", ").join(unparsed_params));
        }
        /* ------------------------------------------------------------------------------------
       * Configuration Setup.
       * ------------------------------------------------------------------------------------ */
        // 1. Load the listener configurations.
        loadListenerConfigurationFile();
        loadLogsIngestionConfig();
        managedExecutors.add(agentConfigurationExecutor);
        // Conditionally enter an interactive debugging session for logsIngestionConfig.yaml
        if (testLogs) {
            InteractiveLogsTester interactiveLogsTester = new InteractiveLogsTester(this::loadLogsIngestionConfig, prefix);
            logger.info("Reading line-by-line sample log messages from STDIN");
            while (interactiveLogsTester.interactiveTest()) {
            // empty
            }
            System.exit(0);
        }
        // 2. Read or create the unique Id for the daemon running on this machine.
        readOrCreateDaemonId();
        if (proxyHost != null) {
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", String.valueOf(proxyPort));
            System.setProperty("https.proxyPort", String.valueOf(proxyPort));
        }
        if (proxyUser != null && proxyPassword != null) {
            Authenticator.setDefault(new Authenticator() {

                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    if (getRequestorType() == RequestorType.PROXY) {
                        return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
                    } else {
                        return null;
                    }
                }
            });
        }
        // create List of custom tags from the configuration string
        String[] tags = customSourceTagsProperty.split(",");
        for (String tag : tags) {
            tag = tag.trim();
            if (!customSourceTags.contains(tag)) {
                customSourceTags.add(tag);
            } else {
                logger.warning("Custom source tag: " + tag + " was repeated. Check the customSourceTags property in " + "wavefront.conf");
            }
        }
        // 3. Setup proxies.
        WavefrontAPI service = createAgentService();
        try {
            setupQueueing(service);
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Cannot setup local file for queueing due to IO error", e);
            throw e;
        }
        // 4. Start the (push) listening endpoints
        startListeners();
        // set up OoM memory guard
        if (memGuardFlushThreshold > 0) {
            setupMemoryGuard((float) memGuardFlushThreshold / 100);
        }
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                try {
                    // exit if no active listeners
                    if (activeListeners.count() == 0) {
                        logger.severe("**** All listener threads failed to start - there is already a running instance " + "listening on configured ports, or no listening ports configured!");
                        logger.severe("Aborting start-up");
                        System.exit(1);
                    }
                    // 5. Poll or read the configuration file to use.
                    AgentConfiguration config;
                    if (configFile != null) {
                        logger.info("Loading configuration file from: " + configFile);
                        try {
                            config = GSON.fromJson(new FileReader(configFile), AgentConfiguration.class);
                        } catch (FileNotFoundException e) {
                            throw new RuntimeException("Cannot read config file: " + configFile);
                        }
                        try {
                            config.validate(localAgent);
                        } catch (RuntimeException ex) {
                            logger.log(Level.SEVERE, "cannot parse config file", ex);
                            throw new RuntimeException("cannot parse config file", ex);
                        }
                        agentId = null;
                    } else {
                        updateAgentMetrics.run();
                        config = fetchConfig();
                        logger.info("scheduling regular configuration polls");
                        agentConfigurationExecutor.scheduleAtFixedRate(updateAgentMetrics, 10, 60, TimeUnit.SECONDS);
                        agentConfigurationExecutor.scheduleWithFixedDelay(updateConfiguration, 0, 1, TimeUnit.SECONDS);
                    }
                    // 6. Setup work units and targets based on the configuration.
                    if (config != null) {
                        logger.info("initial configuration is available, setting up proxy");
                        processConfiguration(config);
                    }
                    Runtime.getRuntime().addShutdownHook(new Thread("proxy-shutdown-hook") {

                        @Override
                        public void run() {
                            shutdown();
                        }
                    });
                    logger.info("setup complete");
                } catch (Throwable t) {
                    logger.log(Level.SEVERE, "Aborting start-up", t);
                    System.exit(1);
                }
            }
        }, 5000);
    } catch (Throwable t) {
        logger.log(Level.SEVERE, "Aborting start-up", t);
        System.exit(1);
    }
}
Also used : WavefrontAPI(com.wavefront.api.WavefrontAPI) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) InteractiveLogsTester(com.wavefront.agent.logsharvesting.InteractiveLogsTester) Timer(java.util.Timer) TimerTask(java.util.TimerTask) JCommander(com.beust.jcommander.JCommander) AgentConfiguration(com.wavefront.api.agent.AgentConfiguration) FileReader(java.io.FileReader) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Example 52 with Authenticator

use of java.net.Authenticator in project tomee by apache.

the class CXFAuthenticator method addAuthenticator.

public static synchronized void addAuthenticator() {
    if (instance == null) {
        instance = new CXFAuthenticator();
        Authenticator wrapped = null;
        if (JavaUtils.isJava9Compatible()) {
            try {
                Method m = ReflectionUtil.getMethod(Authenticator.class, "getDefault");
                wrapped = (Authenticator) m.invoke(null);
            } catch (Exception e) {
            // ignore
            }
        } else {
            for (final Field f : ReflectionUtil.getDeclaredFields(Authenticator.class)) {
                if (f.getType().equals(Authenticator.class)) {
                    ReflectionUtil.setAccessible(f);
                    try {
                        wrapped = (Authenticator) f.get(null);
                        if (wrapped != null && wrapped.getClass().getName().equals(ReferencingAuthenticator.class.getName())) {
                            Method m = wrapped.getClass().getMethod("check");
                            m.setAccessible(true);
                            m.invoke(wrapped);
                        }
                        wrapped = (Authenticator) f.get(null);
                    } catch (Exception e) {
                    // ignore
                    }
                }
            }
        }
        try {
            Class<?> cls;
            InputStream ins = ReferencingAuthenticator.class.getResourceAsStream("ReferencingAuthenticator.class");
            byte[] b = IOUtils.readBytesFromStream(ins);
            if (JavaUtils.isJava9Compatible()) {
                Class<?> methodHandles = Class.forName("java.lang.invoke.MethodHandles");
                Method m = ReflectionUtil.getMethod(methodHandles, "lookup");
                Object lookup = m.invoke(null);
                m = ReflectionUtil.getMethod(lookup.getClass(), "findClass", String.class);
                try {
                    cls = (Class<?>) m.invoke(lookup, "org.apache.cxf.transport.http.ReferencingAuthenticator");
                } catch (InvocationTargetException e) {
                    // use defineClass as fallback
                    m = ReflectionUtil.getMethod(lookup.getClass(), "defineClass", byte[].class);
                    cls = (Class<?>) m.invoke(lookup, b);
                }
            } else {
                ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {

                    public ClassLoader run() {
                        return new URLClassLoader(new URL[0], ClassLoader.getSystemClassLoader());
                    }
                }, null);
                Method m = ReflectionUtil.getDeclaredMethod(ClassLoader.class, "defineClass", String.class, byte[].class, Integer.TYPE, Integer.TYPE);
                ReflectionUtil.setAccessible(m).invoke(loader, ReferencingAuthenticator.class.getName(), b, 0, b.length);
                cls = loader.loadClass(ReferencingAuthenticator.class.getName());
                try {
                    // clear the acc field that can hold onto the webapp classloader
                    Field f = ReflectionUtil.getDeclaredField(loader.getClass(), "acc");
                    ReflectionUtil.setAccessible(f).set(loader, null);
                } catch (Throwable t) {
                // ignore
                }
            }
            final Authenticator auth = (Authenticator) cls.getConstructor(Authenticator.class, Authenticator.class).newInstance(instance, wrapped);
            if (System.getSecurityManager() == null) {
                Authenticator.setDefault(auth);
            } else {
                AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

                    public Boolean run() {
                        Authenticator.setDefault(auth);
                        return true;
                    }
                });
            }
        } catch (Throwable t) {
        // ignore
        }
    }
}
Also used : InputStream(java.io.InputStream) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) URL(java.net.URL) Field(java.lang.reflect.Field) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) Authenticator(java.net.Authenticator)

Example 53 with Authenticator

use of java.net.Authenticator in project tomee by apache.

the class ReferencingAuthenticator method check.

public final void check() {
    Authenticator cxfauth = auth.get();
    if (cxfauth == null) {
        remove();
    }
    if (wrapped != null && wrapped.getClass().getName().equals(ReferencingAuthenticator.class.getName())) {
        try {
            Method m = wrapped.getClass().getMethod("check");
            m.setAccessible(true);
            m.invoke(wrapped);
        } catch (Throwable t) {
        // ignore
        }
    }
}
Also used : Method(java.lang.reflect.Method) Authenticator(java.net.Authenticator)

Example 54 with Authenticator

use of java.net.Authenticator in project tomee by apache.

the class ReferencingAuthenticator method removeInternal.

private void removeInternal() {
    try {
        for (final Field f : Authenticator.class.getDeclaredFields()) {
            if (f.getType().equals(Authenticator.class)) {
                try {
                    f.setAccessible(true);
                    Authenticator o = (Authenticator) f.get(null);
                    if (o == this) {
                        // this is at the root of any chain of authenticators
                        Authenticator.setDefault(wrapped);
                    } else {
                        removeFromChain(o);
                    }
                } catch (Exception e) {
                // ignore
                }
            }
        }
    } catch (Throwable t) {
    // ignore
    }
}
Also used : Field(java.lang.reflect.Field) Authenticator(java.net.Authenticator)

Example 55 with Authenticator

use of java.net.Authenticator in project jena by apache.

the class RDFConnection method connectPW.

/**
 * Make a remote RDFConnection to the URL, with user and password for the client access using basic auth.
 *  Use with care &ndash; basic auth over plain HTTP reveals the password on the network.
 * @param URL
 * @param user
 * @param password
 * @return RDFConnection
 */
public static RDFConnection connectPW(String URL, String user, String password) {
    Objects.requireNonNull(URL);
    Objects.requireNonNull(user);
    Objects.requireNonNull(password);
    // Authenticator to hold user and password.
    Authenticator authenticator = LibSec.authenticator(user, password);
    HttpClient client = HttpEnv.httpClientBuilder().authenticator(authenticator).build();
    return RDFConnectionRemote.newBuilder().destination(URL).httpClient(client).build();
}
Also used : HttpClient(java.net.http.HttpClient) Authenticator(java.net.Authenticator)

Aggregations

Authenticator (java.net.Authenticator)80 PasswordAuthentication (java.net.PasswordAuthentication)50 URL (java.net.URL)18 Proxy (java.net.Proxy)14 InetSocketAddress (java.net.InetSocketAddress)12 HttpClient (java.net.http.HttpClient)11 Field (java.lang.reflect.Field)10 HttpURLConnection (java.net.HttpURLConnection)10 IOException (java.io.IOException)9 Test (org.junit.Test)7 Method (java.lang.reflect.Method)6 File (java.io.File)5 SocketAddress (java.net.SocketAddress)5 InputStream (java.io.InputStream)4 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ArrayList (java.util.ArrayList)3 Content (org.sonatype.goodies.httpfixture.server.jetty.behaviour.Content)3 Debug (org.sonatype.goodies.httpfixture.server.jetty.behaviour.Debug)3 JCommander (com.beust.jcommander.JCommander)2