Example usage for java.net PasswordAuthentication PasswordAuthentication

List of usage examples for java.net PasswordAuthentication PasswordAuthentication

Introduction

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

Prototype

public PasswordAuthentication(String userName, char[] password) 

Source Link

Document

Creates a new PasswordAuthentication object from the given user name and password.

Usage

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());
        }/*from www . j  a  v  a  2s.c om*/
    });

    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 a  va2  s .c  o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("user", "password".toCharArray());
        }
    });
}

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  w  w . jav 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:net.orpiske.ssps.sdm.utils.net.ProxyHelper.java

private static Authenticator getAuth(final String user, final String password) {
    return new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password.toCharArray());
        }//from   ww w  .  j a  va 2s. com
    };
}

From source file:ProxyAuthenticator.java

protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(userName, password.toCharArray());
}

From source file:guiTool.Helper.java

public static String readUrl(String urlString, final String userid, final String password) throws Exception {

    BufferedReader reader = null;
    StringBuilder buffer = null;//  www .jav  a2  s . co  m
    try {
        URL url = new URL(urlString);

        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userid, password.toCharArray());
            }
        });
        InputStreamReader s = new InputStreamReader(url.openStream());
        //       System.out.println("getEncoding " + s.getEncoding());
        reader = new BufferedReader(s);

        buffer = new StringBuilder();
        int read;
        char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1) {
            buffer.append(chars, 0, read);
        }

    } catch (Exception e) {
        System.out.println("Exception       " + e.getMessage());
        //  JOptionPane.showMessageDialog(null, "The server or your internet connection could be down.", "connection test", JOptionPane.ERROR_MESSAGE);

    } finally {
        if (reader != null) {
            reader.close();
        }
    }
    return buffer.toString();
}

From source file:MainClass.java

public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("username", "password".toCharArray());
}

From source file:com.adaptris.core.management.ProxyAuthenticator.java

static void register(BootstrapProperties config) {
    if (!config.isEnabled(CFG_KEY_PROXY_AUTHENTICATOR)) {
        return;/*from   w w  w . j  a v a2s. c  om*/
    }
    String proxyPassword = getSystemProperty(PROXY_PASSWORD_SYSPROPERTIES);
    String proxyUser = getSystemProperty(PROXY_USER_SYSPROPERTIES);
    if (!isEmpty(proxyPassword) && !isEmpty(proxyUser)) {
        AdapterResourceAuthenticator.getInstance().addAuthenticator(
                new ProxyAuth(new PasswordAuthentication(proxyUser, proxyPassword.toCharArray())));
    }
}

From source file:uk.ac.ucl.cs.cmic.giftcloud.restserver.PasswordAuthenticationWrapper.java

static Optional<PasswordAuthentication> getPasswordAuthenticationFromURL(final URL url) {
    final String userInfo = url.getUserInfo();
    if (null != userInfo) {
        final Matcher m = userInfoPattern.matcher(userInfo);
        if (m.matches()) {
            final PasswordAuthentication authenticator = new PasswordAuthentication(m.group(1),
                    m.group(2).toCharArray());
            return Optional.of(authenticator);
        }/*from   ww  w . ja va2  s  . com*/
    }
    return Optional.empty();
}

From source file:com.orange.clara.pivotaltrackermirror.util.ProxyUtil.java

private static void loadAuthenticator() {
    if (authenticatorIsLoaded) {
        return;/*from  ww w . j av  a 2  s .c  o m*/
    }
    authenticatorIsLoaded = true;
    Authenticator authenticator = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication(PROXY_USER, PROXY_PASSWD.toCharArray()));
        }
    };
    Authenticator.setDefault(authenticator);

}