Search in sources :

Example 16 with Authenticator

use of java.net.Authenticator in project maven-plugins by apache.

the class ProjectInfoReportUtils method getContent.

/**
     * Get the input stream from a URL.
     *
     * @param url not null
     * @param project could be null
     * @param settings not null to handle proxy settings
     * @param encoding the wanted encoding for the URL input stream. If null, UTF-8 will be used.
     * @return the input stream decoded with the wanted encoding as string
     * @throws IOException if any
     * @since 2.3
     */
public static String getContent(URL url, MavenProject project, Settings settings, String encoding) throws IOException {
    String scheme = url.getProtocol();
    if (StringUtils.isEmpty(encoding)) {
        encoding = DEFAULT_ENCODING;
    }
    if ("file".equals(scheme)) {
        InputStream in = null;
        try {
            URLConnection conn = url.openConnection();
            in = conn.getInputStream();
            final String content = IOUtil.toString(in, encoding);
            in.close();
            in = null;
            return content;
        } finally {
            IOUtil.close(in);
        }
    }
    Proxy proxy = settings.getActiveProxy();
    if (proxy != null) {
        if ("http".equals(scheme) || "https".equals(scheme) || "ftp".equals(scheme)) {
            scheme += ".";
        } else {
            scheme = "";
        }
        String host = proxy.getHost();
        if (!StringUtils.isEmpty(host)) {
            Properties p = System.getProperties();
            p.setProperty(scheme + "proxySet", "true");
            p.setProperty(scheme + "proxyHost", host);
            p.setProperty(scheme + "proxyPort", String.valueOf(proxy.getPort()));
            if (!StringUtils.isEmpty(proxy.getNonProxyHosts())) {
                p.setProperty(scheme + "nonProxyHosts", proxy.getNonProxyHosts());
            }
            final String userName = proxy.getUsername();
            if (!StringUtils.isEmpty(userName)) {
                final String pwd = StringUtils.isEmpty(proxy.getPassword()) ? "" : proxy.getPassword();
                Authenticator.setDefault(new Authenticator() {

                    /** {@inheritDoc} */
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(userName, pwd.toCharArray());
                    }
                });
            }
        }
    }
    InputStream in = null;
    try {
        URLConnection conn = getURLConnection(url, project, settings);
        in = conn.getInputStream();
        final String string = IOUtil.toString(in, encoding);
        in.close();
        in = null;
        return string;
    } finally {
        IOUtil.close(in);
    }
}
Also used : Proxy(org.apache.maven.settings.Proxy) InputStream(java.io.InputStream) Properties(java.util.Properties) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Example 17 with Authenticator

use of java.net.Authenticator in project tdi-studio-se by Talend.

the class SforceBasicBulkConnection method setProxyToConnection.

private void setProxyToConnection(ConnectorConfig conn) {
    Proxy socketProxy = null;
    if (!useProxy) {
        proxyHost = System.getProperty("https.proxyHost");
        if (proxyHost != null && System.getProperty("https.proxyPort") != null) {
            proxyPort = Integer.parseInt(System.getProperty("https.proxyPort"));
            proxyUsername = System.getProperty("https.proxyUser");
            proxyPassword = System.getProperty("https.proxyPassword");
            useProxy = true;
        } else {
            proxyHost = System.getProperty("http.proxyHost");
            if (proxyHost != null && System.getProperty("http.proxyPort") != null) {
                proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
                proxyUsername = System.getProperty("http.proxyUser");
                proxyPassword = System.getProperty("http.proxyPassword");
                useProxy = true;
            } else {
                proxyHost = System.getProperty("socksProxyHost");
                if (proxyHost != null && System.getProperty("socksProxyPort") != null) {
                    proxyPort = Integer.parseInt(System.getProperty("socksProxyPort"));
                    proxyUsername = System.getProperty("java.net.socks.username");
                    proxyPassword = System.getProperty("java.net.socks.password");
                    useProxy = true;
                    SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort);
                    socketProxy = new Proxy(Proxy.Type.SOCKS, addr);
                }
            }
        }
    }
    if (useProxy) {
        if (socketProxy != null) {
            conn.setProxy(socketProxy);
        } else {
            conn.setProxy(proxyHost, proxyPort);
        }
        if (proxyUsername != null && !"".equals(proxyUsername)) {
            conn.setProxyUsername(proxyUsername);
            if (proxyPassword != null && !"".equals(proxyPassword)) {
                conn.setProxyPassword(proxyPassword);
                Authenticator.setDefault(new Authenticator() {

                    @Override
                    public PasswordAuthentication getPasswordAuthentication() {
                        if (getRequestorType() == Authenticator.RequestorType.PROXY) {
                            return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray());
                        } else {
                            return super.getPasswordAuthentication();
                        }
                    }
                });
            }
        }
    }
}
Also used : Proxy(java.net.Proxy) InetSocketAddress(java.net.InetSocketAddress) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Example 18 with Authenticator

