Search in sources :

Example 1 with HttpClientManager

use of com.helger.httpclient.HttpClientManager in project phoss-directory by phax.

the class SMPBusinessCardProvider method getBusinessCardPeppolSMP.

@Nullable
@VisibleForTesting
PDExtendedBusinessCard getBusinessCardPeppolSMP(@Nonnull final IParticipantIdentifier aParticipantID, @Nonnull final SMPClientReadOnly aSMPClient, @Nonnull final HttpClientSettings aHCS) {
    LOGGER.info("Querying BusinessCard for '" + aParticipantID.getURIEncoded() + "' from Peppol SMP '" + aSMPClient.getSMPHostURI() + "'");
    // First query the service group
    com.helger.xsds.peppol.smp1.ServiceGroupType aServiceGroup;
    try {
        aServiceGroup = aSMPClient.getServiceGroupOrNull(aParticipantID);
    } catch (final SMPClientException ex) {
        LOGGER.error("Error querying SMP for ServiceGroup of '" + aParticipantID.getURIEncoded() + "'", ex);
        return null;
    }
    // If the service group is present, try querying the business card
    final PDBusinessCard aBusinessCard;
    try (final HttpClientManager aHCM = HttpClientManager.create(aHCS)) {
        // Use the optional business card API
        final HttpGet aRequest = new HttpGet(aSMPClient.getSMPHostURI() + "businesscard/" + aParticipantID.getURIPercentEncoded());
        aBusinessCard = aHCM.execute(aRequest, new PDSMPHttpResponseHandlerBusinessCard());
    } catch (final IOException ex) {
        if ((ex instanceof HttpResponseException && ((HttpResponseException) ex).getStatusCode() == CHttp.HTTP_NOT_FOUND) || ex instanceof UnknownHostException) {
            LOGGER.warn("No BusinessCard available for '" + aParticipantID.getURIEncoded() + "' - not in configured SMK/SML? - " + ex.getMessage());
        } else
            LOGGER.error("Error querying SMP for BusinessCard of '" + aParticipantID.getURIEncoded() + "'", ex);
        return null;
    }
    if (aBusinessCard == null) {
        // No extension present - no need to try again
        LOGGER.warn("Failed to get SMP BusinessCard of " + aParticipantID.getURIEncoded());
        return null;
    }
    // Query all document types
    final IIdentifierFactory aIdentifierFactory = PDMetaManager.getIdentifierFactory();
    final ICommonsList<IDocumentTypeIdentifier> aDocumentTypeIDs = SMPClientReadOnly.getAllDocumentTypes(aServiceGroup, aIdentifierFactory, UNHANDLED_HREF_HANDLER);
    return new PDExtendedBusinessCard(aBusinessCard, aDocumentTypeIDs);
}
Also used : PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) UnknownHostException(java.net.UnknownHostException) HttpGet(org.apache.http.client.methods.HttpGet) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) HttpClientManager(com.helger.httpclient.HttpClientManager) SMPClientException(com.helger.smpclient.exception.SMPClientException) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) VisibleForTesting(com.helger.commons.annotation.VisibleForTesting) Nullable(javax.annotation.Nullable)

Example 2 with HttpClientManager

use of com.helger.httpclient.HttpClientManager in project phoss-directory by phax.

the class SMPBusinessCardProvider method getBusinessCardBDXR2.

