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:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void wrongPasswordDontSave() throws Exception {
    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);

    // Make the server expect different password so our cache is no longer
    // valid/* w ww .j a v a  2 s  . co m*/
    userRealm.put(USERNAME, PASSWORD2);
    // But we'll try with the old one, which we'll this time ask to save in
    // DB
    UsernamePassword usernamePassword = new UsernamePassword(USERNAME, PASSWORD);
    assertFalse("Should not be set to save by default", usernamePassword.isShouldSave());
    //FixedPasswordProvider.setUsernamePassword(usernamePassword);

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), usernamePassword);
    URLConnection c = url.openConnection();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    assertEquals("HTTP/1.1 401 Unauthorized", c.getHeaderField(0));

    assertTrue("Did not invoke authenticator enough times", authenticator.calls > 1);
    assertEquals("Should have asked provider as much as authenticator", authenticator.calls,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    // Update provider to now provide the right one
    //      HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(new UsernamePassword(
    //            USERNAME, PASSWORD2));
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, PASSWORD2));
    HTTPAuthenticatorServiceUsernameAndPasswordProvider.resetCalls();
    authenticator.calls = 0;

    URLConnection c2 = url.openConnection();
    try {
        c2.getContent();
    } catch (Exception ex) {
    }
    assertEquals("Did not call authenticator again with cache pw invalid", 1, authenticator.calls);
    assertEquals("id not called our password provider once", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

public static String updateAddToComposite(int id, String[] atomic) {
    Client c = Client.create();/*www  .j av  a 2  s.c o  m*/
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/configParamComposite/" + id);
    ConfigParamCompositeInstanceDocument pDoc = ConfigParamCompositeInstanceDocument.Factory.newInstance();
    pDoc.addNewConfigParamCompositeInstance();

    ConfigParamComposite cC = getComposite(id);

    String[] paramArray = new String[atomic.length + cC.getConfigParams().sizeOfConfigParamAtomicArray()];

    System.arraycopy(atomic, 0, paramArray, 0, atomic.length);

    ConfigParamAtomic[] cA = cC.getConfigParams().getConfigParamAtomicArray();

    for (int i = 0; i < cA.length; i++)
        paramArray[i + atomic.length] = cA[i].getId();

    pDoc.getConfigParamCompositeInstance().setConfigParamsArray(paramArray);

    String request = pDoc.toString();
    request = request.replace(" xmlns=\"http://xml.netbeans.org/schema/repo.xsd\"", "");
    request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + request;

    String resp = r.type(MediaType.TEXT_XML).put(String.class, request);
    System.out.println(resp);
    resp = addSchemaDefinition(resp);
    try {
        ConfigParamCompositeDocument pcDoc = ConfigParamCompositeDocument.Factory.parse(resp);
        return pcDoc.getConfigParamComposite().getId();
    } catch (XmlException ex) {
        ex.printStackTrace();
        return null;
    }

}

From source file:com.cisco.dvbu.ps.common.util.wsapi.CisApiFactory.java

/**
 * Returns the ExecutePort of AdminAPI//from w  w  w  .  j  a va  2 s  .co  m
 * @param server Composite Server
 * @return ExecutePort of AdminAPI
 */
public static ExecutePortType getExecutePort(CompositeServer server) {

    Authenticator.setDefault(new BasicAuthenticator(server));

    URL url = null;
    String protocol = "http";
    int wsPort = server.getPort();
    if (server.isUseHttps()) {
        protocol = "https";
        wsPort += 2;
    }
    try {
        url = new URL(protocol + "://" + server.getHostname() + ":" + wsPort + "/services/system/admin?wsdl");
        if (logger.isDebugEnabled()) {
            logger.debug("Entering CisApiFactory.getExecutePort() with following params " + " url: " + url);
        }
    } catch (MalformedURLException e) {
        String errorMessage = DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                "Creating Execute Port", "Admin API", "ExecutePort", server);
        CompositeLogger.logException(e, errorMessage);
        throw new CompositeException(errorMessage, e);
    }

    int retry = 0;
    while (retry < numRetries) {
        retry++;
        try {
            Execute exec = new Execute(url, new QName(nsExecuteUrl, nsExecuteName)); // Get the connection to the server.
            if (logger.isDebugEnabled()) {
                if (exec != null)
                    logger.debug("Entering CisApiFactory.getExecutePort(). Execute acquired " + " Execute: "
                            + exec.toString());
            }
            ExecutePortType port = exec.getExecutePort(); // Get the server port
            if (logger.isDebugEnabled()) {
                if (port != null)
                    logger.debug("Entering CisApiFactory.getExecutePort(). Port acquired " + " Port: "
                            + port.toString());
            }
            return port; // Return the port connection to the server.
        } catch (Exception e) {
            String errorMessage = DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                    "Getting Server Port, [CONNECT ATTEMPT=" + retry + "]", "Admin API", "ServerPort", server);
            if (retry == numRetries) {
                throw new CompositeException(errorMessage, e);
            } else {
                // Log the error and sleep before retrying
                CompositeLogger.logException(e, errorMessage);
                Sleep.sleep(sleepDebug, sleepRetry);
            }
        }
    }
    throw new CompositeException(
            "Maximum connection attempts reached without connecting to the Composite Information Server.");
}

