Search in sources :

Example 1 with IndyHttpException

use of org.commonjava.indy.subsys.http.IndyHttpException in project indy by Commonjava.

the class ReplicationController method getEndpoints.

private List<EndpointView> getEndpoints(final ReplicationDTO dto) throws IndyWorkflowException {
    final String apiUrl = dto.getApiUrl();
    String url = null;
    try {
        url = buildUrl(apiUrl, "/stats/all-endpoints");
    } catch (final MalformedURLException e) {
        throw new IndyWorkflowException("Failed to construct endpoint-retrieval URL from api-base: {}. Reason: {}", e, apiUrl, e.getMessage());
    }
    final HttpGet req = newGet(url, dto);
    CloseableHttpClient client = null;
    try {
        String siteId = new URL(url).getHost();
        client = http.createClient(siteId);
        CloseableHttpResponse response = client.execute(req, http.createContext(siteId));
        final StatusLine statusLine = response.getStatusLine();
        final int status = statusLine.getStatusCode();
        if (status == HttpStatus.SC_OK) {
            final String json = HttpResources.entityToString(response);
            final EndpointViewListing listing = serializer.readValue(json, EndpointViewListing.class);
            return listing.getItems();
        }
        throw new IndyWorkflowException(status, "Endpoint request failed: {}", statusLine);
    } catch (final IOException | IndyHttpException e) {
        throw new IndyWorkflowException("Failed to retrieve endpoints from: {}. Reason: {}", e, url, e.getMessage());
    } finally {
        IOUtils.closeQuietly(client);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) MalformedURLException(java.net.MalformedURLException) HttpGet(org.apache.http.client.methods.HttpGet) IndyHttpException(org.commonjava.indy.subsys.http.IndyHttpException) IOException(java.io.IOException) URL(java.net.URL) StatusLine(org.apache.http.StatusLine) EndpointViewListing(org.commonjava.indy.model.core.dto.EndpointViewListing) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 2 with IndyHttpException

use of org.commonjava.indy.subsys.http.IndyHttpException in project indy by Commonjava.

the class IndyZabbixReporter method report.

@SuppressWarnings("rawtypes")
@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
    final long clock = System.currentTimeMillis() / 1000;
    List<DataObject> dataObjectList = new LinkedList<DataObject>();
    for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
        DataObject dataObject = toDataObject(entry.getKey(), "", String.valueOf(entry.getValue().getValue()), clock);
        dataObjectList.add(dataObject);
    }
    for (Map.Entry<String, Counter> entry : counters.entrySet()) {
        DataObject dataObject = toDataObject(entry.getKey(), "", String.valueOf(entry.getValue().getCount()), clock);
        dataObjectList.add(dataObject);
    }
    for (Map.Entry<String, Histogram> entry : histograms.entrySet()) {
        Histogram histogram = entry.getValue();
        Snapshot snapshot = histogram.getSnapshot();
        addSnapshotDataObject(entry.getKey(), snapshot, clock, dataObjectList);
    }
    for (Map.Entry<String, Meter> entry : meters.entrySet()) {
        Meter meter = entry.getValue();
        addMeterDataObject(entry.getKey(), meter, clock, dataObjectList);
    }
    for (Map.Entry<String, Timer> entry : timers.entrySet()) {
        Timer timer = entry.getValue();
        addMeterDataObject(entry.getKey(), timer, clock, dataObjectList);
        addSnapshotDataObjectWithConvertDuration(entry.getKey(), timer.getSnapshot(), clock, dataObjectList);
    }
    try {
        SenderResult senderResult = indyZabbixSender.send(dataObjectList, clock);
        if (!senderResult.success()) {
            logger.warn("report metrics to zabbix not success!" + senderResult);
        } else if (logger.isDebugEnabled()) {
            logger.info("report metrics to zabbix success. " + senderResult);
        }
    } catch (IOException e) {
        logger.error("report metrics to zabbix error! " + e);
        e.printStackTrace();
    } catch (IndyMetricsException e) {
        logger.error("Indy metrics config error " + e);
        e.printStackTrace();
    } catch (IndyHttpException e) {
        logger.error("Indy http client error " + e);
        e.printStackTrace();
    }
}
Also used : Histogram(com.codahale.metrics.Histogram) Meter(com.codahale.metrics.Meter) IndyHttpException(org.commonjava.indy.subsys.http.IndyHttpException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) Gauge(com.codahale.metrics.Gauge) Snapshot(com.codahale.metrics.Snapshot) DataObject(org.commonjava.indy.metrics.zabbix.sender.DataObject) Counter(com.codahale.metrics.Counter) Timer(com.codahale.metrics.Timer) Map(java.util.Map) SortedMap(java.util.SortedMap) SenderResult(org.commonjava.indy.metrics.zabbix.sender.SenderResult) IndyMetricsException(org.commonjava.indy.metrics.exception.IndyMetricsException)

Example 3 with IndyHttpException

use of org.commonjava.indy.subsys.http.IndyHttpException in project indy by Commonjava.

the class IndyZabbixSender method send.

/**
     *
     * @param dataObjectList
     * @param clock
     *            TimeUnit is SECONDS.
     * @return
     * @throws IOException
     */
