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.overlord.sramp.governance.workflow.jbpm.EmbeddedJbpmManager.java

@Override
public void signalProcess(long processInstanceId, String signalType, Object event) throws WorkflowException {
    HttpURLConnection connection = null;
    Governance governance = new Governance();
    final String username = governance.getOverlordUser();
    final String password = governance.getOverlordPassword();
    Authenticator.setDefault(new Authenticator() {
        @Override//w w w .java  2 s . c om
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });

    try {
        String urlStr = governance.getGovernanceUrl()
                + String.format("/rest/process/signal/%s/%s/%s", processInstanceId, signalType, event); //$NON-NLS-1$
        URL url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("PUT"); //$NON-NLS-1$
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (!(responseCode >= 200 && responseCode < 300)) {
            logger.error("HTTP RESPONSE CODE=" + responseCode); //$NON-NLS-1$
            throw new WorkflowException("Unable to connect to " + urlStr); //$NON-NLS-1$
        }

    } catch (Exception e) {
        throw new WorkflowException(e);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:com.eviware.soapui.support.SoapUIVersionUpdate.java

private String fetchVersionDocumentContent(final URL versionUrl) throws URISyntaxException, IOException {
    URLConnection connection = versionUrl.openConnection();
    InputStream inputStream = connection.getInputStream();
    String response = IOUtils.toString(inputStream);
    inputStream.close();//from ww  w.j ava2s.  c o  m
    Authenticator.setDefault(null);
    return response;
}

From source file:sce.RESTXMLJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {/*from   w ww . j  ava 2 s. c  om*/
        //JobKey key = context.getJobDetail().getKey();

        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

        String url = jobDataMap.getString("#url");
        String binding = jobDataMap.getString("#binding");
        if (url == null | binding == null) {
            throw new JobExecutionException("#url and #binding parameters 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();
        //detect and exclude BOM
        //BOMInputStream bomIn = new BOMInputStream(this.urlConnection.getInputStream(), false);
        Document document = docBuilder.parse(this.urlConnection.getInputStream());

        String result = parseXMLResponse(document.getDocumentElement(), binding, context);

        //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:net.sf.eclipsecs.core.config.configtypes.RemoteConfigurationType.java

/**
 * {@inheritDoc}/* ww w . ja v a2 s . com*/
 */
public CheckstyleConfigurationFile getCheckstyleConfiguration(ICheckConfiguration checkConfiguration)
        throws CheckstylePluginException {

    boolean useCacheFile = Boolean.valueOf(checkConfiguration.getAdditionalData().get(KEY_CACHE_CONFIG))
            .booleanValue();

    CheckstyleConfigurationFile data = new CheckstyleConfigurationFile();

    synchronized (Authenticator.class) {

        String currentRedirects = System.getProperty("http.maxRedirects"); //$NON-NLS-1$

        Authenticator oldAuthenticator = RemoteConfigAuthenticator.getDefault();
        try {

            // resolve the true configuration file URL
            data.setResolvedConfigFileURL(resolveLocation(checkConfiguration));

            Authenticator.setDefault(new RemoteConfigAuthenticator(data.getResolvedConfigFileURL()));

            boolean originalFileSuccess = false;
            byte[] configurationFileData = null;

            try {

                System.setProperty("http.maxRedirects", "3"); //$NON-NLS-1$ //$NON-NLS-2$

                URLConnection connection = data.getResolvedConfigFileURL().openConnection();

                // get the configuration file data
                configurationFileData = getBytesFromURLConnection(connection);

                // get last modification timestamp
                data.setModificationStamp(connection.getLastModified());

                originalFileSuccess = true;
            } catch (IOException e) {
                if (useCacheFile) {
                    configurationFileData = getBytesFromCacheFile(checkConfiguration);
                } else {
                    throw e;
                }
            }

            data.setCheckConfigFileBytes(configurationFileData);

            // get the properties bundle
            byte[] additionalPropertiesBytes = null;
            if (originalFileSuccess) {
                additionalPropertiesBytes = getAdditionPropertiesBundleBytes(data.getResolvedConfigFileURL());
            } else if (useCacheFile) {
                additionalPropertiesBytes = getBytesFromCacheBundleFile(checkConfiguration);
            }

            data.setAdditionalPropertyBundleBytes(additionalPropertiesBytes);

            // get the property resolver
            PropertyResolver resolver = getPropertyResolver(checkConfiguration, data);
            data.setPropertyResolver(resolver);

            // write to cache file
            if (originalFileSuccess && useCacheFile) {
                writeToCacheFile(checkConfiguration, configurationFileData, additionalPropertiesBytes);
            }

        } catch (UnknownHostException e) {
            CheckstylePluginException.rethrow(e,
                    NLS.bind(Messages.RemoteConfigurationType_errorUnknownHost, e.getMessage()));
        } catch (FileNotFoundException e) {
            CheckstylePluginException.rethrow(e,
                    NLS.bind(Messages.RemoteConfigurationType_errorFileNotFound, e.getMessage()));
        } catch (IOException e) {
            CheckstylePluginException.rethrow(e);
        } finally {
            Authenticator.setDefault(oldAuthenticator);

            if (currentRedirects != null) {
                System.setProperty("http.maxRedirects", currentRedirects); //$NON-NLS-1$
            } else {
                System.getProperties().remove("http.maxRedirects"); //$NON-NLS-1$
            }
        }

    }
    return data;
}

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

public static String createResourceInstance(String commonname, String rSpec, String state, String[] cfgId) {
    Client c = Client.create();// w w  w.jav a2 s.c o  m
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/resourceInstance/");
    ResourceInstanceInstanceDocument riDoc = ResourceInstanceInstanceDocument.Factory.newInstance();
    riDoc.addNewResourceInstanceInstance();
    riDoc.getResourceInstanceInstance().setCommonName(commonname);
    riDoc.getResourceInstanceInstance().setResourceSpec(rSpec);
    riDoc.getResourceInstanceInstance().setStateId(state);
    riDoc.getResourceInstanceInstance().setShared("true");
    for (int i = 0; i < cfgId.length; i++)
        riDoc.getResourceInstanceInstance().setConfigurationDataArray(cfgId);

    riDoc.getResourceInstanceInstance().setGeometry("1");
    riDoc.getResourceInstanceInstance().setDescription("singleton " + commonname);

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

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

}

From source file:io.github.microcks.task.ImportServiceDefinitionTask.java

/**
 * Extract URL Etag in order to avoid a reimport on unchanged resource.
 * @param repositoryUrl The URL to test as
 * @return The etag or null if none./*www.j  a  va2 s .c  o m*/
 */
private String getRepositoryUrlEtag(String repositoryUrl) {
    Authenticator.setDefault(new UsernamePasswordAuthenticator(username, password));
    try {
        URLConnection connection = new URL(repositoryUrl).openConnection();
        // Try simple syntax.
        String etag = connection.getHeaderField("Etag");
        if (etag != null) {
            log.debug("Found an Etag for " + repositoryUrl + ": " + etag);
            return etag;
        }
        // Try other syntax.
        etag = connection.getHeaderField("ETag");
        if (etag != null) {
            log.debug("Found an ETag for " + repositoryUrl + ": " + etag);
            return etag;
        }
    } catch (Exception e) {
        log.error("Caught an exception while retrieving Etag for " + repositoryUrl, e);
    }
    log.debug("No Etag found for " + repositoryUrl + " !");
    return null;
}

From source file:org.ttrssreader.net.JavaJSONConnector.java

@Override
public void init() {
    super.init();
    if (!httpAuth)
        return;//ww w.ja  v  a  2  s . c o  m

    try {
        base64NameAndPw = Base64.encodeToString((httpUsername + ":" + httpPassword).getBytes("UTF-8"),
                Base64.NO_WRAP);
    } catch (UnsupportedEncodingException e) {
        base64NameAndPw = null;
    }
    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(httpUsername, httpPassword.toCharArray());
        }
    });
}

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

@Test
@RunAsClient//w w w  . j a  va  2s . co m
public void applyChangeSetTwice(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "org.drools.guvnor.Guvnor/package/applyChangeSetTwice/LATEST/ChangeSet.xml");
    Resource res = ResourceFactory.newUrlResource(url);
    KnowledgeAgentConfiguration conf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("admin", "admin".toCharArray());
        }
    });
    KnowledgeAgent ka = KnowledgeAgentFactory.newKnowledgeAgent("test", conf);
    System.out.println("Applying changeset, round #1");
    Thread.sleep(1000);
    ka.applyChangeSet(res);
    for (KnowledgePackage pkg : ka.getKnowledgeBase().getKnowledgePackages()) {
        System.out.printf("  %s (%d)%n", pkg.getName(), pkg.getRules().size());
    }

    System.out.println("Applying changeset, round #2");
    Thread.sleep(1000);
    ka.applyChangeSet(res);
    for (KnowledgePackage pkg : ka.getKnowledgeBase().getKnowledgePackages()) {
        System.out.printf("  %s (%d)%n", pkg.getName(), pkg.getRules().size());
    }
}

