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:org.panlab.tgw.restclient.RepoAdapter.java

public static String updatePtmInfo(String id, String resourceSpecID) {
    PtmInfo ptmInfo = getPtmInfo(id);//  w  w w  . ja  va2s.co  m
    Client c = Client.create();
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/ptmInfo/" + id);
    PtmInfoInstanceDocument pDoc = PtmInfoInstanceDocument.Factory.newInstance();
    pDoc.addNewPtmInfoInstance();
    pDoc.getPtmInfoInstance().setCommonName(ptmInfo.getCommonName());
    pDoc.getPtmInfoInstance().setDescription(ptmInfo.getDescription());
    pDoc.getPtmInfoInstance().setId(ptmInfo.getId());
    ResourceSpecs[] rSpecs = ptmInfo.getResourceSpecsArray();
    rSpecs[0].addNewResourceSpec().setId(resourceSpecID);

    for (int i = 0; i < rSpecs[0].sizeOfResourceSpecArray(); i++) {
        String[] specs = new String[1];
        PtmInfoInstance.ResourceSpecs newSpec = pDoc.getPtmInfoInstance().addNewResourceSpecs();
        specs[0] = rSpecs[0].getResourceSpecArray()[i].getId();
        newSpec.setResourceSpecArray(specs);
    }

    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;
    System.out.println(request);

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

}

From source file:org.eclipse.andmore.android.localization.translators.GoogleTranslator.java

/**
 * Creates an HTTP request with the URL, execute it as a get, and returns
 * the a string with the result.// ww w. j  av a 2s  .  c  om
 * 
 * @param url
 *            URL to be executed.
 * @return String with the URL execution result.
 * @throws IOException
 *             If an exception occurs on transport
 * @throws HttpException
 *             If an exception occurs on the protocol
 * @throws Exception
 *             on error.
 */
protected static String executeHttpGetRequest(final URL url) throws HttpException {

    // Checking query size due to google policies
    if (url.toString().length() > MAX_QUERY_SIZE) {
        throw new HttpException(TranslateNLS.GoogleTranslator_Error_QueryTooBig);
    }

    // Try to retrieve proxy configuration to use if necessary
    IProxyService proxyService = ProxyManager.getProxyManager();
    IProxyData proxyData = null;
    if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) {
        Authenticator.setDefault(new ProxyAuthenticator());
        String urlStr = url.toString();
        if (urlStr.startsWith("https")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE);
            AndmoreLogger.debug(GoogleTranslator.class, "Using https proxy"); //$NON-NLS-1$
        } else if (urlStr.startsWith("http")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE);
            AndmoreLogger.debug(GoogleTranslator.class, "Using http proxy"); //$NON-NLS-1$
        } else {
            AndmoreLogger.debug(GoogleTranslator.class, "Not using any proxy"); //$NON-NLS-1$
        }
    }

    // Creates the http client and the method to be executed
    HttpClient client = null;
    client = new HttpClient();

    // If there is proxy data, work with it
    if (proxyData != null) {
        if (proxyData.getHost() != null) {
            // Sets proxy host and port, if any
            client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort());
        }

        if (proxyData.getUserId() != null && proxyData.getUserId().trim().length() > 0) {
            // Sets proxy user and password, if any
            Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(),
                    proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$
            client.getState().setProxyCredentials(AuthScope.ANY, cred);
        }
    }

    // Creating the method to be executed, the URL at this point is enough
    // because it is complete
    GetMethod method = new GetMethod(url.toString());

    // Set method to be retried three times in case of error
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(RETRIES, false));

    method.setRequestHeader(REFERER_HEADER, REFERER_SITE);

    // Set the connection timeout
    client.getHttpConnectionManager().getParams().setConnectionTimeout(new Integer(TIMEOUT));

    String result = ""; //$NON-NLS-1$
    try {
        // Execute the method.
        int statusCode;
        try {
            statusCode = client.executeMethod(method);
            result = method.getResponseBodyAsString(MAX_SIZE);
        } catch (IOException e) {
            throw new HttpException(TranslateNLS.GoogleTranslator_Error_CannotConnectToServer + e.getMessage());
        }

        checkStatusCode(statusCode, result);

        // Unescape any possible unicode char
        result = unescapeUnicode(result);

        // Unescape any possible HTML sequence
        result = unescapeHTML(result);

    }

    finally {
        // Release the connection.
        method.releaseConnection();
    }

    return result;
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Clear the default java.net.Authenticator (in case current one is loaded in web app)
 *//*from   ww w.j  a  v  a 2 s.  co  m*/
