Example usage for org.apache.commons.lang StringUtils substringBefore

List of usage examples for org.apache.commons.lang StringUtils substringBefore

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringBefore.

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.egt.core.jsf.JSF.java

private static Hyperlink getHyperlinkByUrl(Breadcrumbs parent, String url) {
    if (StringUtils.isBlank(url)) {
        return null;
    }/*from  w  ww  .java 2  s  .co  m*/
    Hyperlink child;
    List children = parent.getChildren();
    Iterator iterator = children.iterator();
    while (iterator.hasNext()) {
        child = (Hyperlink) iterator.next();
        if (child != null) {
            if (StringUtils.substringBefore(url, "?")
                    .equals(StringUtils.substringBefore(child.getUrl(), "?"))) {
                return child;
            }
        }
    }
    return null;
}

From source file:com.egt.core.jsf.JSF.java

private static void addHipervinculos(Breadcrumbs source, Breadcrumbs target, String url) {
    // Esto esta peor que el TreeNode, falla aun con el Array
    // Hay que clonar el hyperlink para poder copiarlo
    /*/* w  ww. j  av a 2  s.c om*/
     * copia solo hasta el hyperlink con el url especoficado
     */
    boolean up2url = !StringUtils.isBlank(url);
    List sourceChildren = source.getChildren();
    List targetChildren = target.getChildren();
    Hyperlink child;
    Object[] sourceChildrenArray = sourceChildren.toArray();
    targetChildren.clear();
    for (int i = 0; i < sourceChildrenArray.length; i++) {
        child = (Hyperlink) sourceChildrenArray[i];
        if (child != null) {
            Hyperlink clone = new Hyperlink();
            clone.setId(child.getId());
            clone.setText(child.getText());
            clone.setToolTip(child.getToolTip());
            clone.setUrl(child.getUrl());
            clone.setTarget(child.getTarget());
            targetChildren.add(clone);
            if (up2url && StringUtils.substringBefore(url, "?")
                    .equals(StringUtils.substringBefore(clone.getUrl(), "?"))) {
                return;
            }
        }
    }
}

