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:org.talend.core.nexus.NexusServerUtils.java

public static String resolveSha1(String nexusUrl, final String userName, final String password,
        String repositoryId, String groupId, String artifactId, String version, String type) throws Exception {
    HttpURLConnection urlConnection = null;
    final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator();
    if (userName != null && !"".equals(userName)) {
        Authenticator.setDefault(new Authenticator() {

            @Override//w ww  .j  a  va  2 s. c o m
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password.toCharArray());
            }

        });
    }
    try {
        String service = NexusConstants.SERVICES_RESOLVE + "a=" + artifactId + "&g=" + groupId + "&r="
                + repositoryId + "&v=" + version + "&p=" + type;
        urlConnection = getHttpURLConnection(nexusUrl, service, userName, password);
        SAXReader saxReader = new SAXReader();

        InputStream inputStream = urlConnection.getInputStream();
        Document document = saxReader.read(inputStream);

        Node sha1Node = document.selectSingleNode("/artifact-resolution/data/sha1");
        String sha1 = null;
        if (sha1Node != null) {
            sha1 = sha1Node.getText();
        }
        return sha1;

    } catch (FileNotFoundException e) {
        // jar not existing on remote nexus
        return null;
    } finally {
        Authenticator.setDefault(defaultAuthenticator);
        if (null != urlConnection) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.intellij.util.net.HttpConfigurable.java

public PasswordAuthentication getPromptedAuthentication(final String host, final String prompt) {
    if (AUTHENTICATION_CANCELLED)
        return null;
    final String password = getPlainProxyPassword();
    if (PROXY_AUTHENTICATION && !StringUtil.isEmptyOrSpaces(PROXY_LOGIN)
            && !StringUtil.isEmptyOrSpaces(password)) {
        return new PasswordAuthentication(PROXY_LOGIN, password.toCharArray());
    }//from   w ww. j  a v a2s  . c  o m

    // do not try to show any dialogs if application is exiting
    if (ApplicationManager.getApplication() == null || ApplicationManager.getApplication().isDisposeInProgress()
            || ApplicationManager.getApplication().isDisposed())
        return null;

    if (ApplicationManager.getApplication().isUnitTestMode()) {
        return myTestGenericAuthRunnable.get();
    }
    final String login = PROXY_LOGIN == null ? "" : PROXY_LOGIN;
    final PasswordAuthentication[] value = new PasswordAuthentication[1];
    final Runnable runnable = new Runnable() {
        public void run() {
            if (AUTHENTICATION_CANCELLED)
                return;
            // password might have changed, and the check below is for that
            final String password = getPlainProxyPassword();
            if (PROXY_AUTHENTICATION && !StringUtil.isEmptyOrSpaces(PROXY_LOGIN)
                    && !StringUtil.isEmptyOrSpaces(password)) {
                value[0] = new PasswordAuthentication(PROXY_LOGIN, password.toCharArray());
                return;
            }
            final AuthenticationDialog dlg = new AuthenticationDialog(PopupUtil.getActiveComponent(),
                    "Proxy authentication: " + host, "Please enter credentials for: " + prompt, login, "",
                    KEEP_PROXY_PASSWORD);
            dlg.show();
            if (dlg.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
                PROXY_AUTHENTICATION = true;
                final AuthenticationPanel panel = dlg.getPanel();
                KEEP_PROXY_PASSWORD = panel.isRememberPassword();
                PROXY_LOGIN = panel.getLogin();
                setPlainProxyPassword(String.valueOf(panel.getPassword()));
                value[0] = new PasswordAuthentication(panel.getLogin(), panel.getPassword());
            } else {
                AUTHENTICATION_CANCELLED = true;
            }
        }
    };
    runAboveAll(runnable);
    return value[0];
}

From source file:org.fuin.esmp.AbstractEventStoreMojo.java

private void addProxySelector(final String proxyHost, final int proxyPort, final String proxyUser,
        final String proxyPassword, final URL downloadUrl) throws URISyntaxException {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override//from w  w  w.  j  a va 2  s . c  om
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }
    final ProxySelector defaultProxySelector = ProxySelector.getDefault();

    final URI downloadUri = downloadUrl.toURI();

    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals(downloadUri.getHost()) && proxyHost != null && proxyHost.length() != 0) {
                return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
            } else {
                return defaultProxySelector.select(uri);
            }
        }

        @Override
        public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
        }
    });
}

