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:io.uploader.drive.config.Configuration.java

private void setProxy() {
    setProxySystemProperty(httpProxySettings, "http");
    setProxySystemProperty(httpsProxySettings, "https");

    Authenticator.setDefault(new Authenticator() {
        @Override//from   w  w  w.j av  a 2s  . c o m
        protected PasswordAuthentication getPasswordAuthentication() {
            if (getRequestorType() == RequestorType.PROXY) {
                String prot = getRequestingProtocol().toLowerCase();

                String host = System.getProperty(prot + ".proxyHost", "");
                String port = System.getProperty(prot + ".proxyPort", "80");
                String user = System.getProperty(prot + ".proxyUser", "");
                String password = System.getProperty(prot + ".proxyPassword", "");

                if (getRequestingHost().equalsIgnoreCase(host)) {
                    if (Integer.parseInt(port) == getRequestingPort())
                        return new PasswordAuthentication(user, password.toCharArray());
                }
            }
            return null;
        }
    });
}

From source file:org.caleydo.data.importer.tcga.Settings.java

public boolean validate() {
    if (dataRuns == null)
        dataRuns = analysisRuns;//w w w.j  a v a  2  s.c o  m
    if (dataRuns.size() != analysisRuns.size()) {
        System.err.println(
                "Error during parsing of program arguments. You need to provide a corresponding data run for each analysis run. Closing program.");
        return false;
    }

    if (numThreads <= 0)
        numThreads = Runtime.getRuntime().availableProcessors();

    if (username != null && password != null) {
        username = fixPrompt(username, "Enter the username: ");
        password = fixPrompt(password, "Enter the password: ");
        // set Authenticator for following urls
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password.toCharArray());
            }
        });
    }

    if (awgGroup != null) {
        String tumor = awgGroup.toUpperCase();
        // check if not manually overridden
        if (analysisPattern.equals(ANALYSIS_PATTERN))
            analysisPattern = BASE_URL + "awg_" + awgGroup
                    + "__{0,date,yyyy_MM_dd}/data/{2}/{0,date,yyyyMMdd}/{3}";
        if (filePattern.equals(FILE_PATTERN))
            filePattern = "gdac.broadinstitute.org_{1}.{3}.Level_{4}.{0,date,yyyyMMdd}00.0.0.tar.gz";
        if (dataPattern.equals(DATA_PATTERN))
            dataPattern = BASE_URL + "/stddata__{0,date,yyyy_MM_dd}/data/" + tumor + "/{0,date,yyyyMMdd}/{3}";
        if (dataFilePattern.equals(DATAFILE_PATTERN))
            dataFilePattern = "gdac.broadinstitute.org_" + tumor
                    + ".{3}.Level_{4}.{0,date,yyyyMMdd}00.0.0.tar.gz";
        if (reportPattern.equals(REPORT_PATTERN))
            reportPattern = BASE_URL + "awg_" + awgGroup + "__{0,date,yyyy_MM_dd}/reports/cancer/{1}/";
    }

    return true;
}

From source file:hudson.ProxyConfiguration.java

public static InputStream getInputStream(URL url) throws IOException {
    Jenkins h = Jenkins.getInstance(); // this code might run on slaves
    final ProxyConfiguration p = (h != null) ? h.proxy : null;
    if (p == null)
        return new RetryableHttpStream(url);

    InputStream is = new RetryableHttpStream(url, p.createProxy(url.getHost()));
    if (p.getUserName() != null) {
        // Add an authenticator which provides the credentials for proxy authentication
        Authenticator.setDefault(new Authenticator() {

            @Override// w w  w. j  a  v a  2 s  .  c o m
            public PasswordAuthentication getPasswordAuthentication() {
                if (getRequestorType() != RequestorType.PROXY) {
                    return null;
                }
                return new PasswordAuthentication(p.getUserName(), p.getPassword().toCharArray());
            }
        });
    }

    return is;
}

From source file:nl.b3p.viewer.stripes.CycloramaActionBean.java