From source file:org.apache.cxf.maven_plugin.AbstractCodegenMoho.java

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");
        } else {/* ww  w  .j a  va2 s .  co  m*/
            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);
            }
        }

    }
}

From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java

private void addProxySelector() {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override//from   w  ww . j a v a 2  s . com
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }

    final ProxySelector defaultProxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals("fastdl.mongodb.org")) {
                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.clustercontrol.agent.Agent.java

/**
 * /*from www  . j av  a  2 s .co  m*/
 */
public Agent(String propFileName) throws Exception {

    //------------
    //-- ??
    //------------

    //???
    AgentProperties.init(propFileName);

    // ?IP????
    getAgentInfo();
    m_log.info(getAgentStr());

    // log4j???
    String log4jFileName = System.getProperty("hinemos.agent.conf.dir") + File.separator + "log4j.properties";
    m_log.info("log4j.properties = " + log4jFileName);
    m_log4jFileName = log4jFileName;

    int connectTimeout = DEFAULT_CONNECT_TIMEOUT;
    int requestTimeout = DEFAULT_REQUEST_TIMEOUT;

    // 
    String proxyHost = DEFAULT_PROXY_HOST;
    int proxyPort = DEFAULT_PROXY_PORT;
    String proxyUser = DEFAULT_PROXY_USER;
    String proxyPassword = DEFAULT_PROXY_PASSWORD;

    // ???hostnameVerifier?HTTPS????
    try {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, javax.net.ssl.SSLSession session) {
                return true;
            }
        };

        // Create the trust manager.
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        class AllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                    throws java.security.cert.CertificateException {
                return;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                    throws java.security.cert.CertificateException {
                return;
            }
        }
        javax.net.ssl.TrustManager tm = new AllTrustManager();
        trustAllCerts[0] = tm;
        // Create the SSL context
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        // Create the session context
        javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
        // Initialize the contexts; the session context takes the
        // trust manager.
        sslsc.setSessionTimeout(0);
        sc.init(null, trustAllCerts, null);
        // Use the default socket factory to create the socket for
        // the secure
        // connection
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Set the default host name verifier to enable the connection.
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

    } catch (Throwable e) {
        m_log.warn("hostname verifier (all trust) disable : " + e.getMessage(), e);
    }

    try {
        String strConnect = AgentProperties.getProperty("connect.timeout");
        if (strConnect != null) {
            connectTimeout = Integer.parseInt(strConnect);
        }
        String strRequest = AgentProperties.getProperty("request.timeout");
        if (strRequest != null) {
            requestTimeout = Integer.parseInt(strRequest);
        }
        String strProxyHost = AgentProperties.getProperty("http.proxy.host");
        if (strProxyHost != null) {
            proxyHost = strProxyHost;
        }
        String strProxyPort = AgentProperties.getProperty("http.proxy.port");
        if (strProxyPort != null) {
            proxyPort = Integer.parseInt(strProxyPort);
        }
        String strProxyUser = AgentProperties.getProperty("http.proxy.user");
        if (strProxyUser != null) {
            proxyUser = strProxyUser;
        }
        String strProxyPassword = AgentProperties.getProperty("http.proxy.password");
        if (strProxyPassword != null) {
            proxyPassword = strProxyPassword;
        }
    } catch (Exception e) {
        m_log.warn(e.getMessage());
    }

    if (!"".equals(proxyHost)) {
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", Integer.toString(proxyPort));
        BasicAuth basicAuth = new BasicAuth(proxyUser, proxyPassword);
        Authenticator.setDefault(basicAuth);
        m_log.info("proxy.host=" + System.getProperty("http.proxyHost") + ", proxy.port="
                + System.getProperty("http.proxyPort") + ", proxy.user=" + proxyUser);
    }

    // ?? ${ManagerIP} ?????????????
    // ??PING????????IP????FacilityID??????
    String managerAddress = AgentProperties.getProperty("managerAddress");
    URL url = new URL(managerAddress);
    boolean replacePropFileSuccess = true;
    String errMsg = "";
    if (REPLACE_VALUE_MANAGER_IP.equals((url.getHost()))) {
        try {

            // ???PING?????PING???????
            Map<String, String> discoveryInfoMap = new HashMap<String, String>();
            while (true) {
                m_log.info("waiting for manager connection...");
                String recvMsg = receiveManagerDiscoveryInfo();

                // ????key=value,key=value ??????Map??
                try {
                    discoveryInfoMap.clear();
                    String[] commaSplittedRecvMsgArray = recvMsg.split(",");
                    for (String keyvalueset : commaSplittedRecvMsgArray) {
                        String key = keyvalueset.split("=")[0];
                        String value = keyvalueset.split("=")[1];
                        discoveryInfoMap.put(key, value);
                    }
                } catch (Exception e) {
                    m_log.error("can't parse receive message : " + e.toString());
                    continue;
                }
                if (discoveryInfoMap.containsKey("agentFacilityId")
                        && discoveryInfoMap.containsKey("managerIp")) {
                    break;
                } else {
                    m_log.error("receive message is invalid");
                }
            }
            // Agent.properties?????????????
            {
                String managerIp = discoveryInfoMap.get("managerIp");
                String key = "managerAddress";
                String value = url.getProtocol() + "://" + managerIp + ":" + url.getPort() + "/HinemosWS/";
                m_log.info("Rewrite property. key : " + key + ", value : " + value);
                PropertiesFileUtil.replacePropertyFile(propFileName, key, managerAddress, value);
                AgentProperties.setProperty(key, value);
            }

            // Agent.properties?ID??????????
            {
                String key = "facilityId";
                String value = discoveryInfoMap.get("agentFacilityId");
                m_log.info("Rewrite property. key : " + key + ", value : " + value);
                PropertiesFileUtil.replacePropertyFile(propFileName, key, "", value);
                AgentProperties.setProperty(key, value);
            }

            // log4j.properties?????Windows??
            {
                String managerIp = discoveryInfoMap.get("managerIp");
                String key = "log4j.appender.syslog.SyslogHost";
                PropertiesFileUtil.replacePropertyFile(log4jFileName, "log4j.appender.syslog.SyslogHost",
                        REPLACE_VALUE_MANAGER_IP, managerIp);
                if (REPLACE_VALUE_MANAGER_IP.equals(AgentProperties.getProperty(key))) {
                    m_log.info("Rewrite property. key : " + key + ", value : " + managerIp);
                    PropertiesFileUtil.replacePropertyFile(log4jFileName, key, REPLACE_VALUE_MANAGER_IP,
                            managerIp);
                }
            }
        } catch (HinemosUnknown e) {
            // ????????????
            errMsg = e.getMessage();
            m_log.warn(errMsg, e);
            replacePropFileSuccess = false;
        } catch (Exception e) {
            m_log.warn(e.getMessage(), e);
            throw e;
        }
    }

    try {
        EndpointManager.init(AgentProperties.getProperty("user"), AgentProperties.getProperty("password"),
                AgentProperties.getProperty("managerAddress"), connectTimeout, requestTimeout);
    } catch (Exception e) {
        m_log.error("EndpointManager.init error : " + e.getMessage(), e);
        m_log.error("current-dir=" + (new File(".")).getAbsoluteFile().getParent());
        throw e;
    }

    if (!replacePropFileSuccess) {
        OutputBasicInfo output = new OutputBasicInfo();
        output.setPluginId("AGT_UPDATE_CONFFILE");
        output.setPriority(PriorityConstant.TYPE_WARNING);
        output.setApplication(MessageConstant.AGENT.getMessage());
        String[] args = { errMsg };
        output.setMessage(MessageConstant.MESSAGE_AGENT_REPLACE_FILE_FAULURE_NOTIFY_MSG.getMessage());
        output.setMessageOrg(
                MessageConstant.MESSAGE_AGENT_REPLACE_FILE_FAULURE_NOTIFY_ORIGMSG.getMessage(args));
        output.setGenerationDate(HinemosTime.getDateInstance().getTime());
        output.setMonitorId("SYS");
        output.setFacilityId(""); // ???
        output.setScopeText(""); // ???
        m_sendQueue.put(output);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            terminate();
            m_log.info("Hinemos agent stopped");
        }
    });
}