From source file:com.diablominer.DiabloMiner.DiabloMiner.java

void execute(String[] args) throws Exception {
    threads.add(Thread.currentThread());

    Options options = new Options();
    options.addOption("u", "user", true, "bitcoin host username");
    options.addOption("p", "pass", true, "bitcoin host password");
    options.addOption("o", "host", true, "bitcoin host IP");
    options.addOption("r", "port", true, "bitcoin host port");
    options.addOption("l", "url", true, "bitcoin host url");
    options.addOption("x", "proxy", true, "optional proxy settings IP:PORT<:username:password>");
    options.addOption("g", "worklifetime", true, "maximum work lifetime in seconds");
    options.addOption("d", "debug", false, "enable debug output");
    options.addOption("dt", "debugtimer", false, "run for 1 minute and quit");
    options.addOption("D", "devices", true, "devices to enable, default all");
    options.addOption("f", "fps", true, "target GPU execution timing");
    options.addOption("na", "noarray", false, "turn GPU kernel array off");
    options.addOption("v", "vectors", true, "vector size in GPU kernel");
    options.addOption("w", "worksize", true, "override GPU worksize");
    options.addOption("ds", "ksource", false, "output GPU kernel source and quit");
    options.addOption("h", "help", false, "this help");

    PosixParser parser = new PosixParser();

    CommandLine line = null;//from  ww  w. j ava2  s  . co  m

    try {
        line = parser.parse(options, args);

        if (line.hasOption("help")) {
            throw new ParseException("");
        }
    } catch (ParseException e) {
        System.out.println(e.getLocalizedMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DiabloMiner -u myuser -p mypassword [args]\n", "", options,
                "\nRemember to set rpcuser and rpcpassword in your ~/.bitcoin/bitcoin.conf "
                        + "before starting bitcoind or bitcoin --daemon");
        return;
    }

    String splitUrl[] = null;
    String splitUser[] = null;
    String splitPass[] = null;
    String splitHost[] = null;
    String splitPort[] = null;

    if (line.hasOption("url"))
        splitUrl = line.getOptionValue("url").split(",");

    if (line.hasOption("user"))
        splitUser = line.getOptionValue("user").split(",");

    if (line.hasOption("pass"))
        splitPass = line.getOptionValue("pass").split(",");

    if (line.hasOption("host"))
        splitHost = line.getOptionValue("host").split(",");

    if (line.hasOption("port"))
        splitPort = line.getOptionValue("port").split(",");

    int networkStatesCount = 0;

    if (splitUrl != null)
        networkStatesCount = splitUrl.length;

    if (splitUser != null)
        networkStatesCount = Math.max(splitUser.length, networkStatesCount);

    if (splitPass != null)
        networkStatesCount = Math.max(splitPass.length, networkStatesCount);

    if (splitHost != null)
        networkStatesCount = Math.max(splitHost.length, networkStatesCount);

    if (splitPort != null)
        networkStatesCount = Math.max(splitPort.length, networkStatesCount);

    if (networkStatesCount == 0) {
        error("You forgot to give any bitcoin connection info, please add either -l, or -u -p -o and -r");
        System.exit(-1);
    }

    int j = 0;

    for (int i = 0; j < networkStatesCount; i++, j++) {
        String protocol = "http";
        String host = "localhost";
        int port = 8332;
        String path = "/";
        String user = "diablominer";
        String pass = "diablominer";
        byte hostChain = 0;

        if (splitUrl != null && splitUrl.length > i) {
            String[] usernameFix = splitUrl[i].split("@", 3);
            if (usernameFix.length > 2)
                splitUrl[i] = usernameFix[0] + "+++++" + usernameFix[1] + "@" + usernameFix[2];

            URL url = new URL(splitUrl[i]);

            if (url.getProtocol() != null && url.getProtocol().length() > 1)
                protocol = url.getProtocol();

            if (url.getHost() != null && url.getHost().length() > 1)
                host = url.getHost();

            if (url.getPort() != -1)
                port = url.getPort();

            if (url.getPath() != null && url.getPath().length() > 1)
                path = url.getPath();

            if (url.getUserInfo() != null && url.getUserInfo().length() > 1) {
                String[] userPassSplit = url.getUserInfo().split(":");

                user = userPassSplit[0].replace("+++++", "@");

                if (userPassSplit.length > 1 && userPassSplit[1].length() > 1)
                    pass = userPassSplit[1];
            }
        }

        if (splitUser != null && splitUser.length > i)
            user = splitUser[i];

        if (splitPass != null && splitPass.length > i)
            pass = splitPass[i];

        if (splitHost != null && splitHost.length > i)
            host = splitHost[i];

        if (splitPort != null && splitPort.length > i)
            port = Integer.parseInt(splitPort[i]);

        NetworkState networkState;

        try {
            networkState = new JSONRPCNetworkState(this, new URL(protocol, host, port, path), user, pass,
                    hostChain);
        } catch (MalformedURLException e) {
            throw new DiabloMinerFatalException(this, "Malformed connection paramaters");
        }

        if (networkStateHead == null) {
            networkStateHead = networkStateTail = networkState;
        } else {
            networkStateTail.setNetworkStateNext(networkState);
            networkStateTail = networkState;
        }
    }

    networkStateTail.setNetworkStateNext(networkStateHead);

    if (line.hasOption("proxy")) {
        final String[] proxySettings = line.getOptionValue("proxy").split(":");

        if (proxySettings.length >= 2) {
            proxy = new Proxy(Type.HTTP,
                    new InetSocketAddress(proxySettings[0], Integer.valueOf(proxySettings[1])));
        }

        if (proxySettings.length >= 3) {
            Authenticator.setDefault(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxySettings[2], proxySettings[3].toCharArray());
                }
            });
        }
    }

    if (line.hasOption("worklifetime"))
        workLifetime = Integer.parseInt(line.getOptionValue("worklifetime")) * 1000;

    if (line.hasOption("debug"))
        debug = true;

    if (line.hasOption("debugtimer")) {
        debugtimer = true;
    }

    if (line.hasOption("devices")) {
        String devices[] = line.getOptionValue("devices").split(",");
        enabledDevices = new HashSet<String>();
        for (String s : devices) {
            enabledDevices.add(s);

            if (Integer.parseInt(s) == 0) {
                error("Do not use 0 with -D, devices start at 1");
                System.exit(-1);
            }
        }
    }

    if (line.hasOption("fps")) {
        GPUTargetFPS = Float.parseFloat(line.getOptionValue("fps"));

        if (GPUTargetFPS < 0.1) {
            error("--fps argument is too low, adjusting to 0.1");
            GPUTargetFPS = 0.1;
        }
    }

    if (line.hasOption("noarray")) {
        GPUNoArray = true;
    }

    if (line.hasOption("worksize"))
        GPUForceWorkSize = Integer.parseInt(line.getOptionValue("worksize"));

    if (line.hasOption("vectors")) {
        String tempVectors[] = line.getOptionValue("vectors").split(",");

        GPUVectors = new Integer[tempVectors.length];

        try {
            for (int i = 0; i < GPUVectors.length; i++) {
                GPUVectors[i] = Integer.parseInt(tempVectors[i]);

                if (GPUVectors[i] > 16) {
                    error("DiabloMiner now uses comma-seperated vector layouts, use those instead");
                    System.exit(-1);
                } else if (GPUVectors[i] != 1 && GPUVectors[i] != 2 && GPUVectors[i] != 3 && GPUVectors[i] != 4
                        && GPUVectors[i] != 8 && GPUVectors[i] != 16) {
                    error(GPUVectors[i] + " is not a vector length of 1, 2, 3, 4, 8, or 16");
                    System.exit(-1);
                }
            }

            Arrays.sort(GPUVectors, Collections.reverseOrder());
        } catch (NumberFormatException e) {
            error("Cannot parse --vector argument(s)");
            System.exit(-1);
        }
    } else {
        GPUVectors = new Integer[1];
        GPUVectors[0] = 1;
    }

    if (line.hasOption("ds"))
        GPUDebugSource = true;

    info("Started");

    StringBuilder list = new StringBuilder(networkStateHead.getQueryUrl().toString());
    NetworkState networkState = networkStateHead.getNetworkStateNext();

    while (networkState != networkStateHead) {
        list.append(", " + networkState.getQueryUrl());
        networkState = networkState.getNetworkStateNext();
    }

    info("Connecting to: " + list);

    long previousHashCount = 0;
    double previousAdjustedHashCount = 0.0;
    long previousAdjustedStartTime = startTime = (now()) - 1;
    StringBuilder hashMeter = new StringBuilder(80);
    Formatter hashMeterFormatter = new Formatter(hashMeter);

    int deviceCount = 0;

    List<List<? extends DeviceState>> allDeviceStates = new ArrayList<List<? extends DeviceState>>();

    List<? extends DeviceState> GPUDeviceStates = new GPUHardwareType(this).getDeviceStates();
    deviceCount += GPUDeviceStates.size();
    allDeviceStates.add(GPUDeviceStates);

    while (running.get()) {
        for (List<? extends DeviceState> deviceStates : allDeviceStates) {
            for (DeviceState deviceState : deviceStates) {
                deviceState.checkDevice();
            }
        }

        long now = now();
        long currentHashCount = hashCount.get();
        double adjustedHashCount = (double) (currentHashCount - previousHashCount)
                / (double) (now - previousAdjustedStartTime);
        double hashLongCount = (double) currentHashCount / (double) (now - startTime) / 1000.0;

        if (now - startTime > TIME_OFFSET * 2) {
            double averageHashCount = (adjustedHashCount + previousAdjustedHashCount) / 2.0 / 1000.0;

            hashMeter.setLength(0);

            if (!debug) {
                hashMeterFormatter.format("\rmhash: %.1f/%.1f | accept: %d | reject: %d | hw error: %d",
                        averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get());
            } else {
                hashMeterFormatter.format("\rmh: %.1f/%.1f | a/r/hwe: %d/%d/%d | gh: ", averageHashCount,
                        hashLongCount, blocks.get(), rejects.get(), hwErrors.get());

                double basisAverage = 0.0;

                for (List<? extends DeviceState> deviceStates : allDeviceStates) {
                    for (DeviceState deviceState : deviceStates) {
                        hashMeterFormatter.format("%.1f ",
                                deviceState.getDeviceHashCount() / 1000.0 / 1000.0 / 1000.0);
                        basisAverage += deviceState.getBasis();
                    }
                }

                basisAverage = 1000 / (basisAverage / deviceCount);

                hashMeterFormatter.format("| fps: %.1f", basisAverage);
            }

            System.out.print(hashMeter);
        } else {
            System.out.print("\rWaiting...");
        }

        if (now() - TIME_OFFSET * 2 > previousAdjustedStartTime) {
            previousHashCount = currentHashCount;
            previousAdjustedHashCount = adjustedHashCount;
            previousAdjustedStartTime = now - 1;
        }

        if (debugtimer && now() > startTime + 60 * 1000) {
            System.out.print("\n");
            info("Debug timer is up, quitting...");
            System.exit(0);
        }

        try {
            if (now - startTime > TIME_OFFSET)
                Thread.sleep(1000);
            else
                Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }

    hashMeterFormatter.close();
}

