Search in sources :

Example 1 with HttpResponse

use of kong.unirest.HttpResponse in project Slimefun4 by Slimefun.

the class MetricsService method download.

/**
 * Downloads the version specified to Slimefun's data folder.
 *
 * @param version
 *            The version to download.
 */
private boolean download(int version) {
    File file = new File(parentFolder, "Metrics-" + version + ".jar");
    try {
        plugin.getLogger().log(Level.INFO, "# Starting download of MetricsModule build: #{0}", version);
        if (file.exists()) {
            // Delete the file in case we accidentally downloaded it before
            Files.delete(file.toPath());
        }
        AtomicInteger lastPercentPosted = new AtomicInteger();
        GetRequest request = Unirest.get(DOWNLOAD_URL + "/" + version + "/" + JAR_NAME + ".jar");
        HttpResponse<File> response = request.downloadMonitor((b, fileName, bytesWritten, totalBytes) -> {
            int percent = (int) (20 * (Math.round((((double) bytesWritten / totalBytes) * 100) / 20)));
            if (percent != 0 && percent != lastPercentPosted.get()) {
                plugin.getLogger().info("# Downloading... " + percent + "% " + "(" + bytesWritten + "/" + totalBytes + " bytes)");
                lastPercentPosted.set(percent);
            }
        }).asFile(file.getPath());
        if (response.isSuccess()) {
            plugin.getLogger().log(Level.INFO, "Successfully downloaded {0} build: #{1}", new Object[] { JAR_NAME, version });
            // Replace the metric file with the new one
            cleanUp();
            Files.move(file.toPath(), metricsModuleFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            metricVersion = String.valueOf(version);
            hasDownloadedUpdate = true;
            return true;
        }
    } catch (UnirestException e) {
        plugin.getLogger().log(Level.WARNING, "Failed to fetch the latest jar file from the builds page. Perhaps GitHub is down? Response: {0}", e.getMessage());
    } catch (IOException e) {
        plugin.getLogger().log(Level.WARNING, "Failed to replace the old metric file with the new one. Please do this manually! Error: {0}", e.getMessage());
    }
    return false;
}
Also used : Plugin(org.bukkit.plugin.Plugin) HttpResponse(kong.unirest.HttpResponse) Files(java.nio.file.Files) URL(java.net.URL) IOException(java.io.IOException) GetRequest(kong.unirest.GetRequest) Unirest(kong.unirest.Unirest) File(java.io.File) CommonPatterns(io.github.bakedlibs.dough.common.CommonPatterns) InvocationTargetException(java.lang.reflect.InvocationTargetException) StandardCopyOption(java.nio.file.StandardCopyOption) Level(java.util.logging.Level) URLClassLoader(java.net.URLClassLoader) JsonNode(kong.unirest.JsonNode) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Slimefun(io.github.thebusybiscuit.slimefun4.implementation.Slimefun) UnirestException(kong.unirest.UnirestException) Method(java.lang.reflect.Method) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) GetRequest(kong.unirest.GetRequest) UnirestException(kong.unirest.UnirestException) IOException(java.io.IOException) File(java.io.File)

Example 2 with HttpResponse

use of kong.unirest.HttpResponse in project openbanking-aspsp by OpenBankingToolkit.

the class FilePaymentConsentsApiControllerIT method testCreateFilePaymentConsentsFile.

@Test
public void testCreateFilePaymentConsentsFile() throws UnirestException {
    // Given
    String fileConsentId = UUID.randomUUID().toString();
    springSecForTest.mockAuthCollector.mockAuthorities(OBRIRole.ROLE_PISP);
    setupMockTpp(tppRepository);
    String fileContent = utf8FileToString.apply("OBIEPaymentInitiation_3_0.json");
    FRFileConsent existingConsent = JMockData.mock(FRFileConsent.class);
    existingConsent.setStatus(ConsentStatusCode.AWAITINGUPLOAD);
    existingConsent.setId(fileConsentId);
    existingConsent.setFileContent(null);
    existingConsent.setPayments(Collections.emptyList());
    OBWriteFileConsent3 obWriteFileConsent3 = new OBWriteFileConsent3().data(new OBWriteFileConsent3Data().initiation(new OBWriteFile2DataInitiation().fileHash("kdjfklsdjflksjf").numberOfTransactions("3").controlSum(new BigDecimal("66.0")).fileType(PaymentFileType.UK_OBIE_PAYMENT_INITIATION_V3_0.getFileType())));
    existingConsent.setWriteFileConsent(toFRWriteFileConsent(obWriteFileConsent3));
    repository.save(existingConsent);
    // When
    HttpResponse response = Unirest.post("https://rs-store:" + port + "/open-banking/v3.1/pisp/file-payment-consents/" + fileConsentId + "/file").header(OBHeaders.X_FAPI_FINANCIAL_ID, rsConfiguration.financialId).header(OBHeaders.AUTHORIZATION, "token").header(OBHeaders.X_IDEMPOTENCY_KEY, UUID.randomUUID().toString()).header(OBHeaders.X_JWS_SIGNATURE, UUID.randomUUID().toString()).header(CONTENT_TYPE, "plain/xml").header(ACCEPT, "application/json").header("x-ob-client-id", MOCK_CLIENT_ID).body(fileContent).asObject(String.class);
    // Then
    log.debug("Response: {}", response);
    assertThat(response.getStatus()).isEqualTo(200);
    FRFileConsent consent = repository.findById(fileConsentId).get();
    assertThat(consent.getId()).isEqualTo(fileConsentId);
    assertThat(consent.getStatus().toOBExternalConsentStatus2Code()).isEqualTo(OBExternalConsentStatus2Code.AWAITINGAUTHORISATION);
    assertThat(consent.getFileContent()).isEqualTo(fileContent);
}
Also used : FRFileConsent(com.forgerock.openbanking.common.model.openbanking.persistence.payment.FRFileConsent) OBWriteFileConsent3(uk.org.openbanking.datamodel.payment.OBWriteFileConsent3) OBWriteFileConsent3Data(uk.org.openbanking.datamodel.payment.OBWriteFileConsent3Data) OBWriteFile2DataInitiation(uk.org.openbanking.datamodel.payment.OBWriteFile2DataInitiation) HttpResponse(kong.unirest.HttpResponse) BigDecimal(java.math.BigDecimal) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) SpringSecForTest(com.forgerock.openbanking.integration.test.support.SpringSecForTest) Test(org.junit.Test)

