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:com.cloudera.recordservice.tests.ClusterConfiguration.java

/**
 * This method gets a cluster configuration and write the configuration to a
 * zipfile. The method returns the path of the zipfile.
 *//* ww w  .j  av  a2s . c om*/
private String getClusterConfiguration(URL url) throws IOException {
    // This Authenticator object sets the user and password field, similar to
    // using the --user username:password flag with the linux curl command
    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username_, password_.toCharArray());
        }
    });

    int num = rand_.nextInt(10000000);
    String confZipFileName = "/tmp/" + "clusterConf" + "_" + num + ".zip";
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        URLConnection conn = url.openConnection();
        is = conn.getInputStream();
        fos = new FileOutputStream(confZipFileName);
        byte[] buffer = new byte[4096];
        int len;
        while ((len = is.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }
    return confZipFileName;
}

From source file:sce.RESTJobStateful.java

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

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

        String url = jobDataMap.getString("#url");

        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();
        String result = getUrlContents(this.urlConnection);

        //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);

        //Mail.sendMail("prova", "disdsit@gmail.com", "prova di email", "", "");
        System.out.println("Instance " + key + " of REST Job returns: " + truncateResult(result));
    } catch (MalformedURLException e) {
        throw new JobExecutionException(e);
    } catch (IOException e) {
        throw new JobExecutionException(e);
    }
}

From source file:org.talend.core.nexus.NexusServerUtils.java

private static void search(String nexusUrl, final String userName, final String password, String repositoryId,
        String groupIdToSearch, String artifactId, String versionToSearch, int searchFrom, int searchCount,
        List<MavenArtifact> artifacts) throws Exception {
    HttpURLConnection urlConnection = null;
    int totalCount = 0;
    final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator();
    if (userName != null && !"".equals(userName)) {
        Authenticator.setDefault(new Authenticator() {

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

        });
    }
    try {
        String service = NexusConstants.SERVICES_SEARCH + getSearchQuery(repositoryId, groupIdToSearch,
                artifactId, versionToSearch, searchFrom, searchCount);
        urlConnection = getHttpURLConnection(nexusUrl, service, userName, password);
        SAXReader saxReader = new SAXReader();

        InputStream inputStream = urlConnection.getInputStream();
        Document document = saxReader.read(inputStream);
        // test
        // writeDocument(document, new File("D:/search.txt"));
        Node countNode = document.selectSingleNode("/searchNGResponse/totalCount");
        if (countNode != null) {
            try {
                totalCount = Integer.parseInt(countNode.getText());
            } catch (NumberFormatException e) {
                totalCount = 0;
            }
        }

        List<Node> list = document.selectNodes("/searchNGResponse/data/artifact");//$NON-NLS-1$ 
        for (Node arNode : list) {
            MavenArtifact artifact = new MavenArtifact();
            artifacts.add(artifact);
            artifact.setGroupId(arNode.selectSingleNode("groupId").getText());//$NON-NLS-1$ 
            artifact.setArtifactId(arNode.selectSingleNode("artifactId").getText());//$NON-NLS-1$ 
            artifact.setVersion(arNode.selectSingleNode("version").getText());//$NON-NLS-1$ 
            Node descNode = arNode.selectSingleNode("description");//$NON-NLS-1$ 
            if (descNode != null) {
                artifact.setDescription(descNode.getText());
            }
            Node urlNode = arNode.selectSingleNode("url");//$NON-NLS-1$ 
            if (urlNode != null) {
                artifact.setUrl(urlNode.getText());
            }
            Node licenseNode = arNode.selectSingleNode("license");//$NON-NLS-1$ 
            if (licenseNode != null) {
                artifact.setLicense(licenseNode.getText());
            }

            Node licenseUrlNode = arNode.selectSingleNode("licenseUrl");//$NON-NLS-1$ 
            if (licenseUrlNode != null) {
                artifact.setLicenseUrl(licenseUrlNode.getText());
            }

            List<Node> artLinks = arNode.selectNodes("artifactHits/artifactHit/artifactLinks/artifactLink");//$NON-NLS-1$ 
            for (Node link : artLinks) {
                Node extensionElement = link.selectSingleNode("extension");//$NON-NLS-1$ 
                String extension = null;
                String classifier = null;
                if (extensionElement != null) {
                    if ("pom".equals(extensionElement.getText())) {//$NON-NLS-1$ 
                        continue;
                    }
                    extension = extensionElement.getText();
                }
                Node classifierElement = link.selectSingleNode("classifier");//$NON-NLS-1$ 
                if (classifierElement != null) {
                    classifier = classifierElement.getText();
                }
                artifact.setType(extension);
                artifact.setClassifier(classifier);
            }
        }
        int searchDone = searchFrom + searchCount;
        int count = MAX_SEARCH_COUNT;
        if (searchDone < totalCount) {
            if (totalCount - searchDone < MAX_SEARCH_COUNT) {
                count = totalCount - searchDone;
            }
            search(nexusUrl, userName, password, repositoryId, groupIdToSearch, artifactId, versionToSearch,
                    searchDone + 1, count, artifacts);
        }

    } finally {
        Authenticator.setDefault(defaultAuthenticator);
        if (null != urlConnection) {
            urlConnection.disconnect();
        }
    }
}

