method2testcases
stringlengths
118
6.63k
### Question: StripeJsonUtils { @Nullable static Map<String, String> jsonObjectToStringMap(@Nullable JSONObject jsonObject) { if (jsonObject == null) { return null; } Map<String, String> map = new HashMap<>(); Iterator<String> keyIterator = jsonObject.keys(); while (keyIterator.hasNext()) { String key = keyIterator.nex...
### Question: ViewUtils { static boolean isCvcMaximalLength( @NonNull @Card.CardBrand String cardBrand, @Nullable String cvcText) { if (cvcText == null) { return false; } if (Card.AMERICAN_EXPRESS.equals(cardBrand)) { return cvcText.trim().length() == CVC_LENGTH_AMERICAN_EXPRESS; } else { return cvcText.trim().length()...
### Question: ViewUtils { static boolean isColorDark(@ColorInt int color){ double luminescence = 0.299* Color.red(color) + 0.587*Color.green(color) + 0.114* Color.blue(color); double luminescencePercentage = luminescence / 255; return luminescencePercentage <= 0.5; } }### Answer: @Test public void isColorDark_forExa...
### Question: PaymentUtils { static String formatPriceStringUsingFree(long amount, @NonNull Currency currency, String free) { if (amount == 0) { return free; } NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); DecimalFormatSymbols decimalFormatSymbols = ((java.text.DecimalFormat) currencyFormat).getDeci...
### Question: PaymentUtils { static String formatPriceString(double amount, @NonNull Currency currency) { double majorUnitAmount = amount / Math.pow(10, currency.getDefaultFractionDigits()); NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); DecimalFormatSymbols decimalFormatSymbols = ((java.text.Decimal...
### Question: ShippingInfoWidget extends LinearLayout { public void setOptionalFields(@Nullable List<String> optionalAddressFields) { if (optionalAddressFields != null) { mOptionalShippingInfoFields = optionalAddressFields; } else { mOptionalShippingInfoFields = new ArrayList<>(); } renderLabels(); renderCountrySpecifi...
### Question: ShippingInfoWidget extends LinearLayout { public void setHiddenFields(@Nullable List<String> hiddenAddressFields) { if (hiddenAddressFields != null) { mHiddenShippingInfoFields = hiddenAddressFields; } else { mHiddenShippingInfoFields = new ArrayList<>(); } renderLabels(); renderCountrySpecificLabels(mCou...
### Question: ShippingInfoWidget extends LinearLayout { public ShippingInformation getShippingInformation() { if (!validateAllFields()) { return null; } Address address = new Address.Builder() .setCity(mCityEditText.getText().toString()) .setCountry(mCountryAutoCompleteTextView.getSelectedCountryCode()) .setLine1(mAddr...
### Question: ShippingInfoWidget extends LinearLayout { public void populateShippingInfo(@Nullable ShippingInformation shippingInformation) { if (shippingInformation == null) { return; } Address address = shippingInformation.getAddress(); if (address != null) { mCityEditText.setText(address.getCity()); if (address.getC...
### Question: CountryAutoCompleteTextView extends FrameLayout { String getSelectedCountryCode() { return mCountrySelected; } CountryAutoCompleteTextView(Context context); CountryAutoCompleteTextView(Context context, AttributeSet attrs); CountryAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr...
### Question: CountryUtils { static boolean doesCountryUsePostalCode(@NonNull String countryCode) { return !NO_POSTAL_CODE_COUNTRIES_SET.contains(countryCode); } }### Answer: @Test public void postalCodeCountryTest() { assertTrue(CountryUtils.doesCountryUsePostalCode("US")); assertTrue(CountryUtils.doesCountryUsePos...
### Question: CountryUtils { static boolean isUSZipCodeValid(@NonNull String zipCode) { return Pattern.matches("^[0-9]{5}(?:-[0-9]{4})?$", zipCode); } }### Answer: @Test public void usZipCodeTest() { assertTrue(CountryUtils.isUSZipCodeValid("94107")); assertTrue(CountryUtils.isUSZipCodeValid("94107-1234")); assertFa...
### Question: CountryUtils { static boolean isCanadianPostalCodeValid(@NonNull String postalCode) { return Pattern.matches("^(?!.*[DFIOQU])[A-VXY][0-9][A-Z] ?[0-9][A-Z][0-9]$", postalCode); } }### Answer: @Test public void canadianPostalCodeTest() { assertTrue(CountryUtils.isCanadianPostalCodeValid("K1A 0B1")); asse...
### Question: CountryUtils { static boolean isUKPostcodeValid(@NonNull String postcode) { return Pattern.matches("^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$", postcode); } }### Answer: @Test public void ukPostalCodeTest() { assertTrue(CountryUtils.isUKPostcodeValid("L1 8JQ")); assertTrue(CountryUtils.isUKP...
### Question: CardInputWidget extends LinearLayout { public void setCardInputListener(@Nullable CardInputListener listener) { mCardInputListener = listener; } CardInputWidget(Context context); CardInputWidget(Context context, AttributeSet attrs); CardInputWidget(Context context, AttributeSet attrs, int defStyleAttr);...
### Question: CardInputWidget extends LinearLayout { @NonNull @VisibleForTesting PlacementParameters getPlacementParameters() { return mPlacementParameters; } CardInputWidget(Context context); CardInputWidget(Context context, AttributeSet attrs); CardInputWidget(Context context, AttributeSet attrs, int defStyleAttr);...
### Question: CardInputWidget extends LinearLayout { @VisibleForTesting @Nullable StripeEditText getFocusRequestOnTouch(int touchX) { int frameStart = mFrameLayout.getLeft(); if (mCardNumberIsViewed) { if (touchX < frameStart + mPlacementParameters.cardWidth) { return null; } else if (touchX < mPlacementParameters.card...
### Question: CardInputWidget extends LinearLayout { public void setCardNumber(String cardNumber) { mCardNumberEditText.setText(cardNumber); setCardNumberIsViewed(!mCardNumberEditText.isCardNumberValid()); } CardInputWidget(Context context); CardInputWidget(Context context, AttributeSet attrs); CardInputWidget(Contex...
### Question: StripeJsonUtils { @Nullable static JSONObject stringHashToJsonObject(@Nullable Map<String, String> stringStringMap) { if (stringStringMap == null) { return null; } JSONObject jsonObject = new JSONObject(); for (String key : stringStringMap.keySet()) { try { jsonObject.put(key, stringStringMap.get(key)); }...
### Question: Customer extends StripeJsonModel { @Nullable public static Customer fromString(String jsonString) { if (jsonString == null) { return null; } try { return fromJson(new JSONObject(jsonString)); } catch (JSONException ignored) { return null; } } private Customer(); String getId(); String getDefaultSource();...
### Question: CardInputWidget extends LinearLayout { public void setExpiryDate( @IntRange(from = 1, to = 12) int month, @IntRange(from = 0, to = 9999) int year) { mExpiryDateEditText.setText(DateUtils.createDateStringFromIntegerInput(month, year)); } CardInputWidget(Context context); CardInputWidget(Context context, A...
### Question: CardInputWidget extends LinearLayout { public void setCvcCode(String cvcCode) { mCvcNumberEditText.setText(cvcCode); } CardInputWidget(Context context); CardInputWidget(Context context, AttributeSet attrs); CardInputWidget(Context context, AttributeSet attrs, int defStyleAttr); @Nullable Card getCard();...
### Question: CardInputWidget extends LinearLayout { @VisibleForTesting static boolean shouldIconShowBrand( @NonNull @Card.CardBrand String brand, boolean cvcHasFocus, @Nullable String cvcText) { if (!cvcHasFocus) { return true; } return ViewUtils.isCvcMaximalLength(brand, cvcText); } CardInputWidget(Context context); ...
### Question: Address extends StripeJsonModel implements Parcelable { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); putStringIfNotNull(jsonObject, FIELD_CITY, mCity); putStringIfNotNull(jsonObject, FIELD_COUNTRY, mCountry); putStringIfNotNull(jsonObject, FIELD_LINE_1, mLine1)...
### Question: StripeApiHandler { @VisibleForTesting static String getApiUrl() { return String.format(Locale.ENGLISH, "%s/v1/%s", LIVE_API_BASE, TOKENS); } }### Answer: @Test public void testGetApiUrl() { String tokensApi = StripeApiHandler.getApiUrl(); assertEquals("https: }
### Question: StripeApiHandler { @VisibleForTesting static String getSourcesUrl() { return String.format(Locale.ENGLISH, "%s/v1/%s", LIVE_API_BASE, SOURCES); } }### Answer: @Test public void testGetSourcesUrl() { String sourcesUrl = StripeApiHandler.getSourcesUrl(); assertEquals("https: }
### Question: StripeApiHandler { @VisibleForTesting static String getRetrieveSourceApiUrl(@NonNull String sourceId) { return String.format(Locale.ENGLISH, "%s/%s", getSourcesUrl(), sourceId); } }### Answer: @Test public void testGetRetrieveSourceUrl() { String sourceUrlWithId = StripeApiHandler.getRetrieveSourceApiU...
### Question: StripeApiHandler { @VisibleForTesting static String getRetrieveTokenApiUrl(@NonNull String tokenId) { return String.format("%s/%s", getApiUrl(), tokenId); } }### Answer: @Test public void testGetRequestTokenApiUrl() { String tokenId = "tok_sample"; String requestApi = StripeApiHandler.getRetrieveTokenA...
### Question: StripeApiHandler { @VisibleForTesting static String getRetrieveCustomerUrl(@NonNull String customerId) { return String.format(Locale.ENGLISH, "%s/%s", getCustomersUrl(), customerId); } }### Answer: @Test public void testGetRetrieveCustomerUrl() { String customerId = "cus_123abc"; String customerRequest...
### Question: StripeApiHandler { @VisibleForTesting static String getAddCustomerSourceUrl(@NonNull String customerId) { return String.format(Locale.ENGLISH, "%s/%s", getRetrieveCustomerUrl(customerId), SOURCES); } }### Answer: @Test public void testGetAddCustomerSourceUrl() { String customerId = "cus_123abc"; String...
### Question: Address extends StripeJsonModel implements Parcelable { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_CITY, mCity); hashMap.put(FIELD_COUNTRY, mCountry); hashMap.put(FIELD_LINE_1, mLine1); hashMap.put(FIELD_LINE_2, mLine2); hashMap...
### Question: StripeApiHandler { static String createQuery(Map<String, Object> params) throws UnsupportedEncodingException, InvalidRequestException { StringBuilder queryStringBuffer = new StringBuilder(); List<Parameter> flatParams = flattenParams(params); Iterator<Parameter> it = flatParams.iterator(); while (it.hasNe...
### Question: EphemeralKeyManager { static boolean shouldRefreshKey( @Nullable EphemeralKey key, long bufferInSeconds, @Nullable Calendar proxyCalendar) { if (key == null) { return true; } Calendar now = proxyCalendar == null ? Calendar.getInstance() : proxyCalendar; long nowInSeconds = TimeUnit.MILLISECONDS.toSeconds(...
### Question: SourceRedirect extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); putStringIfNotNull(jsonObject, FIELD_RETURN_URL, mReturnUrl); putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); putStringIfNotNull(jsonObject, FIELD_URL, mUrl); return js...
### Question: EphemeralKeyManager { @Nullable @VisibleForTesting EphemeralKey getEphemeralKey() { return mEphemeralKey; } EphemeralKeyManager( @NonNull EphemeralKeyProvider ephemeralKeyProvider, @NonNull KeyManagerListener keyManagerListener, long timeBufferInSeconds, @Nu...
### Question: EphemeralKeyManager { void retrieveEphemeralKey(@Nullable String actionString, Map<String, Object> arguments) { if (shouldRefreshKey( mEphemeralKey, mTimeBufferInSeconds, mOverrideCalendar)) { mEphemeralKeyProvider.createEphemeralKey( StripeApiHandler.API_VERSION, new ClientKeyUpdateListener(this, actionS...
### Question: Stripe { public void setDefaultPublishableKey(@NonNull @Size(min = 1) String publishableKey) { validateKey(publishableKey); mDefaultPublishableKey = publishableKey; } Stripe(@NonNull Context context); Stripe(@NonNull Context context, String publishableKey); void createBankAccountToken( @NonNu...
### Question: SourceRedirect extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_RETURN_URL, mReturnUrl); hashMap.put(FIELD_STATUS, mStatus); hashMap.put(FIELD_URL, mUrl); removeNullAndEmptyParams(hashMap); return hashMap; } ...
### Question: Stripe { public Token createBankAccountTokenSynchronous(final BankAccount bankAccount) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return createBankAccountTokenSynchronous(bankAccount, mDefaultPublishableKey); } Stripe(@NonNull Context con...
### Question: StripeJsonModel { @Override public int hashCode() { return this.toString().hashCode(); } @NonNull abstract Map<String, Object> toMap(); @NonNull abstract JSONObject toJson(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer: @Test public void hashC...
### Question: PaymentConfiguration { @NonNull public static PaymentConfiguration getInstance() { if (mInstance == null) { throw new IllegalStateException( "Attempted to get instance of PaymentConfiguration without initialization."); } return mInstance; } private PaymentConfiguration(@NonNull String publishableKey); @N...
### Question: StripeTextUtils { static boolean hasAnyPrefix(String number, String... prefixes) { if (number == null) { return false; } for (String prefix : prefixes) { if (number.startsWith(prefix)) { return true; } } return false; } @Nullable static String nullIfBlank(@Nullable String value); static boolean isBlank(@...
### Question: StripeJsonModel { static void putStripeJsonModelListIfNotNull( @NonNull Map<String, Object> upperLevelMap, @NonNull @Size(min = 1) String key, @Nullable List<? extends StripeJsonModel> jsonModelList) { if (jsonModelList == null) { return; } List<Map<String, Object>> mapList = new ArrayList<>(); for (int i...
### Question: StripeTextUtils { @Nullable public static String nullIfBlank(@Nullable String value) { if (isBlank(value)) { return null; } return value; } @Nullable static String nullIfBlank(@Nullable String value); static boolean isBlank(@Nullable String value); @Nullable static String removeSpacesAndHyphens(@Nullable...
### Question: StripeTextUtils { public static boolean isBlank(@Nullable String value) { return value == null || value.trim().length() == 0; } @Nullable static String nullIfBlank(@Nullable String value); static boolean isBlank(@Nullable String value); @Nullable static String removeSpacesAndHyphens(@Nullable String card...
### Question: SourceOwner extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); JSONObject jsonAddressObject = mAddress == null ? null : mAddress.toJson(); JSONObject jsonVerifiedAddressObject = mVerifiedAddress == null ? null : mVerifiedAddress.toJson(); tr...
### Question: StripeTextUtils { @Nullable public static String removeSpacesAndHyphens(@Nullable String cardNumberWithSpaces) { if (isBlank(cardNumberWithSpaces)) { return null; } return cardNumberWithSpaces.replaceAll("\\s|-", ""); } @Nullable static String nullIfBlank(@Nullable String value); static boolean isBlank(@...
### Question: StripeTextUtils { @Nullable static String shaHashInput(@Nullable String toHash) { if (StripeTextUtils.isBlank(toHash)) { return null; } String hash; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); byte[] bytes = toHash.getBytes("UTF-8"); digest.update(bytes, 0, bytes.length); bytes = dige...
### Question: StripeNetworkUtils { @SuppressWarnings("unchecked") public static void removeNullAndEmptyParams(@NonNull Map<String, Object> mapToEdit) { for (String key : new HashSet<>(mapToEdit.keySet())) { if (mapToEdit.get(key) == null) { mapToEdit.remove(key); } if (mapToEdit.get(key) instanceof CharSequence) { Char...
### Question: StripeNetworkUtils { @SuppressWarnings("HardwareIds") static void addUidParams( @Nullable UidProvider provider, @NonNull Context context, @NonNull Map<String, Object> params) { String guid = provider == null ? Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID) : provider.g...
### Question: AndroidPayConfiguration { @Nullable public PaymentMethodTokenizationParameters getPaymentMethodTokenizationParameters() { if (TextUtils.isEmpty(mPublicApiKey)) { return null; } return PaymentMethodTokenizationParameters.newBuilder() .setPaymentMethodTokenizationType(PAYMENT_GATEWAY) .addParameter("gateway...
### Question: AndroidPayConfiguration { @NonNull public static FullWalletRequest generateFullWalletRequest( @NonNull String googleTransactionId, @NonNull Cart cart) { return FullWalletRequest.newBuilder() .setGoogleTransactionId(googleTransactionId) .setCart(cart) .build(); } @VisibleForTesting AndroidPayConfiguration...
### Question: AndroidPayConfiguration { @Nullable public MaskedWalletRequest generateMaskedWalletRequest(@Nullable Cart cart) { return generateMaskedWalletRequest( cart, mIsPhoneNumberRequired, mIsShippingAddressRequired, mCurrency.getCurrencyCode()); } @VisibleForTesting AndroidPayConfiguration( @NonNull ...
### Question: LineItemBuilder { public LineItem build() { LineItem.Builder androidPayBuilder = LineItem.newBuilder(); androidPayBuilder.setCurrencyCode(mCurrency.getCurrencyCode()).setRole(mRole); if (mTotalPrice != null) { androidPayBuilder.setTotalPrice(PaymentUtils.getPriceString(mTotalPrice, mCurrency)); } if (mUni...
### Question: LineItemBuilder { static boolean isWholeNumber(BigDecimal number) { return number.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0; } LineItemBuilder(); LineItemBuilder(String currencyCode); LineItemBuilder setCurrencyCode(String currencyCode); LineItemBuilder setUnitPrice(long unitPrice); Line...
### Question: LineItemBuilder { static boolean isPriceBreakdownConsistent( Long unitPrice, BigDecimal quantity, Long totalPrice) { if (unitPrice == null || quantity == null || totalPrice == null) { return true; } BigDecimal expectedPrice = quantity.multiply(BigDecimal.valueOf(unitPrice)); BigDecimal actualPrice = BigDe...
### Question: PaymentUtils { public static boolean matchesCurrencyPatternOrEmpty(@Nullable String priceString) { if (TextUtils.isEmpty(priceString)) { return true; } Pattern pattern = Pattern.compile("^-?[0-9]+(\\.[0-9][0-9])?"); return pattern.matcher(priceString).matches(); } static boolean matchesCurrencyPatternOrE...
### Question: PaymentUtils { public static boolean matchesQuantityPatternOrEmpty(@Nullable String quantityString) { if (TextUtils.isEmpty(quantityString)) { return true; } Pattern pattern = Pattern.compile("[0-9]+(\\.[0-9])?"); return pattern.matcher(quantityString).matches(); } static boolean matchesCurrencyPatternOr...
### Question: PaymentUtils { public static CartError searchLineItemForErrors(LineItem lineItem) { if (lineItem == null) { return null; } if (!matchesCurrencyPatternOrEmpty(lineItem.getUnitPrice())) { return new CartError(CartError.LINE_ITEM_PRICE, String.format(Locale.ENGLISH, "Invalid price string: %s does not match r...
### Question: PaymentUtils { public static IsReadyToPayRequest getStripeIsReadyToPayRequest() { return IsReadyToPayRequest.newBuilder() .addAllowedCardNetwork(WalletConstants.CardNetwork.AMEX) .addAllowedCardNetwork(WalletConstants.CardNetwork.DISCOVER) .addAllowedCardNetwork(WalletConstants.CardNetwork.JCB) .addAllowe...
### Question: PaymentUtils { @NonNull public static List<CartError> removeErrorType( @NonNull List<CartError> errors, @NonNull @CartError.CartErrorType String errorType) { List<CartError> filteredErrors = new ArrayList<>(); for (CartError error : errors) { if (errorType.equals(error.getErrorType())) { continue; } filte...
### Question: CartManager { @NonNull public String getCurrencyCode() { return mCurrency.getCurrencyCode(); } CartManager(); CartManager(String currencyCode); CartManager(@NonNull Cart oldCart); CartManager(@NonNull Cart oldCart, boolean shouldKeepShipping, boolean shouldKeepTax); @Nullable String addLineItem(@NonNul...
### Question: CartManager { @NonNull static String generateUuidForRole(int role) { String baseId = UUID.randomUUID().toString(); String base = null; if (role == LineItem.Role.REGULAR) { base = REGULAR_ID; } else if (role == LineItem.Role.SHIPPING) { base = SHIPPING_ID; } StringBuilder builder = new StringBuilder(); if ...
### Question: CartManager { public Long calculateTax() { if (mLineItemTax == null) { return 0L; } if (!mCurrency.getCurrencyCode().equals(mLineItemTax.getCurrencyCode())) { return null; } return PaymentUtils.getPriceLong(mLineItemTax.getTotalPrice(), mCurrency); } CartManager(); CartManager(String currencyCode); Cart...
### Question: CartManager { @Nullable public Long getTotalPrice() { if (mCachedTotalPrice != null) { return mCachedTotalPrice; } Long[] sectionPrices = new Long[3]; sectionPrices[0] = calculateRegularItemTotal(); sectionPrices[1] = calculateShippingItemTotal(); sectionPrices[2] = calculateTax(); Long totalPrice = null;...
### Question: ShippingMethod extends StripeJsonModel implements Parcelable { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); putLongIfNotNull(jsonObject, FIELD_AMOUNT, mAmount); putStringIfNotNull(jsonObject, FIELD_CURRENCY_CODE, mCurrencyCode); putStringIfNotNull(jsonObject, F...
### Question: ShippingMethod extends StripeJsonModel implements Parcelable { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> map = new HashMap<>(); map.put(FIELD_AMOUNT, mAmount); map.put(FIELD_CURRENCY_CODE, mCurrencyCode); map.put(FIELD_DETAIL, mDetail); map.put(FIELD_IDENTIFIER, mIdentifi...
### Question: StripeJsonUtils { @Nullable static String nullIfNullOrEmpty(@Nullable String possibleNull) { return NULL.equals(possibleNull) || EMPTY.equals(possibleNull) ? null : possibleNull; } }### Answer: @Test public void nullIfNullOrEmpty_returnsNullForNull() { assertNull(StripeJsonUtils.nullIfNullOrEmpty("null...
### Question: Card extends StripeJsonModel implements StripePaymentSource { public boolean validateExpiryDate() { return validateExpiryDate(Calendar.getInstance()); } Card( String number, Integer expMonth, Integer expYear, String cvc, String name, ...
### Question: Card extends StripeJsonModel implements StripePaymentSource { @Nullable public static Card fromString(String jsonString) { try { JSONObject jsonObject = new JSONObject(jsonString); return fromJson(jsonObject); } catch (JSONException ignored) { return null; } } Card( String number, ...
### Question: Token implements StripePaymentSource { @Nullable public static Token fromString(@Nullable String jsonString) { try { JSONObject tokenObject = new JSONObject(jsonString); return fromJson(tokenObject); } catch (JSONException exception) { return null; } } Token( String id, boolean liv...
### Question: NativeQuestionSetImporter extends AbstractQuestionSetImporter { @Override public QuestionSet processDocument( Document doc ) throws ParseException { Element root = doc.getRootElement(); if ( !root.getName().equalsIgnoreCase( "QuestionSet" ) ) throw new ParseException( "QuestionSet: Root not <QuestionSet>"...
### Question: DragAndDropQuestion extends AbstractQuestion { public Element asXML() { Element element = new Element("DragAndDropQuestion"); element.setAttribute("reuseFragments", Boolean.toString(reuseFragments)); ReadableElement questionTextElement = new ReadableElement("QuestionText"); questionTextElement.setText(que...
### Question: Option implements Serializable { public Element asXML() { ReadableElement element = new ReadableElement(XML_TAG_OPTION); element.setAttribute(XML_ATTRIBUTE_CORRECT, Boolean.toString(correct)); element.setText(optionText); return element; } Option(String optionText, boolean correct, int id); Option(Elemen...
### Question: MultipleChoiceQuestion extends AbstractQuestion { public int numberOfCorrectOptions() { int count = countCorrectOptions(options); return count; } MultipleChoiceQuestion(String questionText, String explanationText, List<Option> options, boolean shufflable, boolean singleOptionMode); List<Option...
### Question: AbstractQuestion implements Serializable, Question { public String getSubstitutedExplanationText() { return substituteExplanationText(questionText, explanationText); } protected AbstractQuestion(String questionText, String explanationText); protected AbstractQuestion(); static String removeCopyToExplana...
### Question: PlacesClient extends AbstractClient { public Request searchAsync(@NonNull PlacesQuery params, @NonNull CompletionHandler completionHandler) { final PlacesQuery paramsCopy = new PlacesQuery(params); return new AsyncTaskRequest(completionHandler) { @Override protected @NonNull JSONObject run() throws Algoli...
### Question: PlacesClient extends AbstractClient { public JSONObject getByObjectID(@NonNull String objectID) throws AlgoliaException { return getRequest("/1/places/" + objectID, null, false, null) ; } PlacesClient(@NonNull String applicationID, @NonNull String apiKey); PlacesClient(); Request searchAsync(@NonNull Pla...
### Question: Client extends AbstractClient { public @NonNull Index getIndex(@NonNull String indexName) { Index index = null; WeakReference<Object> existingIndex = indices.get(indexName); if (existingIndex != null) { index = (Index) existingIndex.get(); } if (index == null) { index = new Index(this, indexName); indices...
### Question: UriBuilder { public static String buildUriString(String tokenContractAddress, String iabContractAddress, BigDecimal amount, String developerAddress, String skuId, int networkId) { StringBuilder stringBuilder = new StringBuilder(4); try (Formatter formatter = new Formatter(stringBuilder)) { formatter.forma...
### Question: TransactionFactory { static String extractValueFromEthGetTransactionReceipt(String data) { if (data.startsWith("0x")) { data = data.substring(2); } return decodeInt(Hex.decode(data), 0).toString(); } private TransactionFactory(); static Transaction fromEthGetTransactionReceipt( EthGetTransactionRec...
### Question: ByteUtils { public static byte[] prependZeros(byte[] arr, int size) { if (arr.length > size) { throw new IllegalArgumentException("Size cannot be bigger than array size!"); } byte[] bytes = new byte[size]; System.arraycopy(arr, 0, bytes, (bytes.length - arr.length), arr.length); return bytes; } private B...
### Question: ByteUtils { public static byte[] concat(byte[]... arrays) { int count = 0; for (byte[] array : arrays) { count += array.length; } byte[] mergedArray = new byte[count]; int start = 0; for (byte[] array : arrays) { System.arraycopy(array, 0, mergedArray, start, array.length); start += array.length; } return...
### Question: Address extends ByteArray { public static Address from(byte[] address) { return new Address(new ByteArray(address)); } Address(ByteArray byteArray); static Address from(byte[] address); static Address from(String address); @Override String toString(); }### Answer: @Test public void from() { String hexStr...
### Question: ByteArray { public static ByteArray from(String hex) { if (hex.startsWith("0x")) { return new ByteArray(Hex.decode(hex.substring(2))); } else { return new ByteArray(Hex.decode(hex)); } } ByteArray(byte[] bytes); static ByteArray from(String hex); final String toHexString(); final String toHexString(boolea...
### Question: ByteArray { public final String toHexString() { return toHexString(false); } ByteArray(byte[] bytes); static ByteArray from(String hex); final String toHexString(); final String toHexString(boolean withPrefix); final byte[] getBytes(); @Override String toString(); @Override final int hashCode(); @Override...
### Question: ByteArray { public final byte[] getBytes() { return bytes; } ByteArray(byte[] bytes); static ByteArray from(String hex); final String toHexString(); final String toHexString(boolean withPrefix); final byte[] getBytes(); @Override String toString(); @Override final int hashCode(); @Override final boolean e...
### Question: TransactionFactory { static String extractValueFromEthTransaction(String input) { String valueHex = input.substring(input.length() - ((256 >> 2))); BigInteger value = decodeInt(Hex.decode(valueHex), 0); return value.toString(); } private TransactionFactory(); static Transaction fromEthGetTransactionRecei...
### Question: TransactionFactory { static String extractToFromEthTransaction(String input) { String valueHex = input.substring(10, input.length() - ((256 >> 2))); Address address = new Address(decodeInt(Hex.decode(valueHex), 0)); return address.toString(); } private TransactionFactory(); static Transaction fromEthGetT...
### Question: GenerateMojo extends AbstractMojo { List<String> getPackages() { return packages; } void execute(); }### Answer: @Test public void testBasic() throws Exception { File basedir = resources.getBasedir("basic"); GenerateMojo generate = (GenerateMojo) maven.lookupConfiguredMojo(maven.newMavenSession(maven.re...
### Question: FileResolver { static List<Path> resolveExistingMigrations(File migrationsDir, boolean reversed, boolean onlySchemaMigrations) { if (!migrationsDir.exists()) { migrationsDir.mkdirs(); } File[] files = migrationsDir.listFiles(); if (files == null) { return Collections.emptyList(); } Comparator<Path> pathCo...
### Question: FileResolver { static File resolveNextMigrationFile(File migrationDir) { Optional<Path> lastFile = resolveExistingMigrations(migrationDir, true, false) .stream() .findFirst(); Long fileIndex = lastFile.map((Path input) -> FILENAME_PATTERN.matcher(input.getFileName().toString())) .map(matcher -> { if (matc...
### Question: IPNMessageParser { public IPNMessage parse() { IPNMessage.Builder builder = new IPNMessage.Builder(nvp); if(validated) builder.validated(); for(Map.Entry<String, String> param : nvp.entrySet()) { addVariable(builder, param); } return builder.build(); } IPNMessageParser(Map<String, String> nvp, boolean val...
### Question: Urls { public static UrlBuilder http(String host) { return new UrlBuilder(Scheme.HTTP, host); } private Urls(); @Nonnull static URI createURI(@Nonnull String fullUrl); @Nonnull static String escape(@Nonnull String url); static UrlBuilder http(String host); static UrlBuilder https(String host); @Nonnull s...
### Question: Urls { @Nonnull public static String escape(@Nonnull String url) { String trim = Strings.sanitizeWhitespace(url); SplitUrl split = SplitUrl.split(trim); if (split.urlType() != Type.FULL) { throw new IllegalArgumentException( "Not a full URL: " + url); } StringBuilder sb = new StringBuilder(); if (split.sc...
### Question: Urls { @Nonnull public static URI createURI(@Nonnull String fullUrl) { String escaped = escape(fullUrl); try { return new URI(escaped); } catch (URISyntaxException e) { throw new AssertionError(e); } } private Urls(); @Nonnull static URI createURI(@Nonnull String fullUrl); @Nonnull static String escape(@...
### Question: PercentDecoder { public static String decodeAll(String str) { return decode(str, CodepointMatcher.ALL); } private PercentDecoder(); static String decodeAll(String str); static String decodeUnreserved(String str); }### Answer: @Test public void allAscii() { StringBuilder expected = new StringBuilder(); S...
### Question: PercentDecoder { public static String decodeUnreserved(String str) { return decode(str, CodepointMatcher.UNRESERVED); } private PercentDecoder(); static String decodeAll(String str); static String decodeUnreserved(String str); }### Answer: @Test public void allAsciiUnreserved() { StringBuilder expected ...
### Question: Paths { public static Path parse(String path) { return path.isEmpty() ? ImmutablePath.EMPTY : ImmutablePath.create(new PathBuilder().splitAndAdd(path, true)); } static Path of(String... segments); static Path parse(String path); static Path empty(); }### Answer: @Test public void resolve() { assertEqual...
### Question: Paths { public static Path of(String... segments) { if (segments.length == 0) { return ImmutablePath.EMPTY; } PathBuilder pathBuilder = new PathBuilder(); for (String segment : segments) { pathBuilder.splitAndAdd(segment, false); } return ImmutablePath.create(pathBuilder); } static Path of(String... segm...