public Resolution directRequest() throws UnsupportedEncodingException, URISyntaxException, URIException,
        IOException, SAXException, ParserConfigurationException {
    Double x1 = x - offset;/*from ww w  .j a  v a  2 s . c om*/
    Double y1 = y - offset;
    Double x2 = x + offset;
    Double y2 = y + offset;
    final String username = "B3_develop";
    final String password = "8ndj39";
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

    Coordinate coord = new Coordinate(x, y);
    Point point = geometryFactory.createPoint(coord);

    URL url2 = new URL(
            "https://atlas.cyclomedia.com/recordings/wfs?service=WFS&VERSION=1.1.0&maxFeatures=100&request=GetFeature&SRSNAME=EPSG:28992&typename=atlas:Recording"
                    + "&filter=<Filter><And><BBOX><gml:Envelope%20srsName=%27EPSG:28992%27>"
                    + "<gml:lowerCorner>" + x1.intValue() + "%20" + y1.intValue() + "</gml:lowerCorner>"
                    + "<gml:upperCorner>" + x2.intValue() + "%20" + y2.intValue()
                    + "</gml:upperCorner></gml:Envelope></BBOX><ogc:PropertyIsNull><ogc:PropertyName>expiredAt</ogc:PropertyName></ogc:PropertyIsNull></And></Filter>");

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });
    InputStream is = url2.openStream();

    // wrap the urlconnection in a bufferedreader
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

    String line;

    StringBuilder content = new StringBuilder();
    // read from the urlconnection via the bufferedreader
    while ((line = bufferedReader.readLine()) != null) {
        content.append(line + "\n");
    }
    bufferedReader.close();

    String s = content.toString();
    String tsString = "timeStamp=";
    int indexOfTimestamp = s.indexOf(tsString);
    int indexOfLastQuote = s.indexOf("\"", indexOfTimestamp + 2 + tsString.length());
    String contentString = s.substring(0, indexOfTimestamp - 2);
    contentString += s.substring(indexOfLastQuote);

    contentString = removeDates(contentString, "<atlas:recordedAt>", "</atlas:recordedAt>");

    Configuration configuration = new org.geotools.gml3.GMLConfiguration();
    configuration.getContext().registerComponentInstance(new GeometryFactory(new PrecisionModel(), 28992));

    Parser parser = new Parser(configuration);
    parser.setValidating(false);
    parser.setStrict(false);
    parser.setFailOnValidationError(false);

    ByteArrayInputStream bais = new ByteArrayInputStream(contentString.getBytes());
    Object obj = parser.parse(bais);

    SimpleFeatureCollection fc = (SimpleFeatureCollection) obj;

    SimpleFeatureIterator it = fc.features();
    SimpleFeature sf = null;
    List<SimpleFeature> fs = new ArrayList<SimpleFeature>();
    while (it.hasNext()) {
        sf = it.next();
        sf.getUserData().put(DISTANCE_KEY, point.distance((Geometry) sf.getDefaultGeometry()));
        fs.add(sf);
    }
    Collections.sort(fs, new Comparator<SimpleFeature>() {
        @Override
        public int compare(SimpleFeature o1, SimpleFeature o2) {
            Double d1 = (Double) o1.getUserData().get(DISTANCE_KEY);
            Double d2 = (Double) o2.getUserData().get(DISTANCE_KEY);
            return d1.compareTo(d2);
        }
    });
    SimpleFeature f = fs.get(0);
    imageId = (String) f.getAttribute("imageId");
    sign();
    return new ForwardResolution("/WEB-INF/jsp/app/globespotter.jsp");
}

From source file:org.openbravo.test.datasource.TestAllowUnpagedDatasourcePreference.java

private HttpURLConnection createConnection(String wsPart, String method) throws Exception {
    Authenticator.setDefault(new Authenticator() {
        @Override//w w w.  j a v a  2  s  .co  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(LOGIN, PWD.toCharArray());
        }
    });
    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:sce.RESTKBJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {/*from   www. j ava 2  s. c o  m*/
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

        String url = jobDataMap.getString("#url");
        if (url == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }

        URL u = new URL(url);

        //get user credentials from URL, if present
        final String usernamePassword = u.getUserInfo();

        //set the basic authentication credentials for the connection
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }

        //set the url connection, to disconnect if interrupt() is requested
        this.urlConnection = u.openConnection();

        //set the "Accept" header
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+xml");

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(this.urlConnection.getInputStream());

        parseKBResponse(document.getDocumentElement(), context);

        //set of the result is done in the method parseKBresponse, because it is built invoking it iteratively
        //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
        //context.setResult(result);
        //if notificationEmail is defined in the job data map, then send a notification email to it
        if (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }

        //trigger the linked jobs of the finished job, depending on the job result [true, false]
        jobChain(context);
        //System.out.println("Instance " + key + " of REST Job returns: " + truncateResult(result));
    } catch (IOException | ParserConfigurationException | SAXException e) {
        e.printStackTrace(System.out);
        throw new JobExecutionException(e);
    }
}

