com.neovisionaries.i18n.CountryCode Java Examples

The following examples show how to use com.neovisionaries.i18n.CountryCode. 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: ProjectContextTest.java    From commercetools-sunrise-java with Apache License 2.0 6 votes vote down vote up
private static ProjectContext createProjectContext(final List<Locale> locales, final List<CountryCode> countries,
                                                   final List<CurrencyUnit> currencies) {
    return new ProjectContext() {
        @Override
        public List<Locale> locales() {
            return locales;
        }

        @Override
        public List<CountryCode> countries() {
            return countries;
        }

        @Override
        public List<CurrencyUnit> currencies() {
            return currencies;
        }
    };
}
 
Example #2
Source File: PriceReferenceResolverTest.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@Test
void resolveCustomTypeReference_WithNullIdOnCustomTypeReference_ShouldNotResolveCustomTypeReference() {
    final CustomFieldsDraft customFieldsDraft = mock(CustomFieldsDraft.class);
    final ResourceIdentifier<Type> typeReference = ResourceIdentifier.ofId(null);
    when(customFieldsDraft.getType()).thenReturn(typeReference);

    final PriceDraftBuilder priceBuilder = PriceDraftBuilder
        .of(MoneyImpl.of(BigDecimal.TEN, DefaultCurrencyUnits.EUR))
        .country(CountryCode.DE)
        .custom(customFieldsDraft);

    final PriceReferenceResolver priceReferenceResolver =
        new PriceReferenceResolver(syncOptions, typeService, channelService, customerGroupService);

    assertThat(priceReferenceResolver.resolveCustomTypeReference(priceBuilder).toCompletableFuture())
        .hasFailed()
        .hasFailedWithThrowableThat()
        .isExactlyInstanceOf(ReferenceResolutionException.class)
        .hasMessage(format("Failed to resolve custom type reference on PriceDraft"
            + " with country:'DE' and value: 'EUR 10'. Reason: %s", BLANK_ID_VALUE_ON_RESOURCE_IDENTIFIER));
}
 
Example #3
Source File: PriceReferenceResolverTest.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@Test
void resolveCustomTypeReference_WithEmptyIdOnCustomTypeReference_ShouldNotResolveCustomTypeReference() {
    final CustomFieldsDraft customFieldsDraft = CustomFieldsDraft.ofTypeIdAndJson("", new HashMap<>());
    final PriceDraftBuilder priceBuilder = PriceDraftBuilder
        .of(MoneyImpl.of(BigDecimal.TEN, DefaultCurrencyUnits.EUR))
        .country(CountryCode.DE)
        .custom(customFieldsDraft);

    final PriceReferenceResolver priceReferenceResolver =
        new PriceReferenceResolver(syncOptions, typeService, channelService, customerGroupService);

    assertThat(priceReferenceResolver.resolveCustomTypeReference(priceBuilder).toCompletableFuture())
        .hasFailed()
        .hasFailedWithThrowableThat()
        .isExactlyInstanceOf(ReferenceResolutionException.class)
        .hasMessage(format("Failed to resolve custom type reference on PriceDraft"
            + " with country:'DE' and value: 'EUR 10'. Reason: %s", BLANK_ID_VALUE_ON_RESOURCE_IDENTIFIER));
}
 
