Java tutorial
/* * Copyright (C) 2017 FormKiQ Inc. * * 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 com.formkiq.core.equifax.service; import static com.formkiq.core.form.FormFinder.findValueByKey; import static com.formkiq.core.form.JSONService.DEFAULT_DATE_FORMAT; import static org.apache.commons.lang3.StringUtils.isEmpty; import java.io.IOException; import java.io.StringWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.beanio.BeanWriter; import org.beanio.StreamFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import com.formkiq.core.equifax.segment.ConsumerAddressSegment; import com.formkiq.core.equifax.segment.DialSegment; import com.formkiq.core.equifax.segment.IDNTSegment; import com.formkiq.core.equifax.segment.SegmentFactory; import com.formkiq.core.form.JSONService; import com.formkiq.core.form.dto.FormBuiltInType; import com.formkiq.core.form.dto.FormJSON; import com.formkiq.core.form.dto.FormJSONField; import com.formkiq.core.form.service.FormEventHandler; /** * Equifax {@link FormEventHandler}. * */ public class EquifaxFormEventHandler implements FormEventHandler { /** Logger. */ private static final Logger LOG = Logger.getLogger(EquifaxFormEventHandler.class.getName()); /** Default Segment Length. */ private static final int DEFAULT_SEGMENT_LEN = 576; /** Value Regex. */ private static final Pattern VALUE_PATTERN = Pattern.compile("^(.*)\\[(.*)\\]$"); /** {@link EquifaxService}. */ @Autowired private EquifaxService service; /** * constructor. */ public EquifaxFormEventHandler() { } @Override public FormJSON handleEvent(final FormJSON form, final String event) throws IOException { // TODO store response.. // TODO hide customer / member number / securitycode? try { String request = generateEquifaxRequest(form); EquifaxCreditCheck cc = this.service.sendCreditCheck(form, request); SimpleDateFormat s = new SimpleDateFormat(JSONService.DEFAULT_DATE_FORMAT); findValueByKey(form, "equifax_credit_check_id").get().setValue(cc.getCreditcheckid()); findValueByKey(form, "url").get().setValue(cc.getUrl()); findValueByKey(form, "request").get().setValue(cc.getRequest()); findValueByKey(form, "response").get().setValue(cc.getResponse()); findValueByKey(form, "requesttype").get() .setValue(cc.getRequesttype() != null ? cc.getRequesttype().name() : ""); findValueByKey(form, "requester").get().setValue(cc.getRequester()); findValueByKey(form, "inserteddate").get() .setValue(cc.getInserteddate() != null ? s.format(cc.getInserteddate()) : null); EquifaxResponseProcessor processor = new EquifaxResponseProcessor(); form.setValidators(processor.createValidators(form, cc.getResponse())); } catch (Exception e) { LOG.log(Level.SEVERE, e.getMessage(), e); throw new IOException("Unable to process Equifax Request. " + "Please try again later."); } return form; } @Override public FormBuiltInType getType() { return FormBuiltInType.EQUIFAX_CREDIT_CHECK; } /** * Gets value from Map and trims. * @param form {@link FormJSON} * @param valuekey {@link String} * @return {@link String} */ private String get(final FormJSON form, final String valuekey) { String value = null; Optional<FormJSONField> op = findValueByKey(form, valuekey); if (op.isPresent()) { value = op.get().getValue(); value = !isEmpty(value) ? value.trim() : value; } return value; } /** * Removes all spaces from String. * @param string String * @return String */ private String removeAllSpaces(final String string) { return !StringUtils.isEmpty(string) ? string.replaceAll(" ", "") : string; } /** * Gets 'value' from a string. IE: string instead of [..] * IE: Manitoba[MB] returns 'MB' * IE: Manitoba returns 'Manitoba' * @param string String * @return String */ private String getValue(final String string) { if (!StringUtils.isEmpty(string)) { Matcher m = VALUE_PATTERN.matcher(string); if (m.matches()) { if (m.groupCount() == 2) { return m.group(2); } } } return string; } /** * Generates String to send to Equifax. * @param form {@link FormJSON} * @throws ParseException ParseException * @return {@link String} */ private String generateEquifaxRequest(final FormJSON form) throws ParseException { SegmentFactory factory = new SegmentFactory(); StringWriter sw = new StringWriter(); String firstName = get(form, "firstname"); String lastName = get(form, "familyname"); String middleName = get(form, "middlename"); Date birthDate = getDate(form, "birthdate"); String streetNo = get(form, "streetno0"); String streetName = get(form, "streetname0"); String city = get(form, "city0"); String province = getValue(get(form, "province0")); String postalCode = removeAllSpaces(get(form, "postalcode0")); String sin = get(form, "sin"); String homePhone = get(form, "homephonenumber"); if (!StringUtils.isEmpty(homePhone)) { homePhone = homePhone.replaceAll("\\D+", ""); } String suffix = get(form, "suffix"); String previousstreetno = get(form, "streetno1"); String previousstreetname = get(form, "streetname1"); String previouscity = get(form, "city1"); String previousprovince = get(form, "province1"); String previouspostalcode = removeAllSpaces(get(form, "postalcode1")); StreamFactory sf = factory.createWriterFactory(); int length = DEFAULT_SEGMENT_LEN; if (!StringUtils.isEmpty(previouscity) && !StringUtils.isEmpty(previousprovince)) { ConsumerAddressSegment s = new ConsumerAddressSegment(); length += s.getSegmentLength(); } boolean isProduction = isProduction(form); BeanWriter out = sf.createWriter("employeeFile", sw); out.write(factory.createEFX1Segment(isProduction, length)); DialSegment dialseg = factory.createDialSegment(get(form, "customercode")); factory.setMemberSegment(dialseg, get(form, "membernumber"), get(form, "securitycode")); out.write(dialseg); IDNTSegment idnt = factory.createIDNTSegment(suffix, firstName, middleName, lastName, birthDate, homePhone, sin); factory.setMemberSegment(idnt, get(form, "membernumber"), get(form, "securitycode")); out.write(idnt); ConsumerAddressSegment addr = factory.createConsumerAddressSegment(streetNo, streetName, city, province, postalCode); out.write(addr); if (!StringUtils.isEmpty(previouscity) && !StringUtils.isEmpty(previousprovince)) { out.write(factory.createConsumerAddressSegment(previousstreetno, previousstreetname, previouscity, previousprovince, previouspostalcode)); } out.write(factory.createMODLSegment()); out.flush(); out.close(); String s = sw.toString().replace("\r\n", "").replace("\n", ""); IOUtils.closeQuietly(sw); return s; } /** * Get Date. * @param form {@link FormJSON} * @param key {@link String} * @return {@link Date} * @throws ParseException ParseException */ private Date getDate(final FormJSON form, final String key) throws ParseException { String value = get(form, key); SimpleDateFormat dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); try { return dateFormatter.parse(value); } catch (ParseException e) { dateFormatter = new SimpleDateFormat("yyyy/MM/dd"); return dateFormatter.parse(value); } } /** * Is {@link FormJSON} for production? * @param form {@link FormJSON} * @return boolean */ private boolean isProduction(final FormJSON form) { Optional<FormJSONField> field = findValueByKey(form, "host"); return field.isPresent() && field.get().getValue().contains("https://www"); } }