From source file:com.blackducksoftware.integration.hub.jenkins.PostBuildScanDescriptor.java

/**
 * Performs on-the-fly validation of the form field 'serverUrl'.
 *
 *///w  ww. j a  v  a 2 s . co m
public FormValidation doCheckServerUrl(@QueryParameter("serverUrl") final String serverUrl)
        throws IOException, ServletException {
    if (StringUtils.isBlank(serverUrl)) {
        return FormValidation.error(Messages.HubBuildScan_getPleaseSetServerUrl());
    }
    URL url;
    try {
        url = new URL(serverUrl);
        try {
            url.toURI();
        } catch (final URISyntaxException e) {
            return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl());
        }
    } catch (final MalformedURLException e) {
        return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl());
    }
    try {
        Proxy proxy = null;

        final Jenkins jenkins = Jenkins.getInstance();
        if (jenkins != null) {
            final ProxyConfiguration proxyConfig = jenkins.proxy;
            if (proxyConfig != null) {
                proxy = ProxyConfiguration.createProxy(url.getHost(), proxyConfig.name, proxyConfig.port,
                        proxyConfig.noProxyHost);

                if (proxy != null && proxy != Proxy.NO_PROXY) {

                    if (StringUtils.isNotBlank(proxyConfig.getUserName())
                            && StringUtils.isNotBlank(proxyConfig.getPassword())) {
                        Authenticator.setDefault(new Authenticator() {
                            @Override
                            public PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(proxyConfig.getUserName(),
                                        proxyConfig.getPassword().toCharArray());
                            }
                        });
                    } else {
                        Authenticator.setDefault(null);
                    }
                }
            }
        }

        URLConnection connection = null;
        if (proxy != null) {
            connection = url.openConnection(proxy);
        } else {
            connection = url.openConnection();
        }

        connection.getContent();
    } catch (final IOException ioe) {
        return FormValidation.error(ioe, Messages.HubBuildScan_getCanNotReachThisServer_0_(serverUrl));
    } catch (final RuntimeException e) {
        return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl());
    }
    return FormValidation.ok();
}