From source file:sce.RESTAppMetricJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    Connection conn = null;/*  ww w .  j  a  v  a 2s.c o m*/
    try {
        String url1 = prop.getProperty("kb_url");
        //required parameters #url
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String callUrl = jobDataMap.getString("#url"); // url to call when passing result data from SPARQL query
        if (callUrl == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }
        String timeout = jobDataMap.getString("#timeout"); // timeout in ms to use when calling the #url
        if (timeout == null) {
            timeout = "5000";
        }

        //first SPARQL query to retrieve application related metrics and business configurations
        String url = url1 + "?query=" + URLEncoder.encode(getSPARQLQuery(), "UTF-8");
        URL u = new URL(url);
        final String usernamePassword = u.getUserInfo();
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");
        HashMap<String, Object> res = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r = (HashMap<String, Object>) res.get("results");
        ArrayList<Object> list = (ArrayList<Object>) r.get("bindings");
        ArrayList<String[]> lst = new ArrayList<>();
        for (Object obj : list) {
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value");
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value");
            lst.add(new String[] { mn, bc });
        }

        //second SPARQL query to retrieve alerts for SLA
        url = url1 + "?query=" + URLEncoder.encode(getValuesForMetrics(lst), "UTF-8");
        u = new URL(url);
        //java.io.FileWriter fstream = new java.io.FileWriter("/var/www/html/sce/log.txt", false);
        //java.io.BufferedWriter out = new java.io.BufferedWriter(fstream);
        //out.write(getAlertsForSLA(lst, slaTimestamp));
        //out.close();
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");

        //format the result
        HashMap<String, Object> alerts = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r1 = (HashMap<String, Object>) alerts.get("results");
        ArrayList<Object> list1 = (ArrayList<Object>) r1.get("bindings");
        String result = "";

        //MYSQL CONNECTION
        conn = Main.getConnection();
        // conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // use for transactions and at the end call conn.commit() conn.close()
        int counter = 0;

        //SET timestamp FOR MYSQL ROW
        Date dt = new java.util.Date();
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = sdf.format(dt);

        // JSON to be sent to the SM
        JSONArray jsonArray = new JSONArray();

        for (Object obj : list1) {
            //JSON to insert into database
            //JSONArray jsonArray = new JSONArray();
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value"); //metric
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value"); //metric_name
            String mu = (String) ((HashMap<String, Object>) o.get("mu")).get("value"); //metric_unit
            String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); //value
            String mt = (String) ((HashMap<String, Object>) o.get("mt")).get("value"); //metric_timestamp
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); //business_configuration

            // add these metric value to the json array
            JSONObject object = new JSONObject();
            object.put("business_configuration", bc);
            object.put("metric", sm);
            object.put("metric_name", mn);
            object.put("metric_unit", mu);
            object.put("value", v);
            object.put("metric_timestamp", mt);
            jsonArray.add(object);

            //INSERT THE DATA INTO DATABASE
            PreparedStatement preparedStatement = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_APP_METRICS (timestamp, metric, metric_name, metric_unit, value, metric_timestamp, business_configuration) VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE timestamp=?");
            preparedStatement.setString(1, timestamp); // date
            preparedStatement.setString(2, sm); // metric
            preparedStatement.setString(3, mn); // metric_name
            preparedStatement.setString(4, mu); // metric_unit
            preparedStatement.setString(5, v); // value
            preparedStatement.setString(6, mt); // metric_timestamp (e.g., 2014-12-01T16:14:00)
            preparedStatement.setString(7, bc); // business_configuration 
            preparedStatement.setString(8, timestamp); // date
            preparedStatement.executeUpdate();
            preparedStatement.close();

            result += "\nService Metric: " + sm + "\n";
            result += "\nMetric Name: " + mn + "\n";
            result += "\nMetric Unit: " + mu + "\n";
            result += "Timestamp: " + mt + "\n";
            result += "Business Configuration: " + bc + "\n";
            result += "Value" + (counter + 1) + ": " + v + "\n";
            result += "Call Url: " + callUrl + "\n";

            counter++;
        }

        // send the JSON to the CM
        URL tmp_u = new URL(callUrl);
        final String usr_pwd = tmp_u.getUserInfo();
        String usr = null;
        String pwd = null;
        if (usr_pwd != null) {
            usr = usr_pwd.split(":")[0];
            pwd = usr_pwd.split(":")[1];
        }
        sendPostRequest(jsonArray.toJSONString(), callUrl, usr, pwd, Integer.parseInt(timeout));

        //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 (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }
        jobChain(context);
    } catch (MalformedURLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (IOException | SQLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (!conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java

/**
 * This method is used get the proxy instance by using user provided proxy details
 * /*from  w  w  w  .  ja v a 2 s.c  o m*/
 * @param httpProxyUrl proxy url configured in property file
 * @param httpProxyPort proxy port configured in property file
 * @param httpProxyUsername proxy username to authenticate
 * @param httpProxyPassword proxy password to authenticate
 * @return proxy instance
 */
private Proxy getProxy(final String httpProxyUrl, final String httpProxyPort, final String httpProxyUsername,
        final String httpProxyPassword) {
    if (!httpProxyUrl.isEmpty() && !httpProxyPort.isEmpty()) {
        final InetSocketAddress socket = InetSocketAddress.createUnresolved(httpProxyUrl,
                Integer.parseInt(httpProxyPort));
        if (!httpProxyUsername.isEmpty() && !httpProxyPassword.isEmpty()) {
            Authenticator authenticator = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    LOGGER.info("proxy authentication called");
                    return (new PasswordAuthentication(httpProxyUsername, httpProxyPassword.toCharArray()));
                }
            };
            Authenticator.setDefault(authenticator);
        }
        return new Proxy(Proxy.Type.HTTP, socket);
    }
    return null;
}

From source file:org.nuxeo.ecm.core.storage.sql.JCloudsBinaryManager.java

@Override
public void initialize(BinaryManagerDescriptor binaryManagerDescriptor) throws IOException {
    super.initialize(binaryManagerDescriptor);

    // Get settings from the configuration
    storeProvider = Framework.getProperty(BLOBSTORE_PROVIDER_KEY);
    if (isBlank(storeProvider)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_PROVIDER_KEY);
    }//from   ww  w.  j  a va 2 s  .  c o  m
    container = Framework.getProperty(BLOBSTORE_MAP_NAME_KEY);
    if (isBlank(container)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_MAP_NAME_KEY);
    }

    String storeLocation = Framework.getProperty(BLOBSTORE_LOCATION_KEY);
    if (isBlank(storeLocation)) {
        storeLocation = null;
    }

    String storeIdentity = Framework.getProperty(BLOBSTORE_IDENTITY_KEY);
    if (isBlank(storeIdentity)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_IDENTITY_KEY);
    }

    String storeSecret = Framework.getProperty(BLOBSTORE_SECRET_KEY);
    if (isBlank(storeSecret)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_SECRET_KEY);
    }

    String cacheSizeStr = Framework.getProperty(CACHE_SIZE_KEY);
    if (isBlank(cacheSizeStr)) {
        cacheSizeStr = DEFAULT_CACHE_SIZE;
    }

    String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST);
    String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT);
    final String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN);
    final String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD);

    // Set up proxy
    if (isNotBlank(proxyHost)) {
        System.setProperty("https.proxyHost", proxyHost);
    }
    if (isNotBlank(proxyPort)) {
        System.setProperty("https.proxyPort", proxyPort);
    }
    if (isNotBlank(proxyLogin)) {
        System.setProperty("https.proxyUser", proxyLogin);
        System.setProperty("https.proxyPassword", proxyPassword);
        Authenticator.setDefault(new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyLogin, proxyPassword.toCharArray());
            }
        });
    }

    BlobStoreContext context = ContextBuilder.newBuilder(storeProvider).credentials(storeIdentity, storeSecret)
            .buildView(BlobStoreContext.class);

    // Try to create container if it doesn't exist
    blobStore = context.getBlobStore();
    boolean created = false;
    if (storeLocation == null) {
        created = blobStore.createContainerInLocation(null, container);
    } else {
        Location location = new LocationBuilder().scope(LocationScope.REGION).id(storeLocation)
                .description(storeLocation).build();
        created = blobStore.createContainerInLocation(location, container);
    }
    if (created) {
        log.debug("Created container " + container);
    }

    // Create file cache
    initializeCache(cacheSizeStr, new JCloudsFileStorage());
    createGarbageCollector();
}

