Example usage for java.net Authenticator Authenticator

List of usage examples for java.net Authenticator Authenticator

Introduction

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

Prototype

Authenticator

Source Link

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());
        }// ww w .  j  ava  2  s  . c o  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  www  . ja  v  a 2s . 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;//  w  w  w.j ava  2  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   w  w w. j  av a  2  s  .com
    };
}

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;//from   w  ww.  ja va  2 s. c o 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:com.orange.clara.pivotaltrackermirror.util.ProxyUtil.java

private static void loadAuthenticator() {
    if (authenticatorIsLoaded) {
        return;//  w w w . ja  v  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);

}

From source file:org.restheart.test.performance.AbstractPT.java

public void prepare() {
    Authenticator.setDefault(new Authenticator() {
        @Override/* ww  w  .j a  v  a  2s.  c  om*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(id, pwd.toCharArray());
        }
    });

    Configuration conf;

    StringBuilder ymlSB = new StringBuilder();

    if (mongoUri != null) {
        ymlSB.append(Configuration.MONGO_URI_KEY).append(": ").append(mongoUri).append("\n");
    }

    Yaml yaml = new Yaml();

    Map<String, Object> configuration = (Map<String, Object>) yaml.load(ymlSB.toString());

    try {
        MongoDBClientSingleton.init(new Configuration(configuration, true));
    } catch (ConfigurationException ex) {
        System.out.println(ex.getMessage() + ", exiting...");
        System.exit(-1);
    }

    httpExecutor = Executor.newInstance();

    // for perf test better to disable the restheart security
    if (url != null && id != null && pwd != null) {
        String host = "127.0.0.1";
        int port = 8080;
        String scheme = "http";

        try {
            URI uri = new URI(url);

            host = uri.getHost();
            port = uri.getPort();
            scheme = uri.getScheme();
        } catch (URISyntaxException ex) {
            Logger.getLogger(LoadPutPT.class.getName()).log(Level.SEVERE, null, ex);
        }

        httpExecutor.authPreemptive(new HttpHost(host, port, scheme)).auth(new HttpHost(host), id, pwd);
    }
}

From source file:org.elite.jdcbot.util.GoogleCalculation.java

public GoogleCalculation(jDCBot bot, String calc, String u) throws Exception {
    final String authUser = "pforpallav";
    final String authPassword = "buckmin$ter";
    Authenticator.setDefault(new Authenticator() {
        @Override/*from  w w w .ja  va 2s . c o  m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            //logger.info(MessageFormat.format("Generating PasswordAuthentitcation for proxy authentication, using username={0} and password={1}.", username, password));
            return new PasswordAuthentication(authUser, authPassword.toCharArray());
        }
    });

    System.setProperty("http.proxyHost", "netmon.iitb.ac.in");
    System.setProperty("http.proxyPort", "80");
    System.setProperty("http.proxyUser", authUser);
    System.setProperty("http.proxyPassword", authPassword);

    String url = "http://www.google.com/ig/calculator?hl=en&q=";
    _bot = bot;
    user = u;
    calc = URLEncoder.encode(calc, "UTF-8");
    url = url + calc;
    SetURL(url);
}

From source file:org.owasp.dependencycheck.utils.URLConnectionFactory.java

/**
 * Utility method to create an HttpURLConnection. If the application is configured to use a proxy this method will retrieve
 * the proxy settings and use them when setting up the connection.
 *
 * @param url the url to connect to//w  w  w  .j av a 2 s  .  c  o  m
 * @return an HttpURLConnection
 * @throws URLConnectionFailureException thrown if there is an exception
 */
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", justification = "Just being extra safe")
public static HttpURLConnection createHttpURLConnection(URL url) throws URLConnectionFailureException {
    HttpURLConnection conn = null;
    final String proxyUrl = Settings.getString(Settings.KEYS.PROXY_SERVER);

    try {
        if (proxyUrl != null && !matchNonProxy(url)) {
            final int proxyPort = Settings.getInt(Settings.KEYS.PROXY_PORT);
            final SocketAddress address = new InetSocketAddress(proxyUrl, proxyPort);

            final String username = Settings.getString(Settings.KEYS.PROXY_USERNAME);
            final String password = Settings.getString(Settings.KEYS.PROXY_PASSWORD);

            if (username != null && password != null) {
                final Authenticator auth = new Authenticator() {
                    @Override
                    public PasswordAuthentication getPasswordAuthentication() {
                        if (getRequestorType().equals(Authenticator.RequestorType.PROXY)) {
                            return new PasswordAuthentication(username, password.toCharArray());
                        }
                        return super.getPasswordAuthentication();
                    }
                };
                Authenticator.setDefault(auth);
            }

            final Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
            conn = (HttpURLConnection) url.openConnection(proxy);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000);
        conn.setConnectTimeout(timeout);
        conn.setInstanceFollowRedirects(true);
    } catch (IOException ex) {
        if (conn != null) {
            try {
                conn.disconnect();
            } finally {
                conn = null;
            }
        }
        throw new URLConnectionFailureException("Error getting connection.", ex);
    }
    return conn;
}

From source file:org.overlord.sramp.governance.workflow.jbpm.EmbeddedJbpmManager.java

@Override
public long newProcessInstance(String deploymentId, String processId, Map<String, Object> context)
        throws WorkflowException {
    HttpURLConnection connection = null;
    Governance governance = new Governance();
    final String username = governance.getOverlordUser();
    final String password = governance.getOverlordPassword();
    Authenticator.setDefault(new Authenticator() {
        @Override/*from w w w  .  ja v a2s. c o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });

    try {
        deploymentId = URLEncoder.encode(deploymentId, "UTF-8"); //$NON-NLS-1$
        processId = URLEncoder.encode(processId, "UTF-8"); //$NON-NLS-1$
        String urlStr = governance.getGovernanceUrl()
                + String.format("/rest/process/start/%s/%s", deploymentId, processId); //$NON-NLS-1$
        URL url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        StringBuffer params = new StringBuffer();
        for (String key : context.keySet()) {
            String value = String.valueOf(context.get(key));
            value = URLEncoder.encode(value, "UTF-8"); //$NON-NLS-1$
            params.append(String.format("&%s=%s", key, value)); //$NON-NLS-1$
        }
        //remove leading '&'
        if (params.length() > 0)
            params.delete(0, 1);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST"); //$NON-NLS-1$
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        if (params.length() > 0) {
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.print(params.toString());
            out.close();
        }
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode >= 200 && responseCode < 300) {
            InputStream is = (InputStream) connection.getContent();
            String reply = IOUtils.toString(is);
            logger.info("reply=" + reply); //$NON-NLS-1$
            return Long.parseLong(reply);
        } else {
            logger.error("HTTP RESPONSE CODE=" + responseCode); //$NON-NLS-1$
            throw new WorkflowException("Unable to connect to " + urlStr); //$NON-NLS-1$
        }
    } catch (Exception e) {
        throw new WorkflowException(e);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}