From source file:com.panet.imeta.cluster.SlaveServer.java

/**
 * Contact the server and get back the reply as a string
 * @return the requested information//from   w  w  w. j a  va2 s.co  m
 * @throws Exception in case something goes awry 
 */
public String getContentFromServer(String service) throws Exception {
    // Following variable hides class variable. MB 7/10/07
    // LogWriter log = LogWriter.getInstance();

    String urlToUse = constructUrl(service);
    URL server;
    StringBuffer result = new StringBuffer();

    try {
        String beforeProxyHost = System.getProperty("http.proxyHost"); //$NON-NLS-1$
        String beforeProxyPort = System.getProperty("http.proxyPort"); //$NON-NLS-1$
        String beforeNonProxyHosts = System.getProperty("http.nonProxyHosts"); //$NON-NLS-1$

        BufferedReader input = null;

        try {
            if (log.isBasic())
                log.logBasic(toString(), Messages.getString("SlaveServer.DEBUG_ConnectingTo", urlToUse)); //$NON-NLS-1$

            if (proxyHostname != null) {
                System.setProperty("http.proxyHost", environmentSubstitute(proxyHostname)); //$NON-NLS-1$
                System.setProperty("http.proxyPort", environmentSubstitute(proxyPort)); //$NON-NLS-1$
                if (nonProxyHosts != null)
                    System.setProperty("http.nonProxyHosts", environmentSubstitute(nonProxyHosts)); //$NON-NLS-1$
            }

            if (username != null && username.length() > 0) {
                Authenticator.setDefault(new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(environmentSubstitute(username),
                                password != null ? environmentSubstitute(password).toCharArray()
                                        : new char[] {});
                    }
                });
            }

            // Get a stream for the specified URL
            server = new URL(urlToUse);
            URLConnection connection = server.openConnection();

            log.logDetailed(toString(), Messages.getString("SlaveServer.StartReadingReply")); //$NON-NLS-1$

            // Read the result from the server...
            InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 1000);

            input = new BufferedReader(new InputStreamReader(inputStream));

            long bytesRead = 0L;
            String line;
            while ((line = input.readLine()) != null) {
                result.append(line).append(Const.CR);
                bytesRead += line.length();
            }
            if (log.isBasic())
                log.logBasic(toString(), Messages.getString("SlaveServer.FinishedReadingResponse"), bytesRead); //$NON-NLS-1$
            if (log.isDebug())
                log.logDebug(toString(), "response from the webserver: {0}", result);
        } catch (MalformedURLException e) {
            log.logError(toString(), Messages.getString("SlaveServer.UrlIsInvalid", urlToUse, e.getMessage())); //$NON-NLS-1$
            log.logError(toString(), Const.getStackTracker(e));
        } catch (IOException e) {
            log.logError(toString(), Messages.getString("SlaveServer.CannotSaveDueToIOError", e.getMessage())); //$NON-NLS-1$
            log.logError(toString(), Const.getStackTracker(e));
        } catch (Exception e) {
            log.logError(toString(), Messages.getString("SlaveServer.ErrorReceivingFile", e.getMessage())); //$NON-NLS-1$
            log.logError(toString(), Const.getStackTracker(e));
        } finally {
            // Close it all
            try {
                if (input != null)
                    input.close();
            } catch (Exception e) {
                log.logError(toString(), Messages.getString("SlaveServer.CannotCloseStream", e.getMessage())); //$NON-NLS-1$
                log.logError(toString(), Const.getStackTracker(e));
            }

        }

        // Set the proxy settings back as they were on the system!
        System.setProperty("http.proxyHost", Const.NVL(beforeProxyHost, "")); //$NON-NLS-1$  //$NON-NLS-2$
        System.setProperty("http.proxyPort", Const.NVL(beforeProxyPort, "")); //$NON-NLS-1$  //$NON-NLS-2$
        System.setProperty("http.nonProxyHosts", Const.NVL(beforeNonProxyHosts, "")); //$NON-NLS-1$  //$NON-NLS-2$

        // Get the result back...
        return result.toString();
    } catch (Exception e) {
        throw new Exception(Messages.getString("SlaveServer.CannotContactURLForSecurityInformation", urlToUse), //$NON-NLS-1$
                e);
    }
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