From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java

@SuppressWarnings("deprecation")
public PasswordAuthentication requestProxyAuthentication() {
    if (proxyInfo != null && proxyInfo.getUserName() != null) {
        String password = "";
        if (proxyInfo.getPassword() != null) {
            password = proxyInfo.getPassword();
        }/*from  www .  j a v a2s.  co m*/
        return new PasswordAuthentication(proxyInfo.getUserName(), password.toCharArray());
    }
    return null;
}

From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java

public PasswordAuthentication requestServerAuthentication() {
    if (authenticationInfo != null && authenticationInfo.getUserName() != null) {
        String password = "";
        if (authenticationInfo.getPassword() != null) {
            password = authenticationInfo.getPassword();
        }/*from   ww w. jav a 2  s  . c  om*/
        return new PasswordAuthentication(authenticationInfo.getUserName(), password.toCharArray());
    }
    return null;
}

From source file:io.takari.maven.testing.executor.junit.MavenVersionResolver.java

private void setHttpCredentials(final Credentials credentials) {
    Authenticator authenticator = null;
    if (credentials != null) {
        authenticator = new Authenticator() {
            @Override/* w ww  . j a  v a 2  s  .c  om*/
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(credentials.username, credentials.password.toCharArray());
            }
        };
    }
    Authenticator.setDefault(authenticator);
}

