From c62e8bb68226041c46b75a735d0fd4c40a383d15 Mon Sep 17 00:00:00 2001 From: John Fereira Date: Tue, 16 Aug 2022 13:30:48 -0400 Subject: [PATCH 1/3] fix indenting --- .../java/org/olf/folio/order/OrderImport.java | 733 +++++++++--------- 1 file changed, 370 insertions(+), 363 deletions(-) diff --git a/src/main/java/org/olf/folio/order/OrderImport.java b/src/main/java/org/olf/folio/order/OrderImport.java index 33bef1e..0530a28 100644 --- a/src/main/java/org/olf/folio/order/OrderImport.java +++ b/src/main/java/org/olf/folio/order/OrderImport.java @@ -54,216 +54,219 @@ public class OrderImport { private ApiService apiService; MarcUtils marcUtils = new MarcUtils(); - public JSONArray upload(String fileName) throws IOException, InterruptedException, Exception { - long start = 0L; // to be used for timing - long end = 0L; // to be used for timing - logger.debug("...starting..."); - JSONArray responseMessages = new JSONArray(); - JSONArray errorMessages = new JSONArray(); - - //COLLECT VALUES FROM THE CONFIGURATION FILE - // TODO: Fix this typo everywhere... Should be baseOkapiEndpoint - this.baseOkapEndpoint = (String) getMyContext().getAttribute("baseOkapEndpoint"); - String apiUsername = (String) getMyContext().getAttribute("okapi_username"); - String apiPassword = (String) getMyContext().getAttribute("okapi_password"); - tenant = (String) getMyContext().getAttribute("tenant"); - // we might need this later to validate if resources are electronic...leave commented out - //String permELocationName = (String) getMyContext().getAttribute("permELocation"); - String noteTypeName = (String) getMyContext().getAttribute("noteType"); - String materialTypeName = (String) getMyContext().getAttribute("materialType"); - String billToDefault = (String) getMyContext().getAttribute("billToDefault"); - String billToApprovals = (String) getMyContext().getAttribute("billToApprovals"); - - JSONArray envErrors = validateEnvironment(); - if (envErrors != null) { - return envErrors; - } - - //GET THE FOLIO TOKEN - JSONObject jsonObject = new JSONObject(); - jsonObject.put("username", apiUsername); - jsonObject.put("password", apiPassword); - jsonObject.put("tenant",tenant); - - this.apiService = new ApiService(tenant); - this.token = this.apiService.callApiAuth( baseOkapEndpoint + "authn/login", jsonObject); - - //GET THE UPLOADED FILE - String filePath = (String) myContext.getAttribute("uploadFilePath"); - InputStream in = null; - //MAKE SURE A FILE WAS UPLOADED - InputStream is = null; - if (fileName != null) { - in = new FileInputStream(filePath + fileName); - } else { - JSONObject errorMessage = new JSONObject(); - errorMessage.put("error", "no input file provided"); - errorMessage.put("PONumber", "~error~"); - errorMessages.put(errorMessage); - return errorMessages; - } - - //READ THE MARC RECORD FROM THE FILE AND VALIDATE IT - //VALIDATES THE FUND CODE and VENDOR CODE DATA - // We don't want to continue if any of the marc records do not contain valid data - MarcReader reader = new MarcStreamReader(in); - - JSONArray validateRequiredResult = validateRequiredValues(reader); - if (!validateRequiredResult.isEmpty()) return validateRequiredResult; - - //SAVE REFERENCE TABLE VALUES (JUST LOOKUP THEM UP ONCE) - logger.debug("Get Lookup table"); - if (myContext.getAttribute(Constants.LOOKUP_TABLE) == null) { - LookupUtil lookupUtil = new LookupUtil(); - lookupUtil.setBaseOkapEndpoint(this.baseOkapEndpoint); - lookupUtil.setApiService(apiService); - lookupUtil.load(); - this.lookupTable = lookupUtil.getReferenceValues(this.token); - String billingEndpoint = this.baseOkapEndpoint+"configurations/entries?query=(configName==tenant.addresses)"; - this.billingMap = lookupUtil.getBillingAddresses(billingEndpoint, this.token); - myContext.setAttribute(Constants.LOOKUP_TABLE, lookupTable); - myContext.setAttribute(Constants.BILLINGMAP, billingMap); - - - logger.debug("put lookup table in context"); - } else { - this.lookupTable = (HashMap) myContext.getAttribute(Constants.LOOKUP_TABLE); - this.billingMap = (HashMap) myContext.getAttribute(Constants.BILLINGMAP); - logger.debug("got lookup table from context"); - } - String ISBNId = this.lookupTable.get("ISBN"); - String personalNameTypeId = this.lookupTable.get("Personal name"); - - - // READ THE MARC RECORD FROM THE FILE - in = new FileInputStream(filePath + fileName); - reader = new MarcStreamReader(in); - - // GENERATE UUID for the PO - - UUID orderUUID = UUID.randomUUID(); - String vendorCode = new String(); - - //GET THE NEXT PO NUMBER - logger.trace("get next PO number"); - String poNumber = this.apiService.callApiGet(baseOkapEndpoint + "orders/po-number", this.token); - JSONObject poNumberObj = new JSONObject(poNumber); - logger.trace("NEXT PO NUMBER: " + poNumberObj.get("poNumber")); - // does this have to be a UUID object? - - // CREATING THE PURCHASE ORDER - JSONObject order = new JSONObject(); - - order.put("orderType", "One-Time"); - order.put("reEncumber", false); - order.put("id", orderUUID.toString()); - order.put("approved", true); - order.put("workflowStatus", "Open"); - - JSONArray poLines = new JSONArray(); - - // map of records with orderline uuid as key - HashMap recordMap = new HashMap(); - - // iterator over records in the marc file. - - logger.debug("reading marc file"); - int numRec = 0; - - while (reader.hasNext()) { - try { - Record record = reader.next(); - //logger.debug(record.toString()); - - DataField twoFourFive = (DataField) record.getVariableField("245"); - DataField nineEighty = (DataField) record.getVariableField("980"); - DataField nineFiveTwo = (DataField) record.getVariableField("952"); - DataField nineEightyOne = (DataField) record.getVariableField("981"); - DataField nineSixtyOne = (DataField) record.getVariableField("961"); - DataField twoSixtyFour = (DataField) record.getVariableField("264"); - - String title = marcUtils.getTitle(twoFourFive); - String fundCode = marcUtils.getFundCode(nineEighty); - // vendor code instantiated outside of loop because it will be the same for all orderLines and added to response later - vendorCode = marcUtils.getVendorCode(nineEighty); - - String quantity = marcUtils.getQuantity(nineEighty); - Integer quantityNo = 0; //INIT - if (quantity != null) quantityNo = Integer.valueOf(quantity); - - String price = marcUtils.getPrice(nineEightyOne); - String vendorItemId = marcUtils.getVendorItemId(nineSixtyOne); - String locationName = marcUtils.getLocation(nineFiveTwo); - - - // LOOK UP THE ORGANIZATION (vendor) again! - // TODO: Refactor validateRequiredValues() to store org & fund IDs and avoid redundant HTTP requests - //logger.debug("lookupVendor"); - try { - // URL encode organization code to avoid cql parse error on forward slash - String encodedOrgCode = URLEncoder.encode("\"" + vendorCode + "\"", StandardCharsets.UTF_8.name()); - logger.debug("encodedOrgCode: " + encodedOrgCode); - - String organizationEndpoint = baseOkapEndpoint - + "organizations-storage/organizations?query=(code==" + encodedOrgCode + ")"; - logger.debug("organizationEndpoint: " + organizationEndpoint); - String orgLookupResponse = apiService.callApiGet(organizationEndpoint, this.token); - JSONObject orgObject = new JSONObject(orgLookupResponse); - String vendorId = (String) orgObject.getJSONArray("organizations").getJSONObject(0).get("id"); - order.put("vendor", vendorId); - } catch (UnsupportedEncodingException e) { - logger.error(e.getMessage()); - } + public JSONArray upload(String fileName) throws IOException, InterruptedException, Exception { + long start = 0L; // to be used for timing + long end = 0L; // to be used for timing + logger.debug("...starting..."); + JSONArray responseMessages = new JSONArray(); + JSONArray errorMessages = new JSONArray(); + + // COLLECT VALUES FROM THE CONFIGURATION FILE + // TODO: Fix this typo everywhere... Should be baseOkapiEndpoint + this.baseOkapEndpoint = (String) getMyContext().getAttribute("baseOkapEndpoint"); + String apiUsername = (String) getMyContext().getAttribute("okapi_username"); + String apiPassword = (String) getMyContext().getAttribute("okapi_password"); + tenant = (String) getMyContext().getAttribute("tenant"); + // we might need this later to validate if resources are electronic...leave + // commented out + // String permELocationName = (String) + // getMyContext().getAttribute("permELocation"); + String noteTypeName = (String) getMyContext().getAttribute("noteType"); + String materialTypeName = (String) getMyContext().getAttribute("materialType"); + String billToDefault = (String) getMyContext().getAttribute("billToDefault"); + String billToApprovals = (String) getMyContext().getAttribute("billToApprovals"); + + JSONArray envErrors = validateEnvironment(); + if (envErrors != null) { + return envErrors; + } + + // GET THE FOLIO TOKEN + JSONObject jsonObject = new JSONObject(); + jsonObject.put("username", apiUsername); + jsonObject.put("password", apiPassword); + jsonObject.put("tenant", tenant); - // Determine billTo/shipTo address - String recordSource = marcUtils.getRecordSource(record); - String billingUUID = new String(); - if (recordSource.equals("appr")) { - billingUUID = this.billingMap.get(billToApprovals); + this.apiService = new ApiService(tenant); + this.token = this.apiService.callApiAuth(baseOkapEndpoint + "authn/login", jsonObject); + + // GET THE UPLOADED FILE + String filePath = (String) myContext.getAttribute("uploadFilePath"); + InputStream in = null; + // MAKE SURE A FILE WAS UPLOADED + InputStream is = null; + if (fileName != null) { + in = new FileInputStream(filePath + fileName); } else { - billingUUID = this.billingMap.get(billToDefault); + JSONObject errorMessage = new JSONObject(); + errorMessage.put("error", "no input file provided"); + errorMessage.put("PONumber", "~error~"); + errorMessages.put(errorMessage); + return errorMessages; } - order.put("billTo", billingUUID); - order.put("shipTo", billingUUID); - - //LOOK UP THE FUND - //logger.debug("lookup Fund"); - String fundEndpoint = baseOkapEndpoint + "finance/funds?limit=30&offset=0&query=((code='" + fundCode + "'))"; - String fundResponse = this.apiService.callApiGet(fundEndpoint, token); - JSONObject fundsObject = new JSONObject(fundResponse); - String fundId = (String) fundsObject.getJSONArray("funds").getJSONObject(0).get("id"); - - //LOOK UP THE Acquisiton method - //logger.debug("lookup acquisition method"); - String acquistionMethodString = "Purchase"; - String acquisitionMethodUUID = getAcquisitionMethodUUID(acquistionMethodString); - // CREATING THE PURCHASE ORDER - - - // POST ORDER LINE - // FOLIO Orders app will create the Instance and Holdings - JSONObject orderLine = new JSONObject(); - JSONObject cost = new JSONObject(); - JSONObject location = new JSONObject(); - JSONArray locations = new JSONArray(); - - // all items are assumed to be physical - JSONObject physical = new JSONObject(); - // Item will be created afterwards via mod-copycat) - physical.put("createInventory", "Instance, Holding"); - physical.put("materialType", lookupTable.get(materialTypeName)); - orderLine.put("physical", physical); - orderLine.put("orderFormat", "Physical Resource"); - cost.put("listUnitPrice", price); - cost.put("quantityPhysical", quantityNo); - location.put("quantityPhysical", quantityNo); - location.put("locationId", lookupTable.get(locationName + "-location")); - locations.put(location); - - - // as of IRIS release vendorDetail is slightly more complex - if (StringUtils.isNotEmpty(vendorItemId)) { + // READ THE MARC RECORD FROM THE FILE AND VALIDATE IT + // VALIDATES THE FUND CODE and VENDOR CODE DATA + // We don't want to continue if any of the marc records do not contain valid + // data + MarcReader reader = new MarcStreamReader(in); + + JSONArray validateRequiredResult = validateRequiredValues(reader); + if (!validateRequiredResult.isEmpty()) + return validateRequiredResult; + + // SAVE REFERENCE TABLE VALUES (JUST LOOKUP THEM UP ONCE) + logger.debug("Get Lookup table"); + if (myContext.getAttribute(Constants.LOOKUP_TABLE) == null) { + LookupUtil lookupUtil = new LookupUtil(); + lookupUtil.setBaseOkapEndpoint(this.baseOkapEndpoint); + lookupUtil.setApiService(apiService); + lookupUtil.load(); + this.lookupTable = lookupUtil.getReferenceValues(this.token); + String billingEndpoint = this.baseOkapEndpoint + + "configurations/entries?query=(configName==tenant.addresses)"; + this.billingMap = lookupUtil.getBillingAddresses(billingEndpoint, this.token); + myContext.setAttribute(Constants.LOOKUP_TABLE, lookupTable); + myContext.setAttribute(Constants.BILLINGMAP, billingMap); + + logger.debug("put lookup table in context"); + } else { + this.lookupTable = (HashMap) myContext.getAttribute(Constants.LOOKUP_TABLE); + this.billingMap = (HashMap) myContext.getAttribute(Constants.BILLINGMAP); + logger.debug("got lookup table from context"); + } + String ISBNId = this.lookupTable.get("ISBN"); + String personalNameTypeId = this.lookupTable.get("Personal name"); + + // READ THE MARC RECORD FROM THE FILE + in = new FileInputStream(filePath + fileName); + reader = new MarcStreamReader(in); + + // GENERATE UUID for the PO + + UUID orderUUID = UUID.randomUUID(); + String vendorCode = new String(); + + // GET THE NEXT PO NUMBER + logger.trace("get next PO number"); + String poNumber = this.apiService.callApiGet(baseOkapEndpoint + "orders/po-number", this.token); + JSONObject poNumberObj = new JSONObject(poNumber); + logger.trace("NEXT PO NUMBER: " + poNumberObj.get("poNumber")); + + // CREATING THE PURCHASE ORDER + JSONObject order = new JSONObject(); + + order.put("orderType", "One-Time"); + order.put("reEncumber", false); + order.put("id", orderUUID.toString()); + order.put("approved", true); + order.put("workflowStatus", "Open"); + + JSONArray poLines = new JSONArray(); + + // map of records with orderline uuid as key + HashMap recordMap = new HashMap(); + + // iterator over records in the marc file. + + logger.debug("reading marc file"); + int numRec = 0; + + while (reader.hasNext()) { + try { + Record record = reader.next(); + // logger.debug(record.toString()); + + DataField twoFourFive = (DataField) record.getVariableField("245"); + DataField nineEighty = (DataField) record.getVariableField("980"); + DataField nineFiveTwo = (DataField) record.getVariableField("952"); + DataField nineEightyOne = (DataField) record.getVariableField("981"); + DataField nineSixtyOne = (DataField) record.getVariableField("961"); + DataField twoSixtyFour = (DataField) record.getVariableField("264"); + + String title = marcUtils.getTitle(twoFourFive); + String fundCode = marcUtils.getFundCode(nineEighty); + // vendor code instantiated outside of loop because it will be the same for all + // orderLines and added to response later + vendorCode = marcUtils.getVendorCode(nineEighty); + + String quantity = marcUtils.getQuantity(nineEighty); + Integer quantityNo = 0; // INIT + if (quantity != null) + quantityNo = Integer.valueOf(quantity); + + String price = marcUtils.getPrice(nineEightyOne); + String vendorItemId = marcUtils.getVendorItemId(nineSixtyOne); + String locationName = marcUtils.getLocation(nineFiveTwo); + + // LOOK UP THE ORGANIZATION (vendor) again! + // TODO: Refactor validateRequiredValues() to store org & fund IDs and avoid + // redundant HTTP requests + // logger.debug("lookupVendor"); + try { + // URL encode organization code to avoid cql parse error on forward slash + String encodedOrgCode = URLEncoder.encode("\"" + vendorCode + "\"", StandardCharsets.UTF_8.name()); + logger.debug("encodedOrgCode: " + encodedOrgCode); + + String organizationEndpoint = baseOkapEndpoint + "organizations-storage/organizations?query=(code==" + + encodedOrgCode + ")"; + logger.debug("organizationEndpoint: " + organizationEndpoint); + String orgLookupResponse = apiService.callApiGet(organizationEndpoint, this.token); + JSONObject orgObject = new JSONObject(orgLookupResponse); + String vendorId = (String) orgObject.getJSONArray("organizations").getJSONObject(0).get("id"); + order.put("vendor", vendorId); + } catch (UnsupportedEncodingException e) { + logger.error(e.getMessage()); + } + + // Determine billTo/shipTo address + String recordSource = marcUtils.getRecordSource(record); + String billingUUID = new String(); + if (recordSource.equals("appr")) { + billingUUID = this.billingMap.get(billToApprovals); + } else { + billingUUID = this.billingMap.get(billToDefault); + } + order.put("billTo", billingUUID); + order.put("shipTo", billingUUID); + + // LOOK UP THE FUND + // logger.debug("lookup Fund"); + String fundEndpoint = baseOkapEndpoint + "finance/funds?limit=30&offset=0&query=((code='" + fundCode + + "'))"; + String fundResponse = this.apiService.callApiGet(fundEndpoint, token); + JSONObject fundsObject = new JSONObject(fundResponse); + String fundId = (String) fundsObject.getJSONArray("funds").getJSONObject(0).get("id"); + + // LOOK UP THE Acquisiton method + // logger.debug("lookup acquisition method"); + String acquistionMethodString = "Purchase"; + String acquisitionMethodUUID = getAcquisitionMethodUUID(acquistionMethodString); + + // CREATING THE PURCHASE ORDER + + // POST ORDER LINE + // FOLIO Orders app will create the Instance and Holdings + JSONObject orderLine = new JSONObject(); + JSONObject cost = new JSONObject(); + JSONObject location = new JSONObject(); + JSONArray locations = new JSONArray(); + + // all items are assumed to be physical + JSONObject physical = new JSONObject(); + // Item will be created afterwards via mod-copycat) + physical.put("createInventory", "Instance, Holding"); + physical.put("materialType", lookupTable.get(materialTypeName)); + orderLine.put("physical", physical); + orderLine.put("orderFormat", "Physical Resource"); + cost.put("listUnitPrice", price); + cost.put("quantityPhysical", quantityNo); + location.put("quantityPhysical", quantityNo); + location.put("locationId", lookupTable.get(locationName + "-location")); + locations.put(location); + + // as of IRIS release vendorDetail is slightly more complex + if (StringUtils.isNotEmpty(vendorItemId)) { JSONArray referenceNumbers = new JSONArray(); JSONObject vendorDetail = new JSONObject(); vendorDetail.put("instructions", ""); // required element, even if empty @@ -275,36 +278,36 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept vendorDetail.put("referenceNumbers", referenceNumbers); orderLine.put("vendorDetail", vendorDetail); } - - UUID orderLineUUID = UUID.randomUUID(); - // save the record - recordMap.put(orderLineUUID.toString(), record); - orderLine.put("id", orderLineUUID); - orderLine.put("source", "User"); - cost.put("currency", "USD"); // TODO: get this from marc or use an env variable - orderLine.put("cost", cost); - orderLine.put("locations", locations); - orderLine.put("titleOrPackage", title); - //orderLine.put("acquisitionMethod", "Purchase"); - orderLine.put("acquisitionMethod", acquisitionMethodUUID); - - // get the "internal note", which apparently will be used as a description - String internalNotes = marcUtils.getInternalNotes(nineEighty); - if (StringUtils.isNotEmpty(internalNotes)) { - orderLine.put("description", internalNotes); - } - - // add a detailsObject if a receiving note or ISBN identifiers are found + + UUID orderLineUUID = UUID.randomUUID(); + // save the record + recordMap.put(orderLineUUID.toString(), record); + orderLine.put("id", orderLineUUID); + orderLine.put("source", "User"); + cost.put("currency", "USD"); // TODO: get this from marc or use an env variable + orderLine.put("cost", cost); + orderLine.put("locations", locations); + orderLine.put("titleOrPackage", title); + // orderLine.put("acquisitionMethod", "Purchase"); + orderLine.put("acquisitionMethod", acquisitionMethodUUID); + + // get the "internal note", which apparently will be used as a description + String internalNotes = marcUtils.getInternalNotes(nineEighty); + if (StringUtils.isNotEmpty(internalNotes)) { + orderLine.put("description", internalNotes); + } + + // add a detailsObject if a receiving note or ISBN identifiers are found JSONObject detailsObject = new JSONObject(); - - // get ISBN values in a productIds array and add to detailsObject if not empty + + // get ISBN values in a productIds array and add to detailsObject if not empty JSONArray productIds = new JSONArray(); JSONArray identifiers = marcUtils.buildIdentifiers(record, lookupTable); Iterator identIter = identifiers.iterator(); while (identIter.hasNext()) { JSONObject identifierObj = (JSONObject) identIter.next(); String identifierType = identifierObj.getString("identifierTypeId"); - String oldVal = identifierObj.getString("value"); + String oldVal = identifierObj.getString("value"); JSONObject productId = new JSONObject(); String newVal = StringUtils.substringBefore(oldVal, " "); String qualifier = StringUtils.substringAfter(oldVal, " "); @@ -313,28 +316,27 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept if (StringUtils.isNotEmpty(qualifier)) { productId.put("qualifier", qualifier); } - productIds.put(productId); - + productIds.put(productId); + } if (productIds.length() > 0) { logger.debug(productIds.toString(3)); detailsObject.put("productIds", productIds); } - + // get the "receiving note" - String receivingNote = marcUtils.getReceivingNote(nineEightyOne); + String receivingNote = marcUtils.getReceivingNote(nineEightyOne); if (StringUtils.isNotEmpty(receivingNote)) { detailsObject.put("receivingNote", receivingNote); } - - if (! detailsObject.isEmpty()) { - orderLine.put("details", detailsObject); + + if (!detailsObject.isEmpty()) { + orderLine.put("details", detailsObject); } - - + // add contributors JSONArray contribArray = new JSONArray(); - + JSONArray contributors = marcUtils.buildContributors(record, lookupTable); Iterator contribIter = contributors.iterator(); while (contribIter.hasNext()) { @@ -348,46 +350,45 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept orderLine.put("contributors", contribArray); logger.debug(contribArray.toString(3)); } - - // get rush value - String rush = marcUtils.getRush(nineEightyOne); - // TODO: check if match rush value to ;Rush:yes before adding to orderLine + + // get rush value + String rush = marcUtils.getRush(nineEightyOne); + // TODO: check if match rush value to ;Rush:yes before adding to orderLine if (StringUtils.isNotEmpty(rush) && StringUtils.contains(rush.toLowerCase(), "rush:yes")) { orderLine.put("rush", true); } - // get selector - String selector = marcUtils.getSelector(nineEighty); - if (StringUtils.isNotEmpty(selector)) { - orderLine.put("selector", selector); - } - - // add publisher and publicationDate + // get selector + String selector = marcUtils.getSelector(nineEighty); + if (StringUtils.isNotEmpty(selector)) { + orderLine.put("selector", selector); + } + + // add publisher and publicationDate String publisher = marcUtils.getPublisher(record); if (StringUtils.isNotEmpty(publisher)) { orderLine.put("publisher", publisher); } - + if (twoSixtyFour != null) { String pubYear = marcUtils.getPublicationDate(twoSixtyFour); - if (StringUtils.isNotEmpty(pubYear)) { + if (StringUtils.isNotEmpty(pubYear)) { orderLine.put("publicationDate", pubYear); } } - - - // add fund distribution info - JSONArray funds = new JSONArray(); - JSONObject fundDist = new JSONObject(); - fundDist.put("code", fundCode); - fundDist.put("fundId", fundId); - fundDist.put("expenseClassId", Constants.EXPENSE_CLASS); - fundDist.put("distributionType", "percentage"); - fundDist.put("value", 100); - funds.put(fundDist); - orderLine.put("fundDistribution", funds); - - // get requester + + // add fund distribution info + JSONArray funds = new JSONArray(); + JSONObject fundDist = new JSONObject(); + fundDist.put("code", fundCode); + fundDist.put("fundId", fundId); + fundDist.put("expenseClassId", Constants.EXPENSE_CLASS); + fundDist.put("distributionType", "percentage"); + fundDist.put("value", 100); + funds.put(fundDist); + orderLine.put("fundDistribution", funds); + + // get requester String requester = marcUtils.getRequester(nineEightyOne); if (StringUtils.isNotEmpty(requester)) { orderLine.put("requester", requester); @@ -397,52 +398,53 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept // if rushPO is ever set, prefix the poNumber with "RUSH" if (rushPO) { order.put("poNumberPrefix", "RUSH"); - order.put("poNumber", "RUSH"+ poNumberObj.get("poNumber")); + order.put("poNumber", "RUSH" + poNumberObj.get("poNumber")); } else { order.put("poNumber", poNumberObj.get("poNumber")); } - orderLine.put("purchaseOrderId", orderUUID.toString()); - poLines.put(orderLine); - order.put("compositePoLines", poLines); - - } catch(Exception e) { - logger.error(e.toString()); - JSONObject errorMessage = new JSONObject(); - errorMessage.put("error",e.toString()); - errorMessage.put("PONumber", poNumber); - errorMessages.put(errorMessage); - return errorMessages; - } - numRec++; - } - - logger.debug("Here is the PO, order number: "+ poNumberObj.get("poNumber")); - logger.debug(order.toString(3)); - - //POST THE ORDER AND LINE: - String orderResponse = apiService.callApiPostWithUtf8(this.baseOkapEndpoint + "orders/composite-orders", order, this.token); - - - //GET THE UPDATED PURCHASE ORDER FROM THE API AND PULL OUT THE ID FOR THE INSTANCE FOLIO CREATED: - logger.debug("getUpdatedPurchaseOrder"); - String updatedPurchaseOrder = apiService.callApiGet(this.baseOkapEndpoint + "orders/composite-orders/" +orderUUID.toString() ,this.token); - JSONObject updatedPurchaseOrderJson = new JSONObject(updatedPurchaseOrder); - logger.info("updated purchase order..."); - logger.info(updatedPurchaseOrderJson.toString(3)); - - - numRec = 0; + orderLine.put("purchaseOrderId", orderUUID.toString()); + poLines.put(orderLine); + order.put("compositePoLines", poLines); + + } catch (Exception e) { + logger.error(e.toString()); + JSONObject errorMessage = new JSONObject(); + errorMessage.put("error", e.toString()); + errorMessage.put("PONumber", poNumber); + errorMessages.put(errorMessage); + return errorMessages; + } + numRec++; + } + + logger.debug("Here is the PO, order number: " + poNumberObj.get("poNumber")); + logger.debug(order.toString(3)); + + // POST THE ORDER AND LINE: + String orderResponse = apiService.callApiPostWithUtf8(this.baseOkapEndpoint + "orders/composite-orders", order, + this.token); + + // GET THE UPDATED PURCHASE ORDER FROM THE API AND PULL OUT THE ID FOR THE + // INSTANCE FOLIO CREATED: + logger.debug("getUpdatedPurchaseOrder"); + String updatedPurchaseOrder = apiService + .callApiGet(this.baseOkapEndpoint + "orders/composite-orders/" + orderUUID.toString(), this.token); + JSONObject updatedPurchaseOrderJson = new JSONObject(updatedPurchaseOrder); + logger.info("updated purchase order..."); + logger.info(updatedPurchaseOrderJson.toString(3)); + + numRec = 0; start = System.currentTimeMillis(); Iterator poLineIterator = updatedPurchaseOrderJson.getJSONArray("compositePoLines").iterator(); - - while (poLineIterator.hasNext()) { + + while (poLineIterator.hasNext()) { JSONObject poLineObject = (JSONObject) poLineIterator.next(); - try { - - JSONObject responseMessage = new JSONObject(); + try { + + JSONObject responseMessage = new JSONObject(); responseMessage.put("poNumber", updatedPurchaseOrderJson.getString("poNumber")); - responseMessage.put("poUUID", orderUUID.toString()); - + responseMessage.put("poUUID", orderUUID.toString()); + String poLineUUID = poLineObject.getString("id"); String poLineNumber = poLineObject.getString("poLineNumber"); String instanceId = poLineObject.getString("instanceId"); @@ -450,15 +452,15 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept String requester = poLineObject.optString("requester"); String internalNote = poLineObject.optString("description"); JSONObject polDetails = poLineObject.optJSONObject("details"); - + Record record = recordMap.get(poLineUUID); - + List isbnList = new ArrayList(); - String receivingNote = null; - - if (polDetails != null) { - JSONArray polProductIds = polDetails.optJSONArray("productIds"); - receivingNote = polDetails.optString("receivingNote"); + String receivingNote = null; + + if (polDetails != null) { + JSONArray polProductIds = polDetails.optJSONArray("productIds"); + receivingNote = polDetails.optString("receivingNote"); // Extract ISBNs from POL productIds to display in results Iterator isbnIterator = polProductIds.iterator(); @@ -466,36 +468,38 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept JSONObject productIdObj = (JSONObject) isbnIterator.next(); isbnList.add((String) productIdObj.get("productId")); } - } + } - String holdings = apiService.callApiGet(baseOkapEndpoint + "holdings-storage/holdings?limit=0&query=(instanceId==" + instanceId + ")", token); - JSONObject holdingsJson = new JSONObject(holdings); - int holdingsCount = (int) holdingsJson.get("totalRecords"); - - responseMessage.put("poLineUUID", poLineUUID); - responseMessage.put("poLineNumber", poLineNumber); - responseMessage.put("holdingsCount", holdingsCount); - responseMessage.put("title", title); - responseMessage.put("requester", requester); - responseMessage.put("internalNote", internalNote); - responseMessage.put("receivingNote", receivingNote); - responseMessage.put("vendorCode", vendorCode); - responseMessage.put("isbn", isbnList); - - - - // add 490 and 830 raw marc fields as a list to response - List seriesFields = marcUtils.getSeriesFields(record); - if (seriesFields.size() > 0) { - responseMessage.put("seriesFields", seriesFields); - } - - // Get the Inventory Instance FOLIO created, so we can render the Instance HRID in the results - logger.debug("get InstanceResponse"); - String instanceResponse = apiService.callApiGet(this.baseOkapEndpoint + "inventory/instances/" + instanceId, this.token); - JSONObject instanceAsJson = new JSONObject(instanceResponse); - logger.debug(instanceAsJson.toString(3)); - String hrid = instanceAsJson.getString("hrid"); + String holdings = apiService.callApiGet( + baseOkapEndpoint + "holdings-storage/holdings?limit=0&query=(instanceId==" + instanceId + ")", + token); + JSONObject holdingsJson = new JSONObject(holdings); + int holdingsCount = (int) holdingsJson.get("totalRecords"); + + responseMessage.put("poLineUUID", poLineUUID); + responseMessage.put("poLineNumber", poLineNumber); + responseMessage.put("holdingsCount", holdingsCount); + responseMessage.put("title", title); + responseMessage.put("requester", requester); + responseMessage.put("internalNote", internalNote); + responseMessage.put("receivingNote", receivingNote); + responseMessage.put("vendorCode", vendorCode); + responseMessage.put("isbn", isbnList); + + // add 490 and 830 raw marc fields as a list to response + List seriesFields = marcUtils.getSeriesFields(record); + if (seriesFields.size() > 0) { + responseMessage.put("seriesFields", seriesFields); + } + + // Get the Inventory Instance FOLIO created, so we can render the Instance HRID + // in the results + logger.debug("get InstanceResponse"); + String instanceResponse = apiService + .callApiGet(this.baseOkapEndpoint + "inventory/instances/" + instanceId, this.token); + JSONObject instanceAsJson = new JSONObject(instanceResponse); + logger.debug(instanceAsJson.toString(3)); + String hrid = instanceAsJson.getString("hrid"); responseMessage.put("instanceHrid", hrid); responseMessage.put("instanceUUID", instanceId); @@ -511,7 +515,8 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept logger.info("DIFF (MINS): " + duration.toMinutes()); logger.info(getMyContext().getAttribute("baseFolioUrl") + "inventory/view/" + instanceId); - // Only proceed with overlay of instance (and holdings & item creation) if instance is newly created + // Only proceed with overlay of instance (and holdings & item creation) if + // instance is newly created // -- consider newly created within the last hour if (duration.toHours() < 1) { // Transform the MARC record into JSON @@ -530,7 +535,8 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept copycatImportObject.put("profileId", Constants.COPYCAT_DEFAULT_PROFILE); copycatImportObject.put("record", marcJsonObject); - // get barcode from 976$p, if it exists, switch to shelf-ready mod-copycat profile + // get barcode from 976$p, if it exists, switch to shelf-ready mod-copycat + // profile DataField nineSevenSix = (DataField) record.getVariableField("976"); String barcode = marcUtils.getBarcode(nineSevenSix); if (StringUtils.isNotEmpty(barcode)) { @@ -539,29 +545,30 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept // Overlay/Update Inventory Instance & Holding via mod-copycat logger.debug("post copycatImportObject"); - String copycatResponse = apiService.callApiPostWithUtf8(this.baseOkapEndpoint + "copycat/imports", copycatImportObject, this.token); + String copycatResponse = apiService.callApiPostWithUtf8(this.baseOkapEndpoint + "copycat/imports", + copycatImportObject, this.token); } - - responseMessages.put(responseMessage); - numRec++; - - } catch(Exception e) { - e.printStackTrace(); - logger.error(e.toString()); - JSONObject errorMessage = new JSONObject(); - errorMessage.put("error", e.toString()); - errorMessage.put("PONumber", poNumberObj.get("poNumber")); - errorMessages.put(errorMessage); - return errorMessages; - } - - } - logger.info("Number of records: "+ numRec); - logger.info(responseMessages.toString(3)); - return responseMessages; + responseMessages.put(responseMessage); + numRec++; - } + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.toString()); + JSONObject errorMessage = new JSONObject(); + errorMessage.put("error", e.toString()); + errorMessage.put("PONumber", poNumberObj.get("poNumber")); + errorMessages.put(errorMessage); + return errorMessages; + } + + } + + logger.info("Number of records: " + numRec); + logger.info(responseMessages.toString(3)); + return responseMessages; + + } // this method validates required values and will return a JSONArray with error messages or an empty array if it passes From 33a38928e4026657b9c6739512441e105b63df72 Mon Sep 17 00:00:00 2001 From: John Fereira Date: Tue, 16 Aug 2022 13:31:15 -0400 Subject: [PATCH 2/3] return exception on invalid price data --- .../org/olf/folio/order/util/MarcUtils.java | 32 +++++++++++-------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/olf/folio/order/util/MarcUtils.java b/src/main/java/org/olf/folio/order/util/MarcUtils.java index 5ee3c57..06f3804 100644 --- a/src/main/java/org/olf/folio/order/util/MarcUtils.java +++ b/src/main/java/org/olf/folio/order/util/MarcUtils.java @@ -15,6 +15,7 @@ import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; import org.json.JSONObject; +import org.marc4j.MarcException; import org.marc4j.MarcJsonWriter; import org.marc4j.marc.DataField; import org.marc4j.marc.MarcFactory; @@ -76,19 +77,22 @@ public String getTitle(DataField twoFourFive) { * @param nineEightyOne * @return */ - public String getPrice(DataField nineEightyOne) { + public String getPrice(DataField nineEightyOne) throws Exception { String price = new String(); if (nineEightyOne != null) { price = nineEightyOne.getSubfieldsAsString(PRICE); if (price == null) { - price = "0.00"; + throw new MarcException("Price missing from NineEightyOne field"); } else { - return normalizePrice(price); + try { + return normalizePrice(price); + } catch (Exception e) { + throw e; + } } } else { - price = "0.00"; - } - return price; + throw new MarcException("price (981$i) field missing"); + } } public String getQuantity(DataField nineEighty ) { @@ -432,14 +436,14 @@ public List getSeriesFields(Record record) { return seriesFields; } - public String normalizePrice(String priceStr) { - try { - double f = Double.parseDouble(priceStr); - return String.format("%.2f", new BigDecimal(f)); - } catch (NumberFormatException e) { - return "0.00"; - } - } + public String normalizePrice(String priceStr) throws NumberFormatException { + try { + double f = Double.parseDouble(priceStr); + return String.format("%.2f", new BigDecimal(f)); + } catch (NumberFormatException e) { + throw new NumberFormatException("Price format is invalid. price is: "+ priceStr); + } + } public String matchYear(String pubDate) { String year = new String(); From a37e13c2992ecbae41db16dd8f1459808b522d16 Mon Sep 17 00:00:00 2001 From: John Fereira Date: Tue, 16 Aug 2022 13:31:48 -0400 Subject: [PATCH 3/3] restore tests with data that was reverted from merge --- .../folio/order/services/GetBudgetTest.java | 69 ++++++++---- .../folio/order/services/GetFundCodeTest.java | 42 +++++--- .../folio/order/services/GetHoldingsTest.java | 26 ++--- .../order/services/GetOrganizationsTest.java | 33 +++--- .../order/util/LookupUtilMaterialsTest.java | 2 +- .../folio/order/util/LookupUtilNoteTest.java | 2 +- .../folio/order/util/MarcUtilsPriceTest.java | 102 +++++++++++++----- .../util/MarcUtilsPublicationDateTest.java | 10 +- .../order/util/MarcUtilsSeriesFieldsTest.java | 2 +- 9 files changed, 196 insertions(+), 92 deletions(-) diff --git a/src/test/java/org/olf/folio/order/services/GetBudgetTest.java b/src/test/java/org/olf/folio/order/services/GetBudgetTest.java index 73f604e..6bbdec4 100644 --- a/src/test/java/org/olf/folio/order/services/GetBudgetTest.java +++ b/src/test/java/org/olf/folio/order/services/GetBudgetTest.java @@ -6,6 +6,9 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.fail; +import java.io.FileOutputStream; +import java.io.PrintStream; + import org.json.JSONArray; import org.json.JSONObject; import org.junit.Ignore; @@ -13,7 +16,9 @@ public class GetBudgetTest extends ApiBaseTest { - + boolean debug = false; + PrintStream stdout = System.out; + public GetBudgetTest() { // TODO Auto-generated constructor stub } @@ -26,15 +31,27 @@ public void nullTest() { @Test public void testGetAllBudget() { - String budgetEndpoint = getBaseOkapEndpoint() + "finance/budgets?limit=1"; + String budgetEndpoint = getBaseOkapEndpoint() + "finance/budgets?limit=1000"; //System.out.println("endpoint: "+ budgetEndpoint); try { String budgetResponse = getApiService().callApiGet(budgetEndpoint, getToken()); JSONObject budgetsObject = new JSONObject(budgetResponse); - //System.out.println(budgetsObject.toString(3)); - - JSONArray budgetsArray = budgetsObject.getJSONArray("budgets"); + JSONArray budgetsArray = budgetsObject.getJSONArray("budgets"); + if (debug) { + System.setOut(new PrintStream(new FileOutputStream("/cul/src/order-import-poc/output.json"))); + //System.out.println(budgetsObject.toString(3)); + for (int i = 0; i < budgetsArray.length(); i++) { + JSONObject fundObj = (JSONObject) budgetsArray.get(i); + + System.out.println("name: " + fundObj.get("name")); + //System.out.println("id: " + fundObj.get("id")); + System.out.println("available: " + fundObj.get("available")); + System.out.println(); + } + System.setOut(stdout); + } + assertNotNull(budgetsArray); assertTrue(budgetsArray.length() > 0); @@ -45,19 +62,25 @@ public void testGetAllBudget() { @Test public void testGetBudget() { - String fundCode = "p6793"; - String badFundCode = "bad"; - String fiscalYearCode = "FY2021"; + String fundCode = "6945"; + String badFundCode = "p2651"; + String fiscalYearCode = "FY2023"; String budgetEndpoint = getBaseOkapEndpoint() + "finance/budgets?query=(name==" + fundCode + "-" + fiscalYearCode + ")"; - //System.out.println("endpoint: "+ budgetEndpoint); + try { String budgetResponse = getApiService().callApiGet(budgetEndpoint, getToken()); JSONObject budgetsObject = new JSONObject(budgetResponse); - assertNotNull(budgetsObject); - int totalRecords = (Integer) budgetsObject.get("totalRecords"); - assertNotNull(totalRecords); - assertEquals(totalRecords, 1); - //System.out.println(budgetsObject.toString(3)); + if (debug) { + System.out.println("endpoint: "+ budgetEndpoint); + System.out.println("fundcode: "+ fundCode); + System.out.println(budgetsObject.toString(3)); + } else { + assertNotNull(budgetsObject); + int totalRecords = (Integer) budgetsObject.get("totalRecords"); + assertNotNull(totalRecords); + assertEquals(totalRecords, 1); + //System.out.println(budgetsObject.toString(3)); + } } catch (Exception e) { fail(e.getMessage()); } @@ -66,14 +89,20 @@ public void testGetBudget() { try { String budgetResponse = getApiService().callApiGet(budgetEndpoint, getToken()); JSONObject budgetsObject = new JSONObject(budgetResponse); - assertNotNull(budgetsObject); - int totalRecords = (Integer) budgetsObject.get("totalRecords"); - assertNotNull(totalRecords); - assertEquals(totalRecords, 0); + if (debug) { + System.out.println("endpoint: "+ budgetEndpoint); + System.out.println("bad fundcode: "+ badFundCode); + System.out.println(budgetsObject.toString(3)); + } else { + assertNotNull(budgetsObject); + int totalRecords = (Integer) budgetsObject.get("totalRecords"); + assertNotNull(totalRecords); + assertEquals(totalRecords, 1); + //System.out.println(budgetsObject.toString(3)); + } } catch (Exception e) { fail(e.getMessage()); } - } - + } } diff --git a/src/test/java/org/olf/folio/order/services/GetFundCodeTest.java b/src/test/java/org/olf/folio/order/services/GetFundCodeTest.java index ed61cdf..abfd2cc 100644 --- a/src/test/java/org/olf/folio/order/services/GetFundCodeTest.java +++ b/src/test/java/org/olf/folio/order/services/GetFundCodeTest.java @@ -8,11 +8,13 @@ import org.json.JSONArray; import org.json.JSONObject; -import org.junit.Ignore; +import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; public class GetFundCodeTest extends ApiBaseTest { + boolean debug = false; public GetFundCodeTest() { // TODO Auto-generated constructor stub @@ -23,28 +25,32 @@ public void nullTest() { // } - @Test + @Disabled public void testGetAllFundCode() { - String fundEndpoint = getBaseOkapEndpoint() + "finance/funds?limit=1"; + String fundEndpoint = getBaseOkapEndpoint() + "finance/funds?limit=200"; try { String fundResponse = getApiService().callApiGet(fundEndpoint, getToken()); JSONObject fundsObject = new JSONObject(fundResponse); //System.out.println(fundsObject.toString(3)); JSONArray fundsArray = fundsObject.getJSONArray("funds"); - assertNotNull(fundsArray); - assertEquals(fundsArray.length(), 1); - //for (int i=0; i < fundsArray.length(); i++) { - // JSONObject fundObj = (JSONObject) fundsArray.get(i); - // System.out.println("code: "+ fundObj.get("code")); - // System.out.println("name: "+ fundObj.get("name")); - // System.out.println("id: "+ fundObj.get("id")); - // System.out.println(); - //} - String fundId = (String) fundsArray.getJSONObject(0).get("id"); - assertNotNull(fundId); + if (debug) { + for (int i=0; i < fundsArray.length(); i++) { + JSONObject fundObj = (JSONObject) fundsArray.get(i); + System.out.println("code: "+ fundObj.get("code")); + System.out.println("name: "+ fundObj.get("name")); + System.out.println("id: "+ fundObj.get("id")); + System.out.println(); + } + } else { + assertNotNull(fundsArray); + assertEquals(fundsArray.length(), 1); + + String fundId = (String) fundsArray.getJSONObject(0).get("id"); + assertNotNull(fundId); + } } catch (Exception e) { fail(e.getMessage()); } @@ -53,14 +59,16 @@ public void testGetAllFundCode() { @Test public void testGetFundCode() { - String fundCode = "1010"; - //String fundCode = "p2755"; + //String fundCode = "1010"; + String fundCode = "p2651"; String fundEndpoint = getBaseOkapEndpoint() + "finance/funds?limit=3&offset=0&query=((code='" + fundCode + "'))"; try { String fundResponse = getApiService().callApiGet(fundEndpoint, getToken()); JSONObject fundsObject = new JSONObject(fundResponse); JSONArray fundsArray = fundsObject.getJSONArray("funds"); - //System.out.println(fundsObject.toString(3)); + if (debug) { + System.out.println(fundsObject.toString(3)); + } String returnCode = (String) fundsArray.getJSONObject(0).get("code"); assertEquals(fundCode, returnCode); } catch (Exception e) { diff --git a/src/test/java/org/olf/folio/order/services/GetHoldingsTest.java b/src/test/java/org/olf/folio/order/services/GetHoldingsTest.java index 0b5d18c..6e775a9 100644 --- a/src/test/java/org/olf/folio/order/services/GetHoldingsTest.java +++ b/src/test/java/org/olf/folio/order/services/GetHoldingsTest.java @@ -17,7 +17,9 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -public class GetHoldingsTest extends ApiBaseTest { +public class GetHoldingsTest extends ApiBaseTest { + + boolean debug = false; @Ignore public void nullTest() { @@ -34,45 +36,43 @@ public void testGetHoldings() { try { String holdingsResponse = getApiService().callApiGet(holdingsEndpoint, getToken()); JSONObject holdingsObject = new JSONObject(holdingsResponse); - //System.out.println(holdingsObject.toString(3)); + if (debug) System.out.println(holdingsObject.toString(3)); JSONObject holdingsAsJson = new JSONObject(holdingsResponse); JSONArray holdingsArray = holdingsAsJson.getJSONArray("holdingsRecords"); - System.out.println("holdingsArray size: "+ holdingsArray.length()); + if (debug) System.out.println("holdingsArray size: "+ holdingsArray.length()); Iterator holdingsIter = holdingsArray.iterator(); while (holdingsIter.hasNext() ) { JSONObject holdingsRecord = (JSONObject) holdingsIter.next(); String holdingsId = holdingsRecord.getString("id"); - System.out.println("holdingsId: "+ holdingsId); + if (debug) System.out.println("holdingsId: "+ holdingsId); String queryString = "holdingsRecordId==" +holdingsId+ " not barcode=\"\""; String encodedQS = URLEncoder.encode(queryString, StandardCharsets.UTF_8.name()); String itemsEndpoint = getBaseOkapEndpoint() + "inventory/items?query=(" + encodedQS + ")"; - System.out.println("itemsEndpoint: "+ itemsEndpoint); + if (debug) System.out.println("itemsEndpoint: "+ itemsEndpoint); String itemsResponse = getApiService().callApiGet(itemsEndpoint, getToken()); //System.out.println("itemsObject"); JSONObject itemsObject = new JSONObject(itemsResponse); //System.out.println(itemsObject.toString(3)); JSONArray itemsArray = itemsObject.getJSONArray("items"); - System.out.println("number of items: "+itemsArray.length()); + if (debug) System.out.println("number of items: "+itemsArray.length()); Iterator itemsIter = itemsArray.iterator(); while (itemsIter.hasNext()) { JSONObject itemRecord = (JSONObject) itemsIter.next(); String itemId = itemRecord.getString("id"); - System.out.println("item record: "+ itemId); - System.out.println(itemRecord.toString(3)); + if (debug) { + System.out.println("item record: "+ itemId); + System.out.println(itemRecord.toString(3)); + } } - - } - - - + } } catch (Exception e) { e.printStackTrace(); diff --git a/src/test/java/org/olf/folio/order/services/GetOrganizationsTest.java b/src/test/java/org/olf/folio/order/services/GetOrganizationsTest.java index 46a52da..9840eed 100644 --- a/src/test/java/org/olf/folio/order/services/GetOrganizationsTest.java +++ b/src/test/java/org/olf/folio/order/services/GetOrganizationsTest.java @@ -5,7 +5,8 @@ import java.nio.charset.StandardCharsets; import org.json.JSONArray; import org.json.JSONObject; -import org.junit.Ignore; +import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -19,6 +20,7 @@ public class GetOrganizationsTest extends ApiBaseTest { + boolean debug = false; public GetOrganizationsTest() { // TODO Auto-generated constructor stub @@ -37,9 +39,12 @@ public void testGetAllOrganizations() { String orgLookupResponse = getApiService().callApiGet(organizationEndpoint, getToken()); JSONObject orgObject = new JSONObject(orgLookupResponse); JSONArray jsonArray = orgObject.getJSONArray("organizations"); - assertNotNull(jsonArray); - assertTrue(jsonArray.length() > 0); - + if (debug) { + System.out.println(orgObject.toString(3)); + } else { + assertNotNull(jsonArray); + assertTrue(jsonArray.length() > 0); + } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -48,7 +53,7 @@ public void testGetAllOrganizations() { @Test public void testGetOrganization() { - String orgCode = "HARRASS/E"; + String orgCode = "AFRICARES"; try { String encodedOrgCode = URLEncoder.encode("\"" + orgCode + "\"", StandardCharsets.UTF_8.name()); @@ -56,13 +61,17 @@ public void testGetOrganization() { String organizationEndpoint = getBaseOkapEndpoint() + "organizations-storage/organizations?query=(code==" + encodedOrgCode + ")"; try { String orgLookupResponse = getApiService().callApiGet(organizationEndpoint, getToken()); - JSONObject orgObject = new JSONObject(orgLookupResponse); - JSONArray jsonArray = orgObject.getJSONArray("organizations"); - assertNotNull(jsonArray); - String vendorId = (String) jsonArray.getJSONObject(0).get("id"); - assertTrue(StringUtils.length(vendorId) > 0); - UUID uuid = UUID.fromString(vendorId); - //System.out.println("vendorId: "+ vendorId); + JSONObject orgObject = new JSONObject(orgLookupResponse); + JSONArray jsonArray = orgObject.getJSONArray("organizations"); + if (debug) { + System.out.println(orgObject.toString(3)); + } else { + assertNotNull(jsonArray); + String vendorId = (String) jsonArray.getJSONObject(0).get("id"); + assertTrue(StringUtils.length(vendorId) > 0); + UUID uuid = UUID.fromString(vendorId); + //System.out.println("vendorId: "+ vendorId); + } } catch (IllegalArgumentException e) { fail("vendorID was not a valid UUID"); } catch (Exception e) { diff --git a/src/test/java/org/olf/folio/order/util/LookupUtilMaterialsTest.java b/src/test/java/org/olf/folio/order/util/LookupUtilMaterialsTest.java index 560d6ab..6fdb43e 100644 --- a/src/test/java/org/olf/folio/order/util/LookupUtilMaterialsTest.java +++ b/src/test/java/org/olf/folio/order/util/LookupUtilMaterialsTest.java @@ -41,7 +41,7 @@ public void getMaterialsTest() { System.out.println("id: "+ map.get(key)); } } else { - String testKey = "Music"; + String testKey = "Book"; assertNotNull(map); assertTrue(map.containsKey(testKey)); assertNotNull(map.get(testKey)); diff --git a/src/test/java/org/olf/folio/order/util/LookupUtilNoteTest.java b/src/test/java/org/olf/folio/order/util/LookupUtilNoteTest.java index 5e9ac0e..40b9c7c 100644 --- a/src/test/java/org/olf/folio/order/util/LookupUtilNoteTest.java +++ b/src/test/java/org/olf/folio/order/util/LookupUtilNoteTest.java @@ -38,7 +38,7 @@ public void getNoteTest() { System.out.println("id: "+ map.get(key)); } } else { - String testKey = "General note"; + String testKey = "General Note"; assertNotNull(map); assertTrue(map.containsKey(testKey)); assertNotNull(map.get(testKey)); diff --git a/src/test/java/org/olf/folio/order/util/MarcUtilsPriceTest.java b/src/test/java/org/olf/folio/order/util/MarcUtilsPriceTest.java index 67b74d7..5fe57f1 100644 --- a/src/test/java/org/olf/folio/order/util/MarcUtilsPriceTest.java +++ b/src/test/java/org/olf/folio/order/util/MarcUtilsPriceTest.java @@ -1,45 +1,97 @@ package org.olf.folio.order.util; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.util.List; -//import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; import org.marc4j.marc.DataField; +import org.marc4j.marc.MarcFactory; import org.marc4j.marc.Record; +import org.marc4j.marc.Subfield; - -/** - * @author jaf30 - * - */ public class MarcUtilsPriceTest extends MarcUtilsBaseTest { boolean debug = false; + protected final Log logger = LogFactory.getLog(getClass()); - /** - * - */ + @Test - public void testGetPrice() { - String fname = amazonFO; + public void testGetPriceValid() { + if (debug) { + System.out.println("testGetPriceValid"); + } try { - List records = getRecords(fname); - for (Record record : records) { - DataField nineEightyOne = (DataField) record.getVariableField("981"); - String price = marcUtils.getPrice(nineEightyOne); - if (debug) { - System.out.println(fname + " - price: $" + price); - } else { - assertNotNull(price); - assertTrue(price.length() > 0); - } + + MarcFactory factory = MarcFactory.newInstance(); + Record record = factory.newRecord(); + DataField nineEightyOne = factory.newDataField(); + nineEightyOne.setTag("981"); + Subfield sf = factory.newSubfield('i', "1.98"); + nineEightyOne.addSubfield(sf); + + String price = marcUtils.getPrice(nineEightyOne); + if (debug) { + System.out.println(" price: " + price); + } else { + assertNotNull(price); + assertTrue(price.length() > 0); } + } catch (Exception e) { fail(e.getMessage()); } - - } + + } + + @Test + public void testGetPriceInValid() { + if (debug) { + System.out.println("testGetPriceInValid"); + } + try { + + MarcFactory factory = MarcFactory.newInstance(); + Record record = factory.newRecord(); + DataField nineEightyOne = factory.newDataField(); + nineEightyOne.setTag("981"); + Subfield sf = factory.newSubfield('i', "one"); + nineEightyOne.addSubfield(sf); + + String price = marcUtils.getPrice(nineEightyOne); + if (debug) { + System.out.println(" price: " + price); + } else { + assertTrue(price == null); + } + + } catch (Exception e) { + assertTrue(true); + } + + } + + @Test + public void testGetPriceNullDatafield() { + + try { + String price = marcUtils.getPrice(null); + if (debug) { + System.out.println(" price: " + price); + } else { + assertTrue(price == null); + } + + } catch (Exception e) { + assertTrue(true); + } + + } + + } diff --git a/src/test/java/org/olf/folio/order/util/MarcUtilsPublicationDateTest.java b/src/test/java/org/olf/folio/order/util/MarcUtilsPublicationDateTest.java index 7f76a19..c2651dd 100644 --- a/src/test/java/org/olf/folio/order/util/MarcUtilsPublicationDateTest.java +++ b/src/test/java/org/olf/folio/order/util/MarcUtilsPublicationDateTest.java @@ -17,11 +17,17 @@ public class MarcUtilsPublicationDateTest extends MarcUtilsBaseTest { @Test public void testGetPublicationDate() { List myFnames = new ArrayList(); - myFnames.add(this.amazonFO); + myFnames.add(this.singleharrass); try { - for (String fname: this.fnames) { + for (String fname: myFnames) { + if (debug) { + System.out.println("fname = "+ fname); + } List records = getRecords(fname); for (Record record: records) { + if (debug) { + System.out.println(record.toString()); + } DataField df = (DataField) record.getVariableField("264"); String pubDate = marcUtils.getPublicationDate(df); if (debug) { diff --git a/src/test/java/org/olf/folio/order/util/MarcUtilsSeriesFieldsTest.java b/src/test/java/org/olf/folio/order/util/MarcUtilsSeriesFieldsTest.java index bee5068..add4d25 100644 --- a/src/test/java/org/olf/folio/order/util/MarcUtilsSeriesFieldsTest.java +++ b/src/test/java/org/olf/folio/order/util/MarcUtilsSeriesFieldsTest.java @@ -20,7 +20,7 @@ */ public class MarcUtilsSeriesFieldsTest extends MarcUtilsBaseTest { - boolean debug = true; + boolean debug = false; @Test public void testGetSeriesFields() {