Java Code Examples for org.apache.commons.httpclient.methods.GetMethod#getStatusCode()

The following examples show how to use org.apache.commons.httpclient.methods.GetMethod#getStatusCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractSubmarineServerTest.java    From submarine with Apache License 2.0 6 votes vote down vote up
protected static boolean checkIfServerIsRunning() {
  GetMethod request = null;
  boolean isRunning = false;
  try {
    request = httpGet("/");
    isRunning = request.getStatusCode() == 200;
  } catch (IOException e) {
    LOG.warn("AbstractTestRestApi.checkIfServerIsRunning() fails .. " +
        "Submarine server is not running");
    isRunning = false;
  } finally {
    if (request != null) {
      request.releaseConnection();
    }
  }
  return isRunning;
}
 
Example 2
Source File: HttpResource.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets remote resource.
 * 
 * @return the remove resource
 * 
 * @throws ResourceException thrown if the resource could not be fetched
 */
protected GetMethod getResource() throws ResourceException {
    GetMethod getMethod = new GetMethod(resourceUrl);
    getMethod.addRequestHeader("Connection", "close");

    try {
        httpClient.executeMethod(getMethod);
        if (getMethod.getStatusCode() != HttpStatus.SC_OK) {
            throw new ResourceException("Unable to retrieve resource URL " + resourceUrl
                    + ", received HTTP status code " + getMethod.getStatusCode());
        }
        return getMethod;
    } catch (IOException e) {
        throw new ResourceException("Unable to contact resource URL: " + resourceUrl, e);
    }
}
 
Example 3
Source File: AbstractTestRestApi.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
protected static boolean checkIfServerIsRunning() {
  GetMethod request = null;
  boolean isRunning;
  try {
    request = httpGet("/version");
    isRunning = request.getStatusCode() == 200;
  } catch (IOException e) {
    LOG.error("AbstractTestRestApi.checkIfServerIsRunning() fails .. ZeppelinServer is not " +
            "running");
    isRunning = false;
  } finally {
    if (request != null) {
      request.releaseConnection();
    }
  }
  return isRunning;
}
 
Example 4
Source File: ZeppelinServerMock.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
protected static boolean checkIfServerIsRunning() {
  GetMethod request = null;
  boolean isRunning;
  try {
    request = httpGet("/version");
    isRunning = request.getStatusCode() == 200;
  } catch (IOException e) {
    LOG.error("AbstractTestRestApi.checkIfServerIsRunning() fails .. ZeppelinServer is not " +
        "running");
    isRunning = false;
  } finally {
    if (request != null) {
      request.releaseConnection();
    }
  }
  return isRunning;
}
 
Example 5
Source File: ClientCollection.java    From rome with Apache License 2.0 6 votes vote down vote up
/**
 * Get full entry specified by entry edit URI. Note that entry may or may not be associated with
 * this collection.
 *
 * @return ClientEntry or ClientMediaEntry specified by URI.
 */
public ClientEntry getEntry(final String uri) throws ProponoException {
    final GetMethod method = new GetMethod(uri);
    authStrategy.addAuthentication(httpClient, method);
    try {
        httpClient.executeMethod(method);
        if (method.getStatusCode() != 200) {
            throw new ProponoException("ERROR HTTP status code=" + method.getStatusCode());
        }
        final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(method.getResponseBodyAsStream()), uri, Locale.US);
        if (!romeEntry.isMediaEntry()) {
            return new ClientEntry(service, this, romeEntry, false);
        } else {
            return new ClientMediaEntry(service, this, romeEntry, false);
        }
    } catch (final Exception e) {
        throw new ProponoException("ERROR: getting or parsing entry/media, HTTP code: ", e);
    } finally {
        method.releaseConnection();
    }
}
 
Example 6
Source File: ClientCategories.java    From rome with Apache License 2.0 6 votes vote down vote up
public void fetchContents() throws ProponoException {
    final GetMethod method = new GetMethod(getHrefResolved());
    clientCollection.addAuthentication(method);
    try {
        clientCollection.getHttpClient().executeMethod(method);
        if (method.getStatusCode() != 200) {
            throw new ProponoException("ERROR HTTP status code=" + method.getStatusCode());
        }
        final SAXBuilder builder = new SAXBuilder();
        final Document catsDoc = builder.build(new InputStreamReader(method.getResponseBodyAsStream()));
        parseCategoriesElement(catsDoc.getRootElement());

    } catch (final IOException ioe) {
        throw new ProponoException("ERROR: reading out-of-line categories", ioe);
    } catch (final JDOMException jde) {
        throw new ProponoException("ERROR: parsing out-of-line categories", jde);
    } finally {
        method.releaseConnection();
    }
}
 
Example 7
Source File: ClientAtomService.java    From rome with Apache License 2.0 6 votes vote down vote up
/**
 * Get full entry from service by entry edit URI.
 */
