Example usage for java.net Authenticator setDefault

List of usage examples for java.net Authenticator setDefault

Introduction

In this page you can find the example usage for java.net Authenticator setDefault.

Prototype

public static synchronized void setDefault(Authenticator a) 

Source Link

Document

Sets the authenticator that will be used by the networking code when a proxy or an HTTP server asks for authentication.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Authenticator.setDefault(new MyAuthenticator());
    URL url = new URL("http://hostname:80/index.html");

    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String str;/*w w  w .j a v  a 2 s.c  om*/
    while ((str = in.readLine()) != null) {
        System.out.println(str);
    }
    in.close();
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {

    Authenticator.setDefault(new DialogAuthenticator());

    URL u = new URL("secure url");
    InputStream in = u.openStream();
    in = new BufferedInputStream(in);
    Reader r = new InputStreamReader(in);
    int c;/*www .j  ava  2 s .c  o  m*/
    while ((c = r.read()) != -1) {
        System.out.print((char) c);
    }
}

From source file:AuthDemo.java

public static void main(String args[]) throws MalformedURLException, IOException {
    String urlString = "";
    String username = "";
    String password = "";
    Authenticator.setDefault(new MyAuthenticator(username, password));
    URL url = new URL(urlString);
    InputStream content = (InputStream) url.getContent();
    BufferedReader in = new BufferedReader(new InputStreamReader(content));
    String line;/*from  www. j  av a2 s .  c  om*/
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
    System.out.println("Done.");
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    byte[] b = new byte[1];
    Properties systemSettings = System.getProperties();
    systemSettings.put("http.proxyHost", "proxy.mydomain.local");
    systemSettings.put("http.proxyPort", "80");

    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("mydomain\\username", "password".toCharArray());
        }/*w w  w .  java 2 s  .co m*/
    });

    URL u = new URL("http://www.google.com");
    HttpURLConnection con = (HttpURLConnection) u.openConnection();
    DataInputStream di = new DataInputStream(con.getInputStream());
    while (-1 != di.read(b, 0, 1)) {
        System.out.print(new String(b));
    }
}

From source file:com.ednardo.loteca.WelcomeController.java

public static void main(String[] args) {
    Authenticator.setDefault(new Authenticator() {
        @Override//from  w  w w . j ava2 s . c o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("user", "password".toCharArray());
        }
    });
}

From source file:com.hortonworks.registries.storage.tool.sql.DatabaseUserInitializer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH)
            .desc("Mysql client jar url to download").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_JDBC_URL)
            .desc("JDBC url to connect DBMS via admin.").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_DB_USER)
            .desc("Admin user name: should be able to create and grant privileges.").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_PASSWORD)
            .desc("Admin user's password: should be able to create and grant privileges.").build());

    options.addOption(//from  w  w w . j a  v  a  2s. c o m
            Option.builder().hasArg().longOpt(OPTION_TARGET_USER).desc("Name of target user.").build());

    options.addOption(
            Option.builder().hasArg().longOpt(OPTION_TARGET_PASSWORD).desc("Password of target user.").build());

    options.addOption(
            Option.builder().hasArg().longOpt(OPTION_TARGET_DATABASE).desc("Target database.").build());

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    String[] neededOptions = { OPTION_CONFIG_FILE_PATH, OPTION_MYSQL_JAR_URL_PATH, OPTION_ADMIN_JDBC_URL,
            OPTION_ADMIN_DB_USER, OPTION_ADMIN_PASSWORD, OPTION_TARGET_USER, OPTION_TARGET_PASSWORD,
            OPTION_TARGET_DATABASE };

    boolean optNotFound = Arrays.stream(neededOptions).anyMatch(opt -> !commandLine.hasOption(opt));
    if (optNotFound) {
        usage(options);
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    Optional<AdminOptions> adminOptionsOptional = AdminOptions.from(commandLine);
    if (!adminOptionsOptional.isPresent()) {
        usage(options);
        System.exit(1);
    }

    AdminOptions adminOptions = adminOptionsOptional.get();

    Optional<TargetOptions> targetOptionsOptional = TargetOptions.from(commandLine);
    if (!targetOptionsOptional.isPresent()) {
        usage(options);
        System.exit(1);
    }

    TargetOptions targetOptions = targetOptionsOptional.get();

    DatabaseType databaseType = findDatabaseType(adminOptions.getJdbcUrl());

    Map<String, Object> conf;
    try {
        conf = Utils.readConfig(confFilePath);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    String bootstrapDirPath = null;
    try {
        bootstrapDirPath = System.getProperty("bootstrap.dir");
        Proxy proxy = Proxy.NO_PROXY;
        String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL);
        String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME);
        String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD);
        if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) {
            URL url = new URL(httpProxyUrl);
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort()));
            if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) {
                Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername,
                        httpProxyPassword));
            }
        }

        StorageProviderConfiguration storageProperties = StorageProviderConfiguration.get(
                adminOptions.getJdbcUrl(), adminOptions.getUsername(), adminOptions.getPassword(),
                adminOptions.getDatabaseType());

        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy);
    } catch (Exception e) {
        System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    try (Connection conn = getConnectionViaAdmin(adminOptions)) {
        DatabaseCreator databaseCreator = DatabaseCreatorFactory.newInstance(adminOptions.getDatabaseType(),
                conn);
        UserCreator userCreator = UserCreatorFactory.newInstance(adminOptions.getDatabaseType(), conn);

        String database = targetOptions.getDatabase();
        String username = targetOptions.getUsername();

        createDatabase(databaseCreator, database);
        createUser(targetOptions, userCreator, username);
        grantPrivileges(databaseCreator, database, username);
    }
}