From source file:org.nuxeo.ecm.blob.jclouds.JCloudsBinaryManager.java

@Override
public void initialize(String blobProviderId, Map<String, String> properties) throws IOException {
    super.initialize(blobProviderId, properties);

    // Get settings from the configuration
    storeProvider = getConfigurationProperty(BLOBSTORE_PROVIDER_KEY, properties);
    if (isBlank(storeProvider)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_PROVIDER_KEY);
    }//from   w w  w  .  j a v a 2 s .c om

    container = getConfigurationProperty(BLOBSTORE_MAP_NAME_KEY, properties);
    if (isBlank(container)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_MAP_NAME_KEY);
    }

    endpoint = getConfigurationProperty(BLOBSTORE_ENDPOINT_KEY, properties);

    String storeLocation = getConfigurationProperty(BLOBSTORE_LOCATION_KEY, properties);
    if (isBlank(storeLocation)) {
        storeLocation = null;
    }

    String storeIdentity = getConfigurationProperty(BLOBSTORE_IDENTITY_KEY, properties);
    if (isBlank(storeIdentity)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_IDENTITY_KEY);
    }

    String storeSecret = getConfigurationProperty(BLOBSTORE_SECRET_KEY, properties);
    if (isBlank(storeSecret)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_SECRET_KEY);
    }

    String cacheSizeStr = getConfigurationProperty(CACHE_SIZE_KEY, properties);
    if (isBlank(cacheSizeStr)) {
        cacheSizeStr = DEFAULT_CACHE_SIZE;
    }

    String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST);
    String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT);
    final String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN);
    final String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD);

    // Set up proxy
    if (isNotBlank(proxyHost)) {
        System.setProperty("https.proxyHost", proxyHost);
    }
    if (isNotBlank(proxyPort)) {
        System.setProperty("https.proxyPort", proxyPort);
    }
    if (isNotBlank(proxyLogin)) {
        System.setProperty("https.proxyUser", proxyLogin);
        System.setProperty("https.proxyPassword", proxyPassword);
        Authenticator.setDefault(new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyLogin, proxyPassword.toCharArray());
            }
        });
    }

    ContextBuilder builder = ContextBuilder.newBuilder(storeProvider).credentials(storeIdentity, storeSecret);

    if (isNotBlank(endpoint)) {
        builder.endpoint(endpoint);
    }

    BlobStoreContext context = builder.buildView(BlobStoreContext.class);

    // Try to create container if it doesn't exist
    blobStore = context.getBlobStore();
    boolean created = false;
    if (storeLocation == null) {
        created = blobStore.createContainerInLocation(null, container);
    } else {
        Location location = new LocationBuilder().scope(LocationScope.REGION).id(storeLocation)
                .description(storeLocation).build();
        created = blobStore.createContainerInLocation(location, container);
    }
    if (created) {
        log.debug("Created container " + container);
    }

    // Create file cache
    initializeCache(cacheSizeStr, new JCloudsFileStorage());
    createGarbageCollector();
}

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