From source file:com.cisco.gerrit.plugins.slack.client.WebhookClient.java

/**
 * Opens a connection to the provided Webhook URL.
 *
 * @param webhookUrl The Webhook URL to open a connection to.
 * @return The open connection to the provided Webhook URL.
 *//*from  www.  j av a  2s .com*/
private HttpURLConnection openConnection(String webhookUrl) {
    try {
        HttpURLConnection connection;
        if (StringUtils.isNotBlank(config.getProxyHost())) {
            LOGGER.info("Connecting via proxy");
            if (StringUtils.isNotBlank(config.getProxyUsername())) {
                Authenticator authenticator;
                authenticator = new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return (new PasswordAuthentication(config.getProxyUsername(),
                                config.getProxyPassword().toCharArray()));
                    }
                };
                Authenticator.setDefault(authenticator);
            }

            Proxy proxy;
            proxy = new Proxy(Proxy.Type.HTTP,
                    new InetSocketAddress(config.getProxyHost(), config.getProxyPort()));

            connection = (HttpURLConnection) new URL(webhookUrl).openConnection(proxy);
        } else {
            LOGGER.info("Connecting directly");
            connection = (HttpURLConnection) new URL(webhookUrl).openConnection();
        }
        return connection;
    } catch (MalformedURLException e) {
        throw new RuntimeException("Unable to create webhook URL: " + webhookUrl, e);
    } catch (IOException e) {
        throw new RuntimeException("Error opening connection to Slack URL: [" + e.getMessage() + "].", e);
    }
}