Example #4
Source File: PriceReferenceResolverTest.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@Test
void resolveCustomTypeReference_WithExceptionOnCustomTypeFetch_ShouldNotResolveReferences() {
    final String customTypeKey = "customTypeKey";
    final CustomFieldsDraft customFieldsDraft = CustomFieldsDraft.ofTypeIdAndJson(customTypeKey, new HashMap<>());
    final PriceDraftBuilder priceBuilder = PriceDraftBuilder
        .of(MoneyImpl.of(BigDecimal.TEN, DefaultCurrencyUnits.EUR))
        .country(CountryCode.DE)
        .custom(customFieldsDraft);

    final CompletableFuture<Optional<String>> futureThrowingSphereException = new CompletableFuture<>();
    futureThrowingSphereException.completeExceptionally(new SphereException("CTP error on fetch"));
    when(typeService.fetchCachedTypeId(anyString())).thenReturn(futureThrowingSphereException);

    final PriceReferenceResolver priceReferenceResolver =
        new PriceReferenceResolver(syncOptions, typeService, channelService, customerGroupService);

    assertThat(priceReferenceResolver.resolveCustomTypeReference(priceBuilder).toCompletableFuture())
        .hasFailed()
        .hasFailedWithThrowableThat()
        .isExactlyInstanceOf(SphereException.class)
        .hasMessageContaining("CTP error on fetch");
}
 
Example #5
Source File: CountryEndpoint.java    From java-resource-server with Apache License 2.0 6 votes vote down vote up
private Response getResource(String code)
{
    // Look up a CountryCode instance that has the ISO 3166-1 code.
    CountryCode cc = lookup(code);

    Map<String, Object> data = new LinkedHashMap<String, Object>();

    if (cc != null)
    {
        // Pack the data into a Map.
        data.put("name",     cc.getName());
        data.put("alpha2",   cc.getAlpha2());
        data.put("alpha3",   cc.getAlpha3());
        data.put("numeric",  cc.getNumeric());
        data.put("currency", cc.getCurrency());
    }

    // Convert the data to JSON.
    String json = GSON.toJson(data);

    // Create a response of "200 OK".
    return Response.ok(json, "application/json;charset=UTF-8").build();
}
 
Example #6
Source File: DefaultCheckoutAddressFormData.java    From commercetools-sunrise-java with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public Address billingAddress() {
    if (billingAddressDifferentToBillingAddress) {
        final CountryCode country = CountryCode.getByCode(countryBilling);
        return AddressBuilder.of(country)
                .title(titleBilling)
                .firstName(firstNameBilling)
                .lastName(lastNameBilling)
                .streetName(streetNameBilling)
                .additionalStreetInfo(additionalStreetInfoBilling)
                .city(cityBilling)
                .postalCode(postalCodeBilling)
                .region(regionBilling)
                .phone(phoneBilling)
                .email(emailBilling)
                .build();
    } else {
        return null;
    }
}
 
Example #7
Source File: PriceReferenceResolverTest.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@Test
void
    resolveSupplyChannelReference_WithNonExistingChannelAndEnsureChannel_ShouldResolveSupplyChannelReference() {
    final ProductSyncOptions optionsWithEnsureChannels = ProductSyncOptionsBuilder.of(mock(SphereClient.class))
                                                                                  .ensurePriceChannels(true)
                                                                                  .build();
    when(channelService.fetchCachedChannelId(anyString()))
        .thenReturn(CompletableFuture.completedFuture(Optional.empty()));

    final PriceDraftBuilder priceBuilder = PriceDraftBuilder
        .of(MoneyImpl.of(BigDecimal.TEN, DefaultCurrencyUnits.EUR))
        .country(CountryCode.DE)
        .channel(ResourceIdentifier.ofId("channelKey"));

    final PriceReferenceResolver priceReferenceResolver =
        new PriceReferenceResolver(optionsWithEnsureChannels, typeService, channelService, customerGroupService);

    priceReferenceResolver.resolveChannelReference(priceBuilder)
                          .thenApply(PriceDraftBuilder::build)
                          .thenAccept(resolvedDraft -> {
                              assertThat(resolvedDraft.getChannel()).isNotNull();
                              assertThat(resolvedDraft.getChannel().getId()).isEqualTo(CHANNEL_ID);
                          })
                          .toCompletableFuture()
                          .join();
}
 