Example 3 with HttpResponse

use of kong.unirest.HttpResponse in project openbanking-aspsp by OpenBankingToolkit.

the class FilePaymentsApiControllerIT method testMissingConsentOnGetFileReportShouldReturnNotFound.

@Test
public void testMissingConsentOnGetFileReportShouldReturnNotFound() throws Exception {
    // Given
    springSecForTest.mockAuthCollector.mockAuthorities(OBRIRole.ROLE_PISP);
    // When
    HttpResponse response = Unirest.get("https://rs-store:" + port + "/open-banking/v3.1/pisp/file-payments/123/report-file").header(OBHeaders.X_FAPI_FINANCIAL_ID, rsConfiguration.financialId).header(OBHeaders.AUTHORIZATION, "token").header(OBHeaders.X_IDEMPOTENCY_KEY, "x-idempotency-key").header(OBHeaders.X_JWS_SIGNATURE, "x-jws-signature").header(OBHeaders.CONTENT_TYPE, "application/json; charset=utf-8").header("Accept", "application/json; charset=utf-8").asString();
    log.debug("Response: {}", response.getBody());
    // Then
    assertThat(response.getStatus()).isEqualTo(400);
}
Also used : HttpResponse(kong.unirest.HttpResponse) SpringSecForTest(com.forgerock.openbanking.integration.test.support.SpringSecForTest) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 4 with HttpResponse

use of kong.unirest.HttpResponse in project openbanking-aspsp by OpenBankingToolkit.

the class DomesticPaymentConsentsApiControllerIT method testCreateDomesticPaymentConsent_exists_idempotencyKeyExpired.

@Test
// This fails intermittently on code fresh - ignoring until more time available to investigate
@Ignore
public void testCreateDomesticPaymentConsent_exists_idempotencyKeyExpired() throws UnirestException {
    // Given
    final String idempotencyKey = UUID.randomUUID().toString();
    springSecForTest.mockAuthCollector.mockAuthorities(OBRIRole.ROLE_PISP);
    setupMockTpp(tppRepository);
    OBWriteDomesticConsent1 consentRequest = JMockData.mock(OBWriteDomesticConsent1.class);
    consentRequest.getData().getInitiation().getInstructedAmount().currency("GBP").amount("1.00");
    consentRequest.getData().getInitiation().getCreditorPostalAddress().country("GB").addressLine(Collections.singletonList("3 Queens Square"));
    consentRequest.getRisk().merchantCategoryCode("ABCD").getDeliveryAddress().addressLine(Collections.singletonList("3 Queens Square")).country("GP");
    consentRequest.getData().getAuthorisation().completionDateTime(null);
    OBWriteDomesticConsent4 consent4 = toOBWriteDomesticConsent4(consentRequest);
    FRDomesticConsent existingConsent = JMockData.mock(FRDomesticConsent.class);
    existingConsent.setId(UUID.randomUUID().toString());
    existingConsent.setStatus(ConsentStatusCode.AUTHORISED);
    existingConsent.setDomesticConsent(toFRWriteDomesticConsent(consent4));
    existingConsent.setIdempotencyKey(idempotencyKey);
    existingConsent = repository.save(existingConsent);
    // Created date will be set to now by annotation on initial creation so update it here to 25 hours in past to test idempotency expiry
    existingConsent.setCreated(DateTime.now().minusHours(25));
    repository.save(existingConsent);
    // When
    HttpResponse response = Unirest.post("https://rs-store:" + port + "/open-banking/v3.1/pisp/domestic-payment-consents/").header(OBHeaders.X_FAPI_FINANCIAL_ID, rsConfiguration.financialId).header(OBHeaders.AUTHORIZATION, "token").header(OBHeaders.X_IDEMPOTENCY_KEY, idempotencyKey).header(OBHeaders.X_JWS_SIGNATURE, "x-jws-signature").header("x-ob-client-id", MOCK_CLIENT_ID).header(OBHeaders.CONTENT_TYPE, "application/json; charset=utf-8").body(consentRequest).asObject(OBWriteDomesticConsentResponse1.class);
    // Then
    assertThat(response.getStatus()).isEqualTo(400);
}
Also used : FRDomesticConsent(com.forgerock.openbanking.common.model.openbanking.persistence.payment.FRDomesticConsent) OBWriteDomesticConsent1(uk.org.openbanking.datamodel.payment.OBWriteDomesticConsent1) HttpResponse(kong.unirest.HttpResponse) OBWriteDomesticConsentConverter.toOBWriteDomesticConsent4(uk.org.openbanking.datamodel.service.converter.payment.OBWriteDomesticConsentConverter.toOBWriteDomesticConsent4) OBWriteDomesticConsent4(uk.org.openbanking.datamodel.payment.OBWriteDomesticConsent4) Ignore(org.junit.Ignore) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) SpringSecForTest(com.forgerock.openbanking.integration.test.support.SpringSecForTest) Test(org.junit.Test)