From source file:org.apache.maven.report.projectinfo.ProjectInfoReportUtils.java

/**
 * Get the input stream from an URL./* w  ww  .  ja v a 2 s . c  om*/
 *
 * @param url not null
 * @param project could be null
 * @param settings not null to handle proxy settings
 * @param encoding the wanted encoding for the inputstream. If empty, encoding will be "ISO-8859-1".
 * @return the inputstream found depending the wanted encoding.
 * @throws IOException if any
 * @since 2.3
 */
public static String getContent(URL url, MavenProject project, Settings settings, String encoding)
        throws IOException {
    String scheme = url.getProtocol();

    if (StringUtils.isEmpty(encoding)) {
        encoding = "ISO-8859-1";
    }

    if ("file".equals(scheme)) {
        InputStream in = null;
        try {
            URLConnection conn = url.openConnection();
            in = conn.getInputStream();

            return IOUtil.toString(in, encoding);
        } finally {
            IOUtil.close(in);
        }
    }

    Proxy proxy = settings.getActiveProxy();
    if (proxy != null) {
        if ("http".equals(scheme) || "https".equals(scheme) || "ftp".equals(scheme)) {
            scheme += ".";
        } else {
            scheme = "";
        }

        String host = proxy.getHost();
        if (!StringUtils.isEmpty(host)) {
            Properties p = System.getProperties();
            p.setProperty(scheme + "proxySet", "true");
            p.setProperty(scheme + "proxyHost", host);
            p.setProperty(scheme + "proxyPort", String.valueOf(proxy.getPort()));
            if (!StringUtils.isEmpty(proxy.getNonProxyHosts())) {
                p.setProperty(scheme + "nonProxyHosts", proxy.getNonProxyHosts());
            }

            final String userName = proxy.getUsername();
            if (!StringUtils.isEmpty(userName)) {
                final String pwd = StringUtils.isEmpty(proxy.getPassword()) ? "" : proxy.getPassword();
                Authenticator.setDefault(new Authenticator() {
                    /** {@inheritDoc} */
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(userName, pwd.toCharArray());
                    }
                });
            }
        }
    }

    InputStream in = null;
    try {
        URLConnection conn = getURLConnection(url, project, settings);
        in = conn.getInputStream();

        return IOUtil.toString(in, encoding);
    } finally {
        IOUtil.close(in);
    }
}