protected void clearDefaultAuthenticator() {
    final Authenticator defaultAuthenticator = getStaticFieldValue(Authenticator.class, "theAuthenticator");
    if (defaultAuthenticator == null || // Can both mean not set, or error retrieving, so unset anyway to be safe
            isLoadedInWebApplication(defaultAuthenticator)) {
        Authenticator.setDefault(null);
    }
}

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

public static String createResourceSpec(String type, String compoId) {
    Client c = Client.create();//ww  w  .j  a v a2 s.c o m
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/resourceSpec/");
    ResourceSpecInstanceDocument riDoc = ResourceSpecInstanceDocument.Factory.newInstance();
    riDoc.addNewResourceSpecInstance();
    riDoc.getResourceSpecInstance().setCommonName(type);
    riDoc.getResourceSpecInstance().setDescription("Resource Specification created by Teagle GW");
    riDoc.getResourceSpecInstance().setCost("100");
    riDoc.getResourceSpecInstance().setConfigurationParameters(compoId);

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

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

    resp = addSchemaDefinition(resp);
    try {
        ResourceSpecDocument pcDoc = ResourceSpecDocument.Factory.parse(resp);
        return pcDoc.getResourceSpec().getId();
    } catch (XmlException ex) {
        return null;
    }

}

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

public static String deleteResourceSpec(String Id) {
    Client c = Client.create();// w w  w  .  j  av  a 2s.  c om
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/resourceSpec/" + Id);
    r.type(MediaType.TEXT_XML).delete();
    return null;
}

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

public static Ptm[] getPtms() {
    Client c = Client.create();/*from  w w  w . ja  va  2  s.  c o m*/
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/ptm/");

    String resp = r.get(String.class);

    //System.out.println(resp);
    resp = addSchemaDefinition(resp);
    try {
        ListDocument lDoc = ListDocument.Factory.parse(resp);
        return lDoc.getList().getPtmArray();
    } catch (XmlException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.apache.jmeter.JMeter.java

/**
 * Sets a proxy server for the JVM if the command line arguments are
 * specified./*from ww  w.  ja  v a 2  s  .  com*/
 */
private void setProxy(CLArgsParser parser) throws IllegalUserActionException {
    if (parser.getArgumentById(PROXY_USERNAME) != null) {
        Properties jmeterProps = JMeterUtils.getJMeterProperties();
        if (parser.getArgumentById(PROXY_PASSWORD) != null) {
            String u, p;
            Authenticator
                    .setDefault(new ProxyAuthenticator(u = parser.getArgumentById(PROXY_USERNAME).getArgument(),
                            p = parser.getArgumentById(PROXY_PASSWORD).getArgument()));
            log.info("Set Proxy login: " + u + "/" + p);
            jmeterProps.setProperty(HTTP_PROXY_USER, u);//for Httpclient
            jmeterProps.setProperty(HTTP_PROXY_PASS, p);//for Httpclient
        } else {
            String u;
            Authenticator.setDefault(
                    new ProxyAuthenticator(u = parser.getArgumentById(PROXY_USERNAME).getArgument(), ""));
            log.info("Set Proxy login: " + u);
            jmeterProps.setProperty(HTTP_PROXY_USER, u);
        }
    }
    if (parser.getArgumentById(PROXY_HOST) != null && parser.getArgumentById(PROXY_PORT) != null) {
        String h = parser.getArgumentById(PROXY_HOST).getArgument();
        String p = parser.getArgumentById(PROXY_PORT).getArgument();
        System.setProperty("http.proxyHost", h);// $NON-NLS-1$
        System.setProperty("https.proxyHost", h);// $NON-NLS-1$
        System.setProperty("http.proxyPort", p);// $NON-NLS-1$
        System.setProperty("https.proxyPort", p);// $NON-NLS-1$
        log.info("Set http[s].proxyHost: " + h + " Port: " + p);
    } else if (parser.getArgumentById(PROXY_HOST) != null || parser.getArgumentById(PROXY_PORT) != null) {
        throw new IllegalUserActionException(JMeterUtils.getResString("proxy_cl_error"));// $NON-NLS-1$
    }

    if (parser.getArgumentById(NONPROXY_HOSTS) != null) {
        String n = parser.getArgumentById(NONPROXY_HOSTS).getArgument();
        System.setProperty("http.nonProxyHosts", n);// $NON-NLS-1$
        System.setProperty("https.nonProxyHosts", n);// $NON-NLS-1$
        log.info("Set http[s].nonProxyHosts: " + n);
    }
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

public static void main(String[] args) throws Exception {
    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password.toCharArray());
        }// w  ww  . jav  a  2 s. c o  m
    });
    ListIterator<String> it = Arrays.asList(args).listIterator();
    List<String> files = new ArrayList<String>();
    boolean forceAll = false;
    int maxThreads = -1;
    while (it.hasNext()) {
        String s = it.next();
        if ("-debug".equals(s)) {
            debug = true;
        } else if ("-user".equals(s)) {
            userName = it.next();
        } else if ("-password".equals(s)) {
            password = it.next();
        } else if ("-d".equals(s)) {
            rootOutputDir = new File(it.next());
        } else if ("-force".equals(s)) {
            forceAll = true;
        } else if ("-svn".equals(s)) {
            svn = true;
        } else if ("-commit".equals(s)) {
            commit = true;
        } else if ("-maxThreads".equals(s)) {
            maxThreads = Integer.parseInt(it.next());
        } else if (s != null && s.length() > 0) {
            files.add(s);
        }
    }

    List<SiteExporter> exporters = new ArrayList<SiteExporter>();
    for (String file : files) {
        exporters.add(new SiteExporter(file, forceAll));
    }
    List<SiteExporter> modified = new ArrayList<SiteExporter>();
    for (SiteExporter exporter : exporters) {
        if (exporter.initialize()) {
            modified.add(exporter);
        }
    }

    // render stuff only if needed
    if (!modified.isEmpty()) {
        setSiteExporters(exporters);

        if (maxThreads <= 0) {
            maxThreads = modified.size();
        }

        ExecutorService executor = Executors.newFixedThreadPool(maxThreads, new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setDaemon(true);
                return t;
            }
        });
        List<Future<?>> futures = new ArrayList<Future<?>>(modified.size());
        for (SiteExporter exporter : modified) {
            futures.add(executor.submit(exporter));
        }
        for (Future<?> t : futures) {
            t.get();
        }
    }

    if (commit) {
        File file = FileUtils.createTempFile("svncommit", "txt");
        FileWriter writer = new FileWriter(file);
        writer.write(svnCommitMessage.toString());
        writer.close();
        callSvn(rootOutputDir, "commit", "-F", file.getAbsolutePath(), rootOutputDir.getAbsolutePath());
        svnCommitMessage.setLength(0);
    }
}