Example #8
Source File: PriceReferenceResolverTest.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@Test
void resolveReferences_WithNoReferences_ShouldNotResolveReferences() {
    final PriceDraft priceDraft = PriceDraftBuilder.of(MoneyImpl.of(BigDecimal.TEN, DefaultCurrencyUnits.EUR))
                                                   .country(CountryCode.DE)
                                                   .build();

    final PriceReferenceResolver priceReferenceResolver =
        new PriceReferenceResolver(syncOptions, typeService, channelService, customerGroupService);

    final PriceDraft referencesResolvedDraft = priceReferenceResolver.resolveReferences(priceDraft)
                                                                     .toCompletableFuture().join();

    assertThat(referencesResolvedDraft.getCustom()).isNull();
    assertThat(referencesResolvedDraft.getChannel()).isNull();
    assertThat(referencesResolvedDraft.getCustomerGroup()).isNull();
}
 
Example #9
Source File: PriceFixtures.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static Price getPrice(@Nonnull final BigDecimal value,
                              @Nonnull final CurrencyUnit currencyUnits,
                              @Nullable final CountryCode countryCode,
                              @Nullable final String customerGroupId,
                              @Nullable final ZonedDateTime validFrom,
                              @Nullable final ZonedDateTime validUntil,
                              @Nullable final String channelId,
                              @Nullable final CustomFields customFields) {

    return PriceBuilder.of(Price.of(value, currencyUnits))
                       .id(UUID.randomUUID().toString())
                       .customerGroup(ofNullable(customerGroupId).map(CustomerGroup::referenceOfId).orElse(null))
                       .country(countryCode)
                       .validFrom(validFrom)
                       .validUntil(validUntil)
                       .channel(ofNullable(channelId).map(Channel::referenceOfId).orElse(null))
                       .custom(customFields)
                       .build();
}
 
Example #10
Source File: PriceDraftFixtures.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static PriceDraft getPriceDraft(@Nonnull final BigDecimal value,
                                       @Nonnull final CurrencyUnit currencyUnits,
                                       @Nullable final CountryCode countryCode,
                                       @Nullable final String customerGroupId,
                                       @Nullable final ZonedDateTime validFrom,
                                       @Nullable final ZonedDateTime validUntil,
                                       @Nullable final String channelId,
                                       @Nullable final CustomFieldsDraft customFieldsDraft) {
    return PriceDraftBuilder.of(Price.of(value, currencyUnits))
                            .country(countryCode)
                            .customerGroup(
                                ofNullable(customerGroupId).map(CustomerGroup::referenceOfId).orElse(null))
                            .validFrom(validFrom)
                            .validUntil(validUntil)
                            .channel(ofNullable(channelId).map(ResourceIdentifier::<Channel>ofId)
                                                          .orElse(null))
                            .custom(customFieldsDraft)
                            .build();
}
 
Example #11
Source File: DefaultCheckoutAddressFormData.java    From commercetools-sunrise-java with Apache License 2.0 6 votes vote down vote up
@Override
public Address shippingAddress() {
    final CountryCode country = CountryCode.getByCode(countryShipping);
    return AddressBuilder.of(country)
            .title(titleShipping)
            .firstName(firstNameShipping)
            .lastName(lastNameShipping)
            .streetName(streetNameShipping)
            .additionalStreetInfo(additionalStreetInfoShipping)
            .city(cityShipping)
            .postalCode(postalCodeShipping)
            .region(regionShipping)
            .phone(phoneShipping)
            .email(emailShipping)
            .build();
}
 
Example #12
Source File: SunriseAddAddressController.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
protected SunriseAddAddressController(final ContentRenderer contentRenderer, final FormFactory formFactory,
                                      final AddressFormData formData, final CustomerFinder customerFinder,
                                      final AddAddressControllerAction controllerAction,
                                      final AddAddressPageContentFactory pageContentFactory,
                                      final CountryCode country) {
    super(contentRenderer, formFactory);
    this.formData = formData;
    this.customerFinder = customerFinder;
    this.controllerAction = controllerAction;
    this.pageContentFactory = pageContentFactory;
    this.country = country;
}
 
