List of usage examples for org.apache.commons.csv CSVRecord getRecordNumber
public long getRecordNumber()
From source file:org.nuxeo.ecm.csv.core.CSVImporterWork.java
protected long getLineNumber(CSVRecord record) { return record.getRecordNumber() + 1; }
From source file:org.ofbiz.accounting.invoice.InvoiceServices.java
public static Map<String, Object> importInvoice(DispatchContext dctx, Map<String, Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); ByteBuffer fileBytes = (ByteBuffer) context.get("uploadedFile"); String organizationPartyId = (String) context.get("organizationPartyId"); String encoding = System.getProperty("file.encoding"); String csvString = Charset.forName(encoding).decode(fileBytes).toString(); final BufferedReader csvReader = new BufferedReader(new StringReader(csvString)); CSVFormat fmt = CSVFormat.DEFAULT.withHeader(); List<String> errMsgs = FastList.newInstance(); List<String> newErrMsgs = FastList.newInstance(); String lastInvoiceId = null;/*from www. java 2 s .c o m*/ String currentInvoiceId = null; String newInvoiceId = null; int invoicesCreated = 0; if (fileBytes == null) { return ServiceUtil.returnError("Uploaded file data not found"); } try { for (final CSVRecord rec : fmt.parse(csvReader)) { currentInvoiceId = rec.get("invoiceId"); if (lastInvoiceId == null || !currentInvoiceId.equals(lastInvoiceId)) { newInvoiceId = null; Map<String, Object> invoice = UtilMisc.toMap("invoiceTypeId", rec.get("invoiceTypeId"), "partyIdFrom", rec.get("partyIdFrom"), "partyId", rec.get("partyId"), "invoiceDate", rec.get("invoiceDate"), "dueDate", rec.get("dueDate"), "currencyUomId", rec.get("currencyUomId"), "description", rec.get("description"), "referenceNumber", rec.get("referenceNumber") + " Imported: orginal InvoiceId: " + currentInvoiceId, "userLogin", userLogin); // replace values if required if (UtilValidate.isNotEmpty(rec.get("partyIdFromTrans"))) { invoice.put("partyIdFrom", rec.get("partyIdFromTrans")); } if (UtilValidate.isNotEmpty(rec.get("partyIdTrans"))) { invoice.put("partyId", rec.get("partyIdTrans")); } // invoice validation try { newErrMsgs = FastList.newInstance(); if (UtilValidate.isEmpty(invoice.get("partyIdFrom"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Party Id From and Party Id From Trans missing for invoice: " + currentInvoiceId); } else if (EntityQuery.use(delegator).from("Party") .where("partyId", invoice.get("partyIdFrom")).queryOne() == null) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyIdFrom: " + invoice.get("partyIdFrom") + " not found for invoice: " + currentInvoiceId); } if (UtilValidate.isEmpty(invoice.get("partyId"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Party Id and Party Id Trans missing for invoice: " + currentInvoiceId); } else if (EntityQuery.use(delegator).from("Party").where("partyId", invoice.get("partyId")) .queryOne() == null) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyId: " + invoice.get("partyId") + " not found for invoice: " + currentInvoiceId); } if (UtilValidate.isEmpty(invoice.get("invoiceTypeId"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Invoice Type missing for invoice: " + currentInvoiceId); } else if (EntityQuery.use(delegator).from("InvoiceType") .where("invoiceTypeId", invoice.get("invoiceTypeId")).queryOne() == null) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": InvoiceItem type id: " + invoice.get("invoiceTypeId") + " not found for invoice: " + currentInvoiceId); } GenericValue invoiceType = EntityQuery.use(delegator).from("InvoiceType") .where("invoiceTypeId", invoice.get("invoiceTypeId")).queryOne(); if ("PURCHASE_INVOICE".equals(invoiceType.getString("parentTypeId")) && !invoice.get("partyId").equals(organizationPartyId)) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": A purchase type invoice should have the partyId 'To' being the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyId") + "! invoice: " + currentInvoiceId); } if ("SALES_INVOICE".equals(invoiceType.getString("parentTypeId")) && !invoice.get("partyIdFrom").equals(organizationPartyId)) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": A sales type invoice should have the partyId 'from' being the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyIdFrom") + "! invoice: " + currentInvoiceId); } } catch (GenericEntityException e) { Debug.logError("Valication checking problem against database. due to " + e.getMessage(), module); } if (newErrMsgs.size() > 0) { errMsgs.addAll(newErrMsgs); } else { Map<String, Object> invoiceResult = null; try { invoiceResult = dispatcher.runSync("createInvoice", invoice); } catch (GenericServiceException e) { csvReader.close(); Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } newInvoiceId = (String) invoiceResult.get("invoiceId"); invoicesCreated++; } lastInvoiceId = currentInvoiceId; } if (newInvoiceId != null) { Map<String, Object> invoiceItem = UtilMisc.toMap("invoiceId", newInvoiceId, "invoiceItemSeqId", rec.get("invoiceItemSeqId"), "invoiceItemTypeId", rec.get("invoiceItemTypeId"), "productId", rec.get("productId"), "description", rec.get("itemDescription"), "amount", rec.get("amount"), "quantity", rec.get("quantity"), "userLogin", userLogin); if (UtilValidate.isNotEmpty(rec.get("productIdTrans"))) { invoiceItem.put("productId", rec.get("productIdTrans")); } // invoice item validation try { newErrMsgs = FastList.newInstance(); if (UtilValidate.isEmpty(invoiceItem.get("invoiceItemSeqId"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory item sequence Id missing for invoice: " + currentInvoiceId); } if (UtilValidate.isEmpty(invoiceItem.get("invoiceItemTypeId"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory invoice item type missing for invoice: " + currentInvoiceId); } else if (EntityQuery.use(delegator).from("InvoiceItemType") .where("invoiceItemTypeId", invoiceItem.get("invoiceItemTypeId")) .queryOne() == null) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": InvoiceItem Item type id: " + invoiceItem.get("invoiceItemTypeId") + " not found for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId")); } if (UtilValidate.isEmpty(invoiceItem.get("productId")) && UtilValidate.isEmpty(invoiceItem.get("description"))) { } if (UtilValidate.isNotEmpty(invoiceItem.get("productId")) && EntityQuery.use(delegator).from("Product") .where("productId", invoiceItem.get("productId")).queryOne() == null) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Product Id: " + invoiceItem.get("productId") + " not found for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId")); } if (UtilValidate.isEmpty(invoiceItem.get("amount")) && UtilValidate.isEmpty(invoiceItem.get("quantity"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Either or both quantity and amount is required for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId")); } } catch (GenericEntityException e) { Debug.logError("Validation checking problem against database. due to " + e.getMessage(), module); } if (newErrMsgs.size() > 0) { errMsgs.addAll(newErrMsgs); } else { try { dispatcher.runSync("createInvoiceItem", invoiceItem); } catch (GenericServiceException e) { csvReader.close(); Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } } } } catch (IOException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (errMsgs.size() > 0) { return ServiceUtil.returnError(errMsgs); } Map<String, Object> result = ServiceUtil.returnSuccess(invoicesCreated + " new invoice(s) created"); result.put("organizationPartyId", organizationPartyId); return result; }
From source file:org.ofbiz.party.party.PartyServices.java
public static Map<String, Object> importParty(DispatchContext dctx, Map<String, Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); ByteBuffer fileBytes = (ByteBuffer) context.get("uploadedFile"); String encoding = System.getProperty("file.encoding"); String csvString = Charset.forName(encoding).decode(fileBytes).toString(); final BufferedReader csvReader = new BufferedReader(new StringReader(csvString)); CSVFormat fmt = CSVFormat.DEFAULT.withHeader(); List<String> errMsgs = FastList.newInstance(); List<String> newErrMsgs = FastList.newInstance(); String lastPartyId = null; // last partyId read from the csv file String currentPartyId = null; // current partyId from the csv file String newPartyId = null; // new to create/update partyId in the system String newCompanyPartyId = null; int partiesCreated = 0; Map<String, Object> result = null; String newContactMechId = null; String currentContactMechTypeId = null; String lastAddress1 = null;// w w w . j a v a 2 s . co m String lastAddress2 = null; String lastCity = null; String lastCountryGeoId = null; String lastEmailAddress = null; String lastCountryCode = null; String lastAreaCode = null; String lastContactNumber = null; String lastContactMechPurposeTypeId = null; String currentContactMechPurposeTypeId = null; Boolean addParty = false; // when modify party, contact mech not added again if (fileBytes == null) { return ServiceUtil.returnError("Uploaded file data not found"); } try { for (final CSVRecord rec : fmt.parse(csvReader)) { if (UtilValidate.isNotEmpty(rec.get("partyId"))) { currentPartyId = rec.get("partyId"); } if (lastPartyId == null || !currentPartyId.equals(lastPartyId)) { newPartyId = null; currentContactMechPurposeTypeId = null; lastAddress1 = null; lastAddress2 = null; lastCity = null; lastCountryGeoId = null; lastEmailAddress = null; lastCountryCode = null; lastAreaCode = null; lastContactNumber = null; // party validation List<GenericValue> currencyCheck = EntityQuery.use(delegator).from("Uom").where("abbreviation", rec.get("preferredCurrencyUomId"), "uomTypeId", "CURRENCY_MEASURE").queryList(); if (UtilValidate.isNotEmpty(rec.get("preferredCurrencyUomId")) && currencyCheck.size() == 0) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyId: " + currentPartyId + "Currency code not found for: " + rec.get("preferredCurrencyUomId")); } if (UtilValidate.isEmpty(rec.get("roleTypeId"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory roletype is missing, possible values: CUSTOMER, SUPPLIER, EMPLOYEE and more...."); } else if (EntityQuery.use(delegator).from("RoleType") .where("roleTypeId", rec.get("roleTypeId")).queryOne() == null) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": RoletypeId is not valid: " + rec.get("roleTypeId")); } if (UtilValidate.isNotEmpty(rec.get("contactMechTypeId")) && EntityQuery.use(delegator) .from("ContactMechType").where("contactMechTypeId", rec.get("contactMechTypeId")) .cache().queryOne() == null) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyId: " + currentPartyId + " contactMechTypeId code not found for: " + rec.get("contactMechTypeId")); } if (UtilValidate.isNotEmpty(rec.get("contactMechPurposeTypeId")) && EntityQuery.use(delegator).from("ContactMechPurposeType") .where("contactMechPurposeTypeId", rec.get("contactMechPurposeTypeId")).cache() .queryOne() == null) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyId: " + currentPartyId + "contactMechPurposeTypeId code not found for: " + rec.get("contactMechPurposeTypeId")); } if (UtilValidate.isNotEmpty(rec.get("contactMechTypeId")) && "POSTAL_ADDRESS".equals(rec.get("contactMechTypeId"))) { if (UtilValidate.isEmpty(rec.get("countryGeoId"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyId: " + currentPartyId + "Country code missing"); } else { List<GenericValue> countryCheck = EntityQuery.use(delegator).from("Geo") .where("geoTypeId", "COUNTRY", "abbreviation", rec.get("countryGeoId")) .queryList(); if (countryCheck.size() == 0) { newErrMsgs.add("Line number " + rec.getRecordNumber() + " partyId: " + currentPartyId + " Invalid Country code: " + rec.get("countryGeoId")); } } if (UtilValidate.isEmpty(rec.get("city"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + " partyId: " + currentPartyId + "City name is missing"); } if (UtilValidate.isNotEmpty(rec.get("stateProvinceGeoId"))) { List<GenericValue> stateCheck = EntityQuery.use(delegator).from("Geo") .where("geoTypeId", "STATE", "abbreviation", rec.get("stateProvinceGeoId")) .queryList(); if (stateCheck.size() == 0) { newErrMsgs .add("Line number " + rec.getRecordNumber() + " partyId: " + currentPartyId + " Invalid stateProvinceGeoId code: " + rec.get("countryGeoId")); } } } if (UtilValidate.isNotEmpty(rec.get("contactMechTypeId")) && "TELECOM_NUMBER".equals(rec.get("contactMechTypeId"))) { if (UtilValidate.isEmpty(rec.get("telAreaCode")) && UtilValidate.isEmpty(rec.get("telAreaCode"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + " partyId: " + currentPartyId + " telephone number missing"); } } if (UtilValidate.isNotEmpty(rec.get("contactMechTypeId")) && "EMAIL_ADDRESS".equals(rec.get("contactMechTypeId"))) { if (UtilValidate.isEmpty(rec.get("emailAddress"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + " partyId: " + currentPartyId + " email address missing"); } } if (errMsgs.size() == 0) { List<GenericValue> partyCheck = EntityQuery.use(delegator).from("PartyIdentification") .where("partyIdentificationTypeId", "PARTY_IMPORT", "idValue", rec.get("partyId")) .queryList(); addParty = partyCheck.size() == 0; if (!addParty) { // update party newPartyId = EntityUtil.getFirst(partyCheck).getString("partyId"); if (UtilValidate.isNotEmpty(rec.get("groupName"))) { Map<String, Object> partyGroup = UtilMisc.toMap("partyId", newPartyId, "preferredCurrencyUomId", rec.get("preferredCurrencyUomId"), "groupName", rec.get("groupName"), "userLogin", userLogin); result = dispatcher.runSync("updatePartyGroup", partyGroup); } else { // person Map<String, Object> person = UtilMisc.toMap("partyId", newPartyId, "firstName", rec.get("firstName"), "middleName", rec.get("midleName"), "lastName", rec.get("lastName"), "preferredCurrencyUomId", rec.get("preferredCurrencyUomId"), "userLogin", userLogin); result = dispatcher.runSync("updatePerson", person); } } else { // create new party if (UtilValidate.isNotEmpty(rec.get("groupName"))) { Map<String, Object> partyGroup = UtilMisc.toMap("preferredCurrencyUomId", rec.get("preferredCurrencyUomId"), "groupName", rec.get("groupName"), "userLogin", userLogin, "statusId", "PARTY_ENABLED"); result = dispatcher.runSync("createPartyGroup", partyGroup); } else { // person Map<String, Object> person = UtilMisc.toMap("firstName", rec.get("firstName"), "middleName", rec.get("midleName"), "lastName", rec.get("lastName"), "preferredCurrencyUomId", rec.get("preferredCurrencyUomId"), "statusId", "PARTY_ENABLED", "userLogin", userLogin); result = dispatcher.runSync("createPerson", person); } newPartyId = (String) result.get("partyId"); Map<String, Object> partyIdentification = UtilMisc.toMap("partyId", newPartyId, "partyIdentificationTypeId", "PARTY_IMPORT", "idValue", rec.get("partyId"), "userLogin", userLogin); result = dispatcher.runSync("createPartyIdentification", partyIdentification); Map<String, Object> partyRole = UtilMisc.toMap("partyId", newPartyId, "roleTypeId", rec.get("roleTypeId"), "userLogin", userLogin); dispatcher.runSync("createPartyRole", partyRole); if (UtilValidate.isNotEmpty(rec.get("companyPartyId"))) { List<GenericValue> companyCheck = EntityQuery.use(delegator) .from("PartyIdentification").where("partyIdentificationTypeId", "PARTY_IMPORT", "idValue", rec.get("partyId")) .queryList(); if (companyCheck.size() == 0) { // update party group // company does not exist so create Map<String, Object> companyPartyGroup = UtilMisc.toMap("partyId", newCompanyPartyId, "statusId", "PARTY_ENABLED", "userLogin", userLogin); result = dispatcher.runSync("createPartyGroup", companyPartyGroup); newCompanyPartyId = (String) result.get("partyId"); } else { newCompanyPartyId = EntityUtil.getFirst(companyCheck).getString("partyId"); } Map<String, Object> companyRole = UtilMisc.toMap("partyId", newCompanyPartyId, "roleTypeId", "ACCOUNT", "userLogin", userLogin); dispatcher.runSync("createPartyRole", companyRole); // company exist, so create link Map<String, Object> partyRelationship = UtilMisc.toMap("partyIdTo", newPartyId, "partyIdFrom", newCompanyPartyId, "roleTypeIdFrom", "ACCOUNT", "partyRelationshipTypeId", "EMPLOYMENT", "userLogin", userLogin); result = dispatcher.runSync("createPartyRelationship", partyRelationship); } } Debug.logInfo(" =========================================================party created id: " + newPartyId, module); partiesCreated++; } else { errMsgs.addAll(newErrMsgs); newErrMsgs = FastList.newInstance(); } } currentContactMechTypeId = rec.get("contactMechTypeId"); currentContactMechPurposeTypeId = rec.get("contactMechPurposeTypeId"); // party correctly created (not updated) and contactMechtype provided? if (newPartyId != null && addParty && UtilValidate.isNotEmpty(currentContactMechTypeId)) { // fill maps and check changes Map<String, Object> emailAddress = UtilMisc.toMap("contactMechTypeId", "EMAIL_ADDRESS", "userLogin", userLogin); Boolean emailAddressChanged = false; if ("EMAIL_ADDRESS".equals(currentContactMechTypeId)) { emailAddress.put("infoString", rec.get("emailAddress")); emailAddressChanged = lastEmailAddress == null || !lastEmailAddress.equals(rec.get("emailAddress")); lastEmailAddress = rec.get("emailAddress"); } Map<String, Object> postalAddress = UtilMisc.toMap("userLogin", (Object) userLogin); // casting is here necessary for some compiler versions Boolean postalAddressChanged = false; if ("POSTAL_ADDRESS".equals(currentContactMechTypeId)) { postalAddress.put("address1", rec.get("address1")); postalAddress.put("address2", rec.get("address2")); postalAddress.put("city", rec.get("city")); postalAddress.put("stateProvinceGeoId", rec.get("stateProvinceGeoId")); postalAddress.put("countryGeoId", rec.get("countryGeoId")); postalAddress.put("postalCode", rec.get("postalCode")); postalAddressChanged = lastAddress1 == null || !lastAddress1.equals(postalAddress.get("address1")) || lastAddress2 == null || !lastAddress2.equals(postalAddress.get("address2")) || lastCity == null || !lastCity.equals(postalAddress.get("city")) || lastCountryGeoId == null || !lastCountryGeoId.equals(postalAddress.get("countryGeoId")); lastAddress1 = (String) postalAddress.get("address1"); lastAddress2 = (String) postalAddress.get("address2"); lastCity = (String) postalAddress.get("city"); lastCountryGeoId = (String) postalAddress.get("countryGeoId"); } Map<String, Object> telecomNumber = UtilMisc.toMap("userLogin", (Object) userLogin); // casting is here necessary for some compiler versions Boolean telecomNumberChanged = false; if ("TELECOM_NUMBER".equals(currentContactMechTypeId)) { telecomNumber.put("countryCode", rec.get("telCountryCode")); telecomNumber.put("areaCode", rec.get("telAreaCode")); telecomNumber.put("contactNumber", rec.get("telContactNumber")); telecomNumberChanged = lastCountryCode == null || !lastCountryCode.equals(telecomNumber.get("countryCode")) || lastAreaCode == null || !lastAreaCode.equals(telecomNumber.get("areaCode")) || lastContactNumber == null || !lastContactNumber.equals(telecomNumber.get("contactNumber")); lastCountryCode = (String) telecomNumber.get("countryCode"); lastAreaCode = (String) telecomNumber.get("areaCode"); lastContactNumber = (String) telecomNumber.get("contactNumber"); } Map<String, Object> partyContactMechPurpose = UtilMisc.toMap("partyId", newPartyId, "userLogin", userLogin); Boolean partyContactMechPurposeChanged = false; currentContactMechPurposeTypeId = rec.get("contactMechPurposeTypeId"); if (currentContactMechPurposeTypeId != null && ("TELECOM_NUMBER".equals(currentContactMechTypeId) || "POSTAL_ADDRESS".equals(currentContactMechTypeId) || "EMAIL_ADDRESS".equals(currentContactMechTypeId))) { partyContactMechPurpose.put("contactMechPurposeTypeId", currentContactMechPurposeTypeId); partyContactMechPurposeChanged = (lastContactMechPurposeTypeId == null || !lastContactMechPurposeTypeId.equals(currentContactMechPurposeTypeId)) && !telecomNumberChanged && !postalAddressChanged && !emailAddressChanged; Debug.logInfo( "===================================last:" + lastContactMechPurposeTypeId + " current: " + currentContactMechPurposeTypeId + " t :" + telecomNumberChanged + " p: " + postalAddressChanged + " e: " + emailAddressChanged + " result: " + partyContactMechPurposeChanged, module); } lastContactMechPurposeTypeId = currentContactMechPurposeTypeId; // update if (errMsgs.size() == 0) { if (postalAddressChanged) { result = dispatcher.runSync("createPostalAddress", postalAddress); newContactMechId = (String) result.get("contactMechId"); if (currentContactMechPurposeTypeId == null) { currentContactMechPurposeTypeId = "GENERAL_LOCATION"; } dispatcher.runSync("createPartyContactMech", UtilMisc.toMap("partyId", newPartyId, "contactMechId", newContactMechId, "contactMechPurposeTypeId", currentContactMechPurposeTypeId, "userLogin", userLogin)); } if (telecomNumberChanged) { result = dispatcher.runSync("createTelecomNumber", telecomNumber); newContactMechId = (String) result.get("contactMechId"); if (currentContactMechPurposeTypeId == null) { currentContactMechPurposeTypeId = "PHONE_WORK"; } dispatcher.runSync("createPartyContactMech", UtilMisc.toMap("partyId", newPartyId, "contactMechId", newContactMechId, "contactMechPurposeTypeId", currentContactMechPurposeTypeId, "userLogin", userLogin)); } if (emailAddressChanged) { result = dispatcher.runSync("createContactMech", emailAddress); newContactMechId = (String) result.get("contactMechId"); if (currentContactMechPurposeTypeId == null) { currentContactMechPurposeTypeId = "PRIMARY_EMAIL"; } dispatcher.runSync("createPartyContactMech", UtilMisc.toMap("partyId", newPartyId, "contactMechId", newContactMechId, "contactMechPurposeTypeId", currentContactMechPurposeTypeId, "userLogin", userLogin)); } if (partyContactMechPurposeChanged) { partyContactMechPurpose.put("contactMechId", newContactMechId); result = dispatcher.runSync("createPartyContactMechPurpose", partyContactMechPurpose); } lastPartyId = currentPartyId; errMsgs.addAll(newErrMsgs); newErrMsgs = FastList.newInstance(); } } } } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } catch (IOException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (errMsgs.size() > 0) { return ServiceUtil.returnError(errMsgs); } result = ServiceUtil.returnSuccess(partiesCreated + " new parties created"); return result; }
From source file:org.onebusaway.admin.service.impl.BundleCheckParserServiceImpl.java
private BundleValidationParseResults parseRecord(CSVRecord record, BundleValidationParseResults parseResults) { // Verify that second field contains a valid test. if (record.size() < 2 || !validTests.contains(record.get(1).toLowerCase())) { BundleValidationParseError parseError = new BundleValidationParseError(); parseError.setLinenum((int) record.getRecordNumber()); parseError.setErrorMessage(PARSE_ERROR); parseError.setOffendingLine(record.toString()); parseResults.getParseErrors().add(parseError); return parseResults; }//from w w w . j av a 2 s .com ParsedBundleValidationCheck parsedCheck = new ParsedBundleValidationCheck(); parsedCheck.setLinenum((int) record.getRecordNumber()); parsedCheck.setAgencyId(record.get(0)); parsedCheck.setSpecificTest(record.get(1)); if (record.get(2) != null) { parsedCheck.setRouteName(record.get(2)); } if (record.get(3) != null) { parsedCheck.setRouteId(record.get(3)); } if (record.get(4) != null) { parsedCheck.setStopName(record.get(4)); } if (record.get(5) != null) { parsedCheck.setStopId(record.get(5)); } if (record.get(6) != null) { parsedCheck.setDate(record.get(6)); } if (record.get(7) != null) { parsedCheck.setDepartureTime(record.get(7)); } parseResults.getParsedBundleChecks().add(parsedCheck); return parseResults; }
From source file:org.seasr.meandre.components.transform.text.CSVTextToTokenCounts.java
@Override public void executeCallBack(ComponentContext cc) throws Exception { Hashtable<String, Integer> htCounts = new Hashtable<String, Integer>(); for (String text : DataTypeParser.parseAsString(cc.getDataComponentFromInput(IN_TEXT))) { // boolean skippedHeader = false; //String[][] data = ... .getAllValues(); // CSVParser parser = new CSVParser(new StringReader(text), strategy); // CSVParser parser = new CSVParser(new StringReader(text), format); // String[] tokens = uninitialisedLine; // while (tokens != null) { console.finer("received text:\n" + text + "\n"); for (CSVRecord tokens : format.parse(new StringReader(text))) { // tokens = parser.getLine(); // if (tokens == null) break; // if (bHeader && !skippedHeader) { // skippedHeader = true; // continue; // } // String token = tokens[tokenPos]; console.fine("processing row " + tokens.toString()); if (tokens.size() <= tokenPos || tokens.size() <= countPos) { console.warning(/*from w ww.jav a 2s .co m*/ String.format("csv row %d too short (%d) for count pos %d or token pos %d - discarding", tokens.getRecordNumber(), tokens.size(), countPos, tokenPos)); continue; } String token = tokens.get(tokenPos); int count = 0; try { count = Integer.parseInt(tokens.get(countPos)); } catch (NumberFormatException e) { console.warning(String.format("Token '%s' had malformed count '%s' - assigning zero!", token, tokens.get(countPos))); } if (htCounts.containsKey(token)) console.warning(String.format( "Token '%s' occurs more than once in the dataset - replacing previous count %d with %d...", token, htCounts.get(token), count)); htCounts.put(token, count); } } cc.pushDataComponentToOutput(OUT_TOKEN_COUNTS, BasicDataTypesTools.mapToIntegerMap(htCounts, bOrdered)); }
From source file:org.transitime.utils.csv.CsvBase.java
/** * Main constructor for when creating CSV object from a CSV file. * /*from www .j a va 2 s . c o m*/ * @param record * @param supplementalFile * @param fileName * for logging errors */ protected CsvBase(CSVRecord record, boolean supplementalFile, String fileName) { this.lineNumber = (int) record.getRecordNumber(); this.supplementalFileSoSomeRequiredItemsCanBeMissing = supplementalFile; this.fileName = fileName; }
From source file:org.transitime.utils.csv.CsvBaseReader.java
/** * Parse the CSV file. Reads in the header info and then each line. Calls * the abstract handleRecord() method for each record. Adds each resulting * CSV object to the gtfsObjecgts array. *//*from w w w . ja va 2s . c om*/ private void parse() { CSVRecord record = null; try { IntervalTimer timer = new IntervalTimer(); logger.debug("Parsing CSV file {} ...", fileName); // Open the file for reading. Use UTF-8 format since that will work // for both regular ASCII format and UTF-8 extended format files // since UTF-8 was designed to be backwards compatible with ASCII. // This way will work for Chinese and other character sets. Use // InputStreamReader so can specify that using UTF-8 format. Use // BufferedReader so that can determine if first character is an // optional BOM (Byte Order Mark) character used to indicate that // file is in UTF-8 format. BufferedReader allows us to read in // first character and then discard if it is a BOM character or // reset the reader to back to the beginning if it is not. This // way the CSV parser will process the file starting with the first // true character. Reader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8")); // Deal with the possible BOM character at the beginning of the file in.mark(1); int firstRead = in.read(); final int BOM_CHARACTER = 0xFEFF; if (firstRead != BOM_CHARACTER) in.reset(); // Get ready to parse the CSV file. // Allow lines to be comments if they start with "-" so that can // easily comment out problems and also test what happens when // certain data is missing. Using the '-' character so can // comment out line that starts with "--", which is what is // used for SQL. CSVFormat formatter = CSVFormat.DEFAULT.withHeader().withCommentMarker('-'); // Parse the file Iterable<CSVRecord> records = formatter.parse(in); logger.debug("Finished CSV parsing of file {}. Took {} msec.", fileName, timer.elapsedMsec()); int lineNumberWhenLogged = 0; timer = new IntervalTimer(); IntervalTimer loggingTimer = new IntervalTimer(); Iterator<CSVRecord> iterator = records.iterator(); while (iterator.hasNext()) { // Determine the record to process record = iterator.next(); // If blank line then skip it. This way avoid error messages since // expected data column won't exist if (record.size() == 0) continue; // Process the record using appropriate handler // and create the corresponding CSV object T gtfsObject; try { gtfsObject = handleRecord(record, supplemental); } catch (ParseException e) { logger.error("ParseException occurred for record {} " + "(comment lines not included when determing record #) for " + "filename {} . {}", record.getRecordNumber(), fileName, e.getMessage()); // Continue even though there was an error so that all errors // logged at once. continue; } catch (NumberFormatException e) { logger.error("NumberFormatException occurred for record {} " + "(comment lines not included when determing record #) " + "for filename {} . {}", record.getRecordNumber(), fileName, e.getMessage()); // Continue even though there was an error so that all errors // logged at once. continue; } // Add the newly created CSV object to the object list if (gtfsObject != null) gtfsObjects.add(gtfsObject); // Log info if it has been a while. Check only every 20,000 // lines to see if the 10 seconds has gone by. If so, then log // number of lines. By only looking at timer every 20,000 lines // not slowing things down by for every line doing system call // for to get current time. final int LINES_TO_PROCESS_BEFORE_CHECKING_IF_SHOULD_LOG = 20000; final long SECONDS_ELSAPSED_UNTIL_SHOULD_LOG = 5; if (record.getRecordNumber() >= lineNumberWhenLogged + LINES_TO_PROCESS_BEFORE_CHECKING_IF_SHOULD_LOG) { lineNumberWhenLogged = (int) record.getRecordNumber(); if (loggingTimer.elapsedMsec() > SECONDS_ELSAPSED_UNTIL_SHOULD_LOG * Time.MS_PER_SEC) { logger.info(" Processed {} lines. Took {} msec...", lineNumberWhenLogged, timer.elapsedMsec()); loggingTimer = new IntervalTimer(); } } } // End of while iterating over records // Close up the file reader in.close(); // Determine number of records for logging message long numberRecords = 0; if (record != null) numberRecords = record.getRecordNumber(); logger.info("Finished parsing {} records from file {} . Took {} msec.", numberRecords, fileName, timer.elapsedMsec()); } catch (FileNotFoundException e) { if (required) logger.error("Required CSV file {} not found.", fileName); else logger.info("CSV file {} not found but OK because this file " + "not required.", fileName); } catch (IOException e) { logger.error("IOException occurred when reading in filename {}.", fileName, e); } }