@Nullable
@VisibleForTesting
PDExtendedBusinessCard getBusinessCardBDXR2(@Nonnull final IParticipantIdentifier aParticipantID, @Nonnull final BDXR2ClientReadOnly aSMPClient, @Nonnull final HttpClientSettings aHCS) {
    LOGGER.info("Querying BusinessCard for '" + aParticipantID.getURIEncoded() + "' from OASIS BDXR SMP v2 '" + aSMPClient.getSMPHostURI() + "'");
    // First query the service group
    com.helger.xsds.bdxr.smp2.ServiceGroupType aServiceGroup;
    try {
        aServiceGroup = aSMPClient.getServiceGroupOrNull(aParticipantID);
    } catch (final SMPClientException ex) {
        LOGGER.error("Error querying SMP for ServiceGroup of '" + aParticipantID.getURIEncoded() + "'", ex);
        return null;
    }
    // If the service group is present, try querying the business card
    final PDBusinessCard aBusinessCard;
    try (final HttpClientManager aHCM = HttpClientManager.create(aHCS)) {
        // Use the optional business card API
        // TODO is the path "bdxr-smp-2" needed? Well, the PD is not yet
        // specified for this SMP type....
        final HttpGet aRequest = new HttpGet(aSMPClient.getSMPHostURI() + "businesscard/" + aParticipantID.getURIPercentEncoded());
        aBusinessCard = aHCM.execute(aRequest, new PDSMPHttpResponseHandlerBusinessCard());
    } catch (final IOException ex) {
        if ((ex instanceof HttpResponseException && ((HttpResponseException) ex).getStatusCode() == CHttp.HTTP_NOT_FOUND) || ex instanceof UnknownHostException) {
            LOGGER.warn("No BusinessCard available for '" + aParticipantID.getURIEncoded() + "' - not in configured SMK/SML? - " + ex.getMessage());
        } else
            LOGGER.error("Error querying SMP for BusinessCard of '" + aParticipantID.getURIEncoded() + "'", ex);
        return null;
    }
    if (aBusinessCard == null) {
        // No extension present - no need to try again
        LOGGER.warn("Failed to get SMP BusinessCard of " + aParticipantID.getURIEncoded());
        return null;
    }
    // Query all document types
    final IIdentifierFactory aIdentifierFactory = PDMetaManager.getIdentifierFactory();
    final ICommonsList<IDocumentTypeIdentifier> aDocumentTypeIDs = BDXR2ClientReadOnly.getAllDocumentTypes(aServiceGroup, aIdentifierFactory);
    return new PDExtendedBusinessCard(aBusinessCard, aDocumentTypeIDs);
}
Also used : PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) UnknownHostException(java.net.UnknownHostException) HttpGet(org.apache.http.client.methods.HttpGet) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) HttpClientManager(com.helger.httpclient.HttpClientManager) SMPClientException(com.helger.smpclient.exception.SMPClientException) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) VisibleForTesting(com.helger.commons.annotation.VisibleForTesting) Nullable(javax.annotation.Nullable)

Example 3 with HttpClientManager

use of com.helger.httpclient.HttpClientManager in project phoss-directory by phax.

the class SMPBusinessCardProvider method getBusinessCardBDXR1.

