Search in sources :

Example 6 with Telephone

use of ezvcard.property.Telephone in project data-transfer-project by google.

the class VCardToGoogleContactConverterTest method testConversionToGooglePhones.

@Test
public void testConversionToGooglePhones() {
    // Set up test: vCard with 2 primary phone numbers and 1 secondary phone number
    String primaryValue1 = "334-844-4244";
    String primaryValue2 = "411";
    String secondaryValue = "(555) 867-5309";
    Telephone primaryTelephone1 = new Telephone(primaryValue1);
    primaryTelephone1.setPref(VCARD_PRIMARY_PREF);
    Telephone primaryTelephone2 = new Telephone(primaryValue2);
    primaryTelephone2.setPref(VCARD_PRIMARY_PREF);
    Telephone secondaryTelephone = new Telephone(secondaryValue);
    secondaryTelephone.setPref(VCARD_PRIMARY_PREF + 1);
    // Add numbers to vCard.  Order shouldn't matter.
    VCard vCard = defaultVCard;
    vCard.addTelephoneNumber(secondaryTelephone);
    vCard.addTelephoneNumber(primaryTelephone1);
    vCard.addTelephoneNumber(primaryTelephone2);
    // Run test
    Person person = VCardToGoogleContactConverter.convert(vCard);
    // Check results
    // Correct number of phone numbers
    assertThat(person.getPhoneNumbers().size()).isEqualTo(3);
    // Check primary phone numbers
    List<PhoneNumber> actualPrimaryNumbers = person.getPhoneNumbers().stream().filter(a -> a.getMetadata().getPrimary()).collect(Collectors.toList());
    List<String> actualPrimaryNumberStrings = getValuesFromFields(actualPrimaryNumbers, PhoneNumber::getValue);
    assertThat(actualPrimaryNumberStrings).containsExactly(primaryValue1, primaryValue2);
    // Check secondary phone numbers
    List<PhoneNumber> actualSecondaryNumbers = person.getPhoneNumbers().stream().filter(a -> !a.getMetadata().getPrimary()).collect(Collectors.toList());
    List<String> actualSecondaryNumberStrings = getValuesFromFields(actualSecondaryNumbers, PhoneNumber::getValue);
    assertThat(actualSecondaryNumberStrings).containsExactly(secondaryValue);
}
Also used : VCard(ezvcard.VCard) VCARD_PRIMARY_PREF(org.dataportabilityproject.serviceProviders.google.contacts.GoogleContactsConstants.VCARD_PRIMARY_PREF) EmailAddress(com.google.api.services.people.v1.model.EmailAddress) Telephone(ezvcard.property.Telephone) SOURCE_PARAM_NAME_TYPE(org.dataportabilityproject.serviceProviders.google.contacts.GoogleContactsConstants.SOURCE_PARAM_NAME_TYPE) Test(org.junit.Test) PhoneNumber(com.google.api.services.people.v1.model.PhoneNumber) Truth.assertThat(com.google.common.truth.Truth.assertThat) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) StructuredName(ezvcard.property.StructuredName) Pair(com.google.gdata.util.common.base.Pair) Person(com.google.api.services.people.v1.model.Person) List(java.util.List) CONTACT_SOURCE_TYPE(org.dataportabilityproject.serviceProviders.google.contacts.GoogleContactsConstants.CONTACT_SOURCE_TYPE) Nullable(com.google.gdata.util.common.base.Nullable) Address(com.google.api.services.people.v1.model.Address) Email(ezvcard.property.Email) Name(com.google.api.services.people.v1.model.Name) Collections(java.util.Collections) Before(org.junit.Before) Telephone(ezvcard.property.Telephone) PhoneNumber(com.google.api.services.people.v1.model.PhoneNumber) VCard(ezvcard.VCard) Person(com.google.api.services.people.v1.model.Person) Test(org.junit.Test)

Example 7 with Telephone

use of ezvcard.property.Telephone in project ofbiz-framework by apache.

the class VCard method importVCard.

/**
 * import a vcard from byteBuffer. the reader use is ez-vcard, see official site https://github.com/mangstadt/ez-vcard/
 * @param dctx
 * @param context
 * @return
 * @throws IOException
 */