From source file:org.tupelo_schneck.electric.Options.java

private void readAndProcessPassword() throws IOException {
    System.err.print("Please enter password for username '" + username + "': ");
    password = Options.reader.readLine();
    Authenticator.setDefault(new Authenticator() {
        @Override// w w  w.  j a  va 2  s. c o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });
}

From source file:org.ramadda.repository.Repository.java

/**
 * _more_//  w  ww .  j av  a 2  s .  c  o  m
 */
private void initProxy() {
    //First try the local ramadda properties
    //The default value is the system property 
    String proxyHost = getProperty(PROP_PROXY_HOST, getProperty("http.proxyHost", (String) null));
    String proxyPort = getProperty(PROP_PROXY_PORT, getProperty("http.proxyPort", "8080"));
    final String proxyUser = getProperty(PROP_PROXY_USER, (String) null);
    final String proxyPass = getProperty(PROP_PROXY_PASSWORD, (String) null);
    httpClient = new HttpClient();
    if (proxyHost != null) {
        getLogManager().logInfoAndPrint("Setting proxy server to:" + proxyHost + ":" + proxyPort);
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", proxyPort);
        System.setProperty("ftp.proxyHost", proxyHost);
        System.setProperty("ftp.proxyPort", proxyPort);
        httpClient.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
        // Just if proxy has authentication credentials
        if (proxyUser != null) {
            getLogManager().logInfoAndPrint("Setting proxy user to:" + proxyUser);
            httpClient.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyUser, proxyPass);
            httpClient.getState().setProxyCredentials(
                    new AuthScope(proxyHost, Integer.parseInt(proxyPort), AuthScope.ANY_REALM), defaultcreds);
            Authenticator.setDefault(new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxyUser, proxyPass.toCharArray());
                }
            });
        }
    }

}