Examples of HttpMethodBase


Examples of org.apache.commons.httpclient.HttpMethodBase

            throw new ReviewboardException("username and password is required.");
        }
      
        RestfulReviewboardReader reviewboardReader = new RestfulReviewboardReader();
       
        HttpMethodBase loginRequest = null;
        loginRequest = new GetMethod(serverUrl + URI_LOGIN);
        String authorizationKey   = "Authorization";
        String authorizationValue = "Basic " + ReviewboardUtil.convertStr2BASE64(username + ":" + password);
        //Set a HTTP Headers    WWW-Authenticate
        loginRequest.setRequestHeader(authorizationKey, authorizationValue );
       
        if(monitor == null){
            monitor = new NullProgressMonitor();
        }
       
        try {
            monitor.beginTask("Authorization checking...", IProgressMonitor.UNKNOWN);
            this.httpClient.getState().clear();
           
            if (executeRequest(loginRequest, monitor) == HttpStatus.SC_OK) {
                String response = getResponseBodyAsString(loginRequest, monitor);
                if (reviewboardReader.isStatOK(response)) {
                    Header header = loginRequest.getResponseHeader("Set-Cookie");
                    if(null != header){
                        cookie = header.getValue();
                    }
                } else {
                    throw new ReviewboardException(reviewboardReader.getErrorMessage(response));
                }
            } else {
                throw new ReviewboardException(RbCoreMessages.getString("ERROR_SERVER_NOT_CONFIFIGURED_0"));
            }
        } finally {
            loginRequest.releaseConnection();
            monitor.done();
        }
    }
View Full Code Here

