Example usage for org.apache.http.auth AuthScope ANY

List of usage examples for org.apache.http.auth AuthScope ANY

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY.

Prototype

AuthScope ANY

To view the source code for org.apache.http.auth AuthScope ANY.

Click Source Link

Document

Default scope matching any host, port, realm and authentication scheme.

Usage

From source file:com.evolveum.midpoint.notifications.impl.api.transports.SimpleSmsTransport.java

@Override
public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) {

    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo());
    result.addParam("message subject", message.getSubject());

    SystemConfigurationType systemConfiguration = NotificationFunctionsImpl
            .getSystemConfiguration(cacheRepositoryService, result);
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null) {
        String msg = "No notifications are configured. SMS notification to " + message.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);//from w w w  . j  a v a 2 s .c  o  m
        result.recordWarning(msg);
        return;
    }

    String smsConfigName = StringUtils.substringAfter(transportName, NAME + ":");
    SmsConfigurationType found = null;
    for (SmsConfigurationType smsConfigurationType : systemConfiguration.getNotificationConfiguration()
            .getSms()) {
        if (StringUtils.isEmpty(smsConfigName) && smsConfigurationType.getName() == null
                || StringUtils.isNotEmpty(smsConfigName)
                        && smsConfigName.equals(smsConfigurationType.getName())) {
            found = smsConfigurationType;
            break;
        }
    }

    if (found == null) {
        String msg = "SMS configuration '" + smsConfigName + "' not found. SMS notification to "
                + message.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    SmsConfigurationType smsConfigurationType = found;
    String logToFile = smsConfigurationType.getLogToFile();
    if (logToFile != null) {
        TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER);
    }
    String file = smsConfigurationType.getRedirectToFile();
    if (file != null) {
        writeToFile(message, file, null, emptyList(), null, result);
        return;
    }

    if (smsConfigurationType.getGateway().isEmpty()) {
        String msg = "SMS gateway(s) are not defined, notification to " + message.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    String from;
    if (message.getFrom() != null) {
        from = message.getFrom();
    } else if (smsConfigurationType.getDefaultFrom() != null) {
        from = smsConfigurationType.getDefaultFrom();
    } else {
        from = "";
    }

    if (message.getTo().isEmpty()) {
        String msg = "There is no recipient to send the notification to.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    List<String> to = message.getTo();
    assert to.size() > 0;

    for (SmsGatewayConfigurationType smsGatewayConfigurationType : smsConfigurationType.getGateway()) {
        OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway");
        resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName());
        try {
            ExpressionVariables variables = getDefaultVariables(from, to, message);
            HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET);
            ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(),
                    smsGatewayConfigurationType.getUrl());
            String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task,
                    result);
            LOGGER.debug("Sending SMS to URL {} (method {})", url, method);
            if (url == null) {
                throw new IllegalArgumentException("No URL specified");
            }

            List<String> headersList = evaluateExpressionsChecked(
                    smsGatewayConfigurationType.getHeadersExpression(), variables,
                    "sms gateway request headers", task, result);
            LOGGER.debug("Using request headers:\n{}", headersList);

            String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(),
                    StandardCharsets.ISO_8859_1.name());
            String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables,
                    "sms gateway request body", task, result);
            LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body);

            if (smsGatewayConfigurationType.getLogToFile() != null) {
                TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(),
                        formatToFile(message, url, headersList, body), LOGGER);
            }
            if (smsGatewayConfigurationType.getRedirectToFile() != null) {
                writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body,
                        resultForGateway);
                result.computeStatus();
                return;
            } else {
                HttpClientBuilder builder = HttpClientBuilder.create();
                String username = smsGatewayConfigurationType.getUsername();
                ProtectedStringType password = smsGatewayConfigurationType.getPassword();
                if (username != null) {
                    CredentialsProvider provider = new BasicCredentialsProvider();
                    String plainPassword = password != null ? protector.decryptString(password) : null;
                    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,
                            plainPassword);
                    provider.setCredentials(AuthScope.ANY, credentials);
                    builder = builder.setDefaultCredentialsProvider(provider);
                }
                HttpClient client = builder.build();
                HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                        client);
                ClientHttpRequest request = requestFactory.createRequest(new URI(url),
                        HttpUtil.toHttpMethod(method));
                setHeaders(request, headersList);
                if (body != null) {
                    request.getBody().write(body.getBytes(encoding));
                }
                ClientHttpResponse response = request.execute();
                LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText());
                if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
                    throw new SystemException("SMS gateway communication failed: " + response.getStatusCode()
                            + ": " + response.getStatusText());
                }
                LOGGER.info("Message sent successfully to {} via gateway {}.", message.getTo(),
                        smsGatewayConfigurationType.getName());
                resultForGateway.recordSuccess();
                result.recordSuccess();
                return;
            }
        } catch (Throwable t) {
            String msg = "Couldn't send SMS to " + message.getTo() + " via "
                    + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any";
            LoggingUtils.logException(LOGGER, msg, t);
            resultForGateway.recordFatalError(msg, t);
        }
    }
    LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent.");
    result.recordWarning("Notification to " + message.getTo() + " could not be sent.");
}