@Nullable
@VisibleForTesting
PDExtendedBusinessCard getBusinessCardBDXR1(@Nonnull final IParticipantIdentifier aParticipantID, @Nonnull final BDXRClientReadOnly aSMPClient, @Nonnull final HttpClientSettings aHCS) {
    LOGGER.info("Querying BusinessCard for '" + aParticipantID.getURIEncoded() + "' from OASIS BDXR SMP v1 '" + aSMPClient.getSMPHostURI() + "'");
    // First query the service group
    com.helger.xsds.bdxr.smp1.ServiceGroupType aServiceGroup;
    try {
        aServiceGroup = aSMPClient.getServiceGroupOrNull(aParticipantID);
    } catch (final SMPClientException ex) {
        LOGGER.error("Error querying SMP for ServiceGroup of '" + aParticipantID.getURIEncoded() + "'", ex);
        return null;
    }
    // If the service group is present, try querying the business card
    final PDBusinessCard aBusinessCard;
    try (final HttpClientManager aHCM = HttpClientManager.create(aHCS)) {
        // Use the optional business card API
        final HttpGet aRequest = new HttpGet(aSMPClient.getSMPHostURI() + "businesscard/" + aParticipantID.getURIPercentEncoded());
        aBusinessCard = aHCM.execute(aRequest, new PDSMPHttpResponseHandlerBusinessCard());
    } catch (final IOException ex) {
        if ((ex instanceof HttpResponseException && ((HttpResponseException) ex).getStatusCode() == CHttp.HTTP_NOT_FOUND) || ex instanceof UnknownHostException) {
            LOGGER.warn("No BusinessCard available for '" + aParticipantID.getURIEncoded() + "' - not in configured SMK/SML? - " + ex.getMessage());
        } else
            LOGGER.error("Error querying SMP for BusinessCard of '" + aParticipantID.getURIEncoded() + "'", ex);
        return null;
    }
    if (aBusinessCard == null) {
        // No extension present - no need to try again
        LOGGER.warn("Failed to get SMP BusinessCard of " + aParticipantID.getURIEncoded());
        return null;
    }
    // Query all document types
    final IIdentifierFactory aIdentifierFactory = PDMetaManager.getIdentifierFactory();
    final ICommonsList<IDocumentTypeIdentifier> aDocumentTypeIDs = BDXRClientReadOnly.getAllDocumentTypes(aServiceGroup, aIdentifierFactory, UNHANDLED_HREF_HANDLER);
    return new PDExtendedBusinessCard(aBusinessCard, aDocumentTypeIDs);
}
Also used : PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) UnknownHostException(java.net.UnknownHostException) HttpGet(org.apache.http.client.methods.HttpGet) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) HttpClientManager(com.helger.httpclient.HttpClientManager) SMPClientException(com.helger.smpclient.exception.SMPClientException) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) VisibleForTesting(com.helger.commons.annotation.VisibleForTesting) Nullable(javax.annotation.Nullable)

Example 4 with HttpClientManager

use of com.helger.httpclient.HttpClientManager in project phase4 by phax.

the class BasicHttpPoster method sendGenericMessage.

/**
 * Send an arbitrary HTTP POST message to the provided URL, using the
 * contained HttpClientFactory as well as the customizer. Additionally the AS4
 * HTTP debugging is invoked in here.<br>
 * This method does NOT retry
 *
 * @param <T>
 *        Response data type
 * @param sURL
 *        The URL to send to. May neither be <code>null</code> nor empty.
 * @param aCustomHttpHeaders
 *        An optional http header map that should be applied. May be
 *        <code>null</code>.
 * @param aHttpEntity
 *        The HTTP entity to be send. May not be <code>null</code>.
 * @param aResponseHandler
 *        The Http response handler that should be used to convert the HTTP
 *        response to a domain object.
 * @return The HTTP response. May be <code>null</code>.
 * @throws IOException
 *         In case of IO error
 */