From source file:org.kawanfw.sql.api.client.RemoteDriver.java

/**
 * Attempts to make a database connection to the given URL.
 * //from w w w  .  j a  v a  2 s .co  m
 * The driver will return "null" if it realizes it is the wrong kind of
 * driver to connect to the given URL. {@link #acceptsURL} will return null.
 * 
 * <P>
 * The driver will throw<code>SQLException</code> if it is the right driver
 * to connect to the given URL but has trouble connecting to the database.
 * 
 * <P>
 * The <code>java.util.Properties</code> argument can be used to pass
 * arbitrary string tag/value pairs as connection arguments. At least "user"
 * and "password" properties should be included in the
 * <code>Properties</code> object.
 * 
 * @param url
 *            the URL of the database to which to connect
 * @param info
 *            a list of arbitrary string tag/value pairs as connection
 *            arguments. At least a "user" and "password" property should be
 *            included.
 * @return a <code>Connection</code> object that represents a connection to
 *         the URL
 * @exception SQLException
 *                if a database access error occurs
 */
@Override
public Connection connect(String url, Properties info) throws SQLException {

    if (url == null) {
        throw new SQLException("url not set. Please provide an url.");
    }

    if (!acceptsURL(url)) {
        return null;
    }

    Properties info2 = new Properties();
    RemoteDriverUtil.copyProperties(info, info2);

    // Properties may be passed in url
    if (url.contains("?")) {
        String query = StringUtils.substringAfter(url, "?");
        Map<String, String> mapProps = RemoteDriverUtil.getQueryMap(query);

        Set<String> set = mapProps.keySet();
        for (String propName : set) {
            info2.setProperty(propName, mapProps.get(propName));
        }

        url = StringUtils.substringBefore(url, "?");
    }

    String username = info2.getProperty("user");
    String password = info2.getProperty("password");

    if (username == null) {
        throw new SQLException("user not set. Please provide a user.");
    }

    if (password == null) {
        throw new SQLException("password not set. Please provide a password.");
    }

    // Add proxy lookup
    String proxyType = info2.getProperty("proxyType");
    String proxyHostname = info2.getProperty("proxyHostname");
    String proxyPort = info2.getProperty("proxyPort");
    String proxyUsername = info2.getProperty("proxyUsername");
    String proxyPassword = info2.getProperty("proxyPassword");

    String statelessMode = info2.getProperty("statelessMode");
    String joinResultSetMetaData = info2.getProperty("joinResultSetMetaData");

    String zipResultSet = info2.getProperty("zipResultSet");

    int port = -1;

    Proxy proxy = null;

    if (proxyHostname != null) {
        try {
            port = Integer.parseInt(proxyPort);
        } catch (NumberFormatException e) {
            throw new SQLException("Invalid proxy port. Port is not numeric: " + proxyPort);
        }

        if (proxyType == null) {
            proxyType = "HTTP";
        }

        proxy = new Proxy(Type.valueOf(proxyType), new InetSocketAddress(proxyHostname, port));
    }

    boolean statelessModeBoolean = Boolean.parseBoolean(statelessMode);

    SessionParameters sessionParameters = getSessionParameters(info2);

    debug(sessionParameters.toString());

    // if (url.startsWith("jdbc:kawanfw://")) {
    // url = url.replace("jdbc:kawanfw", "http");
    // }

    // If we have passed the "proxy" property, build back the
    // instance from the property value
    // 1) Treat the case the user did a property.put(proxy) instead of
    // property.setProperty(proxy.toString())

    if (proxy == null) {
        Object objProxy = info2.get("proxy");
        if (objProxy != null && objProxy instanceof Proxy) {
            proxy = (Proxy) proxy;
        }
        // 2) Treat the case the user as correctly used
        // property.setProperty(httpProxy.toString())
        else {
            String proxyStr = info2.getProperty("proxy");
            debug("proxyStr:" + proxyStr);
            if (proxyStr != null) {
                proxy = RemoteDriverUtil.buildProxy(proxyStr);
            }
        }
    }

    // If we have passed the "sessionParameters" property, build back
    // the
    // instance from the property value
    // 1) Treat the case the user did a property.put(sessionParameters)
    // instead of property.setProperty(sessionParameters.toString())
    Object objSessionParameters = info2.get("sessionParameters");
    if (objSessionParameters != null && objSessionParameters instanceof SessionParameters) {
        String jsonString = SessionParametersGson.toJson((SessionParameters) (objSessionParameters));

        if (jsonString != null) {
            sessionParameters = SessionParametersGson.fromJson(jsonString);
        }
    }
    // 2) Treat the case the user as correctly used
    // property.setProperty(sessionParameters.toString())
    else {
        String jsonString = info2.getProperty("sessionParameters");
        if (jsonString != null) {
            sessionParameters = SessionParametersGson.fromJson(jsonString);
        }
    }

    debug("url                   : " + url);
    debug("Proxy                 : " + proxy);
    debug("sessionParameters: " + sessionParameters);

    boolean doJoinResultSetMetaData = false;

    if (joinResultSetMetaData != null) {
        doJoinResultSetMetaData = Boolean.parseBoolean(joinResultSetMetaData);
        debug("joinResultSetMetaData: " + doJoinResultSetMetaData);
    }

    PasswordAuthentication passwordAuthentication = null;

    if (proxy != null && proxyUsername != null) {
        passwordAuthentication = new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray());
    }

    boolean doZipResultSet = true;

    if (zipResultSet != null) {
        doZipResultSet = Boolean.parseBoolean(zipResultSet);
        debug("zipResultSet: " + doZipResultSet);
    }

    Connection connection = new RemoteConnection(url, username, password.toCharArray(), proxy,
            passwordAuthentication, sessionParameters, statelessModeBoolean, doJoinResultSetMetaData,
            doZipResultSet);

    return connection;
}