Example #13
Source File: LocalizationModule.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    bind(Locale.class)
            .toProvider(LocaleFromUrlProvider.class)
            .in(RequestScoped.class);

    bind(CountryCode.class)
            .toProvider(CountryFromSessionProvider.class)
            .in(RequestScoped.class);

    bind(CurrencyUnit.class)
            .toProvider(CurrencyFromCountryProvider.class)
            .in(RequestScoped.class);
}
 
Example #14
Source File: PriceReferenceResolverTest.java    From commercetools-sync-java with Apache License 2.0 5 votes vote down vote up
@Test
void
    resolveSupplyChannelReference_WithNonExistingChannelAndNotEnsureChannel_ShouldNotResolveChannelReference() {
    when(channelService.fetchCachedChannelId(anyString()))
        .thenReturn(CompletableFuture.completedFuture(Optional.empty()));

    final PriceDraftBuilder priceBuilder = PriceDraftBuilder
        .of(MoneyImpl.of(BigDecimal.TEN, DefaultCurrencyUnits.EUR))
        .country(CountryCode.DE)
        .channel(ResourceIdentifier.ofId("channelKey"));

    final PriceReferenceResolver priceReferenceResolver =
        new PriceReferenceResolver(syncOptions, typeService, channelService, customerGroupService);


    priceReferenceResolver.resolveChannelReference(priceBuilder)
                          .exceptionally(exception -> {
                              assertThat(exception).isExactlyInstanceOf(CompletionException.class);
                              assertThat(exception.getCause())
                                  .isExactlyInstanceOf(ReferenceResolutionException.class);
                              assertThat(exception.getCause().getCause())
                                  .isExactlyInstanceOf(ReferenceResolutionException.class);
                              assertThat(exception.getCause().getCause().getMessage())
                                  .isEqualTo("Channel with key 'channelKey' does not exist.");
                              return null;
                          })
                          .toCompletableFuture()
                          .join();
}
 
Example #15
Source File: AddAddressController.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Inject
public AddAddressController(final ContentRenderer contentRenderer,
                            final FormFactory formFactory,
                            final AddressFormData formData,
                            final CustomerFinder customerFinder,
                            final AddAddressControllerAction controllerAction,
                            final AddAddressPageContentFactory pageContentFactory,
                            final CountryCode country,
                            final AuthenticationReverseRouter authenticationReverseRouter,
                            final AddressBookReverseRouter addressBookReverseRouter) {
    super(contentRenderer, formFactory, formData, customerFinder, controllerAction, pageContentFactory, country);
    this.authenticationReverseRouter = authenticationReverseRouter;
    this.addressBookReverseRouter = addressBookReverseRouter;
}
 
Example #16
Source File: CartFieldsUpdaterControllerComponentTest.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Test
public void updatesCartWithCountryIfADifferentCountryDefined() throws Exception {
    final Cart cart = mock(Cart.class);
    when(cart.getCountry()).thenReturn(CountryCode.US);
    final CartUpdateCommand cartUpdateCommand = component().buildRequest(cart, null);
    assertThat(cartUpdateCommand.getUpdateActions())
            .extracting(action -> (UpdateAction<Cart>) action)
            .containsOnlyOnce(SetCountry.of(CURRENT_COUNTRY))
            .containsOnlyOnce(SetShippingAddress.of(Address.of(CURRENT_COUNTRY)));
}
 