Example 5 with HttpResponse

use of kong.unirest.HttpResponse in project openbanking-aspsp by OpenBankingToolkit.

the class CallbackUrlsApiControllerIT method createCallbackUrls_urlAlreadyExistsForTpp_conflict.

@Test
public void createCallbackUrls_urlAlreadyExistsForTpp_conflict() throws Exception {
    // Given
    // mockAuthentication(authenticator, OBRIRole.ROLE_PISP.name());
    String callbackId = UUID.randomUUID().toString();
    // Existing URL
    callbackUrlsRepository.save(newFRCallbackUrl(callbackId));
    OBCallbackUrl1 obCallbackUrl = new OBCallbackUrl1().data(new OBCallbackUrlData1().url(// Already exists
    "http://callback-" + callbackId).version(OBVersion.v3_0.getCanonicalVersion()));
    // When
    HttpResponse response = Unirest.post("https://rs-store:" + port + "/open-banking/" + OBVersion.v3_0.getCanonicalName() + "/callback-urls").header(OBHeaders.X_FAPI_FINANCIAL_ID, rsConfiguration.financialId).header(OBHeaders.AUTHORIZATION, "token").header("x-ob-client-id", clientId).header(OBHeaders.CONTENT_TYPE, "application/json; charset=utf-8").body(obCallbackUrl).asObject(String.class);
    // Then
    assertThat(response.getStatus()).isEqualTo(HttpStatus.CONFLICT.value());
    final Collection<FRCallbackUrl> byClientId = callbackUrlsRepository.findByTppId(tpp.getId());
    // Should still be just 1
    assertThat(byClientId.size()).isEqualTo(1);
}
Also used : OBCallbackUrlData1(uk.org.openbanking.datamodel.event.OBCallbackUrlData1) HttpResponse(kong.unirest.HttpResponse) FRCallbackUrl(com.forgerock.openbanking.common.model.openbanking.persistence.event.FRCallbackUrl) OBCallbackUrl1(uk.org.openbanking.datamodel.event.OBCallbackUrl1) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Aggregations

HttpResponse (kong.unirest.HttpResponse)38 Test (org.junit.Test)16 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)16 GetRequest (kong.unirest.GetRequest)9 SpringSecForTest (com.forgerock.openbanking.integration.test.support.SpringSecForTest)8 ConnectorsTest (com.seleniumtests.ConnectorsTest)6 IOException (java.io.IOException)6 JsonNode (kong.unirest.JsonNode)6 Test (org.testng.annotations.Test)6 UnirestException (kong.unirest.UnirestException)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 FRCallbackUrl (com.forgerock.openbanking.common.model.openbanking.persistence.event.FRCallbackUrl)4 File (java.io.File)3 List (java.util.List)3 JSONObject (kong.unirest.json.JSONObject)3 OBCallbackUrl1 (uk.org.openbanking.datamodel.event.OBCallbackUrl1)3 OBCallbackUrlData1 (uk.org.openbanking.datamodel.event.OBCallbackUrlData1)3 ClientConfig (com.adobe.target.edge.client.ClientConfig)2 FREventSubscription (com.forgerock.openbanking.common.model.openbanking.persistence.event.FREventSubscription)2 FRFileConsent (com.forgerock.openbanking.common.model.openbanking.persistence.payment.FRFileConsent)2