public SenderResult send(List<DataObject> dataObjectList, long clock) throws IOException, IndyHttpException, IndyMetricsException {
    if (bCreateNotExistHostGroup) {
        try {
            checkHostGroup(hostGroup);
        } catch (IndyHttpException e) {
            logger.error("Check HostGroup of Zabbix is error:" + e.getMessage());
            throw e;
        }
    }
    if (bCreateNotExistHost) {
        try {
            checkHost(hostName, ip);
        } catch (IndyHttpException e) {
            logger.error("Check Host of Zabbix is error:" + e.getMessage());
            throw e;
        }
    }
    if (bCreateNotExistItem) {
        for (DataObject object : dataObjectList) {
            String key = object.getKey();
            int vauleType = 0;
            Matcher mat = pat.matcher(object.getValue());
            if (!mat.find()) {
                vauleType = 4;
            }
            try {
                checkItem(hostName, key, vauleType);
            } catch (IndyHttpException e) {
                logger.error("Check Item of Zabbix is error:" + e.getMessage());
                throw e;
            }
        }
    }
    try {
        SenderResult senderResult = sender.send(dataObjectList, clock);
        if (!senderResult.success()) {
            logger.error("send data to zabbix server error! senderResult:" + senderResult);
        }
        return senderResult;
    } catch (IOException e) {
        logger.error("send data to zabbix server error!", e);
        throw e;
    }
}
Also used : Matcher(java.util.regex.Matcher) IndyHttpException(org.commonjava.indy.subsys.http.IndyHttpException) IOException(java.io.IOException)

Example 4 with IndyHttpException

use of org.commonjava.indy.subsys.http.IndyHttpException in project indy by Commonjava.

the class BasicAuthenticationOAuthTranslator method lookupToken.

private AccessTokenResponse lookupToken(final UserPass userPass) {
    final URI uri = KeycloakUriBuilder.fromUri(config.getUrl()).path(ServiceUrlConstants.TOKEN_PATH).build(config.getRealm());
    logger.debug("Looking up token at: {}", uri);
    final HttpPost request = new HttpPost(uri);
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(USERNAME, userPass.getUser()));
    params.add(new BasicNameValuePair(PASSWORD, userPass.getPassword()));
    params.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
    final String authorization = BasicAuthHelper.createHeader(config.getServerResource(), config.getServerCredentialSecret());
    request.setHeader(AUTHORIZATION_HEADER, authorization);
    CloseableHttpClient client = null;
    AccessTokenResponse tokenResponse = null;
    try {
        client = http.createClient(uri.getHost());
        final UrlEncodedFormEntity form = new UrlEncodedFormEntity(params, "UTF-8");
        request.setEntity(form);
        CloseableHttpResponse response = client.execute(request);
        logger.debug("Got response status: {}", response.getStatusLine());
        if (response.getStatusLine().getStatusCode() == 200) {
            try (InputStream in = response.getEntity().getContent()) {
                final String json = IOUtils.toString(in);
                logger.debug("Token response:\n\n{}\n\n", json);
                tokenResponse = JsonSerialization.readValue(json, AccessTokenResponse.class);
            }
        }
    } catch (IOException | IndyHttpException e) {
        logger.error(String.format("Keycloak token request failed: %s", e.getMessage()), e);
    } finally {
        IOUtils.closeQuietly(client);
    }
    return tokenResponse;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IndyHttpException(org.commonjava.indy.subsys.http.IndyHttpException) HttpString(io.undertow.util.HttpString) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) URI(java.net.URI) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 5 with IndyHttpException

use of org.commonjava.indy.subsys.http.IndyHttpException in project indy by Commonjava.

the class ReplicationController method addStoresFrom.

private <T extends ArtifactStore> void addStoresFrom(final List<ArtifactStore> result, final String remotesUrl, final ReplicationDTO dto, final Class<T> type) throws IndyWorkflowException {
    final HttpGet req = newGet(remotesUrl, dto);
    CloseableHttpClient client = null;
    try {
        String siteId = new URL(remotesUrl).getHost();
        client = http.createClient(siteId);
        CloseableHttpResponse response = client.execute(req, http.createContext(siteId));
        final StatusLine statusLine = response.getStatusLine();
        final int status = statusLine.getStatusCode();
        if (status == HttpStatus.SC_OK) {
            final String json = HttpResources.entityToString(response);
            final StoreListingDTO<T> listing = serializer.readValue(json, serializer.getTypeFactory().constructParametricType(StoreListingDTO.class, type));
            if (listing != null) {
                result.addAll(listing.getItems());
            }
        } else {
            throw new IndyWorkflowException(status, "Request: %s failed: %s", remotesUrl, statusLine);
        }
    } catch (final IOException | IndyHttpException e) {
        throw new IndyWorkflowException("Failed to retrieve endpoints from: %s. Reason: %s", e, remotesUrl, e.getMessage());
    } finally {
        IOUtils.closeQuietly(client);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpGet(org.apache.http.client.methods.HttpGet) IndyHttpException(org.commonjava.indy.subsys.http.IndyHttpException) IOException(java.io.IOException) URL(java.net.URL) StatusLine(org.apache.http.StatusLine) StoreListingDTO(org.commonjava.indy.model.core.dto.StoreListingDTO) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Aggregations

IOException (java.io.IOException)5 IndyHttpException (org.commonjava.indy.subsys.http.IndyHttpException)5 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)3 URL (java.net.URL)2 StatusLine (org.apache.http.StatusLine)2 HttpGet (org.apache.http.client.methods.HttpGet)2 IndyWorkflowException (org.commonjava.indy.IndyWorkflowException)2 Counter (com.codahale.metrics.Counter)1 Gauge (com.codahale.metrics.Gauge)1 Histogram (com.codahale.metrics.Histogram)1 Meter (com.codahale.metrics.Meter)1 Snapshot (com.codahale.metrics.Snapshot)1 Timer (com.codahale.metrics.Timer)1 HttpString (io.undertow.util.HttpString)1 InputStream (java.io.InputStream)1 MalformedURLException (java.net.MalformedURLException)1 URI (java.net.URI)1 ArrayList (java.util.ArrayList)1 LinkedList (java.util.LinkedList)1