From source file:com.hortonworks.registries.storage.tool.sql.DatabaseUserInitializer.java

private static Authenticator getBasicAuthenticator(String host, int port, String username, String password) {
    return new Authenticator() {
        @Override/*w w w .j av a  2  s.  c  o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            if (getRequestorType() == RequestorType.PROXY) {
                if (getRequestingHost().equalsIgnoreCase(host)) {
                    if (getRequestingPort() == port) {
                        return new PasswordAuthentication(username, password.toCharArray());
                    }
                }
            }
            return null;
        }
    };
}

From source file:org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin.java

private void configureProxy() {
    // It seems there is no way to set a proxy provider type (manual, native or
    // direct) without the Eclipse UI.
    // The org.eclipse.core.net plugin removes the http., https. system properties
    // when setting its preferences and a proxy provider isn't manual.
    // We save these parameters and set them after starting the
    // org.eclipse.core.net plugin.
    String httpHost = System.getProperty(HTTP_PROXY_HOST);
    String httpPort = System.getProperty(HTTP_PROXY_PORT);
    String httpUser = System.getProperty(HTTP_PROXY_USER);
    String httpPassword = System.getProperty(HTTP_PROXY_PASSWORD);
    String httpsHost = System.getProperty(HTTPS_PROXY_HOST);
    String httpsPort = System.getProperty(HTTPS_PROXY_PORT);
    String httpsUser = System.getProperty(HTTPS_PROXY_USER);
    String httpsPassword = System.getProperty(HTTPS_PROXY_PASSWORD);
    String httpsNonProxyHosts = System.getProperty(HTTPS_NON_PROXY_HOSTS);
    String httpNonProxyHosts = System.getProperty(HTTP_NON_PROXY_HOSTS);
    if (StringUtils.isNotBlank(httpUser) || StringUtils.isNotBlank(httpsUser)) {
        try {//  www. j  a  v a2 s  .c  o  m
            Platform.getBundle("org.eclipse.core.net").start(Bundle.START_TRANSIENT);
        } catch (BundleException e) {
            logException(e.getMessage(), e);
        }
        if (StringUtils.isNotBlank(httpUser) && StringUtils.isNotBlank(httpPassword)) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(httpUser, httpPassword.toCharArray());
                }
            });
        }
        IProxyService proxyService = getProxyService();
        if (proxyService != null) {
            ProxySelector.setActiveProvider(MANUAL);
            IProxyData[] proxies = proxyService.getProxyData();
            for (IProxyData proxy : proxies) {
                if ("HTTP".equals(proxy.getType())) {
                    proxy.setHost(httpHost);
                    proxy.setPort(httpPort == null ? -1 : Integer.valueOf(httpPort));
                    proxy.setPassword(httpPassword);
                    proxy.setUserid(httpUser);
                }
                if ("HTTPS".equals(proxy.getType())) {
                    proxy.setHost(httpsHost);
                    proxy.setPort(httpsPort == null ? -1 : Integer.valueOf(httpsPort));
                    proxy.setPassword(httpsPassword);
                    proxy.setUserid(httpsUser);
                }
            }
            try {
                proxyService.setProxyData(proxies);
                if (httpHost != null) {
                    System.setProperty(HTTP_PROXY_HOST, httpHost);
                }
                if (httpPort != null) {
                    System.setProperty(HTTP_PROXY_PORT, httpPort);
                }
                if (httpUser != null) {
                    System.setProperty(HTTP_PROXY_USER, httpUser);
                }
                if (httpPassword != null) {
                    System.setProperty(HTTP_PROXY_PASSWORD, httpPassword);
                }
                if (httpsHost != null) {
                    System.setProperty(HTTPS_PROXY_HOST, httpsHost);
                }
                if (httpsPort != null) {
                    System.setProperty(HTTPS_PROXY_PORT, httpsPort);
                }
                if (httpsUser != null) {
                    System.setProperty(HTTPS_PROXY_USER, httpsUser);
                }
                if (httpsPassword != null) {
                    System.setProperty(HTTPS_PROXY_PASSWORD, httpsPassword);
                }
                if (httpsNonProxyHosts != null) {
                    System.setProperty(HTTPS_NON_PROXY_HOSTS, httpsNonProxyHosts);
                }
                if (httpNonProxyHosts != null) {
                    System.setProperty(HTTP_NON_PROXY_HOSTS, httpNonProxyHosts);
                }
            } catch (CoreException e) {
                logException(e.getMessage(), e);
            }
        }
    }
}

From source file:org.drools.guvnor.server.files.PackageDeploymentServletChangeSetIntegrationTest.java

@Test
@RunAsClient//from   ww w. ja va2s. co  m
public void downloadPackageWithHttpClientImpl(@ArquillianResource URL baseURL)
        throws IOException, ClassNotFoundException {
    URL url = new URL(baseURL, "org.drools.guvnor.Guvnor/package/downloadPackageWithHttpClientImpl/snapshotC1");
    Resource resource = ResourceFactory.newUrlResource(url);
    KnowledgeAgentConfiguration conf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("admin", "admin".toCharArray());
        }
    });
    InputStream in = null;
    Collection<KnowledgePackage> kpkgs = null;
    try {
        in = resource.getInputStream();
        Object object = DroolsStreamUtils.streamIn(in);
        if (object instanceof Collection) {
            kpkgs = (Collection<KnowledgePackage>) object;
        } else if (object instanceof KnowledgePackageImp) {
            kpkgs = Collections.singletonList((KnowledgePackage) object);
        } else if (object instanceof Package) {
            kpkgs = Collections.singletonList((KnowledgePackage) new KnowledgePackageImp((Package) object));
        } else if (object instanceof Package[]) {
            kpkgs = new ArrayList<KnowledgePackage>();
            for (Package pkg : (Package[]) object) {
                kpkgs.add(new KnowledgePackageImp(pkg));
            }
        } else {
            throw new RuntimeException("Unknown binary format trying to load resource " + resource.toString());
        }
    } finally {
        IOUtils.closeQuietly(in);
    }

    assertNotNull(kpkgs);
    assertFalse(kpkgs.isEmpty());
    assertNotNull(kpkgs.iterator().next());
}

From source file:com.freedomotic.plugins.devices.phwswethv2.ProgettiHwSwEthv2.java

private Document getXMLStatusFile(Board board) {
    final Board b = board;
    //get the xml file from the socket connection
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {/*w w  w.j ava2s.  c  o  m*/
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(ProgettiHwSwEthv2.class.getName()).log(Level.SEVERE, null, ex);
    }
    Document doc = null;
    String statusFileURL = null;
    try {
        if (board.getAuthentication().equalsIgnoreCase("true")) {
            Authenticator.setDefault(new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(b.getUsername(), b.getPassword().toCharArray());
                }
            });
            statusFileURL = "http://" + b.getIpAddress() + ":" + Integer.toString(b.getPort()) + "/protect/"
                    + GET_STATUS_URL;
        } else {
            statusFileURL = "http://" + b.getIpAddress() + ":" + Integer.toString(b.getPort()) + "/"
                    + GET_STATUS_URL;
        }

        LOG.info("ProgettiHwSwEth gets relay status from file " + statusFileURL);
        doc = dBuilder.parse(new URL(statusFileURL).openStream());
        doc.getDocumentElement().normalize();
    } catch (ConnectException connEx) {
        disconnect();
        this.stop();
        this.setDescription("Connection timed out, no reply from the board at " + statusFileURL);
    } catch (SAXException ex) {
        disconnect();
        this.stop();
        LOG.severe(Freedomotic.getStackTraceInfo(ex));
    } catch (Exception ex) {
        disconnect();
        this.stop();
        setDescription("Unable to connect to " + statusFileURL);
        LOG.severe(Freedomotic.getStackTraceInfo(ex));
    }
    return doc;

}