Examples of org.apache.commons.httpclient.HttpMethodBase

    public URLInfo getURLInfo(URL url) {
        return getURLInfo(url, 0);
    }

    public URLInfo getURLInfo(URL url, int timeout) {
        HttpMethodBase method = null;
        try {
            if (getRequestMethod() == URLHandler.REQUEST_METHOD_HEAD) {
                method = doHead(url, timeout);
            } else {
                method = doGet(url, timeout);
            }
            if (checkStatusCode(url, method)) {
                return new URLInfo(true, getResponseContentLength(method), getLastModified(method),
                        method.getRequestCharSet());
            }
        } catch (HttpException e) {
            Message.error("HttpClientHandler: " + e.getMessage() + ":" + e.getReasonCode() + "="
                    + e.getReason() + " url=" + url);
        } catch (UnknownHostException e) {
            Message.warn("Host " + e.getMessage() + " not found. url=" + url);
            Message.info("You probably access the destination server through "
                    + "a proxy server that is not well configured.");
        } catch (IOException e) {
            Message.error("HttpClientHandler: " + e.getMessage() + " url=" + url);
        } catch (IllegalArgumentException e) {
            // thrown by HttpClient to indicate the URL is not valid, this happens for instance
            // when trying to download a dynamic version (cfr IVY-390)
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
        return UNAVAILABLE;
    }
View Full Code Here

Examples of org.apache.commons.httpclient.HttpMethodBase

        String urlStr = url.toString();

        log.debug("Start : sample " + urlStr);
        log.debug("method " + method);

        HttpMethodBase httpMethod = null;

        HTTPSampleResult res = new HTTPSampleResult();
        res.setMonitor(isMonitor());

        res.setSampleLabel(urlStr); // May be replaced later
        res.setHTTPMethod(method);
        res.setURL(url);
        res.sampleStart(); // Count the retries as well in the time
        HttpClient client = null;
        InputStream instream = null;
        try {
            httpMethod = createHttpMethod(method, urlStr);
            // Set any default request headers
            setDefaultRequestHeaders(httpMethod);
            // Setup connection
            client = setupConnection(url, httpMethod, res);
            // Handle the various methods
            if (httpMethod instanceof EntityEnclosingMethod) {
                String postBody = sendData((EntityEnclosingMethod) httpMethod);
                res.setResponseData(postBody.getBytes());
            }
            overrideHeaders(httpMethod);
            res.setRequestHeaders(getConnectionHeaders(httpMethod));

            int statusCode = -1;
            try {
                statusCode = client.executeMethod(httpMethod);
            } catch (RuntimeException e) {
                log.error("Exception when executing '" + httpMethod + "'", e);
                throw e;
            }

            // Request sent. Now get the response:
            instream = httpMethod.getResponseBodyAsStream();

            if (instream != null) {// will be null for HEAD

                Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING);
                if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) {
                    instream = new GZIPInputStream(instream);
                }
                res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
            }

            res.sampleEnd();
            // Done with the sampling proper.

            // Now collect the results into the HTTPSampleResult:

            res.setSampleLabel(httpMethod.getURI().toString());
            // Pick up Actual path (after redirects)

            res.setResponseCode(Integer.toString(statusCode));
            res.setSuccessful(isSuccessCode(statusCode));

            res.setResponseMessage(httpMethod.getStatusText());

            String ct = null;
            org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE);
            if (h != null)// Can be missing, e.g. on redirect
            {
                ct = h.getValue();
                res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
                res.setEncodingAndType(ct);
            }

            String responseHeaders = getResponseHeaders(httpMethod);
            res.setResponseHeaders(responseHeaders);
            if (res.isRedirect()) {
                final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION);
                if (headerLocation == null) { // HTTP protocol violation, but
                    // avoids NPE
                    throw new IllegalArgumentException("Missing location header");
                }
                res.setRedirectLocation(headerLocation.getValue());
            }

            // If we redirected automatically, the URL may have changed
            if (getAutoRedirects()) {
                res.setURL(new URL(httpMethod.getURI().toString()));
            }

            // Store any cookies received in the cookie manager:
            saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());

            // Save cache information
            final CacheManager cacheManager = getCacheManager();
            if (cacheManager != null) {
                cacheManager.saveDetails(httpMethod, res);
            }

            // Follow redirects and download page resources if appropriate:
            res = resultProcessing(areFollowingRedirect, frameDepth, res);

            log.debug("End : sample");
            httpMethod.releaseConnection();
            return res;
        } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL
        {
            res.sampleEnd();
            HTTPSampleResult err = errorResult(e, res);
            err.setSampleLabel("Error: " + url.toString());
            return err;
        } catch (IOException e) {
            res.sampleEnd();
            HTTPSampleResult err = errorResult(e, res);
            err.setSampleLabel("Error: " + url.toString());
            return err;
        } finally {
            JOrphanUtils.closeQuietly(instream);
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        }
    }
View Full Code Here