From source file:com.primovision.lutransport.service.ImportMainSheetServiceImpl.java

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public List<String> importAccidentMainData(InputStream is, Long createdBy) throws Exception {
    SimpleDateFormat accidentDateFormat = new SimpleDateFormat("MM-dd-yyyy");

    List<String> errorList = new ArrayList<String>();

    int recordCount = 0;
    int errorCount = 0;
    int successCount = 0;
    try {//from  ww w . jav a  2 s .  c  o m
        POIFSFileSystem fs = new POIFSFileSystem(is);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);

        Map<String, Integer> colMapping = WorkerCompUtils.getAccidentMainColMapping();

        Iterator<Row> rows = sheet.rowIterator();
        int recordsToBeSkipped = 1;
        while (rows.hasNext()) {
            HSSFRow row = (HSSFRow) rows.next();

            recordCount++;
            System.out.println("Processing record No: " + recordCount);
            if (recordCount <= recordsToBeSkipped) {
                continue;
            }

            boolean recordError = false;
            StringBuffer recordErrorMsg = new StringBuffer();
            Accident currentAccident = null;
            try {
                String endOfData = ((String) getCellValue(row.getCell(0)));
                if (StringUtils.equals("END_OF_DATA", endOfData)) {
                    break;
                }

                currentAccident = new Accident();

                Integer insuranceCompanyCol = colMapping
                        .get(WorkerCompUtils.ACCIDENT_MAIN_COL_INUSRANCE_COMPANY);
                String inuranceCompanyStr = ((String) getCellValue(row.getCell(insuranceCompanyCol)));
                inuranceCompanyStr = StringUtils.trimToEmpty(inuranceCompanyStr);
                InsuranceCompany insuranceCompany = null;
                if (!StringUtils.equalsIgnoreCase(inuranceCompanyStr, "Not Reported")) {
                    insuranceCompany = WorkerCompUtils.retrieveInsuranceCompanyByName(inuranceCompanyStr,
                            genericDAO);
                    if (insuranceCompany == null) {
                        recordError = true;
                        recordErrorMsg.append("Inurance Company, ");
                    } else {
                        currentAccident.setInsuranceCompany(insuranceCompany);
                    }
                }

                Integer insuranceClaimNoCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_CLAIM_NO);
                String claimNo = ((String) getCellValue(row.getCell(insuranceClaimNoCol)));
                claimNo = StringUtils.trimToEmpty(claimNo);
                if (StringUtils.isEmpty(claimNo)) {
                    claimNo = null;
                }
                currentAccident.setClaimNumber(claimNo);

                boolean missingDriver = false;
                Integer driverNameCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_DRIVER_NAME);
                String driverName = ((String) getCellValue(row.getCell(driverNameCol)));
                driverName = StringUtils.trimToEmpty(driverName);
                Driver driver = WorkerCompUtils.retrieveDriverByCommaSep(driverName, genericDAO);
                if (driver == null) {
                    /*recordError = true;
                    recordErrorMsg.append("Employee Name, ");*/
                    missingDriver = true;
                } else {
                    currentAccident.setDriver(driver);
                }

                if (missingDriver) {
                    Integer subcontractorNameCol = colMapping
                            .get(WorkerCompUtils.ACCIDENT_MAIN_COL_SUBCONTRACTOR);
                    String subcontractorName = ((String) getCellValue(row.getCell(subcontractorNameCol)));
                    subcontractorName = StringUtils.trimToEmpty(subcontractorName);
                    SubContractor subcontractor = WorkerCompUtils.retrieveSubcontractor(subcontractorName,
                            genericDAO);
                    if (subcontractor == null) {
                        recordError = true;
                        recordErrorMsg.append("Either Employee or Subcontractor is required ");
                    } else {
                        currentAccident.setSubcontractor(subcontractor);
                    }
                }

                Integer incidentDateCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_INCIDENT_DATE);
                Object incidentDateObj = getCellValue(row.getCell(incidentDateCol), true);
                if (incidentDateObj == null) {
                    recordError = true;
                    recordErrorMsg.append("Incident Date, ");
                } else if (incidentDateObj instanceof Date) {
                    currentAccident.setIncidentDate((Date) incidentDateObj);
                } else {
                    String incidentDateStr = incidentDateObj.toString();
                    incidentDateStr = StringUtils.trimToEmpty(incidentDateStr);
                    Date incidentDate = accidentDateFormat.parse(incidentDateStr);
                    currentAccident.setIncidentDate(incidentDate);
                }
                String dayOfWeek = WorkerCompUtils.deriveDayOfWeek(currentAccident.getIncidentDate());
                currentAccident.setIncidentDayOfWeek(dayOfWeek);

                Integer vehicleCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_UNIT);
                String unit = ((String) getCellValue(row.getCell(vehicleCol)));
                unit = StringUtils.trimToEmpty(unit);
                if (StringUtils.isNotEmpty(unit)) {
                    Vehicle vehicle = WorkerCompUtils.retrieveVehicleForUnit(unit,
                            currentAccident.getIncidentDate(), genericDAO);
                    if (vehicle == null) {
                        recordError = true;
                        recordErrorMsg
                                .append("Vehicle (either unit is invalid or not valid for incident date), ");
                    } else {
                        currentAccident.setVehicle(vehicle);
                    }
                }

                Integer monthsOfServiceCol = colMapping
                        .get(WorkerCompUtils.ACCIDENT_MAIN_COL_MONTHS_OF_SERVICE);
                String monthsOfServiceStr = ((String) getCellValue(row.getCell(monthsOfServiceCol), true));
                monthsOfServiceStr = StringUtils.trimToEmpty(monthsOfServiceStr);
                if (StringUtils.isNotEmpty(monthsOfServiceStr)) {
                    //if (!StringUtils.isNumeric(monthsOfServiceStr)) {
                    monthsOfServiceStr = StringUtils.substringBefore(monthsOfServiceStr, ".");
                    Integer monthsOfService = Integer.valueOf(monthsOfServiceStr);
                    currentAccident.setDriverMonthsOfService(monthsOfService);
                    //}
                }

                Integer hireDateCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_HIRE_DATE);
                Object hireDateObj = getCellValue(row.getCell(hireDateCol), true);
                if (hireDateObj == null) {
                    recordError = true;
                    recordErrorMsg.append("Hire Date, ");
                } else if (hireDateObj instanceof Date) {
                    currentAccident.setDriverHiredDate((Date) hireDateObj);
                } else {
                    String hireDateStr = hireDateObj.toString();
                    hireDateStr = StringUtils.trimToEmpty(hireDateStr);
                    if (StringUtils.isNotEmpty(hireDateStr)) {
                        Date hireDate = accidentDateFormat.parse(hireDateStr);
                        currentAccident.setDriverHiredDate(hireDate);
                    }
                }

                Integer loationCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_LOCATION);
                String locationStr = ((String) getCellValue(row.getCell(loationCol)));
                locationStr = StringUtils.trimToEmpty(locationStr);
                currentAccident.setLocation(locationStr);

                Integer companyCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_COMPANY);
                String companyStr = ((String) getCellValue(row.getCell(companyCol)));
                companyStr = StringUtils.trimToEmpty(companyStr);
                List<Location> locationList = WorkerCompUtils.retrieveCompanyTerminal(companyStr, genericDAO);
                if (locationList == null || locationList.isEmpty()) {
                    recordError = true;
                    recordErrorMsg.append("Company, ");
                } else {
                    currentAccident.setDriverCompany(locationList.get(0));
                    currentAccident.setDriverTerminal(locationList.get(1));
                }

                Integer stateCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_STATE);
                String stateStr = ((String) getCellValue(row.getCell(stateCol)));
                stateStr = StringUtils.trimToEmpty(stateStr);
                if (StringUtils.isNotEmpty(stateStr)) {
                    State state = WorkerCompUtils.retrieveState(stateStr, genericDAO);
                    if (state == null) {
                        recordError = true;
                        recordErrorMsg.append("State, ");
                    } else {
                        currentAccident.setState(state);
                    }
                }

                Integer accidentCauseCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_CAUSE);
                String accidentCauseStr = ((String) getCellValue(row.getCell(accidentCauseCol)));
                accidentCauseStr = StringUtils.trimToEmpty(accidentCauseStr);
                if (StringUtils.isNotEmpty(accidentCauseStr)) {
                    AccidentCause accidentCause = WorkerCompUtils.retrieveAccidentCause(accidentCauseStr,
                            genericDAO);
                    if (accidentCause == null) {
                        recordError = true;
                        recordErrorMsg.append("Accident Cause, ");
                    } else {
                        currentAccident.setAccidentCause(accidentCause);
                    }
                }

                Integer accidentRoadConditionCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_ROAD);
                String accidentRoadConditionStr = ((String) getCellValue(
                        row.getCell(accidentRoadConditionCol)));
                accidentRoadConditionStr = StringUtils.trimToEmpty(accidentRoadConditionStr);
                if (StringUtils.isNotEmpty(accidentRoadConditionStr)) {
                    AccidentRoadCondition accidentRoadCondition = WorkerCompUtils
                            .retrieveAccidentRoadCondition(accidentRoadConditionStr, genericDAO);
                    if (accidentRoadCondition == null) {
                        recordError = true;
                        recordErrorMsg.append("Road Condition, ");
                    } else {
                        currentAccident.setRoadCondition(accidentRoadCondition);
                    }
                }

                Integer accidentWeatherCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_WEATHER);
                String accidentWeatherStr = ((String) getCellValue(row.getCell(accidentWeatherCol)));
                accidentWeatherStr = StringUtils.trimToEmpty(accidentWeatherStr);
                if (StringUtils.isNotEmpty(accidentWeatherStr)) {
                    AccidentWeather accidentWeather = WorkerCompUtils
                            .retrieveAccidentWeather(accidentWeatherStr, genericDAO);
                    if (accidentWeather == null) {
                        recordError = true;
                        recordErrorMsg.append("Weather, ");
                    } else {
                        currentAccident.setWeather(accidentWeather);
                    }
                }

                Integer commentsCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_ACCIDENT_COMMENTS);
                String commentsStr = ((String) getCellValue(row.getCell(commentsCol)));
                commentsStr = StringUtils.trimToEmpty(commentsStr);
                currentAccident.setNotes(commentsStr);

                Integer vehicleDamageCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_VEHICLE_DAMAGE);
                String vehicleDamageStr = ((String) getCellValue(row.getCell(vehicleDamageCol)));
                vehicleDamageStr = StringUtils.trimToEmpty(vehicleDamageStr);
                if (StringUtils.equalsIgnoreCase(vehicleDamageStr, "Yes")) {
                    currentAccident.setVehicleDamage("Yes");
                } else if (StringUtils.equalsIgnoreCase(vehicleDamageStr, "No")) {
                    currentAccident.setVehicleDamage("No");
                }

                Integer towedCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_TOWED);
                String towedStr = ((String) getCellValue(row.getCell(towedCol)));
                towedStr = StringUtils.trimToEmpty(towedStr);
                if (StringUtils.equalsIgnoreCase(towedStr, "Yes")) {
                    currentAccident.setTowed("Yes");
                } else if (StringUtils.equalsIgnoreCase(towedStr, "No")) {
                    currentAccident.setTowed("No");
                }

                Integer noInjuredCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_NO_INJURED);
                String noInjuredStr = ((String) getCellValue(row.getCell(noInjuredCol)));
                noInjuredStr = StringUtils.trimToEmpty(noInjuredStr);
                currentAccident.setNoInjured(noInjuredStr);

                Integer citationCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_CITATION);
                String citationStr = ((String) getCellValue(row.getCell(citationCol)));
                citationStr = StringUtils.trimToEmpty(citationStr);
                if (StringUtils.equalsIgnoreCase(citationStr, "Yes")) {
                    currentAccident.setCitation("Yes");
                } else if (StringUtils.equalsIgnoreCase(citationStr, "No")) {
                    currentAccident.setCitation("No");
                }

                Integer recordableCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_RECORDABLE);
                String recordableStr = ((String) getCellValue(row.getCell(recordableCol)));
                recordableStr = StringUtils.trimToEmpty(recordableStr);
                if (StringUtils.equalsIgnoreCase(recordableStr, "Yes")) {
                    currentAccident.setRecordable("Yes");
                } else if (StringUtils.equalsIgnoreCase(recordableStr, "No")) {
                    currentAccident.setRecordable("No");
                }

                Integer hmRelaseCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_HM_RELEASE);
                String hmReleaseStr = ((String) getCellValue(row.getCell(hmRelaseCol)));
                hmReleaseStr = StringUtils.trimToEmpty(hmReleaseStr);
                if (StringUtils.equalsIgnoreCase(hmReleaseStr, "Yes")) {
                    currentAccident.setHmRelease("Yes");
                } else if (StringUtils.equalsIgnoreCase(hmReleaseStr, "No")) {
                    currentAccident.setHmRelease("No");
                }

                Integer claimRepCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_CLAIM_REP);
                String claimRepStr = ((String) getCellValue(row.getCell(claimRepCol)));
                claimRepStr = StringUtils.trimToEmpty(claimRepStr);
                if (StringUtils.isNotEmpty(claimRepStr) && insuranceCompany != null) {
                    InsuranceCompanyRep claimRep = WorkerCompUtils.retrieveClaimRep(claimRepStr,
                            insuranceCompany, genericDAO);
                    /*if (claimRep == null) {
                       recordError = true;
                       recordErrorMsg.append("Claim Rep, ");
                    } else {*/
                    currentAccident.setClaimRep(claimRep);
                    //}
                }

                Integer statusCol = colMapping.get(WorkerCompUtils.ACCIDENT_MAIN_COL_STATUS);
                String statusStr = ((String) getCellValue(row.getCell(statusCol)));
                statusStr = StringUtils.trimToEmpty(statusStr);
                StaticData status = WorkerCompUtils.retrieveAccidentStatus(statusStr, genericDAO);
                if (status == null) {
                    recordError = true;
                    recordErrorMsg.append("Status, ");
                } else {
                    currentAccident.setAccidentStatus(Integer.valueOf(status.getDataValue()));
                }

                if (WorkerCompUtils.checkDuplicateAccident(currentAccident, genericDAO)) {
                    recordError = true;
                    recordErrorMsg.append("Duplicate Accident, ");
                }

                if (recordError) {
                    errorList.add("Line " + recordCount + ": " + recordErrorMsg.toString() + "<br/>");
                    errorCount++;
                    continue;
                }

                currentAccident.setStatus(1);
                currentAccident.setCreatedBy(createdBy);
                currentAccident.setCreatedAt(Calendar.getInstance().getTime());
                genericDAO.saveOrUpdate(currentAccident);

                successCount++;
            } catch (Exception ex) {
                log.warn("Error while processing Accident Main record: " + recordCount + ". " + ex);

                recordError = true;
                errorCount++;
                recordErrorMsg.append("Error while processing record: " + recordCount + ", ");
                errorList.add("Line " + recordCount + ": " + recordErrorMsg.toString() + "<br/>");
            }
        }

        System.out.println("Done processing accidents...Total record count: " + recordCount + ". Error count: "
                + errorCount + ". Number of records loaded: " + successCount);
    } catch (Exception ex) {
        errorList.add("Not able to upload XL!!! Please try again.");
        log.warn("Error while importing Accident Main: " + ex);
    }

    return errorList;
}