public ClientEntry getEntry(final String uri) throws ProponoException {
    final GetMethod method = new GetMethod(uri);
    authStrategy.addAuthentication(httpClient, method);
    try {
        httpClient.executeMethod(method);
        if (method.getStatusCode() != 200) {
            throw new ProponoException("ERROR HTTP status code=" + method.getStatusCode());
        }
        final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(method.getResponseBodyAsStream()), uri, Locale.US);
        if (!romeEntry.isMediaEntry()) {
            return new ClientEntry(this, null, romeEntry, false);
        } else {
            return new ClientMediaEntry(this, null, romeEntry, false);
        }
    } catch (final Exception e) {
        throw new ProponoException("ERROR: getting or parsing entry/media", e);
    } finally {
        method.releaseConnection();
    }
}
 
Example 8
Source File: AbstractSolrAdminHTTPClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Executes an action or a command in SOLR using REST API 
 * 
 * @param httpClient HTTP Client to be used for the invocation
 * @param url Complete URL of SOLR REST API Endpoint
 * @return A JSON Object including SOLR response
 * @throws UnsupportedEncodingException
 */
protected JSONObject getOperation(HttpClient httpClient, String url) throws UnsupportedEncodingException 
{

    GetMethod get = new GetMethod(url);
    
    try {
        
        httpClient.executeMethod(get);
        if(get.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || get.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
        {
            Header locationHeader = get.getResponseHeader("location");
            if (locationHeader != null)
            {
                String redirectLocation = locationHeader.getValue();
                get.setURI(new URI(redirectLocation, true));
                httpClient.executeMethod(get);
            }
        }
        if (get.getStatusCode() != HttpServletResponse.SC_OK)
        {
            throw new LuceneQueryParserException("Request failed " + get.getStatusCode() + " " + url.toString());
        }

        Reader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), get.getResponseCharSet()));
        JSONObject json = new JSONObject(new JSONTokener(reader));
        return json;
        
    }
    catch (IOException | JSONException e) 
    {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } 
    finally 
    {
        get.releaseConnection();
    }
}
 
Example 9
Source File: GitDiffHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private String fetchPatchContentFromUrl(final String url) throws IOException {
	GetMethod m = new GetMethod(url);
	try {
		getHttpClient().executeMethod(m);
		if (m.getStatusCode() == HttpStatus.SC_OK) {
			return IOUtilities.toString(m.getResponseBodyAsStream());
		}
	} finally {
		m.releaseConnection();
	}
	return null;
}
 
Example 10
Source File: NotebookRepoRestApiTest.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Test
public void reloadRepositories() throws IOException {
  GetMethod get = httpGet("/notebook-repositories/reload");
  int status = get.getStatusCode();
  get.releaseConnection();
  assertThat(status, is(200)); 
}
 
Example 11
Source File: ApacheHttpClient3xPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    HttpClient httpClient = new HttpClient();
    GetMethod httpGet = new GetMethod("http://localhost:" + getPort() + "/hello1");
    httpClient.executeMethod(httpGet);
    httpGet.releaseConnection();
    if (httpGet.getStatusCode() != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + httpGet.getStatusCode());
    }
}
 
Example 12
Source File: ClientMediaEntry.java    From rome with Apache License 2.0 5 votes vote down vote up
private InputStream getResourceAsStream() throws ProponoException {
    if (getEditURI() == null) {
        throw new ProponoException("ERROR: not yet saved to server");
    }
    final GetMethod method = new GetMethod(((Content) getContents()).getSrc());
    try {
        getCollection().getHttpClient().executeMethod(method);
        if (method.getStatusCode() != 200) {
            throw new ProponoException("ERROR HTTP status=" + method.getStatusCode());
        }
        return method.getResponseBodyAsStream();
    } catch (final IOException e) {
        throw new ProponoException("ERROR: getting media entry", e);
    }
}
 
Example 13
Source File: EntryIterator.java    From rome with Apache License 2.0 5 votes vote down vote up
private void getNextEntries() throws ProponoException {
    if (nextURI == null) {
        return;
    }
    final GetMethod colGet = new GetMethod(collection.getHrefResolved(nextURI));
    collection.addAuthentication(colGet);
    try {
        collection.getHttpClient().executeMethod(colGet);
        final SAXBuilder builder = new SAXBuilder();
        final Document doc = builder.build(colGet.getResponseBodyAsStream());
        final WireFeedInput feedInput = new WireFeedInput();
        col = (Feed) feedInput.build(doc);
    } catch (final Exception e) {
        throw new ProponoException("ERROR: fetching or parsing next entries, HTTP code: " + (colGet != null ? colGet.getStatusCode() : -1), e);
    } finally {
        colGet.releaseConnection();
    }
    members = col.getEntries().iterator();
    col.getEntries().size();

    nextURI = null;
    final List<Link> altLinks = col.getOtherLinks();
    if (altLinks != null) {
        for (final Link link : altLinks) {
            if ("next".equals(link.getRel())) {
                nextURI = link.getHref();
            }
        }
    }
}
 
Example 14
Source File: SalesforceProvisioningConnector.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * @return
 * @throws IdentityProvisioningException
 */