@Nullable
public <T> T sendGenericMessage(@Nonnull @Nonempty final String sURL, @Nullable final HttpHeaderMap aCustomHttpHeaders, @Nonnull final HttpEntity aHttpEntity, @Nonnull final ResponseHandler<? extends T> aResponseHandler) throws IOException {
    ValueEnforcer.notEmpty(sURL, "URL");
    ValueEnforcer.notNull(aHttpEntity, "HttpEntity");
    final StopWatch aSW = StopWatch.createdStarted();
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Starting to transmit AS4 Message to '" + sURL + "'");
    IOException aCaughtException = null;
    try (final HttpClientManager aClientMgr = new HttpClientManager(m_aHttpClientFactory)) {
        final HttpPost aPost = new HttpPost(sURL);
        if (aCustomHttpHeaders != null) {
            // Always unify line endings
            // By default quoting is disabled
            aCustomHttpHeaders.forEachSingleHeader(aPost::addHeader, true, m_bQuoteHttpHeaders);
        }
        aPost.setEntity(aHttpEntity);
        // Invoke optional customizer
        if (m_aHttpCustomizer != null)
            m_aHttpCustomizer.accept(aPost);
        // Debug sending
        AS4HttpDebug.debug(() -> {
            final StringBuilder ret = new StringBuilder("SEND-START to ").append(sURL).append("\n");
            try {
                for (final Header aHeader : aPost.getAllHeaders()) ret.append(aHeader.getName()).append(": ").append(aHeader.getValue()).append(CHttp.EOL);
                ret.append(CHttp.EOL);
                if (aHttpEntity.isRepeatable())
                    ret.append(EntityUtils.toString(aHttpEntity));
                else
                    ret.append("## The payload is marked as 'not repeatable' and is the therefore not printed in debugging");
            } catch (final Exception ex) {
                ret.append("## Exception listing payload: " + ex.getClass().getName() + " -- " + ex.getMessage()).append(CHttp.EOL);
                ret.append("## ").append(StackTraceHelper.getStackAsString(ex));
            }
            return ret.toString();
        });
        return aClientMgr.execute(aPost, aResponseHandler);
    } catch (final IOException ex) {
        aCaughtException = ex;
        throw ex;
    } finally {
        aSW.stop();
        if (LOGGER.isInfoEnabled())
            LOGGER.info((aCaughtException != null ? "Failed" : "Finished") + " transmitting AS4 Message to '" + sURL + "' after " + aSW.getMillis() + " ms");
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpClientManager(com.helger.httpclient.HttpClientManager) Header(org.apache.http.Header) IOException(java.io.IOException) IOException(java.io.IOException) StopWatch(com.helger.commons.timing.StopWatch) Nullable(javax.annotation.Nullable)

Example 5 with HttpClientManager

use of com.helger.httpclient.HttpClientManager in project phoss-smp by phax.

the class APIExecutorQueryGetBusinessCard method invokeAPI.

public void invokeAPI(@Nonnull final IAPIDescriptor aAPIDescriptor, @Nonnull @Nonempty final String sPath, @Nonnull final Map<String, String> aPathVariables, @Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final UnifiedResponse aUnifiedResponse) throws Exception {
    final String sPathServiceGroupID = aPathVariables.get(SMPRestFilter.PARAM_SERVICE_GROUP_ID);
    final ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, sPathServiceGroupID);
    // Is the remote query API disabled?
    if (SMPServerConfiguration.isRestRemoteQueryAPIDisabled()) {
        throw new SMPPreconditionFailedException("The remote query API is disabled. getRemoteBusinessCard will not be executed", aDataProvider.getCurrentURI());
    }
    final IIdentifierFactory aIF = SMPMetaManager.getIdentifierFactory();
    final ESMPAPIType eAPIType = SMPServerConfiguration.getRESTType().getAPIType();
    final IParticipantIdentifier aParticipantID = aIF.parseParticipantIdentifier(sPathServiceGroupID);
    if (aParticipantID == null) {
        throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, aDataProvider.getCurrentURI());
    }
    final SMPQueryParams aQueryParams = SMPQueryParams.create(eAPIType, aParticipantID);
    final ZonedDateTime aQueryDT = PDTFactory.getCurrentZonedDateTimeUTC();
    final StopWatch aSW = StopWatch.createdStarted();
    final String sLogPrefix = "[QueryAPI] ";
    LOGGER.info(sLogPrefix + "BusinessCard of '" + aParticipantID.getURIEncoded() + "' is queried using SMP API '" + eAPIType + "' from '" + aQueryParams.getSMPHostURI() + "'");
    IJsonObject aJson = null;
    final String sBCURL = aQueryParams.getSMPHostURI().toString() + "/businesscard/" + aParticipantID.getURIEncoded();
    LOGGER.info(sLogPrefix + "Querying BC from '" + sBCURL + "'");
    byte[] aData;
    try (HttpClientManager aHttpClientMgr = new HttpClientManager()) {
        final HttpGet aGet = new HttpGet(sBCURL);
        aData = aHttpClientMgr.execute(aGet, new ResponseHandlerByteArray());
    } catch (final Exception ex) {
        aData = null;
    }
    if (aData == null)
        LOGGER.warn(sLogPrefix + "No Business Card is available for that participant.");
    else {
        final PDBusinessCard aBC = PDBusinessCardHelper.parseBusinessCard(aData, (Charset) null);
        if (aBC == null) {
            LOGGER.error(sLogPrefix + "Failed to parse BC:\n" + new String(aData, StandardCharsets.UTF_8));
        } else {
            // Business Card found
            aJson = aBC.getAsJson();
        }
    }
    aSW.stop();
    if (aJson == null) {
        LOGGER.error(sLogPrefix + "Failed to perform the BusinessCard SMP lookup");
        aUnifiedResponse.setStatus(CHttp.HTTP_NOT_FOUND);
    } else {
        LOGGER.info(sLogPrefix + "Succesfully finished BusinessCard lookup lookup after " + aSW.getMillis() + " milliseconds");
        aJson.add("queryDateTime", DateTimeFormatter.ISO_ZONED_DATE_TIME.format(aQueryDT));
        aJson.add("queryDurationMillis", aSW.getMillis());
        final String sRet = new JsonWriter(JsonWriterSettings.DEFAULT_SETTINGS_FORMATTED).writeAsString(aJson);
        aUnifiedResponse.setContentAndCharset(sRet, StandardCharsets.UTF_8).setMimeType(CMimeType.APPLICATION_JSON).enableCaching(1 * CGlobal.SECONDS_PER_HOUR);
    }
}
Also used : PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) ResponseHandlerByteArray(com.helger.httpclient.response.ResponseHandlerByteArray) HttpGet(org.apache.http.client.methods.HttpGet) JsonWriter(com.helger.json.serialize.JsonWriter) SMPBadRequestException(com.helger.phoss.smp.exception.SMPBadRequestException) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) ESMPAPIType(com.helger.peppol.sml.ESMPAPIType) StopWatch(com.helger.commons.timing.StopWatch) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) HttpClientManager(com.helger.httpclient.HttpClientManager) ZonedDateTime(java.time.ZonedDateTime) IJsonObject(com.helger.json.IJsonObject) ISMPServerAPIDataProvider(com.helger.phoss.smp.restapi.ISMPServerAPIDataProvider) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Aggregations