From source file:edu.ku.brc.specify.Specify.java

public Storage getStorageItem(final DataProviderSessionIFace session, final String path,
        final Storage parentArg) {
    Storage parent = parentArg;/*from www . j a  v a  2 s  . co m*/
    String nodeStr = StringUtils.substringBefore(path, "/");
    String pathStr = StringUtils.substringAfter(path, "/");
    if (parent == null) {
        parent = session.getData(Storage.class, "name", nodeStr, DataProviderSessionIFace.CompareType.Equals);
        if (StringUtils.isNotEmpty(pathStr)) {
            return getStorageItem(session, pathStr, parent);
        }
        return parent;
    }

    for (Storage node : parent.getChildren()) {
        //log.debug("["+node.getName()+"]["+nodeStr+"]");
        if (node.getName().equals(nodeStr)) {
            if (StringUtils.isNotEmpty(pathStr)) {
                return getStorageItem(session, pathStr, node);
            }
            return node;
        }
    }
    return null;
}

From source file:com.primovision.lutransport.service.ImportMainSheetServiceImpl.java

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public List<String> importInjuryMainData(InputStream is, Long createdBy) throws Exception {
    SimpleDateFormat injuryDateFormat = new SimpleDateFormat("MM-dd-yyyy");

    List<String> errorList = new ArrayList<String>();

    int recordCount = 0;
    int errorCount = 0;
    int successCount = 0;
    try {// www  .j  a v a  2  s  .  c om
        POIFSFileSystem fs = new POIFSFileSystem(is);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);

        Map<String, Integer> colMapping = WorkerCompUtils.getInjuryMainColMapping();

        Iterator<Row> rows = sheet.rowIterator();
        int recordsToBeSkipped = 1;
        while (rows.hasNext()) {
            HSSFRow row = (HSSFRow) rows.next();

            recordCount++;
            System.out.println("Processing record No: " + recordCount);
            if (recordCount <= recordsToBeSkipped) {
                continue;
            }

            boolean recordError = false;
            StringBuffer recordErrorMsg = new StringBuffer();
            Injury currentInjury = null;
            try {
                String endOfData = ((String) getCellValue(row.getCell(0)));
                if (StringUtils.equals("END_OF_DATA", endOfData)) {
                    break;
                }

                currentInjury = new Injury();

                Integer insuranceCompanyCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_INUSRANCE_COMPANY);
                String inuranceCompanyStr = ((String) getCellValue(row.getCell(insuranceCompanyCol)));
                InsuranceCompany insuranceCompany = null;
                if (!StringUtils.equalsIgnoreCase(inuranceCompanyStr, "Not Reported")) {
                    insuranceCompany = WorkerCompUtils.retrieveInsuranceCompanyByName(inuranceCompanyStr,
                            genericDAO);
                    if (insuranceCompany == null) {
                        recordError = true;
                        recordErrorMsg.append("Inurance Company, ");
                    } else {
                        currentInjury.setInsuranceCompany(insuranceCompany);
                    }
                }

                Integer insuranceClaimNoCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_CLAIM_NO);
                String claimNo = ((String) getCellValue(row.getCell(insuranceClaimNoCol)));
                if (StringUtils.isEmpty(claimNo)) {
                    claimNo = null;
                }
                currentInjury.setClaimNumber(claimNo);

                Integer driverLastNameCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_LAST_NAME);
                String driverLastName = ((String) getCellValue(row.getCell(driverLastNameCol)));
                Integer driverFirstNameCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_FIRST_NAME);
                String driverFirstName = ((String) getCellValue(row.getCell(driverFirstNameCol)));
                Driver driver = WorkerCompUtils.retrieveDriver(driverFirstName, driverLastName, genericDAO);
                if (driver == null) {
                    recordError = true;
                    recordErrorMsg.append("Employee Name, ");
                } else {
                    currentInjury.setDriver(driver);
                }

                Integer driverAgeCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_AGE);
                String driverAgeStr = ((String) getCellValue(row.getCell(driverAgeCol), true));
                if (StringUtils.isNotEmpty(driverAgeStr)) {
                    //if (!StringUtils.isNumeric(driverAgeStr)) {
                    driverAgeStr = StringUtils.substringBefore(driverAgeStr, ".");
                    Integer driverAge = Integer.valueOf(driverAgeStr);
                    currentInjury.setDriverAge(driverAge);
                    //}
                }

                Integer monthsOfServiceCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_MONTHS_OF_SERVICE);
                String monthsOfServiceStr = ((String) getCellValue(row.getCell(monthsOfServiceCol), true));
                if (StringUtils.isNotEmpty(monthsOfServiceStr)) {
                    //if (!StringUtils.isNumeric(monthsOfServiceStr)) {
                    monthsOfServiceStr = StringUtils.substringBefore(monthsOfServiceStr, ".");
                    Integer monthsOfService = Integer.valueOf(monthsOfServiceStr);
                    currentInjury.setDriverMonthsOfService(monthsOfService);
                    //}
                }

                Integer companyCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_COMPANY);
                String companyStr = ((String) getCellValue(row.getCell(companyCol)));
                List<Location> locationList = WorkerCompUtils.retrieveCompanyTerminal(companyStr, genericDAO);
                if (locationList == null || locationList.isEmpty()) {
                    recordError = true;
                    recordErrorMsg.append("Company, ");
                } else {
                    currentInjury.setDriverCompany(locationList.get(0));
                    currentInjury.setDriverTerminal(locationList.get(1));
                }

                Integer positionCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_POSITION);
                String positionStr = ((String) getCellValue(row.getCell(positionCol)));
                EmployeeCatagory employeeCategory = WorkerCompUtils.retrieveEmployeeCategory(positionStr,
                        genericDAO);
                if (employeeCategory == null) {
                    recordError = true;
                    recordErrorMsg.append("Position, ");
                } else {
                    currentInjury.setDriverCategory(employeeCategory);
                }

                Integer incidentDateCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_INCIDENT_DATE);
                Object incidentDateObj = getCellValue(row.getCell(incidentDateCol), true);
                if (incidentDateObj == null) {
                    recordError = true;
                    recordErrorMsg.append("Incident Date, ");
                } else if (incidentDateObj instanceof Date) {
                    currentInjury.setIncidentDate((Date) incidentDateObj);
                } else {
                    String incidentDateStr = incidentDateObj.toString();
                    Date incidentDate = injuryDateFormat.parse(incidentDateStr);
                    currentInjury.setIncidentDate(incidentDate);
                }
                String dayOfWeek = WorkerCompUtils.deriveDayOfWeek(currentInjury.getIncidentDate());
                currentInjury.setIncidentDayOfWeek(dayOfWeek);

                Integer timeOfDayCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_TIME_OF_DAY);
                Object timeOfDayObj = getCellValue(row.getCell(timeOfDayCol), true);
                Integer amPMCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_AM_PM);
                String amPMStr = ((String) getCellValue(row.getCell(amPMCol)));
                String incidentTime = WorkerCompUtils.deriveIncidentTime(timeOfDayObj, amPMStr);
                currentInjury.setIncidentTime(incidentTime);
                currentInjury.setIncidentTimeAMPM(amPMStr);

                Integer returnToWorkCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_RETURN_TO_WORK);
                Object returnToWorkObj = getCellValue(row.getCell(returnToWorkCol), true);
                String returnToWorkStr = StringUtils.EMPTY;
                if (returnToWorkObj != null) {
                    if (returnToWorkObj instanceof Date) {
                        returnToWorkStr = injuryDateFormat.format((Date) returnToWorkObj);
                    } else {
                        returnToWorkStr = (String) returnToWorkObj;
                    }
                }
                currentInjury.setReturnToWork(returnToWorkStr);

                Integer incidentTypeCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_INCIDENT_TYPE);
                String incidentTypeStr = ((String) getCellValue(row.getCell(incidentTypeCol)));
                InjuryIncidentType injuryIncidentType = WorkerCompUtils.retrieveIncidentType(incidentTypeStr,
                        genericDAO);
                if (injuryIncidentType == null) {
                    recordError = true;
                    recordErrorMsg.append("Incident Type, ");
                } else {
                    currentInjury.setIncidentType(injuryIncidentType);
                }

                Integer injuryToCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_INJURY_TO);
                String injuryToStr = ((String) getCellValue(row.getCell(injuryToCol)));
                if (StringUtils.isNotEmpty(injuryToStr)) {
                    InjuryToType injuryToType = WorkerCompUtils.retrieveInjuryToType(injuryToStr, genericDAO);
                    if (injuryToType == null) {
                        recordError = true;
                        recordErrorMsg.append("Injury To, ");
                    } else {
                        currentInjury.setInjuryTo(injuryToType);
                    }
                }

                Integer commentsCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_INJURY_COMMENTS);
                String commentsStr = ((String) getCellValue(row.getCell(commentsCol)));
                currentInjury.setNotes(commentsStr);

                Integer lostWorkDaysCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_LOST_WORK_DAYS);
                String lostWorkDaysStr = ((String) getCellValue(row.getCell(lostWorkDaysCol), true));
                if (StringUtils.isNotEmpty(lostWorkDaysStr)) {
                    //if (StringUtils.isNumeric(lostWorkDaysStr)) {
                    lostWorkDaysStr = StringUtils.substringBefore(lostWorkDaysStr, ".");
                    Integer lostWorkDays = Integer.valueOf(lostWorkDaysStr);
                    currentInjury.setNoOfLostWorkDays(lostWorkDays);
                    //}
                }

                Integer tarpRelatedInjuryCol = colMapping
                        .get(WorkerCompUtils.INJURY_MAIN_COL_TARP_RELATED_INJURY);
                String tarpRelatedInjuryStr = ((String) getCellValue(row.getCell(tarpRelatedInjuryCol)));
                if (StringUtils.equals(tarpRelatedInjuryStr, "Yes")
                        || StringUtils.equals(tarpRelatedInjuryStr, "No")) {
                    currentInjury.setTarpRelatedInjury(tarpRelatedInjuryStr);
                }

                Integer firstReportOfInjuryCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_FIRST_INJURY);
                String firstReportOfInjuryStr = ((String) getCellValue(row.getCell(firstReportOfInjuryCol)));
                if (StringUtils.equals(firstReportOfInjuryStr, "Yes")
                        || StringUtils.equals(firstReportOfInjuryStr, "No")) {
                    currentInjury.setFirstReportOfInjury(firstReportOfInjuryStr);
                }

                Integer claimRepCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_CLAIM_REP);
                String claimRepStr = ((String) getCellValue(row.getCell(claimRepCol)));
                if (StringUtils.isNotEmpty(claimRepStr) && insuranceCompany != null) {
                    InsuranceCompanyRep claimRep = WorkerCompUtils.retrieveClaimRep(claimRepStr,
                            insuranceCompany, genericDAO);
                    /*if (claimRep == null) {
                       recordError = true;
                       recordErrorMsg.append("Claim Rep, ");
                    } else {*/
                    currentInjury.setClaimRep(claimRep);
                    //}
                }

                Integer statusCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_STATUS);
                String statusStr = ((String) getCellValue(row.getCell(statusCol)));
                StaticData status = WorkerCompUtils.retrieveInjuryStatus(statusStr, genericDAO);
                if (status == null) {
                    recordError = true;
                    recordErrorMsg.append("Status, ");
                } else {
                    currentInjury.setInjuryStatus(Integer.valueOf(status.getDataValue()));
                }

                Integer loationCol = colMapping.get(WorkerCompUtils.INJURY_MAIN_COL_LOCATION);
                String locationStr = ((String) getCellValue(row.getCell(loationCol)));
                currentInjury.setLocation(locationStr);
                /*if (StringUtils.isNotEmpty(locationStr)) { 
                   Location location = InjuryUtils.retrieveInjuryLocation(locationStr, genericDAO);
                   if (location == null) {
                      recordError = true;
                      recordErrorMsg.append("Location, ");
                   } else {
                      currentInjury.setLocation(location);
                   }
                }*/

                if (WorkerCompUtils.checkDuplicateInjury(currentInjury, genericDAO)) {
                    recordError = true;
                    recordErrorMsg.append("Duplicate Injury, ");
                }

                if (recordError) {
                    errorList.add("Line " + recordCount + ": " + recordErrorMsg.toString() + "<br/>");
                    errorCount++;
                    continue;
                }

                currentInjury.setStatus(1);
                currentInjury.setCreatedBy(createdBy);
                currentInjury.setCreatedAt(Calendar.getInstance().getTime());
                genericDAO.saveOrUpdate(currentInjury);

                successCount++;
            } catch (Exception ex) {
                log.warn("Error while processing Injury Main record: " + recordCount + ". " + ex);

                recordError = true;
                errorCount++;
                recordErrorMsg.append("Error while processing record: " + recordCount + ", ");
                errorList.add("Line " + recordCount + ": " + recordErrorMsg.toString() + "<br/>");
            }
        }

        System.out.println("Done processing injuries...Total record count: " + recordCount + ". Error count: "
                + errorCount + ". Number of records loaded: " + successCount);
    } catch (Exception ex) {
        errorList.add("Not able to upload XL!!! Please try again.");
        log.warn("Error while importing Injury Main: " + ex);
    }

    return errorList;
}