use of java.net.Authenticator in project GeoGig by boundlessgeo.

the class RemoteUtils method newRemote.

/**
     * Constructs an interface to allow access to a remote repository.
     * 
     * @param injector a Guice injector for the new repository
     * @param remoteConfig the remote to connect to
     * @param localRepository the local repository
     * @return an {@link Optional} of the interface to the remote repository, or
     *         {@link Optional#absent()} if a connection to the remote could not be established.
     */
public static Optional<IRemoteRepo> newRemote(Context injector, Remote remoteConfig, Repository localRepository, DeduplicationService deduplicationService) {
    try {
        URI fetchURI = URI.create(remoteConfig.getFetchURL());
        String protocol = fetchURI.getScheme();
        IRemoteRepo remoteRepo = null;
        if (protocol == null || protocol.equals("file")) {
            String filepath = new URL(remoteConfig.getFetchURL()).getFile();
            filepath = URLDecoder.decode(filepath, Charsets.UTF_8.displayName());
            if (remoteConfig.getMapped()) {
                remoteRepo = new LocalMappedRemoteRepo(injector, new File(filepath), localRepository);
            } else {
                remoteRepo = new LocalRemoteRepo(injector, new File(filepath), localRepository);
            }
        } else if (protocol.equals("http") || protocol.equals("https")) {
            final String username = remoteConfig.getUserName();
            final String password = remoteConfig.getPassword();
            if (username != null && password != null) {
                Authenticator.setDefault(new Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, Remote.decryptPassword(password).toCharArray());
                    }
                });
            } else {
                Authenticator.setDefault(null);
            }
            if (remoteConfig.getMapped()) {
                remoteRepo = new HttpMappedRemoteRepo(fetchURI.toURL(), localRepository);
            } else {
                remoteRepo = new HttpRemoteRepo(fetchURI.toURL(), localRepository, deduplicationService);
            }
        } else {
            throw new UnsupportedOperationException("Only file and http remotes are currently supported.");
        }
        return Optional.fromNullable(remoteRepo);
    } catch (Exception e) {
        // Invalid fetch URL
        Throwables.propagate(e);
    }
    return Optional.absent();
}
Also used : URI(java.net.URI) URL(java.net.URL) File(java.io.File) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Example 19 with Authenticator

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

the class AgentLauncher method main.

/**
 * @param args Args.
 */