public static String updateOrganization(int id, String[] configParams) {
    Client c = Client.create();/*  w  w w . ja  va 2s.  c o  m*/
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/configParamComposite/" + id);
    ConfigParamCompositeInstanceDocument pDoc = ConfigParamCompositeInstanceDocument.Factory.newInstance();
    pDoc.addNewConfigParamCompositeInstance();
    //        pDoc.getConfigParamCompositeInstance().setCommonName(commonName);
    //        pDoc.getConfigParamCompositeInstance().setDescription(description);
    //        pDoc.getConfigParamCompositeInstance().setConfigParamsArray(atomic);
    //

    String request = pDoc.toString();
    request = request.replace(" xmlns=\"http://xml.netbeans.org/schema/repo.xsd\"", "");
    request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + request;

    String resp = r.type(MediaType.TEXT_XML).put(String.class, request);
    System.out.println(resp);

    return null;

}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void saveToDatabase() throws Exception {
    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);

    // Make the server expect different password so our cache is no longer
    // valid (In case CredManager.resetAuthCache() did not succeed on non-Sun VMs)
    userRealm.put(USERNAME, PASSWORD3);/* w ww.  j  ava 2  s. c om*/
    // But we'll try with the old one, which we'll this time ask to save in
    // DB
    UsernamePassword usernamePassword = new UsernamePassword(USERNAME, PASSWORD2);
    usernamePassword.setShouldSave(true);
    //HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(usernamePassword);

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), usernamePassword);
    URLConnection c = url.openConnection();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    assertEquals("HTTP/1.1 401 Unauthorized", c.getHeaderField(0));

    assertTrue("Did not invoke authenticator enough times", authenticator.calls > 1);
    assertEquals("Asked our provider more than once, not saved in credMan?", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    // Expect the old one again
    userRealm.put(USERNAME, PASSWORD2);
    // We'll now set our provider to give an invalid password, but we should
    // not be asked
    // as the old one (now correct agian) is stored in DB
    //      HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(new UsernamePassword(
    //            USERNAME, WRONG_PASSWORD));
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, WRONG_PASSWORD));

    HTTPAuthenticatorServiceUsernameAndPasswordProvider.resetCalls();
    authenticator.calls = 0;

    URLConnection c2 = url.openConnection();
    try {
        c2.getContent();
    } catch (Exception ex) {
    }
    assertEquals("Did not call authenticator again with cache pw invalid", 1, authenticator.calls);
    assertEquals("Called our password provider instead of using credMan saved one", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
}