From source file:com.egt.core.db.xdp.RecursoCachedRowSetDataProvider.java

private Object execute(String procedure, Object argumento) { // throws SQLException
    Bitacora.trace(getClass(), "executeFunction", procedure, argumento);
    if (StringUtils.isNotBlank(procedure) && argumento != null) {
        try {//from   ww w. jav  a  2s  .c  om
            if (TLC.getAgenteSql().isStoredProcedure(procedure)) {
                Object[] args = new Object[] { argumento };
                Object resultado = TLC.getAgenteSql().executeProcedure(procedure, args);
                if (resultado instanceof ResultSet) {
                    ResultSet resultSet = (ResultSet) resultado;
                    if (resultSet.next()) {
                        return resultSet.getObject(1);
                    }
                    //                  } else if (resultado instanceof Number) {
                    //                      return resultado;
                }
                return resultado;
            }
        } catch (SQLException ex) {
            String localizedMessage = StringUtils.substringBefore(ex.getLocalizedMessage(), " Where: ");
            TLC.getBitacora().error(localizedMessage);
            return ex;
        }
    }
    return null;
}

From source file:com.amalto.core.query.StorageQueryTest.java

License:asdf

public void testDuplicateFieldNames() {
    UserQueryBuilder qb = from(product);

    List<String> viewables = new ArrayList<String>();
    viewables.add("Product/Id");
    viewables.add("Product/Name");
    viewables.add("Product/Family");
    viewables.add("ProductFamily/Id");
    viewables.add("ProductFamily/Name");

    List<IWhereItem> conditions = new ArrayList<IWhereItem>();
    conditions.add(new WhereCondition("Product/Family", "JOINS", "ProductFamily/Id", "&"));

    IWhereItem fullWhere = new WhereAnd(conditions);
    qb.where(UserQueryHelper.buildCondition(qb, fullWhere, repository));

    // add order by Id to make the test stable
    qb.orderBy(product.getField("Id"), Direction.ASC);

    for (String viewableBusinessElement : viewables) {
        String viewableTypeName = StringUtils.substringBefore(viewableBusinessElement, "/"); //$NON-NLS-1$
        String viewablePath = StringUtils.substringAfter(viewableBusinessElement, "/"); //$NON-NLS-1$
        qb.select(UserQueryHelper.getFields(repository.getComplexType(viewableTypeName), viewablePath).get(0));
    }/*from  ww w.  j a  v a  2s.  c  o  m*/

    StorageResults results = storage.fetch(qb.getSelect());
    assertEquals(2, results.getCount());

    DataRecordWriter writer = new ViewSearchResultsWriter();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    List<String> strings = new ArrayList<String>();
    for (DataRecord result : results) {
        try {
            writer.write(result, output);
            String document = new String(output.toByteArray(), Charset.forName("UTF-8"));
            strings.add(document);
            output.reset();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    assertEquals(2, strings.size());
    assertEquals(
            "<result xmlns:metadata=\"http://www.talend.com/mdm/metadata\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n\t<Id>1</Id>\n\t<Name>Product name</Name>\n\t<Family>[2]</Family>\n\t<Id>2</Id>\n\t<Name>Product family #2</Name>\n</result>",
            strings.get(0));
    assertEquals(
            "<result xmlns:metadata=\"http://www.talend.com/mdm/metadata\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n\t<Id>2</Id>\n\t<Name>Renault car</Name>\n\t<Family/>\n\t<Id/>\n\t<Name/>\n</result>",
            strings.get(1));
}

From source file:com.amalto.core.query.StorageQueryTest.java

License:asdf

public void testTMDM8828() {
    UserQueryBuilder qb = from(organisation);

    List<String> viewables = new ArrayList<String>();
    viewables.add("Organisation/OrganisationId");
    viewables.add("Location/LocationId");
    viewables.add("Location/translation/locationTranslation");

    // add order by Id to make the test stable
    qb.orderBy(organisation.getField("OrganisationId"), Direction.ASC);

    List<IWhereItem> conditions = new ArrayList<IWhereItem>();
    conditions.add(new WhereCondition("Organisation/locations/location", "JOINS", "Location/LocationId", "&"));
    conditions.add(new WhereCondition("Organisation/OrganisationId", "=", "2", "&"));

    IWhereItem fullWhere = new WhereAnd(conditions);
    qb.where(UserQueryHelper.buildCondition(qb, fullWhere, repository));

    for (String viewableBusinessElement : viewables) {
        String viewableTypeName = StringUtils.substringBefore(viewableBusinessElement, "/"); //$NON-NLS-1$
        String viewablePath = StringUtils.substringAfter(viewableBusinessElement, "/"); //$NON-NLS-1$
        TypedExpression expression = UserQueryHelper
                .getFields(repository.getComplexType(viewableTypeName), viewablePath).get(0);
        qb.select(expression);//from   w w  w  . ja  va2 s  .  co m
    }

    StorageResults results = storage.fetch(qb.getSelect());
    assertEquals(2, results.getCount());

    DataRecordWriter writer = new ViewSearchResultsWriter();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    List<String> strings = new ArrayList<String>();
    for (DataRecord result : results) {
        try {
            writer.write(result, output);
            String document = new String(output.toByteArray(), Charset.forName("UTF-8"));
            strings.add(document);
            output.reset();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    assertEquals(2, strings.size());
    assertEquals(
            "<result xmlns:metadata=\"http://www.talend.com/mdm/metadata\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n\t<OrganisationId>2</OrganisationId>\n\t<LocationId>t2</LocationId>\n\t<locationTranslation>Trans1</locationTranslation>\n</result>",
            strings.get(0));
    assertEquals(
            "<result xmlns:metadata=\"http://www.talend.com/mdm/metadata\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n\t<OrganisationId>2</OrganisationId>\n\t<LocationId>t2</LocationId>\n\t<locationTranslation>Trans2</locationTranslation>\n</result>",
            strings.get(1));
}

From source file:net.sourceforge.subsonic.backend.controller.RedirectionController.java

private String getRedirectFrom(HttpServletRequest request) throws MalformedURLException {
    URL url = new URL(request.getRequestURL().toString());
    String host = url.getHost();/*from   ww  w  .  j  a v a2 s  .  c  o  m*/

    String redirectFrom;
    if (host.contains(".")) {
        redirectFrom = StringUtils.substringBefore(host, ".");
    } else {
        // For testing.
        redirectFrom = request.getParameter("redirectFrom");
    }

    return StringUtils.lowerCase(redirectFrom);
}

From source file:net.umpay.mailbill.hql.orm.hibernate.HibernateDao.java

/**
 * countHql.//w ww .  ja  va  2  s .  c o  m
 * 
 * ???hql?,??hql?count?.
 */
protected long countHqlResult(final String hql, final Object... values) {
    String fromHql = hql;
    //select??order by???count,?.
    fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    fromHql = StringUtils.substringBefore(fromHql, "order by");

    String countHql = "select count(*) " + fromHql.replaceAll("fetch", "");

    try {
        Long count = findUnique(countHql, values);
        return count;
    } catch (Exception e) {
        throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
    }
}