public static void main(String[] args) throws Exception {
    log.info("Starting Apache Ignite Web Console Agent...");
    final AgentConfiguration cfg = new AgentConfiguration();
    JCommander jCommander = new JCommander(cfg);
    String osName = System.getProperty("os.name").toLowerCase();
    jCommander.setProgramName("ignite-web-agent." + (osName.contains("win") ? "bat" : "sh"));
    try {
        jCommander.parse(args);
    } catch (ParameterException pe) {
        log.error("Failed to parse command line parameters: " + Arrays.toString(args), pe);
        jCommander.usage();
        return;
    }
    String prop = cfg.configPath();
    AgentConfiguration propCfg = new AgentConfiguration();
    try {
        File f = AgentUtils.resolvePath(prop);
        if (f == null)
            log.warn("Failed to find agent property file: {}", prop);
        else
            propCfg.load(f.toURI().toURL());
    } catch (IOException e) {
        if (!AgentConfiguration.DFLT_CFG_PATH.equals(prop))
            log.warn("Failed to load agent property file: " + prop, e);
    }
    cfg.merge(propCfg);
    if (cfg.help()) {
        jCommander.usage();
        return;
    }
    System.out.println();
    System.out.println("Agent configuration:");
    System.out.println(cfg);
    System.out.println();
    if (cfg.tokens() == null) {
        String webHost;
        try {
            webHost = new URI(cfg.serverUri()).getHost();
        } catch (URISyntaxException e) {
            log.error("Failed to parse Ignite Web Console uri", e);
            return;
        }
        System.out.println("Security token is required to establish connection to the web console.");
        System.out.println(String.format("It is available on the Profile page: https://%s/profile", webHost));
        String tokens = String.valueOf(readPassword("Enter security tokens separated by comma: "));
        cfg.tokens(Arrays.asList(tokens.trim().split(",")));
    }
    URI uri = URI.create(cfg.serverUri());
    // Create proxy authenticator using passed properties.
    switch(uri.getScheme()) {
        case "http":
        case "https":
            final String username = System.getProperty(uri.getScheme() + ".proxyUsername");
            final char[] pwd = System.getProperty(uri.getScheme() + ".proxyPassword", "").toCharArray();
            Authenticator.setDefault(new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, pwd);
                }
            });
            break;
        default:
    }
    IO.Options opts = new IO.Options();
    opts.path = "/agents";
    // Workaround for use self-signed certificate
    if (Boolean.getBoolean("trust.all")) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        // Create an SSLContext that uses our TrustManager
        ctx.init(null, getTrustManagers(), null);
        opts.sslContext = ctx;
    }
    final Socket client = IO.socket(uri, opts);
    final RestExecutor restExecutor = new RestExecutor(cfg.nodeUri());
    try {
        final ClusterListener clusterLsnr = new ClusterListener(client, restExecutor);
        final DemoListener demoHnd = new DemoListener(client, restExecutor);
        Emitter.Listener onConnect = new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                log.info("Connection established.");
                JSONObject authMsg = new JSONObject();
                try {
                    authMsg.put("tokens", toJSON(cfg.tokens()));
                    authMsg.put("disableDemo", cfg.disableDemo());
                    String clsName = AgentLauncher.class.getSimpleName() + ".class";
                    String clsPath = AgentLauncher.class.getResource(clsName).toString();
                    if (clsPath.startsWith("jar")) {
                        String manifestPath = clsPath.substring(0, clsPath.lastIndexOf('!') + 1) + "/META-INF/MANIFEST.MF";
                        Manifest manifest = new Manifest(new URL(manifestPath).openStream());
                        Attributes attr = manifest.getMainAttributes();
                        authMsg.put("ver", attr.getValue("Implementation-Version"));
                        authMsg.put("bt", attr.getValue("Build-Time"));
                    }
                    client.emit("agent:auth", authMsg, new Ack() {

                        @Override
                        public void call(Object... args) {
                            if (args != null) {
                                if (args[0] instanceof String) {
                                    log.error((String) args[0]);
                                    System.exit(1);
                                }
                                if (args[0] == null && args[1] instanceof JSONArray) {
                                    try {
                                        List<String> activeTokens = fromJSON(args[1], List.class);
                                        if (!F.isEmpty(activeTokens)) {
                                            Collection<String> missedTokens = cfg.tokens();
                                            cfg.tokens(activeTokens);
                                            missedTokens.removeAll(activeTokens);
                                            if (!F.isEmpty(missedTokens)) {
                                                String tokens = F.concat(missedTokens, ", ");
                                                log.warn("Failed to authenticate with token(s): {}. " + "Please reload agent archive or check settings", tokens);
                                            }
                                            log.info("Authentication success.");
                                            clusterLsnr.watch();
                                            return;
                                        }
                                    } catch (Exception e) {
                                        log.error("Failed to authenticate agent. Please check agent\'s tokens", e);
                                        System.exit(1);
                                    }
                                }
                            }
                            log.error("Failed to authenticate agent. Please check agent\'s tokens");
                            System.exit(1);
                        }
                    });
                } catch (JSONException | IOException e) {
                    log.error("Failed to construct authentication message", e);
                    client.close();
                }
            }
        };
        DatabaseListener dbHnd = new DatabaseListener(cfg);
        RestListener restHnd = new RestListener(restExecutor);
        final CountDownLatch latch = new CountDownLatch(1);
        log.info("Connecting to: {}", cfg.serverUri());
        client.on(EVENT_CONNECT, onConnect).on(EVENT_CONNECT_ERROR, onError).on(EVENT_ERROR, onError).on(EVENT_DISCONNECT, onDisconnect).on(EVENT_LOG_WARNING, onLogWarning).on(EVENT_CLUSTER_BROADCAST_START, clusterLsnr.start()).on(EVENT_CLUSTER_BROADCAST_STOP, clusterLsnr.stop()).on(EVENT_DEMO_BROADCAST_START, demoHnd.start()).on(EVENT_DEMO_BROADCAST_STOP, demoHnd.stop()).on(EVENT_RESET_TOKENS, new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                String tok = String.valueOf(args[0]);
                log.warn("Security token has been reset: {}", tok);
                cfg.tokens().remove(tok);
                if (cfg.tokens().isEmpty()) {
                    client.off();
                    latch.countDown();
                }
            }
        }).on(EVENT_SCHEMA_IMPORT_DRIVERS, dbHnd.availableDriversListener()).on(EVENT_SCHEMA_IMPORT_SCHEMAS, dbHnd.schemasListener()).on(EVENT_SCHEMA_IMPORT_METADATA, dbHnd.metadataListener()).on(EVENT_NODE_VISOR_TASK, restHnd).on(EVENT_NODE_REST, restHnd);
        client.connect();
        latch.await();
    } finally {
        restExecutor.stop();
        client.close();
    }
}
Also used : Emitter(io.socket.emitter.Emitter) DemoListener(org.apache.ignite.console.agent.handlers.DemoListener) ClusterListener(org.apache.ignite.console.agent.handlers.ClusterListener) RestListener(org.apache.ignite.console.agent.handlers.RestListener) DatabaseListener(org.apache.ignite.console.agent.handlers.DatabaseListener) Attributes(java.util.jar.Attributes) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL) JCommander(com.beust.jcommander.JCommander) ParameterException(com.beust.jcommander.ParameterException) List(java.util.List) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication) DemoListener(org.apache.ignite.console.agent.handlers.DemoListener) IO(io.socket.client.IO) RestExecutor(org.apache.ignite.console.agent.rest.RestExecutor) Ack(io.socket.client.Ack) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IOException(java.io.IOException) SSLContext(javax.net.ssl.SSLContext) DatabaseListener(org.apache.ignite.console.agent.handlers.DatabaseListener) Manifest(java.util.jar.Manifest) CountDownLatch(java.util.concurrent.CountDownLatch) ParameterException(com.beust.jcommander.ParameterException) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) ConnectException(java.net.ConnectException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) RestListener(org.apache.ignite.console.agent.handlers.RestListener) JSONObject(org.json.JSONObject) ClusterListener(org.apache.ignite.console.agent.handlers.ClusterListener) Collection(java.util.Collection) JSONObject(org.json.JSONObject) File(java.io.File) Socket(io.socket.client.Socket)

