Example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager

List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager.

Prototype

public synchronized final ClientConnectionManager getConnectionManager() 

Source Link

Usage

From source file:ching.icecreaming.action.EditAction.java

@Action(value = "edit", results = { @Result(name = "login", location = "edit.jsp"),
        @Result(name = "success", location = "view.jsp"), @Result(name = "error", location = "error.jsp") })
public String execute() throws Exception {
    URL url1 = null;/*from  w w  w .j  ava 2 s .  c om*/
    URI uri1 = null;
    HttpGet httpGet1 = null;
    DefaultHttpClient httpClient1 = new DefaultHttpClient();
    HttpResponse httpResponse1 = null;
    int int1 = 0, int2 = 401;
    String[] array1 = null;
    String string1 = getText("Error") + " %d: %s", result1 = LOGIN;
    byte[] bytes1 = null;
    if (StringUtils.isBlank(timeZone1))
        timeZone1 = portletPreferences.getValue("timeZone", TimeZone.getDefault().getID());
    if (StringUtils.isNotBlank(sid) && StringUtils.isNotBlank(uid) && StringUtils.isNotBlank(pid)) {
        try {
            url1 = new URL(sid);
            URIBuilder uriBuilder = new URIBuilder(sid);
            uriBuilder.setParameter("j_username", uid);
            uriBuilder.setParameter("j_password", pid);
            uriBuilder.setPath(url1.getPath() + "/rest/login");
            uri1 = uriBuilder.build();
            httpGet1 = new HttpGet(uri1);
            httpResponse1 = httpClient1.execute(httpGet1);
            int2 = httpResponse1.getStatusLine().getStatusCode();
        } catch (IOException exception1) {
            exception1.printStackTrace();
        } catch (URISyntaxException exception1) {
            exception1.printStackTrace();
        } finally {
            httpClient1.getConnectionManager().shutdown();
            if (int2 == HttpStatus.SC_OK) {
                sid = new String(Base64.encodeBase64(sid.getBytes()));
                uid = new String(Base64.encodeBase64(uid.getBytes()));
                pid = new String(Base64.encodeBase64(pid.getBytes()));
                urlString = "/";
                wsType = "folder";
                array1 = new String[] { sid, uid, pid, StringUtils.defaultString(alias1) };
                portletPreferences.setValue("urlString", urlString);
                portletPreferences.setValue("wsType", wsType);
                portletPreferences.setValue("timeZone", timeZone1);
                portletPreferences.setValues("server", array1);
                portletPreferences.store();
                result1 = SUCCESS;
            } else {
                array1 = portletPreferences.getValues("server", null);
                if (array1 != null)
                    if (ArrayUtils.isNotEmpty(array1)) {
                        for (int1 = 0; int1 < array1.length; int1++) {
                            switch (int1) {
                            case 0:
                                sid = array1[int1];
                                break;
                            case 1:
                                uid = array1[int1];
                                break;
                            case 2:
                                pid = array1[int1];
                                break;
                            case 3:
                                alias1 = array1[int1];
                                break;
                            default:
                                break;
                            }
                        }
                        sid = new String(Base64.decodeBase64(sid.getBytes()));
                        uid = new String(Base64.decodeBase64(uid.getBytes()));
                        pid = new String(Base64.decodeBase64(pid.getBytes()));
                    }
                addActionError(String.format(string1, int2, getText(Integer.toString(int2))));
            }
        }
    } else {
        array1 = portletPreferences.getValues("server", null);
        if (StringUtils.isBlank(urlString) || StringUtils.isBlank(wsType)) {
            urlString = portletPreferences.getValue("urlString", "/");
            wsType = portletPreferences.getValue("wsType", "folder");
        }
        if (array1 != null) {
            if (ArrayUtils.isNotEmpty(array1)) {
                for (int1 = 0; int1 < array1.length; int1++) {
                    switch (int1) {
                    case 0:
                        sid = array1[int1];
                        break;
                    case 1:
                        uid = array1[int1];
                        break;
                    case 2:
                        pid = array1[int1];
                        break;
                    case 3:
                        alias1 = array1[int1];
                        break;
                    default:
                        break;
                    }
                }
                sid = new String(Base64.decodeBase64(sid.getBytes()));
                uid = new String(Base64.decodeBase64(uid.getBytes()));
                pid = new String(Base64.decodeBase64(pid.getBytes()));
            }
        }
    }
    return result1;
}

From source file:no.kantega.kwashc.server.test.FailureToRestrictUrlTest.java