Example #17
Source File: PriceCompositeIdTest.java    From commercetools-sync-java with Apache License 2.0 5 votes vote down vote up
private static void assertCompositeId(@Nonnull final String currencyCode,
                                      @Nullable final CountryCode countryCode,
                                      @Nullable final String customerGroupId,
                                      @Nullable final String channelId,
                                      @Nullable final ZonedDateTime validFrom,
                                      @Nullable final ZonedDateTime validUntil,
                                      @Nonnull final PriceCompositeId priceCompositeId) {

    assertEquals(currencyCode, priceCompositeId.getCurrencyCode());
    assertEquals(countryCode, priceCompositeId.getCountryCode());
    assertEquals(customerGroupId, priceCompositeId.getCustomerGroupId());
    assertEquals(channelId, priceCompositeId.getChannelId());
    assertEquals(validFrom, priceCompositeId.getValidFrom());
    assertEquals(validUntil, priceCompositeId.getValidUntil());
}
 
Example #18
Source File: DefaultAddressFormData.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
public String validate() {
    final CountryCode country = CountryCode.getByCode(this.country);
    if (country == null || country.equals(CountryCode.UNDEFINED)) {
        return "Invalid country"; // TODO use i18n version
    }
    return null;
}
 
Example #19
Source File: CountryEndpoint.java    From java-resource-server with Apache License 2.0 5 votes vote down vote up
/**
 * Look up a {@link CountryCode} instance from an ISO 3166-1 code.
 *
 * @param code
 *         ISO 3166-1 code (alpha-2, alpha-3, or numeric).
 *
 * @return
 *         A {@link CountryCode} instance that corresponds to the
 *         given code. If the given code is not valid, {@code null}
 *         is returned.
 */
private CountryCode lookup(String code)
{
    if (code == null)
    {
        // Not found.
        return null;
    }

    // Interpret the code as an ISO 3166-1 alpha-2 or alpha-3 code.
    CountryCode cc = CountryCode.getByCodeIgnoreCase(code);

    if (cc != null)
    {
        // Found.
        return cc;
    }

    try
    {
        // Interpret the code as an ISO 3166-1 numeric code.
        return CountryCode.getByCode(Integer.parseInt(code));
    }
    catch (NumberFormatException e)
    {
        // Not found.
        return null;
    }
}
 
Example #20
Source File: DefaultAddressFormData.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
public Address address() {
    final CountryCode countryCode = CountryCode.getByCode(country);
    return AddressBuilder.of(countryCode)
            .title(title)
            .firstName(firstName)
            .lastName(lastName)
            .streetName(streetName)
            .additionalStreetInfo(additionalStreetInfo)
            .city(city)
            .postalCode(postalCode)
            .region(region)
            .build();
}
 
Example #21
Source File: Module.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Provides
@RequestScoped
public PriceSelection providePriceSelection(final CurrencyUnit currency, final CountryCode country,
                                            final CustomerInSession customerInSession) {
    return PriceSelection.of(currency)
            .withPriceCountry(country)
            .withPriceCustomerGroupId(customerInSession.findCustomerGroupId().orElse(null));
}
 
Example #22
Source File: DefaultCartCreator.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Inject
protected DefaultCartCreator(final SphereClient sphereClient, final HookRunner hookRunner,
                             final CountryCode country, final CurrencyUnit currency,
                             final CustomerInSession customerInSession) {
    super(sphereClient, hookRunner);
    this.country = country;
    this.currency = currency;
    this.customerInSession = customerInSession;
}
 
Example #23
Source File: CheckoutAddressFormSettingsViewModelFactory.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Inject
public CheckoutAddressFormSettingsViewModelFactory(final CountryCode country, final CountryFormFieldViewModelFactory countryFormFieldViewModelFactory,
                                                   final TitleFormFieldViewModelFactory titleFormFieldViewModelFactory) {
    this.country = country;
    this.countryFormFieldViewModelFactory = countryFormFieldViewModelFactory;
    this.titleFormFieldViewModelFactory = titleFormFieldViewModelFactory;
}
 