From source file:org.topbraid.jenax.util.ARQFactory.java

public static HttpClient buildHttpClient(String serviceURI, String user, String password) {
    if (user == null)
        return HttpOp.getDefaultHttpClient();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(user, password);
    credsProvider.setCredentials(AuthScope.ANY, credentials);
    return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    // Example for scoped credentials 
    // See http://jena.staging.apache.org/documentation/query/http-auth.html
    //      CredentialsProvider credsProvider = new BasicCredentialsProvider();
    //      Credentials unscopedCredentials = new UsernamePasswordCredentials("user", "passwd");
    //      credsProvider.setCredentials(AuthScope.ANY, unscopedCredentials);
    //      Credentials scopedCredentials = new UsernamePasswordCredentials("user", "passwd");
    //      final String host = "http://example.com/sparql";
    //      final int port = 80;
    //      final String realm = "aRealm";
    //      final String schemeName = "DIGEST";
    //      AuthScope authscope = new AuthScope(host, port, realm, schemeName);
    //      credsProvider.setCredentials(authscope, scopedCredentials);
    //      return HttpClients.custom()
    //          .setDefaultCredentialsProvider(credsProvider)
    //          .build();

}

From source file:com.naryx.tagfusion.cfm.xml.ws.javaplatform.DynamicWebServiceStubGenerator.java

@SuppressWarnings("deprecation")
private String getWSDLContents(String wsdlURL, CallParameters cp) throws cfmRunTimeException {
    try {//from  w w w. ja  va  2  s.  co m
        String wsdlL = wsdlURL.toLowerCase();
        String contents = null;
        if (wsdlL.startsWith("<?xml version")) {
            // The location is the WSDL itself (unexpected)
            contents = wsdlURL;
        } else {
            InputStream is = null;
            InputStreamReader isr = null;
            StringBuilder buffy = null;
            HttpGet method = null;
            try {
                if (wsdlL.startsWith("http:") || wsdlL.startsWith("https:")) {
                    // Read from network
                    DefaultHttpClient client = new DefaultHttpClient();

                    // Set the timeout
                    int timeout = cp.getTimeout();
                    client.getParams().setParameter("http.connection.timeout", timeout);
                    client.getParams().setParameter("http.socket.timeout", timeout);

                    if (cp.getUsername() != null || cp.getPassword() != null) {
                        // Set any credentials
                        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(cp.getUsername(), cp.getPassword()));
                    }

                    if (cp.getProxyServer() != null) {
                        // Set the proxy
                        HttpHost proxy = new HttpHost(cp.getProxyServer(),
                                (cp.getProxyPort() == -1) ? cp.getDefaultProxyPort() : cp.getProxyPort());
                        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                        if (cp.getProxyUser() != null || cp.getProxyPassword() != null) {
                            // Set the proxy credentials
                            client.getCredentialsProvider().setCredentials(
                                    new AuthScope(cp.getProxyServer(), cp.getProxyPort()),
                                    new UsernamePasswordCredentials(cp.getProxyUser(), cp.getProxyPassword()));

                        }
                    }

                    // Create the method and get the response
                    method = new HttpGet(wsdlURL);
                    client.getParams().setParameter("http.protocol.handle-redirects", true);
                    HttpResponse response = client.execute(method);
                    switch (response.getStatusLine().getStatusCode()) {
                    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
                        throw new cfmRunTimeException(
                                catchDataFactory.extendedException("errorCode.runtimeError",
                                        "Failed to access WSDL: " + wsdlURL
                                                + ". Proxy authentication is required.",
                                        response.getStatusLine().toString()));
                    case HttpStatus.SC_UNAUTHORIZED:
                        throw new cfmRunTimeException(
                                catchDataFactory.extendedException("errorCode.runtimeError",
                                        "Failed to access WSDL: " + wsdlURL + ". Authentication is required.",
                                        response.getStatusLine().toString()));
                    case HttpStatus.SC_USE_PROXY:
                        throw new cfmRunTimeException(
                                catchDataFactory.extendedException("errorCode.runtimeError",
                                        "Failed to access WSDL: " + wsdlURL
                                                + ". The use of a proxy is required.",
                                        response.getStatusLine().toString()));
                    }
                    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                        throw new cfmRunTimeException(catchDataFactory.extendedException(
                                "errorCode.runtimeError", "Failed to access WSDL: " + wsdlURL,
                                response.getStatusLine().toString()));
                    is = response.getEntity().getContent();
                } else {
                    // Just try to read off disk
                    File f = new File(wsdlURL);
                    is = new FileInputStream(f);
                }

                // Read the data
                char[] buf = new char[4096];
                int read = -1;
                buffy = new StringBuilder();
                isr = new InputStreamReader(is);
                while ((read = isr.read(buf, 0, buf.length)) != -1)
                    buffy.append(buf, 0, read);
                contents = buffy.toString();
            } finally {
                if (isr != null)
                    isr.close();
                if (is != null)
                    is.close();
                if (method != null)
                    method.releaseConnection();
            }
        }

        // Calc the sum and return
        return contents;
    } catch (IOException ex) {
        throw new cfmRunTimeException(
                catchDataFactory.generalException("errorCode.runtimeError", "Failed to access WSDL located at "
                        + wsdlURL + ". There may be an error in the target WSDL. " + ex.getMessage()));
    }
}