Examples of org.apache.commons.httpclient.HttpMethodBase

            }
        }
    }

    private HttpMethodBase createHttpMethod(String method, String urlStr) {
        HttpMethodBase httpMethod;
        // May generate IllegalArgumentException
        if (method.equals(POST)) {
            httpMethod = new PostMethod(urlStr);
        } else if (method.equals(PUT)) {
            httpMethod = new PutMethod(urlStr);
View Full Code Here

Examples of org.apache.commons.httpclient.HttpMethodBase

                hc.getState().setProxyCredentials(AuthScope.ANY,new UsernamePasswordCredentials(jpc.getUserName(),jpc.getPassword()));
        }

        int authCount=0, totalPageCount=0// counters for avoiding infinite loop

        HttpMethodBase m = new GetMethod(primary.filepath);
        hc.getState().addCookie(new Cookie(".oracle.com","gpw_e24",".", "/", -1, false));
        try {
            while (true) {
                if (totalPageCount++>16) // looping too much
                    throw new IOException("Unable to find the login form");

                LOGGER.fine("Requesting " + m.getURI());
                int r = hc.executeMethod(m);
                if (r/100==3) {
                    // redirect?
                    String loc = m.getResponseHeader("Location").getValue();
                    m.releaseConnection();
                    m = new GetMethod(loc);
                    continue;
                }
                if (r!=200)
                    throw new IOException("Failed to request " + m.getURI() +" exit code="+r);

                if (m.getURI().getHost().equals("login.oracle.com")) {
                    LOGGER.fine("Appears to be a login page");
                    String resp = IOUtils.toString(m.getResponseBodyAsStream(), m.getResponseCharSet());
                    m.releaseConnection();
                    Matcher pm = Pattern.compile("<form .*?action=\"([^\"]*)\" .*?</form>", Pattern.DOTALL).matcher(resp);
                    if (!pm.find())
                        throw new IllegalStateException("Unable to find a form in the response:\n"+resp);

                    String form = pm.group();
                    PostMethod post = new PostMethod(
                            new URL(new URL(m.getURI().getURI()),pm.group(1)).toExternalForm());

                    String u = getDescriptor().getUsername();
                    Secret p = getDescriptor().getPassword();
                    if (u==null || p==null) {
                        log.hyperlink(getCredentialPageUrl(),"Oracle now requires Oracle account to download previous versions of JDK. Please specify your Oracle account username/password.\n");
                        throw new AbortException("Unable to install JDK unless a valid Oracle account username/password is provided in the system configuration.");
                    }

                    for (String fragment : form.split("<input")) {
                        String n = extractAttribute(fragment,"name");
                        String v = extractAttribute(fragment,"value");
                        if (n==null || v==null)     continue;
                        if (n.equals("ssousername"))
                            v = u;
                        if (n.equals("password")) {
                            v = p.getPlainText();
                            if (authCount++ > 3) {
                                log.hyperlink(getCredentialPageUrl(),"Your Oracle account doesn't appear valid. Please specify a valid username/password\n");
                                throw new AbortException("Unable to install JDK unless a valid username/password is provided.");
                            }
                        }
                        post.addParameter(n, v);
                    }

                    m = post;
                } else {
                    log.getLogger().println("Downloading " + m.getResponseContentLength() + "bytes");

                    // download to a temporary file and rename it in to handle concurrency and failure correctly,
                    File tmp = new File(cache.getPath()+".tmp");
                    try {
                        tmp.getParentFile().mkdirs();
                        FileOutputStream out = new FileOutputStream(tmp);
                        try {
                            IOUtils.copy(m.getResponseBodyAsStream(), out);
                        } finally {
                            out.close();
                        }

                        tmp.renameTo(cache);
                        return cache.toURL();
                    } finally {
                        tmp.delete();
                    }
                }
            }
        } finally {
            m.releaseConnection();
        }
    }
View Full Code Here

Examples of org.apache.commons.httpclient.HttpMethodBase

    String contextroot = System.getProperty("appContext");
    root = "http://localhost:8080/"+contextroot;
   
    HttpClient nclient = new HttpClient();
    String url = root+"/CourseAdd?cid=1&cname=course1&classroom=course1&teacher=course1&assistTeacher=course1";
    HttpMethodBase httpMethod;
    httpMethod = new PostMethod(url);
    nclient.executeMethod(httpMethod);
    httpMethod.releaseConnection();
   
    url = root+"/ListQuery?cname=course1";
    HttpMethodBase httpMethod2;
    httpMethod2 = new PostMethod(url);
    int status = nclient.executeMethod(httpMethod2);
    Assert.assertEquals(status, 200);
//    System.out.println("status:" + status);
    String response = null;
    if(status==200)
    {
      response = new String(httpMethod2.getResponseBodyAsString().getBytes("8859_1"));
    }
    Assert.assertTrue(response.contains("course name is :course1 from listQuery."));
 
    httpMethod2.releaseConnection();
  }
View Full Code Here