From source file:pt.ua.tm.neji.web.cli.WebMain.java

public static void main(String[] args) {

    // Set JSP to use Standard JavaC always
    System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption("h", "help", false, "Print this usage information.");
    options.addOption("v", "verbose", false, "Verbose mode.");
    options.addOption("d", "dictionaires", true, "Folder that contains the dictionaries.");
    options.addOption("m", "models", true, "Folder that contains the ML models.");

    options.addOption("port", "port", true, "Server port.");
    options.addOption("c", "configuration", true, "Configuration properties file.");

    options.addOption("t", "threads", true,
            "Number of threads. By default, if more than one core is available, it is the number of cores minus 1.");

    CommandLine commandLine;/*from w  ww .j av  a2  s.c  o m*/
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(150, "./nejiWeb.sh " + USAGE, HEADER, options, FOOTER);
        return;
    }

    // Get threads
    int numThreads = Runtime.getRuntime().availableProcessors() - 1;
    numThreads = numThreads > 0 ? numThreads : 1;
    if (commandLine.hasOption('t')) {
        String threadsText = commandLine.getOptionValue('t');
        numThreads = Integer.parseInt(threadsText);
        if (numThreads <= 0 || numThreads > 32) {
            logger.error("Illegal number of threads. Must be between 1 and 32.");
            return;
        }
    }

    // Get port
    int port = 8010;
    if (commandLine.hasOption("port")) {
        String portString = commandLine.getOptionValue("port");
        port = Integer.parseInt(portString);
    }

    // Get configuration
    String configurationFile = null;
    Properties configurationProperties = null;
    if (commandLine.hasOption("configuration")) {
        configurationFile = commandLine.getOptionValue("configuration");
        try {
            configurationProperties = new Properties();
            configurationProperties.load(new FileInputStream(configurationFile));
        } catch (IOException e) {
            configurationProperties = null;
        }
    }
    if (configurationProperties != null && !configurationProperties.isEmpty()) {
        ServerConfiguration.initialize(configurationProperties);
    } else {
        ServerConfiguration.initialize();
    }

    // Set system proxy
    if (!ServerConfiguration.getInstance().getProxyURL().isEmpty()
            && !ServerConfiguration.getInstance().getProxyPort().isEmpty()) {
        System.setProperty("https.proxyHost", ServerConfiguration.getInstance().getProxyURL());
        System.setProperty("https.proxyPort", ServerConfiguration.getInstance().getProxyPort());
        System.setProperty("http.proxyHost", ServerConfiguration.getInstance().getProxyURL());
        System.setProperty("http.proxyPort", ServerConfiguration.getInstance().getProxyPort());

        if (!ServerConfiguration.getInstance().getProxyUsername().isEmpty()) {
            final String proxyUser = ServerConfiguration.getInstance().getProxyUsername();
            final String proxyPassword = ServerConfiguration.getInstance().getProxyPassword();
            System.setProperty("https.proxyUser", proxyUser);
            System.setProperty("https.proxyPassword", proxyPassword);
            System.setProperty("http.proxyUser", proxyUser);
            System.setProperty("http.proxyPassword", proxyPassword);
            Authenticator.setDefault(new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
                }
            });
        }
    }

    // Get verbose mode
    boolean verbose = commandLine.hasOption('v');
    Constants.verbose = verbose;

    if (Constants.verbose) {
        MalletLogger.getGlobal().setLevel(Level.INFO);
        // Redirect sout
        LoggingOutputStream los = new LoggingOutputStream(LoggerFactory.getLogger("stdout"), false);
        System.setOut(new PrintStream(los, true));

        // Redirect serr
        los = new LoggingOutputStream(LoggerFactory.getLogger("sterr"), true);
        System.setErr(new PrintStream(los, true));
    } else {
        MalletLogger.getGlobal().setLevel(Level.OFF);
    }

    // Get dictionaries folder
    String dictionariesFolder = null;
    if (commandLine.hasOption('d')) {
        dictionariesFolder = commandLine.getOptionValue('d');

        File test = new File(dictionariesFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified dictionaries path is not a folder or is not readable.");
            return;
        }
        dictionariesFolder = test.getAbsolutePath();
        dictionariesFolder += File.separator;
    }

    // Get models folder
    String modelsFolder = null;
    if (commandLine.hasOption('m')) {
        modelsFolder = commandLine.getOptionValue('m');

        File test = new File(modelsFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified models path is not a folder or is not readable.");
            return;
        }
        modelsFolder = test.getAbsolutePath();
        modelsFolder += File.separator;
    }

    // Redirect JUL to SLF4
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();

    // Output formats (All)
    List<OutputFormat> outputFormats = new ArrayList<>();
    outputFormats.add(OutputFormat.A1);
    outputFormats.add(OutputFormat.B64);
    outputFormats.add(OutputFormat.BC2);
    outputFormats.add(OutputFormat.BIOC);
    outputFormats.add(OutputFormat.CONLL);
    outputFormats.add(OutputFormat.JSON);
    outputFormats.add(OutputFormat.NEJI);
    outputFormats.add(OutputFormat.PIPE);
    outputFormats.add(OutputFormat.PIPEXT);
    outputFormats.add(OutputFormat.XML);

    // Context is built through a descriptor first, so that the pipeline can be validated before any processing
    ContextConfiguration descriptor = null;
    try {
        descriptor = new ContextConfiguration.Builder().withInputFormat(InputFormat.RAW) // HARDCODED
                .withOutputFormats(outputFormats).withParserTool(ParserTool.GDEP)
                .withParserLanguage(ParserLanguage.ENGLISH).withParserLevel(ParserLevel.CHUNKING).build();

    } catch (NejiException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    // Create resources dirs if they don't exist
    try {
        File dictionariesDir = new File(DICTIONARIES_PATH);
        File modelsDir = new File(MODELS_PATH);
        if (!dictionariesDir.exists()) {
            dictionariesDir.mkdirs();
            (new File(dictionariesDir, "_priority")).createNewFile();
        }
        if (!modelsDir.exists()) {
            modelsDir.mkdirs();
            (new File(modelsDir, "_priority")).createNewFile();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    // Contenxt
    Context context = new Context(descriptor, MODELS_PATH, DICTIONARIES_PATH);

    // Start server
    try {
        Server server = Server.getInstance();
        server.initialize(context, port, numThreads);

        server.start();
        logger.info("Server started at localhost:{}", port);
        logger.info("Press Cmd-C / Ctrl+C to shutdown the server...");

        server.join();

    } catch (Exception ex) {
        ex.printStackTrace();
        logger.info("Shutting down the server...");
    }
}

From source file:com.hortonworks.registries.storage.tool.sql.TablesInitializer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH)
            .desc("Root directory of script path").build());

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH)
            .desc("Mysql client jar url to download").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.CREATE.toString())
            .desc("Run sql migrations from scatch").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.DROP.toString())
            .desc("Drop all the tables in the target database").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.CHECK_CONNECTION.toString())
            .desc("Check the connection for configured data source").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.MIGRATE.toString())
            .desc("Execute schema migration from last check point").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.INFO.toString())
            .desc("Show the status of the schema migration compared to the target database").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.VALIDATE.toString())
            .desc("Validate the target database changes with the migration scripts").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.REPAIR.toString()).desc(
            "Repairs the DATABASE_CHANGE_LOG by removing failed migrations and correcting checksum of existing migration script")
            .build());//from   w w  w  . jav  a  2 s .co  m

    options.addOption(Option.builder().hasArg(false).longOpt(DISABLE_VALIDATE_ON_MIGRATE)
            .desc("Disable flyway validation checks while running migrate").build());

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    if (!commandLine.hasOption(OPTION_CONFIG_FILE_PATH) || !commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) {
        usage(options);
        System.exit(1);
    }

    boolean isSchemaMigrationOptionSpecified = false;
    SchemaMigrationOption schemaMigrationOptionSpecified = null;
    for (SchemaMigrationOption schemaMigrationOption : SchemaMigrationOption.values()) {
        if (commandLine.hasOption(schemaMigrationOption.toString())) {
            if (isSchemaMigrationOptionSpecified) {
                System.out.println(
                        "Only one operation can be execute at once, please select one of 'create', ',migrate', 'validate', 'info', 'drop', 'repair', 'check-connection'.");
                System.exit(1);
            }
            isSchemaMigrationOptionSpecified = true;
            schemaMigrationOptionSpecified = schemaMigrationOption;
        }
    }

    if (!isSchemaMigrationOptionSpecified) {
        System.out.println(
                "One of the option 'create', ',migrate', 'validate', 'info', 'drop', 'repair', 'check-connection' must be specified to execute.");
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    StorageProviderConfiguration storageProperties;
    Map<String, Object> conf;
    try {
        conf = Utils.readConfig(confFilePath);

        StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader();
        storageProperties = confReader.readStorageConfig(conf);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    String bootstrapDirPath = null;
    try {
        bootstrapDirPath = System.getProperty("bootstrap.dir");
        Proxy proxy = Proxy.NO_PROXY;
        String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL);
        String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME);
        String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD);
        if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) {
            URL url = new URL(httpProxyUrl);
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort()));
            if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) {
                Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername,
                        httpProxyPassword));
            }
        }
        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy);
    } catch (Exception e) {
        System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    boolean disableValidateOnMigrate = commandLine.hasOption(DISABLE_VALIDATE_ON_MIGRATE);
    if (disableValidateOnMigrate) {
        System.out.println("Disabling validation on schema migrate");
    }
    SchemaMigrationHelper schemaMigrationHelper = new SchemaMigrationHelper(
            SchemaFlywayFactory.get(storageProperties, scriptRootPath, !disableValidateOnMigrate));
    try {
        schemaMigrationHelper.execute(schemaMigrationOptionSpecified);
        System.out
                .println(String.format("\"%s\" option successful", schemaMigrationOptionSpecified.toString()));
    } catch (Exception e) {
        System.err.println(
                String.format("\"%s\" option failed : %s", schemaMigrationOptionSpecified.toString(), e));
        System.exit(1);
    }

}

From source file:com.taurus.compratae.appservice.impl.ConsultaCreditoServiceImpl.java

private static RespuestaCredito consultaCredito() {
    Authenticator.setDefault(new MiAutenticador());
    com.taurus.tae.wsclient.WsTae_Service service = new com.taurus.tae.wsclient.WsTae_Service();
    com.taurus.tae.wsclient.WsTae port = service.getWsTaePort();
    return port.consultaCredito();
}

From source file:ProxyAuthenticator.java

private static void downloadFromUrl(String urlString) throws Exception {
    InputStream is = null;//from   w  ww.j a  va2s  .com
    FileOutputStream fos = null;

    URL url = new URL(urlString);

    System.out.println("Reading..." + url);

    Authenticator.setDefault(new ProxyAuthenticator("username", "password"));

    SocketAddress addr = new InetSocketAddress("your proxyserver ip address", 80);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);

    is = conn.getInputStream();

    String filename = getOutputFileName(url);

    fos = new FileOutputStream(filename);

    byte[] readData = new byte[1024];

    int i = is.read(readData);

    while (i != -1) {
        fos.write(readData, 0, i);
        i = is.read(readData);
    }

    System.out.println("Created file: " + filename);
    System.out.println("Completed");
}