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

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

Introduction

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

Prototype

public AuthScope(final String host, final int port) 

Source Link

Document

Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.

Usage

From source file:org.jboss.as.test.integration.web.security.servlet3.ServletSecurityRoleNamesCommon.java

/**
 * Method that needs to be overridden with the HTTPClient code.
 *
 * @param user         username//w ww .ja  v a2  s . co m
 * @param pass         password
 * @param expectedCode http status code
 * @throws Exception
 */
protected void makeCall(String user, String pass, int expectedCode, URL url) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(user, pass));
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(url.toExternalForm());

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();
        assertEquals(expectedCode, statusLine.getStatusCode());

        EntityUtils.consume(entity);
    }
}

From source file:cn.jachohx.crawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);
    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    params.setBooleanParameter("http.protocol.handle-redirects", false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }/*from  www  . java 2s . c o m*/

    connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });

}

From source file:net.bioclipse.dbxp.business.DbxpManager.java

public static Map<String, String> authenticate() throws IOException, NoSuchAlgorithmException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(userName, password));

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    HashMap<String, String> formvars = new HashMap<String, String>();
    formvars.put("deviceID", getDeviceId());
    HttpResponse response = postValues(formvars, baseApiUrl + "authenticate");
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String json = "";
    String s = "";
    while ((s = stdInput.readLine()) != null) {
        json += s;// ww w  .  j  a  v a 2  s. c o m
    }

    Gson gson = new Gson();
    Map<String, String> loginData = gson.fromJson(json, new TypeToken<Map<String, String>>() {
    }.getType());

    token = loginData.get("token");
    sequence = Integer.valueOf(loginData.get("sequence"));

    return loginData;
}

From source file:com.marklogic.client.functionaltest.JavaApiBatchSuite.java