public String listUsers(String query) throws IdentityProvisioningException {

    if (log.isTraceEnabled()) {
        log.trace("Starting listUsers() of " + SalesforceProvisioningConnector.class);
    }
    boolean isDebugEnabled = log.isDebugEnabled();

    if (StringUtils.isBlank(query)) {
        query = SalesforceConnectorDBQueries.SALESFORCE_LIST_USER_SIMPLE_QUERY;
    }

    HttpClient httpclient = new HttpClient();
    GetMethod get = new GetMethod(this.getDataQueryEndpoint());
    setAuthorizationHeader(get);

    // set the SOQL as a query param
    NameValuePair[] params = new NameValuePair[1];
    params[0] = new NameValuePair("q", query);
    get.setQueryString(params);

    StringBuilder sb = new StringBuilder();
    try {
        httpclient.executeMethod(get);
        if (get.getStatusCode() == HttpStatus.SC_OK) {

            JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(
                    get.getResponseBodyAsStream())));
            if (isDebugEnabled) {
                log.debug("Query response: " + response.toString(2));
            }

            // Build the returning string
            sb.append(response.getString("totalSize") + " record(s) returned\n\n");
            JSONArray results = response.getJSONArray("records");
            for (int i = 0; i < results.length(); i++) {
                sb.append(results.getJSONObject(i).getString("Id") + ", "

                        + results.getJSONObject(i).getString("Alias") + ", "
                        + results.getJSONObject(i).getString("Email") + ", "
                        + results.getJSONObject(i).getString("LastName") + ", "
                        + results.getJSONObject(i).getString("Name") + ", "
                        + results.getJSONObject(i).getString("ProfileId") + ", "
                        + results.getJSONObject(i).getString("Username") + "\n");
            }
            sb.append("\n");
        } else {
            log.error("recieved response status code:" + get.getStatusCode() + " text : "
                    + get.getStatusText());
        }
    } catch (JSONException | IOException e) {
        log.error("Error in invoking provisioning operation for the user listing");
        throw new IdentityProvisioningException(e);
    }finally {
        get.releaseConnection();
    }

    if (isDebugEnabled) {
        log.debug("Returning string : " + sb.toString());
    }

    if (log.isTraceEnabled()) {
        log.trace("Ending listUsers() of " + SalesforceProvisioningConnector.class);
    }
    return sb.toString();
}
 
Example 15
Source File: ServerTableSizeReader.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
public Map<String, List<SegmentSizeInfo>> getSegmentSizeInfoFromServers(BiMap<String, String> serverEndPoints,
    String tableNameWithType, int timeoutMs) {
  int numServers = serverEndPoints.size();
  LOGGER.info("Reading segment sizes from {} servers for table: {} with timeout: {}ms", numServers, tableNameWithType,
      timeoutMs);

  List<String> serverUrls = new ArrayList<>(numServers);
  BiMap<String, String> endpointsToServers = serverEndPoints.inverse();
  for (String endpoint : endpointsToServers.keySet()) {
    String tableSizeUri = "http://" + endpoint + "/table/" + tableNameWithType + "/size";
    serverUrls.add(tableSizeUri);
  }

  // TODO: use some service other than completion service so that we know which server encounters the error
  CompletionService<GetMethod> completionService =
      new MultiGetRequest(_executor, _connectionManager).execute(serverUrls, timeoutMs);
  Map<String, List<SegmentSizeInfo>> serverToSegmentSizeInfoListMap = new HashMap<>();

  for (int i = 0; i < numServers; i++) {
    GetMethod getMethod = null;
    try {
      getMethod = completionService.take().get();
      URI uri = getMethod.getURI();
      String instance = endpointsToServers.get(uri.getHost() + ":" + uri.getPort());
      if (getMethod.getStatusCode() >= 300) {
        LOGGER.error("Server: {} returned error: {}", instance, getMethod.getStatusCode());
        continue;
      }
      TableSizeInfo tableSizeInfo =
          JsonUtils.inputStreamToObject(getMethod.getResponseBodyAsStream(), TableSizeInfo.class);
      serverToSegmentSizeInfoListMap.put(instance, tableSizeInfo.segments);
    } catch (Exception e) {
      // Ignore individual exceptions because the exception has been logged in MultiGetRequest
      // Log the number of failed servers after gathering all responses
    } finally {
      if (getMethod != null) {
        getMethod.releaseConnection();
      }
    }
  }

  int numServersResponded = serverToSegmentSizeInfoListMap.size();
  if (numServersResponded != numServers) {
    LOGGER.warn("Finish reading segment sizes for table: {} with {}/{} servers responded", tableNameWithType,
        numServersResponded, numServers);
  } else {
    LOGGER.info("Finish reading segment sizes for table: {}", tableNameWithType);
  }
  return serverToSegmentSizeInfoListMap;
}
 
Example 16
Source File: AuthUtilsTest.java    From httpclientAuthHelper with Apache License 2.0 4 votes vote down vote up
private int executeRequestReturnStatus(String url) throws IOException {
    GetMethod httpget = new GetMethod(url);
    client.executeMethod(httpget);
    return httpget.getStatusCode();
}