1 /* 2 * Copyright (C) 2022 The Libphonenumber Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 * @author Tobias Rogg 17 */ 18 19 package com.google.phonenumbers.demo.render; 20 21 import com.google.i18n.phonenumbers.NumberParseException; 22 import com.google.i18n.phonenumbers.PhoneNumberUtil; 23 import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; 24 import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; 25 import com.google.phonenumbers.demo.template.ResultFileTemplates.File; 26 import java.util.StringTokenizer; 27 28 public class ResultFileRenderer extends LibPhoneNumberRenderer<File> { 29 private final String defaultCountry; 30 private final String fileContents; 31 private final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); 32 ResultFileRenderer(String defaultCountry, String fileContents)33 public ResultFileRenderer(String defaultCountry, String fileContents) { 34 this.fileContents = fileContents; 35 this.defaultCountry = defaultCountry; 36 } 37 38 @Override genHtml()39 public String genHtml() { 40 File.Builder soyTemplate = File.builder(); 41 int phoneNumberId = 0; 42 StringTokenizer tokenizer = new StringTokenizer(fileContents, ","); 43 while (tokenizer.hasMoreTokens()) { 44 String numberStr = tokenizer.nextToken(); 45 phoneNumberId++; 46 try { 47 PhoneNumber number = phoneUtil.parseAndKeepRawInput(numberStr, defaultCountry); 48 boolean isNumberValid = phoneUtil.isValidNumber(number); 49 soyTemplate.addRows( 50 phoneNumberId, 51 numberStr, 52 isNumberValid ? phoneUtil.formatInOriginalFormat(number, defaultCountry) : "invalid", 53 isNumberValid ? phoneUtil.format(number, PhoneNumberFormat.INTERNATIONAL) : "invalid", 54 null); 55 } catch (NumberParseException e) { 56 soyTemplate.addRows(phoneNumberId, numberStr, null, null, e.toString()); 57 } 58 } 59 return super.render(soyTemplate.build()); 60 } 61 } 62