public static Map<String, Object> importVCard(DispatchContext dctx, Map<String, ? extends Object> context) throws IOException {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> result = ServiceUtil.returnSuccess();
    ByteBuffer byteBuffer = (ByteBuffer) context.get("infile");
    byte[] inputByteArray = byteBuffer.array();
    InputStream in = new ByteArrayInputStream(inputByteArray);
    Map<String, Object> serviceCtx = new HashMap<String, Object>();
    boolean isGroup = false;
    List<Map<String, String>> partiesCreated = new ArrayList<Map<String, String>>();
    List<Map<String, String>> partiesExist = new ArrayList<Map<String, String>>();
    // TODO this is not used yet
    String partyName = "";
    try (VCardReader vCardReader = new VCardReader(in)) {
        ezvcard.VCard vcard = null;
        while ((vcard = vCardReader.readNext()) != null) {
            // Todo create a generic service to resolve duplicate party
            FormattedName formattedName = vcard.getFormattedName();
            if (formattedName != null) {
                String refCardId = formattedName.getValue();
                GenericValue partyIdentification = EntityQuery.use(delegator).from("PartyIdentification").where("partyIdentificationTypeId", "VCARD_FN_ORIGIN", "idValue", refCardId).queryFirst();
                if (partyIdentification != null) {
                    partiesExist.add(UtilMisc.toMap("partyId", (String) partyIdentification.get("partyId")));
                    continue;
                }
            // TODO manage update
            }
            // check if it's already load
            isGroup = false;
            if (vcard.getKind() != null)
                isGroup = vcard.getKind().isGroup();
            StructuredName structuredName = vcard.getStructuredName();
            if (UtilValidate.isEmpty(structuredName))
                continue;
            if (!isGroup) {
                serviceCtx.put("firstName", structuredName.getGiven());
                serviceCtx.put("lastName", structuredName.getFamily());
                partyName = structuredName.getGiven() + " " + structuredName.getFamily();
            }
            // Resolve all postal Address
            for (Address address : vcard.getAddresses()) {
                boolean workAddress = false;
                for (AddressType addressType : address.getTypes()) {
                    if (AddressType.PREF.equals(addressType) || AddressType.WORK.equals(addressType)) {
                        workAddress = true;
                        break;
                    }
                }
                if (!workAddress)
                    continue;
                serviceCtx.put("address1", address.getStreetAddressFull());
                serviceCtx.put("city", address.getLocality());
                serviceCtx.put("postalCode", address.getPostalCode());
                GenericValue countryGeo = EntityQuery.use(delegator).from("Geo").where(EntityCondition.makeCondition("geoTypeId", EntityOperator.EQUALS, "COUNTRY"), EntityCondition.makeCondition("geoName", EntityOperator.LIKE, address.getCountry())).cache().queryFirst();
                if (countryGeo != null) {
                    serviceCtx.put("countryGeoId", countryGeo.get("geoId"));
                }
                GenericValue stateGeo = EntityQuery.use(delegator).from("Geo").where(EntityCondition.makeCondition("geoTypeId", EntityOperator.EQUALS, "STATE"), EntityCondition.makeCondition("geoName", EntityOperator.LIKE, address.getRegion())).cache().queryFirst();
                if (stateGeo != null) {
                    serviceCtx.put("stateProvinceGeoId", stateGeo.get("geoId"));
                }
            }
            int nbEmailAddr = (vcard.getEmails() != null) ? vcard.getEmails().size() : 0;
            for (Email email : vcard.getEmails()) {
                if (nbEmailAddr > 1) {
                    boolean workEmail = false;
                    for (EmailType emailType : email.getTypes()) {
                        if (EmailType.PREF.equals(emailType) || EmailType.WORK.equals(emailType)) {
                            workEmail = true;
                            break;
                        }
                    }
                    if (!workEmail)
                        continue;
                }
                String emailAddr = email.getValue();
                if (UtilValidate.isEmail(emailAddr)) {
                    serviceCtx.put("emailAddress", emailAddr);
                } else {
                    // TODO change uncorrect labellisation
                    String emailFormatErrMsg = UtilProperties.getMessage(resourceError, "SfaImportVCardEmailFormatError", locale);
                    vCardReader.close();
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "MarketingEmailFormatError", UtilMisc.toMap("firstName", structuredName.getGiven(), "lastName", structuredName.getFamily(), "emailFOrmatErrMsg", emailFormatErrMsg), locale));
                }
            }
            int nbPhone = (vcard.getTelephoneNumbers() != null) ? vcard.getTelephoneNumbers().size() : 0;
            for (Telephone phone : vcard.getTelephoneNumbers()) {
                if (nbPhone > 1) {
                    boolean workPhone = false;
                    for (TelephoneType phoneType : phone.getTypes()) {
                        if (TelephoneType.PREF.equals(phoneType) || TelephoneType.WORK.equals(phoneType)) {
                            workPhone = true;
                            break;
                        }
                    }
                    if (!workPhone)
                        continue;
                }
                String phoneAddr = phone.getText();
                boolean internationalPhone = phoneAddr.startsWith("+") || phoneAddr.startsWith("00");
                phoneAddr = StringUtil.removeNonNumeric(phoneAddr);
                int indexLocal = 0;
                if (internationalPhone) {
                    indexLocal = 4;
                    if (!phoneAddr.startsWith("00")) {
                        phoneAddr = phoneAddr.concat("00");
                    }
                    serviceCtx.put("areaCode", phoneAddr.substring(0, indexLocal));
                }
                serviceCtx.put("contactNumber", phoneAddr.substring(indexLocal));
            }
            /* TODO improve this part to manage party organization */
            GenericValue userLogin = (GenericValue) context.get("userLogin");
            serviceCtx.put("userLogin", userLogin);
            String serviceName = (String) context.get("serviceName");
            Map<String, Object> serviceContext = UtilGenerics.cast(context.get("serviceContext"));
            if (UtilValidate.isNotEmpty(serviceContext)) {
                for (Map.Entry<String, Object> entry : serviceContext.entrySet()) {
                    serviceCtx.put(entry.getKey(), entry.getValue());
                }
            }
            Map<String, Object> resp = dispatcher.runSync(serviceName, serviceCtx);
            if (ServiceUtil.isError(resp)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resp));
            }
            partiesCreated.add(UtilMisc.toMap("partyId", (String) resp.get("partyId")));
            if (formattedName != null) {
                // store the origin creation
                Map<String, Object> createPartyIdentificationMap = dctx.makeValidContext("createPartyIdentification", ModelService.IN_PARAM, context);
                createPartyIdentificationMap.put("partyId", resp.get("partyId"));
                createPartyIdentificationMap.put("partyIdentificationTypeId", "VCARD_FN_ORIGIN");
                createPartyIdentificationMap.put("idValue", formattedName.getValue());
                resp = dispatcher.runSync("createPartyIdentification", createPartyIdentificationMap);
                if (ServiceUtil.isError(resp)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resp));
                }
            }
        }
    } catch (IOException | GenericEntityException | GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "SfaImportVCardError", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }
    result.put("partiesCreated", partiesCreated);
    result.put("partiesExist", partiesExist);
    return result;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Email(ezvcard.property.Email) EmailType(ezvcard.parameter.EmailType) Address(ezvcard.property.Address) Telephone(ezvcard.property.Telephone) HashMap(java.util.HashMap) FormattedName(ezvcard.property.FormattedName) ArrayList(java.util.ArrayList) TelephoneType(ezvcard.parameter.TelephoneType) StructuredName(ezvcard.property.StructuredName) GenericValue(org.apache.ofbiz.entity.GenericValue) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) VCardReader(ezvcard.io.text.VCardReader) Delegator(org.apache.ofbiz.entity.Delegator) ByteArrayInputStream(java.io.ByteArrayInputStream) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) AddressType(ezvcard.parameter.AddressType) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with Telephone