@Override
protected TestResult testSite(Site site, TestResult testResult) throws Throwable {
    long startTime = System.nanoTime();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String responseBody = "";

    try {//from   w w w  . ja  va2s  . c  o  m
        HttpGet request = new HttpGet(site.getAddress() + "/blog/admin?commentToDelete"
                + "=00121212123123123123123123123123123343435436456745675647456564444444454554");
        HttpResponse response = httpclient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        responseBody = EntityUtils.toString(entity);
        String generalError = "Your application fails to restrict privileged URLs properly!";

        if (statusCode == 500) {
            testResult.setResultEnum(ResultEnum.failed);
            testResult.setMessage(generalError);
        } else if (statusCode == 404) {
            testResult.setResultEnum(ResultEnum.passed);
            testResult.setMessage(
                    "Your application restricts URLs properly, but can you be sure no one was using "
                            + "/blog/admin?");
        } else if (statusCode == 200 && responseBody.contains("You asked for a protected resource")) {
            testResult.setResultEnum(ResultEnum.passed);
            testResult.setMessage("Your application restricts URLs properly!");
        } else {
            testResult.setResultEnum(ResultEnum.failed);
            testResult.setMessage(generalError);
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    setDuration(testResult, startTime);
    return testResult;
}

From source file:org.jenkinsci.plugins.appio.service.AppioService.java

/**
 * @param appName/*from  w  ww.j  a v  a 2s . c  o m*/
 * @return
 * @throws Exception
 */
public AppioAppObject findApp(String appName) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    ResponseHandler<String> handler = new BasicResponseHandler();
    AppioAppObject theApp = new AppioAppObject();

    try {
        // App.io Authorization and Content-Type headers
        String appioAuth = "Basic " + apiKey;
        httpGet.addHeader("Authorization", appioAuth);
        httpGet.addHeader("Accept", appio_v1);

        LOGGER.fine("AppioService.findApp() Request");
        HttpResponse response = httpClient.execute(httpHost, httpGet);
        String jsonAppioApps = handler.handleResponse(response);
        LOGGER.fine("AppioService.findApp() Response: " + jsonAppioApps);

        AppioApps appioApps = new Gson().fromJson(jsonAppioApps, AppioApps.class);
        List<AppioAppObject> list = Arrays.asList(appioApps.getApps());
        Iterator<AppioAppObject> iterator = list.iterator();

        boolean foundAppName = false;
        while ((iterator.hasNext()) && (!foundAppName)) {
            AppioAppObject thisApp = iterator.next();

            if (thisApp.getName().equals(appName)) {
                theApp = thisApp;
                foundAppName = true;
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        try {
            httpClient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
    return theApp;
}

From source file:io.cloudsoft.marklogic.nodes.MarkLogicNodeSshDriver.java

@Override
public Set<String> scanDatabases() {
    LOG.debug("Scanning databases");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {//  w w  w .ja  va2 s .c o  m
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(getEntity().getUser(), getEntity().getPassword()));

        String adminUrl = getEntity().getAdminConnectUrl();
        String uri = adminUrl + "/database_list.xqy";
        HttpGet httpget = new HttpGet(uri);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String result = IOUtils.toString(entity.getContent());
        EntityUtils.consume(entity);

        Set<String> forests = Sets.newHashSet();
        String[] split = result.split("\n");
        Collections.addAll(forests, split);
        return forests;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:test.gov.nih.nci.cacoresdk.domain.manytomany.bidirectional.selfassociation.MemberM2MBSResourceTest.java

public void testPost() throws Exception {

    try {//from  ww  w .  ja v a2 s . com
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/MemberM2MBS";
        WebClient client = WebClient.create(url);
        HttpPost postRequest = new HttpPost(url);
        File myFile = new File("MemberM2MBS" + "XML.xml");
        if (!myFile.exists()) {
            testGet();
            myFile = new File("MemberM2MBS" + "XML.xml");
            if (!myFile.exists())
                return;
        }

        FileEntity input = new FileEntity(myFile);
        input.setContentType("application/xml");
        System.out.println("input: " + myFile);
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:test.gov.nih.nci.cacoresdk.domain.onetoone.bidirectional.selfassociation.MemberO2OBSResourceTest.java

public void testPost() throws Exception {

    try {/*from w ww  .  ja v  a 2s .  c  om*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/MemberO2OBS";
        WebClient client = WebClient.create(url);
        HttpPost postRequest = new HttpPost(url);
        File myFile = new File("MemberO2OBS" + "XML.xml");
        if (!myFile.exists()) {
            testGet();
            myFile = new File("MemberO2OBS" + "XML.xml");
            if (!myFile.exists())
                return;
        }

        FileEntity input = new FileEntity(myFile);
        input.setContentType("application/xml");
        System.out.println("input: " + myFile);
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:io.cloudsoft.marklogic.nodes.MarkLogicNodeSshDriver.java

@Override
public Set<String> scanForests() {
    LOG.debug("Scanning forests");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {//from   w  w w  .j  a v a2s  .co  m
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(getEntity().getUser(), getEntity().getPassword()));

        String adminUrl = getEntity().getAdminConnectUrl();
        String uri = adminUrl + "/forest_list.xqy";
        HttpGet httpget = new HttpGet(uri);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String result = IOUtils.toString(entity.getContent());
        EntityUtils.consume(entity);

        Set<String> forests = new HashSet<String>();
        String[] split = result.split("\n");
        Collections.addAll(forests, split);
        return forests;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.kemri.wellcome.dhisreport.api.model.HttpDhis2Server.java

@Override
public ImportSummary postReport(DataValueSet report) throws DHIS2ReportingException {
    log.debug("Posting datavalueset report");
    ImportSummary summary = null;/*from   w ww .  j  a  v a2s  . c  o  m*/

    StringWriter xmlReport = new StringWriter();
    try {
        JAXBContext jaxbDataValueSetContext = JAXBContext.newInstance(DataValueSet.class);
        Marshaller dataValueSetMarshaller = jaxbDataValueSetContext.createMarshaller();
        // output pretty printed
        dataValueSetMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        dataValueSetMarshaller.marshal(report, xmlReport);
    } catch (JAXBException ex) {
        log.error(ex.getMessage());
        throw new Dxf2Exception("Problem marshalling dataValueSet", ex);
    }

    String host = getUrl().getHost();
    int port = getUrl().getPort();

    HttpHost targetHost = new HttpHost(host, port, getUrl().getProtocol());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    BasicHttpContext localcontext = new BasicHttpContext();

    try {
        String postUrl = getUrl().toString() + DATAVALUESET_PATH;
        log.error("Post URL: " + postUrl);
        HttpPost httpPost = new HttpPost(postUrl);
        Credentials creds = new UsernamePasswordCredentials(username, password);
        Header bs = new BasicScheme().authenticate(creds, httpPost, localcontext);
        httpPost.addHeader("Authorization", bs.getValue());
        httpPost.addHeader("Content-Type", "application/xml; charset=utf-8");
        httpPost.addHeader("Accept", "application/xml");

        httpPost.setEntity(new StringEntity(xmlReport.toString()));
        HttpResponse response = httpclient.execute(targetHost, httpPost, localcontext);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            JAXBContext jaxbImportSummaryContext = JAXBContext.newInstance(ImportSummary.class);
            Unmarshaller importSummaryUnMarshaller = jaxbImportSummaryContext.createUnmarshaller();
            summary = (ImportSummary) importSummaryUnMarshaller.unmarshal(entity.getContent());
        }
    } catch (Exception ex) {
        log.error(ex.getMessage());
        throw new Dhis2Exception(this, "Problem accessing Dhis2 server", ex);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return summary;
}

From source file:bsb.vote.service.DoVote.java

/**
 * @param VOTE_NUM//from   ww  w . j a  va  2  s . c om
 * @param ITEM_ID
 * @param V_ID
 */
public static void doVote(int VOTE_NUM, String ITEM_ID, String V_ID) {
    // TODO code application logic here
    MainUI.startFlag = false;
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //??????????  
    //192.168.1.107?? 808?? UsernamePasswordCredentials??????  
    //        httpclient.getCredentialsProvider().setCredentials(new AuthScope("127.0.0.1", 8888), new UsernamePasswordCredentials("", ""));
    //        HttpHost proxy = new HttpHost("127.0.0.1", 8888);
    //        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    //??
    MainUI.voteNum = 0;
    MainUI.regNum = 0;
    MainUI.validNum = 0;
    int j = 0;
    //        try {
    //            getId(httpclient);
    //            getList(httpclient);
    //        } catch (IOException | JSONException ex) {
    //            Logger.getLogger(DoVote.class.getName()).log(Level.SEVERE, null, ex);
    //        }
    //        
    for (int i = 0; i < VOTE_NUM; i++) {
        try {
            MainUI.voteNum++;
            httpclient.getCookieStore().clear();
            Thread.sleep(1000);
            try {
                if (regUser(httpclient)) {
                    MainUI.regNum++;
                } else {
                    continue;
                }
            } catch (IOException | JSONException ex) {
                Logger.getLogger(DoVote.class.getName()).log(Level.SEVERE, null, ex);
            }
            Thread.sleep(500);
            try {
                if (vote(httpclient, ITEM_ID, V_ID)) {
                    MainUI.validNum++;
                }
            } catch (IOException ex) {
                Logger.getLogger(DoVote.class.getName()).log(Level.SEVERE, null, ex);
            }
            j++;
            if (j == 15) {
                Thread.sleep(60000 * 2);
                j = 0;
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(DoVote.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    MainUI.startFlag = true;
    //
    httpclient.getConnectionManager().shutdown();
}

From source file:org.exoplatform.utils.image.SocialImageLoader.java

private Bitmap getBitmap(String url) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);
    HttpConnectionParams.setTcpNoDelay(httpParameters, true);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    try {/*w w  w.  j a  v a  2  s  .c o m*/
        File f = fileCache.getFile(url);

        // from SD cache
        Bitmap b = decodeFile(f);
        if (b != null)
            return b;
        else {
            // from web
            Bitmap bitmap = null;
            /*
             * Send authentication each time we execute HttpGet to avoid the step
             * checking session time out.
             */
            HttpGet getRequest = new HttpGet(url);
            StringBuilder buffer = new StringBuilder(username);
            buffer.append(":");
            buffer.append(password);
            getRequest.setHeader("Authorization", "Basic " + Base64.encodeBytes(buffer.toString().getBytes()));
            HttpResponse response = httpClient.execute(getRequest);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream is = entity.getContent();
                OutputStream os = new FileOutputStream(f);
                PhotoUtils.copyStream(is, os);
                os.close();
                bitmap = decodeFile(f);
            }

            return bitmap;
        }
    } catch (IOException ex) {
        return null;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}