public static void createRESTAppServer(String restServerName, int restPort) {
    try {//from w ww . j ava2s . c o m
        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpPost post = new HttpPost("http://localhost:8002" + "/v1/rest-apis?format=json");
        String JSONString = "{ \"rest-api\": {\"name\":\"" + restServerName + "\",\"port\":\"" + restPort
                + "\"}}";
        //System.out.println(JSONString);      
        post.addHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(JSONString));

        HttpResponse response = client.execute(post);
        HttpEntity respEntity = response.getEntity();

        if (respEntity != null) {
            // EntityUtils to get the response content
            String content = EntityUtils.toString(respEntity);
            System.out.println(content);
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}

From source file:org.uoyabause.android.AsyncDownload.java

private Integer sendReport(String uri, String product_id) {

    Log.d("sendReport", "================ sendReport start ================");

    mainActivity._report_status = Yabause.REPORT_STATE_FAIL_CONNECTION;

    DefaultHttpClient client = new DefaultHttpClient();
    try {/*from  www .  j a  v  a2s.c om*/
        Credentials credentials = new UsernamePasswordCredentials(mainActivity.getString(R.string.basic_user),
                mainActivity.getString(R.string.basic_password));
        AuthScope scope = new AuthScope(null, -1);
        client.getCredentialsProvider().setCredentials(scope, credentials);
    } catch (Exception e) {
        Log.d("sendReport", "error " + e.getMessage());
        e.printStackTrace();
        client.getConnectionManager().shutdown();
        return 0;
    }

    String device_id = Settings.Secure.getString(mainActivity.getContentResolver(), Settings.Secure.ANDROID_ID);
    try {
        long id = -1;
        Log.d("sendReport", "uri=" + uri + "games/" + product_id);
        HttpGet httpGet = new HttpGet(new URI(uri + "games/" + product_id));
        HttpResponse resp = client.execute(httpGet);
        int status = resp.getStatusLine().getStatusCode();
        Log.d("sendReport", "get status=" + status);
        if (HttpStatus.SC_OK == status) {
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                resp.getEntity().writeTo(outputStream);
                String data;
                data = outputStream.toString(); // JSON
                JSONObject rootObject = new JSONObject(data);
                Log.d("sendReport", "get id respose=" + data);
                if (rootObject.getBoolean("result") == true) {
                    id = rootObject.getLong("id");
                }
            } catch (Exception e) {
                Log.d("sendReport", "error");
                e.printStackTrace();
            }
        } else {
        }
        if (id == -1) {

            HttpPost httpPost = new HttpPost(new URI(uri + "games/"));
            StringEntity se = new StringEntity(mainActivity.current_game_info.toString());
            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            resp = client.execute(httpPost);
            status = resp.getStatusLine().getStatusCode();
            Log.d("sendReport", "post stats=" + status);
            if (HttpStatus.SC_CREATED == status || HttpStatus.SC_OK == status) {
                try {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    resp.getEntity().writeTo(outputStream);
                    String data;
                    data = outputStream.toString(); // JSON
                    Log.d("sendReport", "post respose=" + data);
                    JSONObject rootObject = new JSONObject(data);
                    if (rootObject.getBoolean("result") == true) {
                        id = rootObject.getLong("id");
                    }
                } catch (Exception e) {
                    Log.d("sendReport", "error");
                    e.printStackTrace();
                }
            } else {
            }

        }
        Log.d("sendReport", "ID=" + id);
        if (id == -1) {
            client.getConnectionManager().shutdown();
            return -1;
        }

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mainActivity);
        String cputype = sharedPref.getString("pref_cpu", "2");
        String gputype = sharedPref.getString("pref_video", "1");
        JSONObject reportJson = new JSONObject();
        reportJson.put("rating", mainActivity.current_report._rating);
        if (mainActivity.current_report._message != null) {
            reportJson.put("message", mainActivity.current_report._message);
        }
        reportJson.put("emulator_version", Home.getVersionName(mainActivity));
        reportJson.put("device", android.os.Build.MODEL);
        reportJson.put("user_id", 1);
        reportJson.put("device_id", device_id);
        reportJson.put("game_id", id);
        reportJson.put("cpu_type", cputype);
        reportJson.put("video_type", gputype);
        JSONObject sendJson = new JSONObject();
        sendJson.put("report", reportJson);
        if (mainActivity.current_report._screenshot) {
            JSONObject jsonObjimg = new JSONObject();
            jsonObjimg.put("data", mainActivity.current_report._screenshot_base64);
            jsonObjimg.put("filename", mainActivity.current_report._screenshot_save_path);
            jsonObjimg.put("content_type", "image/png");
            JSONObject jsonObjgame = sendJson.getJSONObject("report");
            jsonObjgame.put("screenshot", jsonObjimg);
            File file = new File(mainActivity.current_report._screenshot_save_path);
            file.delete();
        }
        Log.d("sendReport", reportJson.toString());
        HttpPost httpPost = new HttpPost(new URI(uri + "reports/"));
        StringEntity se = new StringEntity(sendJson.toString());
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        resp = client.execute(httpPost);
        status = resp.getStatusLine().getStatusCode();
        if (HttpStatus.SC_CREATED == status || HttpStatus.SC_OK == status) {
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                resp.getEntity().writeTo(outputStream);
                String data;
                data = outputStream.toString(); // JSON
                JSONObject rootObject = new JSONObject(data);
                Log.d("sendReport", "get respose=" + data);
                if (rootObject.getBoolean("result") == true) {
                    mainActivity._report_status = Yabause.REPORT_STATE_SUCCESS;
                } else {
                    int return_code = rootObject.getInt("code");
                    mainActivity._report_status = return_code;
                }
            } catch (Exception e) {
                Log.d("sendReport", "error");
                e.printStackTrace();
            }
            client.getConnectionManager().shutdown();
            return 0;
        }
        client.getConnectionManager().shutdown();
        return -1;

    } catch (Exception e) {
        Log.d("sendReport", "error:" + e.getMessage());
        e.printStackTrace();
    } finally {
        client.getConnectionManager().shutdown();
    }
    return -1;
}

From source file:net.homelinux.penecoptero.android.citybikes.app.RESTHelper.java

private DefaultHttpClient setCredentials(DefaultHttpClient httpclient, String url)
        throws HttpException, IOException {
    HttpHost targetHost = new HttpHost(url);
    final UsernamePasswordCredentials access = new UsernamePasswordCredentials(USERNAME, PASSWORD);

    httpclient.getCredentialsProvider()//  www  .j  av a2s  .c o  m
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), access);

    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(access);
            }
        }
    }, 0);
    return httpclient;
}

From source file:yin.autoflowcontrol.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    params.setBooleanParameter("http.protocol.handle-redirects", false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }/*  w w w . jav a2s  . c  om*/

    connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();

}

From source file:com.networkmanagerapp.JSONBackgroundDownloaderService.java

/**
 * Delegate method to run the specified intent in another thread.
 * @param arg0 The intent to run in the background
 *//*from   www. j  ava 2 s . c  om*/