@Test
@RunAsClient/* w ww  . ja va  2 s .c  om*/
public void scanForChangeInRepository(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL,
            "org.drools.guvnor.Guvnor/package/scanForChangeInRepository/LATEST/ChangeSet.xml");
    Resource res = ResourceFactory.newUrlResource(url);
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("admin", "admin".toCharArray());
        }
    });

    // system event listener
    SystemEventListenerFactory.setSystemEventListener(new PrintStreamSystemEventListener(System.out));

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    KnowledgeAgentConfiguration conf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
    // needs to be newInstance=true, bugzilla 733008 works fine with newInstance=false
    conf.setProperty("drools.agent.newInstance", "true");
    KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent("agent", kbase, conf);

    try {
        ResourceFactory.getResourceChangeNotifierService().start();
        ResourceFactory.getResourceChangeScannerService().start();

        ResourceChangeScannerConfiguration sconf = ResourceFactory.getResourceChangeScannerService()
                .newResourceChangeScannerConfiguration();
        sconf.setProperty("drools.resource.scanner.interval", "5");
        ResourceFactory.getResourceChangeScannerService().configure(sconf);

        kagent.applyChangeSet(res);
        kbase = kagent.getKnowledgeBase();
        Thread.sleep(1000);
        assertEquals(2, kbase.getKnowledgePackages().iterator().next().getRules().size());
        System.out.println("BUGZILLA 733008 total rules: "
                + kbase.getKnowledgePackages().iterator().next().getRules().size());
        for (Rule r : kbase.getKnowledgePackages().iterator().next().getRules()) {
            System.out.println(r.getName());
        }

        // Change Guvnor's repo with REST api by deleting asset rule2
        Abdera abdera = new Abdera();
        AbderaClient client = new AbderaClient(abdera);
        client.addCredentials(baseURL.toExternalForm(), null, null,
                new org.apache.commons.httpclient.UsernamePasswordCredentials("admin", "admin"));
        ClientResponse deleteResponse = client.delete(
                new URL(baseURL, "rest/packages/scanForChangeInRepository/assets/ruleB2").toExternalForm());
        assertEquals(204, deleteResponse.getStatus());
        ClientResponse binaryResponse = client
                .get(new URL(baseURL, "rest/packages/scanForChangeInRepository/binary").toExternalForm());
        assertEquals(200, binaryResponse.getStatus());

        // detect the change
        Thread.sleep(6000);
        kbase = kagent.getKnowledgeBase();
        assertEquals(1, kbase.getKnowledgePackages().iterator().next().getRules().size());

    } finally {
        kagent.dispose();
        ResourceFactory.getResourceChangeNotifierService().stop();
        ResourceFactory.getResourceChangeScannerService().stop();
    }
}