HttpClientManager (com.helger.httpclient.HttpClientManager)6 PDBusinessCard (com.helger.pd.businesscard.generic.PDBusinessCard)5 IIdentifierFactory (com.helger.peppolid.factory.IIdentifierFactory)5 HttpGet (org.apache.http.client.methods.HttpGet)5 IOException (java.io.IOException)4 Nullable (javax.annotation.Nullable)4 VisibleForTesting (com.helger.commons.annotation.VisibleForTesting)3 StopWatch (com.helger.commons.timing.StopWatch)3 IDocumentTypeIdentifier (com.helger.peppolid.IDocumentTypeIdentifier)3 SMPClientException (com.helger.smpclient.exception.SMPClientException)3 UnknownHostException (java.net.UnknownHostException)3 HttpResponseException (org.apache.http.client.HttpResponseException)3 ResponseHandlerByteArray (com.helger.httpclient.response.ResponseHandlerByteArray)2 IJsonObject (com.helger.json.IJsonObject)2 JsonWriter (com.helger.json.serialize.JsonWriter)2 ESMPAPIType (com.helger.peppol.sml.ESMPAPIType)2 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)2 SMPBadRequestException (com.helger.phoss.smp.exception.SMPBadRequestException)2 SMPPreconditionFailedException (com.helger.phoss.smp.exception.SMPPreconditionFailedException)2 ISMPServerAPIDataProvider (com.helger.phoss.smp.restapi.ISMPServerAPIDataProvider)2