use of ezvcard.property.Telephone in project ofbiz-framework by apache.

the class VCard method exportVCard.

public static Map<String, Object> exportVCard(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String partyId = (String) context.get("partyId");
    Locale locale = (Locale) context.get("locale");
    File file = null;
    try {
        ezvcard.VCard vcard = new ezvcard.VCard();
        StructuredName structuredName = new StructuredName();
        GenericValue person = EntityQuery.use(delegator).from("Person").where("partyId", partyId).queryOne();
        if (person != null) {
            if (UtilValidate.isNotEmpty(person.getString("firstName")))
                structuredName.setGiven(person.getString("firstName"));
            if (UtilValidate.isNotEmpty(person.getString("lastName")))
                structuredName.setFamily(person.getString("lastName"));
            vcard.setStructuredName(structuredName);
        }
        String fullName = PartyHelper.getPartyName(delegator, partyId, false);
        vcard.setFormattedName(fullName);
        GenericValue postalAddress = PartyWorker.findPartyLatestPostalAddress(partyId, delegator);
        if (postalAddress != null) {
            Address address = new Address();
            address.setStreetAddress(postalAddress.getString("address1"));
            address.setLocality(postalAddress.getString("city"));
            address.setPostalCode(postalAddress.getString("postalCode"));
            GenericValue state = postalAddress.getRelatedOne("StateProvinceGeo", false);
            if (state != null) {
                address.setRegion(state.getString("geoName"));
            }
            GenericValue countryGeo = postalAddress.getRelatedOne("CountryGeo", false);
            if (countryGeo != null) {
                String country = postalAddress.getRelatedOne("CountryGeo", false).getString("geoName");
                address.setCountry(country);
                address.getTypes().add(AddressType.WORK);
                ;
            // TODO : this can be better set by checking contactMechPurposeTypeId
            }
            vcard.addAddress(address);
        }
        GenericValue telecomNumber = PartyWorker.findPartyLatestTelecomNumber(partyId, delegator);
        if (telecomNumber != null) {
            Telephone tel = new Telephone(telecomNumber.getString("areaCode") + telecomNumber.getString("contactNumber"));
            tel.getTypes().add(TelephoneType.WORK);
            vcard.addTelephoneNumber(tel);
        // TODO : this can be better set by checking contactMechPurposeTypeId
        }
        GenericValue emailAddress = PartyWorker.findPartyLatestContactMech(partyId, "EMAIL_ADDRESS", delegator);
        if (emailAddress != null && UtilValidate.isNotEmpty(emailAddress.getString("infoString"))) {
            vcard.addEmail(new Email(emailAddress.getString("infoString")));
        }
        // TODO : convert to directdownload of a vcf file
        String saveToDirectory = EntityUtilProperties.getPropertyValue("sfa", "save.outgoing.directory", "", delegator);
        if (UtilValidate.isEmpty(saveToDirectory)) {
            saveToDirectory = System.getProperty("ofbiz.home");
        }
        String saveToFilename = fullName + ".vcf";
        file = FileUtil.getFile(saveToDirectory + "/" + saveToFilename);
        Ezvcard.write(vcard).go(file);
    } catch (FileNotFoundException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "SfaExportVCardErrorOpeningFile", UtilMisc.toMap("errorString", file.getAbsolutePath()), locale));
    } catch (IOException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "SfaExportVCardErrorWritingFile", UtilMisc.toMap("errorString", file.getAbsolutePath()), locale));
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "SfaExportVCardError", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Email(ezvcard.property.Email) Address(ezvcard.property.Address) Telephone(ezvcard.property.Telephone) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) File(java.io.File) StructuredName(ezvcard.property.StructuredName)