From source file:com.maestrodev.plugins.collabnet.FrsCopyWorker.java

private String copyArtifact(FrsSession frsSession, String releaseId)
        throws MalformedURLException, RemoteException {
    Artifact artifact = new DefaultArtifact(artifactGroupId, artifactId,
            VersionRange.createFromVersion(artifactVersion), null, artifactType, artifactClassifier,
            new DefaultArtifactHandler(artifactType));
    String path = new DefaultRepositoryLayout().pathOf(artifact);
    String url = repositoryUrl + "/" + path;

    String filename = this.filename;
    if (StringUtils.isBlank(filename)) {
        filename = path.substring(path.lastIndexOf('/') + 1);
    }//from ww w . j  av a 2s .  c  o  m

    String msg = "Uploading '" + url + "' to release '" + releaseId + "' as '" + filename + "'";
    logger.debug(msg);
    writeOutput(msg + "\n");

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(repositoryUsername, repositoryPassword.toCharArray());
        }
    });

    return frsSession.uploadFileFromUrl(releaseId, new URL(url), filename, overwrite);
}

From source file:org.eclipse.mylyn.gerrit.tests.support.GerritProject.java

public String registerAuthenticator(PrivilegeLevel privilegeLevel) throws Exception {
    // register authenticator to avoid HTTP password prompt
    AuthenticationCredentials credentials = fixture.location(privilegeLevel)
            .getCredentials(AuthenticationType.REPOSITORY);
    final PasswordAuthentication authentication = new PasswordAuthentication(credentials.getUserName(),
            credentials.getPassword().toCharArray());
    Authenticator.setDefault(new Authenticator() {
        @Override/* w w  w .ja v  a2  s  .co  m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    });
    return credentials.getUserName();
}