@Override
protected void onHandleIntent(Intent arg0) {
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    showNotification();
    String filename = arg0.getStringExtra("FILENAME");
    String jsonFile = arg0.getStringExtra("JSONFILE");
    try {
        String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference",
                "");
        Log.d("password", password);
        String ip = PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference",
                "192.168.1.1");
        String enc = URLEncoder.encode(ip, "UTF-8");
        String scriptUrl = "http://" + enc + ":1080" + filename;

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "utf-8");

        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 20000;
        HttpConnectionParams.setSoTimeout(params, timeoutSocket);
        HttpHost targetHost = new HttpHost(enc, 1080, "http");

        DefaultHttpClient client = new DefaultHttpClient(params);
        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("root", password));
        HttpGet request = new HttpGet(scriptUrl);
        HttpResponse response = client.execute(targetHost, request);
        Log.d("JBDS", response.getStatusLine().toString());
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder str = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            str.append(line + "\n");
        }
        in.close();

        if (str.toString().equals("Success\n")) {
            String xmlUrl = "http://" + enc + ":1080/json" + jsonFile;
            request = new HttpGet(xmlUrl);
            HttpResponse jsonData = client.execute(targetHost, request);
            in = jsonData.getEntity().getContent();
            reader = new BufferedReader(new InputStreamReader(in));
            str = new StringBuilder();
            line = null;
            while ((line = reader.readLine()) != null) {
                str.append(line + "\n");
            }
            in.close();

            FileOutputStream fos = openFileOutput(jsonFile.substring(1), Context.MODE_PRIVATE);
            fos.write(str.toString().getBytes());
            fos.close();
        }
    } catch (MalformedURLException ex) {
        Log.e("NETWORKMANAGER_XBD_MUE", ex.getMessage());
    } catch (IOException e) {
        try {
            Log.e("NETWORK_MANAGER_XBD_IOE", e.getMessage());
            StackTraceElement[] st = e.getStackTrace();
            for (int i = 0; i < st.length; i++) {
                Log.e("NETWORK_MANAGER_XBD_IOE", st[i].toString());
            }
        } catch (NullPointerException ex) {
            Log.e("Network_manager_xbd_npe", ex.getLocalizedMessage());
        }

    } finally {
        mNM.cancel(R.string.download_service_started);
        Intent bci = new Intent(NEW_DATA_AVAILABLE);
        sendBroadcast(bci);
        stopSelf();
    }
}

From source file:nu.yona.server.sms.PlivoSmsService.java

private HttpClientContext createHttpClientContext() {
    try {//from   ww w  .  ja  v a2 s.c o  m
        SmsProperties smsProperties = yonaProperties.getSms();

        URI uri = getPlivoUrl(smsProperties);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(smsProperties.getPlivoAuthId(),
                        smsProperties.getPlivoAuthToken()));

        HttpClientContext httpClientContext = HttpClientContext.create();
        httpClientContext.setCredentialsProvider(credentialsProvider);
        return httpClientContext;
    } catch (URISyntaxException e) {
        throw SmsException.smsSendingFailed(e);
    }
}

From source file:ca.sqlpower.wabit.enterprise.client.ServerInfoProvider.java

private static void init(String host, String port, String path, String username, String password)
        throws IOException {

    URL serverInfoUrl = toServerInfoURL(host, port, path);
    if (version.containsKey(generateServerKey(host, port, path, username, password)))
        return;//ww  w  .  j  a  v a 2 s. co  m

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(WabitClientSession.getCookieStore());
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(serverInfoUrl.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(serverInfoUrl.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(host, port, path, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(host, port, path, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(host, port, path, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(null, watermarkMessage, "SQL Power Wabit Server License",
                            JOptionPane.WARNING_MESSAGE);
                }
            });
        }

        // Now get the available fonts.
        URL serverFontsURL = toServerFontsURL(host, port, path);
        HttpUriRequest fontsRequest = new HttpGet(serverFontsURL.toURI());
        String fontsResponseBody = httpClient.execute(fontsRequest, new BasicResponseHandler());
        try {
            JSONArray fontsArray = new JSONArray(fontsResponseBody);
            List<String> fontNames = new ArrayList<String>();
            for (int i = 0; i < fontsArray.length(); i++) {
                fontNames.add(fontsArray.getString(i));
            }
            // Sort the list.
            Collections.sort(fontNames);
            fonts.put(generateServerKey(host, port, path, username, password), fontNames);
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

    } catch (URISyntaxException e) {
        throw new IOException(e.getLocalizedMessage());
    }
}