Example 20 with Authenticator

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

the class AbstractCodegenMoho method configureProxyServerSettings.

protected void configureProxyServerSettings() throws MojoExecutionException {
    Proxy proxy = mavenSession.getSettings().getActiveProxy();
    if (proxy != null) {
        getLog().info("Using proxy server configured in maven.");
        if (proxy.getHost() == null) {
            throw new MojoExecutionException("Proxy in settings.xml has no host");
        }
        if (proxy.getHost() != null) {
            System.setProperty(HTTP_PROXY_HOST, proxy.getHost());
        }
        if (String.valueOf(proxy.getPort()) != null) {
            System.setProperty(HTTP_PROXY_PORT, String.valueOf(proxy.getPort()));
        }
        if (proxy.getNonProxyHosts() != null) {
            System.setProperty(HTTP_NON_PROXY_HOSTS, proxy.getNonProxyHosts());
        }
        if (!StringUtils.isEmpty(proxy.getUsername()) && !StringUtils.isEmpty(proxy.getPassword())) {
            final String authUser = proxy.getUsername();
            final String authPassword = proxy.getPassword();
            Authenticator.setDefault(new Authenticator() {

                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(authUser, authPassword.toCharArray());
                }
            });
            System.setProperty(HTTP_PROXY_USER, authUser);
            System.setProperty(HTTP_PROXY_PORT, authPassword);
        }
    }
}
Also used : Proxy(org.apache.maven.settings.Proxy) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Aggregations

Authenticator (java.net.Authenticator)24 PasswordAuthentication (java.net.PasswordAuthentication)18 URL (java.net.URL)6 InetSocketAddress (java.net.InetSocketAddress)5 Proxy (java.net.Proxy)5 ArrayList (java.util.ArrayList)4 IOException (java.io.IOException)3 Field (java.lang.reflect.Field)3 ServerSocket (java.net.ServerSocket)3 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)3 Test (org.junit.Test)3 File (java.io.File)2 InputStream (java.io.InputStream)2 Method (java.lang.reflect.Method)2 InetAddress (java.net.InetAddress)2 URI (java.net.URI)2 List (java.util.List)2 Properties (java.util.Properties)2 SSLServerSocket (javax.net.ssl.SSLServerSocket)2 SSLSocket (javax.net.ssl.SSLSocket)2