Example #24
Source File: ProjectContextTest.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createsInstanceWithStaticConstructor() throws Exception {
    final Map<String, Object> map = new HashMap<>();
    map.put("languages", asList("de", "en-US"));
    map.put("countries", asList("DE", "US"));
    map.put("currencies", asList("EUR", "USD"));
    final Configuration configuration = new Configuration(singletonMap("foo", map));

    final Project dummyProject = mock(Project.class);
    final ProjectContext projectContext = ProjectContext.of(configuration, "foo", dummyProject);
    assertThat(projectContext.locales()).containsExactly(Locale.GERMAN, Locale.US);
    assertThat(projectContext.countries()).containsExactly(CountryCode.DE, CountryCode.US);
    assertThat(projectContext.currencies()).containsExactly(EUR, USD);
}
 
Example #25
Source File: DefaultCheckoutAddressFormData.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
public String validate() {
    final CountryCode shippingCountry = CountryCode.getByCode(countryShipping);
    if (shippingCountry == null || shippingCountry.equals(CountryCode.UNDEFINED)) {
        return "Invalid shipping country"; // TODO use i18n version
    }
    if (billingAddressDifferentToBillingAddress) {
        final CountryCode billingCountry = CountryCode.getByCode(countryBilling);
        if (billingCountry == null || billingCountry.equals(CountryCode.UNDEFINED)) {
            return "Invalid billing country"; // TODO use i18n version
        }
    }
    return null;
}
 
Example #26
Source File: ISO3166Utils.java    From CLIFF with Apache License 2.0 5 votes vote down vote up
public static String alpha3toAlpha2(String alpha3) throws UnknownCountryException {
    if(alpha3.length()==0) return " ";
    CountryCode countryCode = CountryCode.getByCode(alpha3);
    if(null==countryCode){
        throw new UnknownCountryException("Can't find country "+alpha3, alpha3);
    }
    return countryCode.getAlpha2();
}
 
Example #27
Source File: LocalizationSelectorViewModelFactory.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Inject
public LocalizationSelectorViewModelFactory(final Locale locale, final CountryCode country, final ProjectContext projectContext,
                                            final CountryFormSelectableOptionViewModelFactory countryFormSelectableOptionViewModelFactory,
                                            final LanguageFormSelectableOptionViewModelFactory languageFormSelectableOptionViewModelFactory) {
    this.locale = locale;
    this.country = country;
    this.projectContext = projectContext;
    this.countryFormSelectableOptionViewModelFactory = countryFormSelectableOptionViewModelFactory;
    this.languageFormSelectableOptionViewModelFactory = languageFormSelectableOptionViewModelFactory;
}
 
Example #28
Source File: LocalizationSelectorViewModelFactory.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
protected void fillCountry(final LocalizationSelectorViewModel viewModel) {
    final List<CountryFormSelectableOptionViewModel> options = new ArrayList<>();
    final List<CountryCode> countries = projectContext.countries();
    if (countries.size() > 1) {
        countries.forEach(country ->
                options.add(countryFormSelectableOptionViewModelFactory.create(country, this.country)));
    }
    viewModel.setCountry(options);
}
 
Example #29
Source File: PriceCompositeId.java    From commercetools-sync-java with Apache License 2.0 5 votes vote down vote up
private PriceCompositeId(@Nonnull final String currencyCode,
                         @Nullable final CountryCode countryCode,
                         @Nullable final String channelId,
                         @Nullable final String customerGroupId,
                         @Nullable final ZonedDateTime validFrom,
                         @Nullable final ZonedDateTime validUntil) {
    this.currencyCode = currencyCode;
    this.countryCode = countryCode;
    this.channelId = channelId;
    this.customerGroupId = customerGroupId;
    this.validFrom = validFrom;
    this.validUntil = validUntil;
}
 
Example #30
Source File: CountryFormSelectableOptionViewModelFactory.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
protected void fillLabel(final CountryFormSelectableOptionViewModel viewModel, final CountryCode option, @Nullable final CountryCode selectedValue) {
    viewModel.setLabel(option.toLocale().getDisplayCountry(locale));
}