Example 9 with Telephone

use of ezvcard.property.Telephone in project ez-vcard by mangstadt.

the class TelephoneScribe method _parseHtml.

@Override
protected Telephone _parseHtml(HCardElement element, ParseContext context) {
    Telephone property;
    String href = element.attr("href");
    try {
        property = new Telephone(TelUri.parse(href));
    } catch (IllegalArgumentException e) {
        // not a tel URI
        property = new Telephone(element.value());
    }
    List<String> types = element.types();
    property.getParameters().putAll(VCardParameters.TYPE, types);
    return property;
}
Also used : Telephone(ezvcard.property.Telephone)

Example 10 with Telephone

use of ezvcard.property.Telephone in project ez-vcard by mangstadt.

the class TelephoneScribe method _parseXml.

@Override
protected Telephone _parseXml(XCardElement element, VCardParameters parameters, ParseContext context) {
    String text = element.first(VCardDataType.TEXT);
    if (text != null) {
        return new Telephone(text);
    }
    String uri = element.first(VCardDataType.URI);
    if (uri != null) {
        try {
            return new Telephone(TelUri.parse(uri));
        } catch (IllegalArgumentException e) {
            context.addWarning(18);
            return new Telephone(uri);
        }
    }
    throw missingXmlElements(VCardDataType.TEXT, VCardDataType.URI);
}
Also used : Telephone(ezvcard.property.Telephone)

Aggregations

Telephone (ezvcard.property.Telephone)22 VCard (ezvcard.VCard)12 StructuredName (ezvcard.property.StructuredName)11 Test (org.junit.Test)10 Address (ezvcard.property.Address)8 TelUri (ezvcard.util.TelUri)8 Email (ezvcard.property.Email)6 Birthday (ezvcard.property.Birthday)5 Timezone (ezvcard.property.Timezone)5 UtcOffset (ezvcard.util.UtcOffset)5 Person (com.google.api.services.people.v1.model.Person)4 PhoneNumber (com.google.api.services.people.v1.model.PhoneNumber)4 Anniversary (ezvcard.property.Anniversary)4 Geo (ezvcard.property.Geo)4 Key (ezvcard.property.Key)4 List (java.util.List)3 Address (com.google.api.services.people.v1.model.Address)2 EmailAddress (com.google.api.services.people.v1.model.EmailAddress)2 Name (com.google.api.services.people.v1.model.Name)2 Truth.assertThat (com.google.common.truth.Truth.assertThat)2