From source file:net.java.sip.communicator.impl.protocol.sip.xcap.BaseHttpXCapClient.java

/**
 * Creates HTTP client with special parameters.
 *
 * @return the HTTP client.//from   w  w  w .  ja va2  s.  co m
 */
private DefaultHttpClient createHttpClient() throws IOException {
    XCapCredentialsProvider credentialsProvider = new XCapCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(getUserName(), password));

    return HttpUtils.getHttpClient(null, null, uri.getHost(), credentialsProvider);
}

From source file:org.springframework.data.solr.server.support.SolrClientUtilTests.java

/**
 * @see DATASOLR-189/* w w  w .  java 2  s  .co  m*/
 */
@Test
public void cloningHttpSolrClientShouldCopyCredentialsProviderCorrectly() {

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("foo", "bar"));

    DefaultHttpClient client = new DefaultHttpClient();
    client.setCredentialsProvider(credentialsProvider);

    HttpSolrClient solrClient = new HttpSolrClient(BASE_URL, client);
    HttpSolrClient cloned = SolrClientUtils.clone(solrClient);

    Assert.assertThat(((AbstractHttpClient) cloned.getHttpClient()).getCredentialsProvider(),
            IsEqual.<CredentialsProvider>equalTo(credentialsProvider));
}

From source file:com.heneryh.aquanotes.io.ApexExecutor.java

public void updateOutlet(Cursor cursor, String outletName, int position) throws HandlerException {

    /**//from   ww  w . ja  va 2 s  . com
     * The cursor contains all of the controller details.
     */
    String lanUri = cursor.getString(ControllersQuery.LAN_URL);
    String wanUri = cursor.getString(ControllersQuery.WAN_URL);
    String user = cursor.getString(ControllersQuery.USER);
    String pw = cursor.getString(ControllersQuery.PW);
    String ssid = cursor.getString(ControllersQuery.WIFI_SSID);
    String model = cursor.getString(ControllersQuery.MODEL);

    // Uhg, WifiManager stuff below crashes in AVD if wifi not enabled so first we have to check if on wifi
    ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nInfo = cm.getActiveNetworkInfo();
    String apexBaseURL;

    if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) {
        // Get the currently connected SSID, if it matches the 'Home' one then use the local WiFi URL rather than the public one
        WifiManager wm = (WifiManager) mActContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wInfo = wm.getConnectionInfo();

        // somewhere read this was a quoted string but appears not to be
        if (wInfo.getSSID().equalsIgnoreCase(ssid)) { // the ssid will be quoted in the info class
            apexBaseURL = lanUri;
        } else {
            apexBaseURL = wanUri;
        }
    } else {
        apexBaseURL = wanUri;

    }

    // for this function we need to append to the URL.  I should really
    // check if the "/" was put on the end by the user here to avoid 
    // possible errors.
    if (!apexBaseURL.endsWith("/")) {
        String tmp = apexBaseURL + "/";
        apexBaseURL = tmp;
    }

    // oh, we should also check if it starts with an "http://"
    if (!apexBaseURL.toLowerCase().startsWith("http://")) {
        String tmp = "http://" + apexBaseURL;
        apexBaseURL = tmp;
    }

    // oh, we should also check if it ends with an "status.sht" on the end and remove it.

    // This used to be common for both the Apex and ACiii but during
    // the 4.04 beta Apex release it seemed to have broke and forced
    // me to use status.sht for the Apex.  Maybe it was fixed but I 
    // haven't checked it.
    // edit - this was not needed for the longest while but now that we are pushing just one
    // outlet, the different methods seem to be needed again.  Really not sure why.
    String apexURL;
    if (model.equalsIgnoreCase("AC4")) {
        apexURL = apexBaseURL + "status.sht";
    } else {
        apexURL = apexBaseURL + "cgi-bin/status.cgi";
    }

    //Create credentials for basic auth
    // create a basic credentials provider and pass the credentials
    // Set credentials provider for our default http client so it will use those credentials
    UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw);
    BasicCredentialsProvider cP = new BasicCredentialsProvider();
    cP.setCredentials(AuthScope.ANY, c);
    ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP);

    // Build the POST update which looks like this:
    // form="status"
    // method="post"
    // action="status.sht"
    //
    // name="T5s_state", value="0"   (0=Auto, 1=Man Off, 2=Man On)
    // submit -> name="Update", value="Update"
    // -- or
    // name="FeedSel", value="0"   (0=A, 1=B)
    // submit -> name="FeedCycle", value="Feed"
    // -- or
    // submit -> name="FeedCycle", value="Feed Cancel"

    HttpPost httppost = new HttpPost(apexURL);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

    // Add your data  
    nameValuePairs.add(new BasicNameValuePair("name", "status"));
    nameValuePairs.add(new BasicNameValuePair("method", "post"));
    if (model.equalsIgnoreCase("AC4")) {
        nameValuePairs.add(new BasicNameValuePair("action", "status.sht"));
    } else {
        nameValuePairs.add(new BasicNameValuePair("action", "/cgi-bin/status.cgi"));
    }

    String pendingStateS = String.valueOf(position);
    nameValuePairs.add(new BasicNameValuePair(outletName + "_state", pendingStateS));

    nameValuePairs.add(new BasicNameValuePair("Update", "Update"));
    try {

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse resp = mHttpClient.execute(httppost);
        final int status = resp.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            throw new HandlerException(
                    "Unexpected server response " + resp.getStatusLine() + " for " + httppost.getRequestLine());
        }
    } catch (HandlerException e) {
        throw e;
    } catch (ClientProtocolException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    } catch (IOException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    }

}