Examples of org.apache.commons.httpclient.HttpMethodBase

  @Test(dependsOnMethods = { "addCourseTest" })
  public void addCommentTest() throws HttpException, Exception
  {
    HttpClient nclient = new HttpClient();
    String url = root+"/CommentAdd?cid=1";
    HttpMethodBase httpMethod;
    httpMethod = new PostMethod(url);
    nclient.executeMethod(httpMethod);
    httpMethod.releaseConnection();
   
    url = root+"/viewAllComments?cid=1";
    HttpMethodBase httpMethod2;
    httpMethod2 = new PostMethod(url);
    int status = nclient.executeMethod(httpMethod2);
    System.out.println("status:" + status);
    String response = null;
    if(status==200)
    {
      response = new String(httpMethod2.getResponseBodyAsString().getBytes("8859_1"));
    }
    Assert.assertTrue(response.contains("Comment:comment0 from viewAllComments"));
   
    httpMethod2.releaseConnection()
  }
View Full Code Here

Examples of org.apache.commons.httpclient.HttpMethodBase

  @Test(dependsOnMethods = { "addCourseTest" })
  public void AddStudentTest() throws HttpException, Exception
  {
    HttpClient nclient = new HttpClient();
    String url = root+"/StudentAdd?sid=1&sname=s1&country=country1&city=city1&street=street1&telephone=111111&age=11&score=0";
    HttpMethodBase httpMethod;
    httpMethod = new PostMethod(url);
    nclient.executeMethod(httpMethod);
    httpMethod.releaseConnection();
   
    url = root+"/viewStudents";
    HttpMethodBase httpMethod2;
    httpMethod2 = new PostMethod(url);
    nclient.executeMethod(httpMethod2);
    int status = nclient.executeMethod(httpMethod2);
    Assert.assertEquals(status,200);
//    System.out.println("status:" + status);
   
    String response = null;
    if(status==200)
    {
      response = new String(httpMethod2.getResponseBodyAsString().getBytes("8859_1"));
    }
    Assert.assertTrue(response.contains("Country:country1"));
    Assert.assertTrue(response.contains("City:city1"));
    Assert.assertTrue(response.contains("Street:street1"));
    httpMethod2.releaseConnection();
  }
View Full Code Here

Examples of org.apache.commons.httpclient.HttpMethodBase

  @Test(dependsOnMethods = { "AddStudentTest" })
  public void SelectCourseTest() throws HttpException, Exception
  {
    HttpClient nclient = new HttpClient();
    String url = root+"/viewSelect_CourseRelation?sid=1";
    HttpMethodBase httpMethod;
    httpMethod = new PostMethod(url);
    int status = nclient.executeMethod(httpMethod);
//    System.out.println("status:" + status);
    String response = null;
    Assert.assertEquals(status, 200);
    if(status==200)
    {
      response = new String(httpMethod.getResponseBodyAsString().getBytes("8859_1"));
    }
    Assert.assertTrue(response.contains("Click Here to Select course1 from selectCourse"));
    httpMethod.releaseConnection();
   
   
    url = root+"/CourseSelect?cid=1&sid=1";
    httpMethod = new PostMethod(url);
    status = nclient.executeMethod(httpMethod);
    Assert.assertEquals(status, 200);
//    System.out.println("status:" + status);
    response = null;
    if(status==200)
    {
      response = new String(httpMethod.getResponseBodyAsString().getBytes("8859_1"));
    }
    Assert.assertTrue(response.contains("Click Here to Unselect course1 from selectCourse"));
    httpMethod.releaseConnection();
  }
View Full Code Here

Examples of org.apache.commons.httpclient.HttpMethodBase

  {
    String result=null;
    String response = null;
    HttpClient nclient = new HttpClient();
    String url = root+"/CourseUnselect?cid=1&sid=1";
    HttpMethodBase httpMethod;
    httpMethod = new PostMethod(url);
    int status = nclient.executeMethod(httpMethod);
//    System.out.println("status:" + status);

    Assert.assertEquals(status, 200);

    if(status==200)
    {
      response = new String(httpMethod.getResponseBodyAsString().getBytes("8859_1"));
    }
    Assert.assertTrue(response.contains("Click Here to Select course1 from selectCourse"));
    httpMethod.releaseConnection();
  }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.