From source file:org.openbravo.test.webservice.BaseWSTest.java

/**
 * Creates a HTTP connection.//w w  w . j a v a  2 s  .  c o  m
 * 
 * @param wsPart
 * @param method
 *          POST, PUT, GET or DELETE
 * @return the created connection
 * @throws Exception
 */
protected HttpURLConnection createConnection(String wsPart, String method) throws Exception {
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(LOGIN, PWD.toCharArray());
        }
    });
    log.debug(method + ": " + getOpenbravoURL() + wsPart);
    final URL url = new URL(getOpenbravoURL() + wsPart);
    final HttpURLConnection hc = (HttpURLConnection) url.openConnection();
    hc.setRequestMethod(method);
    hc.setAllowUserInteraction(false);
    hc.setDefaultUseCaches(false);
    hc.setDoOutput(true);
    hc.setDoInput(true);
    hc.setInstanceFollowRedirects(true);
    hc.setUseCaches(false);
    hc.setRequestProperty("Content-Type", "text/xml");
    return hc;
}

From source file:com.hpe.application.automation.tools.common.rest.RestClient.java

public static URLConnection openConnection(final ProxyInfo proxyInfo, String urlString) throws IOException {
    Proxy proxy = null;//from w w  w  .j  a v a2s . c  om
    URL url = new URL(urlString);

    if (proxyInfo != null && StringUtils.isNotBlank(proxyInfo._host)
            && StringUtils.isNotBlank(proxyInfo._port)) {
        int port = Integer.parseInt(proxyInfo._port.trim());
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyInfo._host, port));
    }

    if (proxy != null && StringUtils.isNotBlank(proxyInfo._userName)
            && StringUtils.isNotBlank(proxyInfo._password)) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyInfo._userName, proxyInfo._password.toCharArray()); //To change body of overridden methods use File | Settings | File Templates.
            }
        };
        Authenticator.setDefault(authenticator);
    }

    if (proxy == null) {
        return url.openConnection();
    }

    return url.openConnection(proxy);
}