From source file:aajavafx.DevicesController.java

public ObservableList<String> getCustomer() throws IOException, JSONException {

    ObservableList<String> customerStrings = FXCollections.observableArrayList();
    //customers.add(new CustomerProperty(1, "Johny", "Walker", "London", "1972-07-01", "7207012222"));
    Customers myCustomer = new Customers();
    //Managers manager = new Managers();
    Gson gson = new Gson();
    ObservableList<CustomerProperty> customersProperty = FXCollections.observableArrayList();
    JSONObject jo = new JSONObject();

    // SSL update .......
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/customers");
    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);

    //JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL("http://localhost:8080/MainServerREST/api/customers"), Charset.forName("UTF-8")));
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    // ...........
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        myCustomer = gson.fromJson(jo.toString(), Customers.class);
        customers.add(myCustomer);/*from   ww  w.  j a v  a2 s. c om*/
        System.out.println(myCustomer.getCuId());
        String s = myCustomer.getCuId() + ". " + myCustomer.getCuFirstname() + " " + myCustomer.getCuLastname()
                + " " + myCustomer.getCuPersonnummer();
        customerStrings.add(s);
        customersProperty.add(new CustomerProperty(myCustomer.getCuId(), myCustomer.getCuFirstname(),
                myCustomer.getCuLastname(), myCustomer.getCuBirthdate(), myCustomer.getCuAddress(),
                myCustomer.getCuPersonnummer()));

    }
    return customerStrings;
}

From source file:aajavafx.CustomerMedicineController.java

@FXML
private void handleRemoveButton(ActionEvent event) {
    //remove is annotated with @DELETE on server so we use a HttpDelete object
    try {/*w w w  . ja  va2s .  c o  m*/
        //.......SSL Update....
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        //......

        HttpClient httpClient = HttpClientBuilder.create().build();
        String idToDelete = startDate.getText();
        //add the id to the end of the URL so this will call the method at MainServerREST/api/visitors/id
        HttpDelete delete = new HttpDelete(MedicineCustomerRootURL + idToDelete);
        HttpResponse response = httpClient.execute(delete);
        System.out.println("response from server " + response.getStatusLine());
    } catch (Exception ex) {
        System.out.println(ex);
    }
    try {
        //refresh table
        tableCustomer.setItems(getCustomersTakesMedicines());
    } catch (IOException ex) {
        Logger.getLogger(VisitorController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(VisitorController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:aajavafx.EmployeeController.java

public void deleteRow(int id) {
    try {//w w w .  j  a v a 2 s . c o  m
        String idToDelete = id + "";
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
        HttpDelete delete = new HttpDelete(postEmployeesURL + idToDelete);
        HttpResponse response = httpClient.execute(delete);
        System.out.println("you want to delete: " + id);
    } catch (Exception ex) {
        System.out.println(ex);
    }
}