Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format currency amounts in fare_products.txt with 2 decimal digits #320

Merged
merged 4 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;
import java.util.Map;

Expand All @@ -37,6 +38,8 @@ public class DecimalFieldMappingFactory implements FieldMappingFactory {

private Locale _locale = Locale.US;

private Currency _currency;

public DecimalFieldMappingFactory() {

}
Expand All @@ -50,6 +53,10 @@ public DecimalFieldMappingFactory(String format, Locale locale) {
_locale = locale;
}

public DecimalFieldMappingFactory(Currency currency) {
_currency = currency;
}

@Override
public FieldMapping createFieldMapping(EntitySchemaFactory schemaFactory,
Class<?> entityType, String csvFieldName, String objFieldName,
Expand All @@ -63,7 +70,11 @@ public FieldMapping createFieldMapping(EntitySchemaFactory schemaFactory,

private NumberFormat getFormat(Class<?> entityType, String objFieldName) {
String format = determineFormat(entityType, objFieldName);
if (_locale == null) {
if (_currency != null) {
NumberFormat currFormatter = NumberFormat.getCurrencyInstance(Locale.US);
currFormatter.setCurrency(_currency);
return currFormatter;
} else if (_locale == null) {
return new DecimalFormat(format);
} else {
return new DecimalFormat(format, new DecimalFormatSymbols(_locale));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.onebusaway.gtfs.serialization.mappings.DefaultAgencyIdFieldMappingFactory;
import org.onebusaway.gtfs.serialization.mappings.EntityFieldMappingFactory;
import org.onebusaway.gtfs.serialization.mappings.FareProductFieldMappingFactory;
import org.onebusaway.gtfs.serialization.mappings.FareAmountFieldMappingFactory;

@CsvFields(filename = "fare_products.txt", required = false)
public final class FareProduct extends IdentityBean<AgencyAndId> {
Expand All @@ -32,7 +33,7 @@ public final class FareProduct extends IdentityBean<AgencyAndId> {
private AgencyAndId fareProductId;
@CsvField(optional = true, name = "fare_product_name")
private String name;
@CsvField
@CsvField(name = "amount", optional = false, mapping = FareAmountFieldMappingFactory.class)
private float amount = MISSING_VALUE;
@CsvField
private String currency;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* Copyright (C) 2024 Sound Transit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onebusaway.gtfs.serialization.mappings;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;
import java.util.Map;

import org.onebusaway.csv_entities.CsvEntityContext;
import org.onebusaway.csv_entities.exceptions.CsvEntityException;
import org.onebusaway.csv_entities.schema.AbstractFieldMapping;
import org.onebusaway.csv_entities.schema.BeanWrapper;
import org.onebusaway.csv_entities.schema.EntitySchemaFactory;
import org.onebusaway.csv_entities.schema.FieldMapping;
import org.onebusaway.csv_entities.schema.FieldMappingFactory;

public class FareAmountFieldMappingFactory implements FieldMappingFactory {


public FieldMapping createFieldMapping(EntitySchemaFactory schemaFactory,
Class<?> entityType, String csvFieldName, String objFieldName,
Class<?> objFieldType, boolean required) {

return new FareAmountFieldMapping(entityType, csvFieldName, objFieldName, required);
}

private static class FareAmountFieldMapping extends AbstractFieldMapping {

public FareAmountFieldMapping(Class<?> entityType, String csvFieldName,
String objFieldName, boolean required) {
super(entityType, csvFieldName, objFieldName, required);
}

@Override
public void translateFromObjectToCSV(CsvEntityContext context,
BeanWrapper object, Map<String, Object> csvValues) {

String currencyString = (String) object.getPropertyValue("currency");
Currency currency = Currency.getInstance(currencyString);
Float amount = (Float) object.getPropertyValue(_objFieldName);

DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US);
formatter.setCurrency(currency);

// remove "$", "¥", "₹" and other currency symbols from the output
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setCurrencySymbol("");
formatter.setDecimalFormatSymbols(symbols);
formatter.setMaximumFractionDigits(currency.getDefaultFractionDigits());

csvValues.put(_csvFieldName, formatter.format(amount));
}

@Override
public void translateFromCSVToObject(CsvEntityContext context, Map<String, Object> csvValues, BeanWrapper object)
throws CsvEntityException {

if (isMissingAndOptional(csvValues))
return;

Object value = csvValues.get(_csvFieldName);

Float amount = Float.parseFloat(value.toString());
object.setPropertyValue(_objFieldName, amount);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/**
* Copyright (C) 2025 Sound Transit <GTFSTeam@soundtransit.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.onebusaway.gtfs.serialization;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.onebusaway.gtfs.impl.FileSupport;
import org.onebusaway.gtfs.impl.GtfsRelationalDaoImpl;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.FareProduct;

public class FareProductWriterTest {
private FileSupport _support = new FileSupport();
private File _tmpDirectory;

@BeforeEach
public void setup() throws IOException {
_tmpDirectory = File.createTempFile("FareProductWriterTest-", "-tmp");
if (_tmpDirectory.exists())
_support.deleteFileRecursively(_tmpDirectory);
_tmpDirectory.mkdirs();
_support.markForDeletion(_tmpDirectory);
}

@AfterEach
public void teardown() {
_support.cleanup();
}

@Test
public void testWriteAmountWithCorrectDecimalPlaces() throws IOException {

GtfsWriter writer = new GtfsWriter();
writer.setOutputLocation(_tmpDirectory);

FareProduct fp = new FareProduct();
String agencyId = "a1";
String fareProductId = "fp1";
AgencyAndId fpAgencyAndId = new AgencyAndId(agencyId, fareProductId);
float floatCurrency = 4.7f;
String formattedCurrency = "4.70";

fp.setId(fpAgencyAndId);
fp.setFareProductId(fpAgencyAndId);
fp.setCurrency("USD");
fp.setAmount(floatCurrency);

writer.handleEntity(fp);

writer.close();

GtfsReader reader = new GtfsReader();
reader.setDefaultAgencyId(agencyId);
reader.setInputLocation(_tmpDirectory);

Scanner scan = new Scanner(new File(_tmpDirectory + "/fare_products.txt"));

Boolean onHeader = true;
Boolean containsExpected = false;
while(scan.hasNext()){
String line = scan.nextLine();
if (onHeader) {
onHeader = false;
} else {
if (line.contains(formattedCurrency)) {
containsExpected = true;
}
}
}
scan.close();

assertTrue(containsExpected, "Line in fare_products.txt did not contain formatted currency amount 4.70");

GtfsRelationalDaoImpl dao = new GtfsRelationalDaoImpl();
reader.setEntityStore(dao);

reader.readEntities(FareProduct.class);

FareProduct fareProductFromFile = dao.getAllFareProducts().iterator().next();

assertEquals(fareProductFromFile.getAmount(), floatCurrency);
}

public static void deleteFileRecursively(File file) {

if (!file.exists())
return;

if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files)
deleteFileRecursively(child);
}
}

file.delete();
}
}
Loading
Loading