Example usage for java.lang NumberFormatException printStackTrace

List of usage examples for java.lang NumberFormatException printStackTrace

Introduction

In this page you can find the example usage for java.lang NumberFormatException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.znsx.cms.service.impl.DeviceManagerImpl.java

public Camera readCameraCells(Row row, int rowIndex, Organ organ, Dvr dvr, String standardNumber,
        List<Manufacturer> manufs, List<String> snList) {
    Camera camera = new Camera();
    VideoDeviceProperty property = new VideoDeviceProperty();
    Cell cell = null;/* w w w  . j av a  2  s .c  om*/
    cell = row.getCell(0);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 1 + "," + TypeDefinition.CAMERA_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",name is not null");
    } else {
        row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
        camera.setName(cell.getStringCellValue());
    }

    cell = row.getCell(1);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex: " + 2 + "," + TypeDefinition.CAMERA_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",subType is not null");
    } else {
        Integer subType = null;
        try {
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            subType = Integer.parseInt(cell.getStringCellValue());
        } catch (NumberFormatException n) {
            n.printStackTrace();
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex:" + 2 + "," + TypeDefinition.CAMERA_TEMPLATE
                            + "," + TypeDefinition.PARAMETER_ERROR + ",parameter subType["
                            + cell.getStringCellValue() + "] invalid !");
        }
        if (subType == 1) {
            camera.setSubType(TypeDefinition.SUBTYPE_CAMERA_DEFAULT);
        } else if (subType == 2) {
            camera.setSubType(TypeDefinition.SUBTYPE_CAMERA_BALL);
        }
    }

    cell = row.getCell(2);
    Short storeType = 0;
    if (cell != null) {
        try {
            row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
            storeType = Short.parseShort(cell.getStringCellValue());
        } catch (NumberFormatException n) {
            n.printStackTrace();
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex:" + 3 + "," + TypeDefinition.CAMERA_TEMPLATE
                            + "," + TypeDefinition.PARAMETER_ERROR + ",parameter storeType["
                            + cell.getStringCellValue() + "] invalid !");
        }
        property.setStoreType(storeType);
    } else {
        property.setStoreType(storeType);
    }

    cell = row.getCell(3);

    Short channelNumber = null;
    row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
    channelNumber = Short.parseShort(cell.getStringCellValue());
    camera.setChannelNumber(channelNumber);

    cell = row.getCell(4);
    Manufacturer manuf = null;
    if (cell != null) {
        String manufacturerId = "";
        try {
            row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
            manufacturerId = cell.getStringCellValue();
        } catch (NumberFormatException n) {
            n.printStackTrace();
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex:" + 5 + "," + TypeDefinition.CAMERA_TEMPLATE
                            + "," + TypeDefinition.PARAMETER_ERROR + ",parameter channelNumber["
                            + cell.getStringCellValue() + "] invalid !");
        }
        if (StringUtils.isNotBlank(manufacturerId)) {
            manuf = findManuf(manufs, manufacturerId, rowIndex, 5, 2);
        }
    }
    camera.setManufacturer(manuf);

    cell = row.getCell(5);
    if (cell != null) {
        row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
    }
    camera.setLocation(cell == null ? " " : cell.getStringCellValue());

    cell = row.getCell(6);
    if (cell != null) {
        row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
    }
    camera.setNote(cell == null ? " " : cell.getStringCellValue());

    cell = row.getCell(8);
    LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
    if (property.getStoreType() == 1 || property.getStoreType() == 2) {
        if (cell == null) {
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex: " + 9 + "," + TypeDefinition.CAMERA_TEMPLATE
                            + "," + TypeDefinition.PARAMETER_NULL + ",crs is not null");
        }
        row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
        if (StringUtils.isNotBlank(cell.getStringCellValue())) {
            params.put("standardNumber", cell.getStringCellValue());
            camera.setCrs(crsDAO.findByPropertys(params).get(0));
            params.clear();
            property.setCenterStorePlan(TypeDefinition.STORE_PLAN_DEFAULT);
        } else {
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex: " + 9 + "," + TypeDefinition.CAMERA_TEMPLATE
                            + "," + TypeDefinition.PARAMETER_NULL + ",crs is not null");
        }
    }

    cell = row.getCell(9);
    if (cell != null) {
        row.getCell(9).setCellType(Cell.CELL_TYPE_STRING);
        if (StringUtils.isNotBlank(cell.getStringCellValue())) {
            params.put("standardNumber", cell.getStringCellValue());
            camera.setMss(mssDAO.findByPropertys(params).get(0));
            params.clear();
        } else {
            camera.setMss(null);
        }
    }

    cell = row.getCell(10);
    if (cell != null) {
        row.getCell(10).setCellType(Cell.CELL_TYPE_STRING);
        camera.setNavigation(cell.getStringCellValue());
    }

    cell = row.getCell(11);
    if (cell != null) {
        row.getCell(11).setCellType(Cell.CELL_TYPE_STRING);
        camera.setStakeNumber(cell.getStringCellValue());
    }

    cell = row.getCell(12);
    if (cell != null) {
        row.getCell(12).setCellType(Cell.CELL_TYPE_STRING);
        String cellSn = cell.getStringCellValue();
        if (StringUtils.isNotBlank(cellSn)) {
            for (String sn : snList) {
                if (sn.equals(cell.getStringCellValue())) {
                    throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                            "excel row:" + (rowIndex + 1) + ",cellIndex:" + 13 + ","
                                    + TypeDefinition.CAMERA_TEMPLATE + "," + TypeDefinition.PARAMETER_ERROR
                                    + ",sn error");
                }
            }
            camera.setStandardNumber(cellSn);
        } else {
            camera.setStandardNumber(standardNumber);
        }
    } else {
        camera.setStandardNumber(standardNumber);
    }

    camera.setCreateTime(System.currentTimeMillis());
    camera.setParent(dvr);
    camera.setOrgan(organ);
    camera.setProperty(property);
    camera.setType(TypeDefinition.DEVICE_TYPE_CAMERA);
    return camera;
}

From source file:com.znsx.cms.service.impl.DeviceManagerImpl.java

public Dvr readDvrCells(Row row, int rowIndex, Organ organ, String standardNumber, List<Manufacturer> manufs,
        List<String> snList) {
    Dvr dvr = new Dvr();
    VideoDeviceProperty property = new VideoDeviceProperty();
    Cell cell = row.getCell(0);/*www .j a  v a 2s .  co m*/
    row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
    dvr.setName(cell.getStringCellValue());

    cell = row.getCell(1);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex: " + 2 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",subType is not null");
    } else {
        Integer subType = 1;
        try {
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            subType = Integer.parseInt(cell.getStringCellValue());
        } catch (NumberFormatException n) {
            n.printStackTrace();
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex:" + 2 + "," + TypeDefinition.DVR_TEMPLATE + ","
                            + TypeDefinition.PARAMETER_ERROR + ",parameter subType[" + cell.getStringCellValue()
                            + "] invalid !");
        }
        dvr.setSubType("0" + subType);
    }

    cell = row.getCell(2);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 3 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",maxConnect is not null");
    } else {
        Integer maxConnect = 10;
        try {
            row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
            maxConnect = Integer.parseInt(cell.getStringCellValue());
            if (maxConnect < 1 || maxConnect > 32) {
                throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                        "excel row:" + (rowIndex + 1) + ",cellIndex:" + 3 + "," + TypeDefinition.DVR_TEMPLATE
                                + "," + TypeDefinition.PARAMETER_ERROR + ",parameter maxConnect["
                                + cell.getStringCellValue() + "] invalid !");
            }
        } catch (NumberFormatException n) {
            n.printStackTrace();
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex:" + 3 + "," + TypeDefinition.DVR_TEMPLATE + ","
                            + TypeDefinition.PARAMETER_ERROR + ",parameter maxConnect["
                            + cell.getStringCellValue() + "] invalid !");
        }
        dvr.setMaxConnect(maxConnect);
    }

    property.setHeartCycle(120);

    cell = row.getCell(3);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 4 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",channelAmount is not null");
    } else {
        Integer channelAmount = 1;
        try {
            row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
            channelAmount = Integer.parseInt(cell.getStringCellValue());
            if (channelAmount < 1 || channelAmount > 1000) {
                throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                        "excel row:" + (rowIndex + 1) + ",cellIndex:" + 4 + "," + TypeDefinition.DVR_TEMPLATE
                                + "," + TypeDefinition.PARAMETER_ERROR + ",parameter channelAmount["
                                + cell.getStringCellValue() + "] invalid !");
            }
        } catch (NumberFormatException n) {
            n.printStackTrace();
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex:" + 4 + "," + TypeDefinition.DVR_TEMPLATE + ","
                            + TypeDefinition.PARAMETER_ERROR + ",parameter channelAmount["
                            + cell.getStringCellValue() + "] invalid !");
        }
        dvr.setChannelAmount(channelAmount);
    }

    cell = row.getCell(4);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex: " + 5 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",userName is not null");
    } else {
        row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
        String userName = cell.getStringCellValue();
        property.setUserName(userName);
    }

    cell = row.getCell(5);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 6 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",password is not null");
    } else {
        row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
        String password = cell.getStringCellValue();
        property.setPassword(Base64Utils.getBASE64(password.getBytes()));
    }

    cell = row.getCell(6);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 7 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",manufacturer is not null");
    } else {
        String manufacturerId = "1";
        try {
            row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
            manufacturerId = cell.getStringCellValue();
        } catch (NumberFormatException n) {
            n.printStackTrace();
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex:" + 7 + "," + TypeDefinition.DVR_TEMPLATE + ","
                            + TypeDefinition.PARAMETER_ERROR + ",parameter manufacturer["
                            + cell.getStringCellValue() + "] invalid !");
        }
        Manufacturer manuf = findManuf(manufs, manufacturerId, rowIndex, 7, 1);
        dvr.setManufacturer(manuf);
    }

    cell = row.getCell(7);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 8 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",ip is not null");
    } else {
        row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
        if (!isIp(cell.getStringCellValue())) {
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex:" + 8 + "," + TypeDefinition.DVR_TEMPLATE + ","
                            + TypeDefinition.PARAMETER_ERROR + ",ip error");
        } else {
            String lanIp = cell.getStringCellValue();
            dvr.setLanIp(lanIp);
        }
    }

    cell = row.getCell(8);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 9 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",port is not null");
    } else {
        Integer port = 8000;
        try {
            row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
            port = Integer.parseInt(cell.getStringCellValue());
        } catch (NumberFormatException n) {
            n.printStackTrace();
            throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                    "excel row:" + (rowIndex + 1) + ",cellIndex:" + 9 + "," + TypeDefinition.DVR_TEMPLATE + ","
                            + TypeDefinition.PARAMETER_ERROR + ",parameter port[" + cell.getStringCellValue()
                            + "] invalid !");
        }
        dvr.setPort(port + "");
    }

    cell = row.getCell(9);
    if (cell != null) {
        row.getCell(9).setCellType(Cell.CELL_TYPE_STRING);
    }
    dvr.setLocation(cell == null ? " " : cell.getStringCellValue());

    cell = row.getCell(10);
    if (cell != null) {
        row.getCell(10).setCellType(Cell.CELL_TYPE_STRING);
    }
    dvr.setNote(cell == null ? "" : cell.getStringCellValue());

    cell = row.getCell(11);
    row.getCell(11).setCellType(Cell.CELL_TYPE_STRING);
    dvr.setLinkType(cell.getStringCellValue());

    cell = row.getCell(12);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 12 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",ccs is not null");
    }
    row.getCell(12).setCellType(Cell.CELL_TYPE_STRING);
    LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
    params.put("standardNumber", cell.getStringCellValue());
    dvr.setCcs(ccsDAO.findByPropertys(params).get(0));

    cell = row.getCell(13);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 14 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",transport is not null");
    }
    row.getCell(13).setCellType(Cell.CELL_TYPE_STRING);
    dvr.setTransport(cell.getStringCellValue());

    cell = row.getCell(14);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 15 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",mode is not null");
    }
    row.getCell(14).setCellType(Cell.CELL_TYPE_STRING);
    dvr.setMode(cell.getStringCellValue());

    cell = row.getCell(15);
    if (cell == null) {
        throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                "excel row:" + (rowIndex + 1) + ",cellIndex:" + 16 + "," + TypeDefinition.DVR_TEMPLATE + ","
                        + TypeDefinition.PARAMETER_NULL + ",mode is not null");
    }
    row.getCell(15).setCellType(Cell.CELL_TYPE_STRING);
    property.setDecode(cell.getStringCellValue());
    property.setProtocol(cell.getStringCellValue());
    cell = row.getCell(16);
    if (null != cell) {
        row.getCell(16).setCellType(Cell.CELL_TYPE_STRING);
        String cellSn = cell.getStringCellValue();
        if (StringUtils.isNotBlank(cellSn)) {
            for (String sn : snList) {
                if (sn.equals(cell.getStringCellValue())) {
                    throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR,
                            "excel row:" + (rowIndex + 1) + ",cellIndex:" + 17 + ","
                                    + TypeDefinition.DVR_TEMPLATE + "," + TypeDefinition.PARAMETER_ERROR
                                    + ",sn error");
                }
            }
            dvr.setStandardNumber(cellSn);
        } else {
            dvr.setStandardNumber(standardNumber);
        }
    } else {
        dvr.setStandardNumber(standardNumber);
    }

    dvr.setOrgan(organ);
    dvr.setProperty(property);
    String id = (String) new UUIDHexGenerator().generate(null, null);
    dvr.setId(id);
    dvr.setType(TypeDefinition.DEVICE_TYPE_DVR);
    return dvr;
}

From source file:org.fsl.roms.service.action.RoadCheckServiceAction.java

public Event searchTrn(RequestContext context) {
    try {//from ww  w .j  a v a  2  s.  com
        RoadCheckVerifyIdView roadCheckVerifyIdView = (RoadCheckVerifyIdView) context.getFlowScope()
                .get("verifyIdView");

        if (StringUtils.isBlank(roadCheckVerifyIdView.getTrn())) {
            addErrorMessageWithParameter(context, "RequiredFields", "Trn");
            return error();
        }

        //Checks if the TRN is a business
        if (isBusinessTRN(roadCheckVerifyIdView.getTrn())) {
            addErrorMessageText(context, "Invalid TRN");
            return error();
        }

        // check ROMS database first
        PersonBO personBO = getDocumentsManagerService().getPersonByTRN(roadCheckVerifyIdView.getTrn());
        TrnDTO trnDTO = getTRNWebService().getrnDTOByTrn(Integer.parseInt(roadCheckVerifyIdView.getTrn())); //Check TRN Service as well for name changes
        RoadCheckInitiateView roadCheckInitiateView = setDetailsToInitiateRoadCheck(context);
        if (personBO == null) {

            // PersonBO personBO;

            // personBO =
            // getTRNWebServicePortProxy().getPersonBOByTrn(Integer.parseInt(roadCheckVerifyIdView.getTrn()));

            if (trnDTO == null) {
                addErrorMessage(context, "Norecordfound");
                return error();
            } else {
                if (trnDTO.isBusinessTrn()) {
                    addErrorMessageText(context, "Invalid TRN");
                    return error();
                }

                this.setDetails(roadCheckInitiateView, trnDTO);

                roadCheckInitiateView.setTrn(trnDTO.getNbrTrn());
                roadCheckInitiateView.setLastName(
                        WordUtils.capitalize(trnDTO.getLastName().toLowerCase(), Constants.STRING_DELIM_ARRAY));

                roadCheckInitiateView
                        .setPhotoURL(this.getPictureFromBIMS(trnDTO.getNbrTrn(), roadCheckInitiateView));
                if (StringUtil.isSet(roadCheckInitiateView.getPhotoURL()))
                    roadCheckInitiateView.setShowPhoto(true);

                if (trnDTO.getFirstName() != null) {
                    roadCheckInitiateView.setFirstName(WordUtils.capitalize(trnDTO.getFirstName().toLowerCase(),
                            Constants.STRING_DELIM_ARRAY));
                }
                if (trnDTO.getMiddleName() != null) {
                    roadCheckInitiateView.setMiddleName(WordUtils
                            .capitalize(trnDTO.getMiddleName().toLowerCase(), Constants.STRING_DELIM_ARRAY));
                }

            }
        } else {

            this.setDetails(roadCheckInitiateView, personBO);

            /*Set name and picture information based on TRN data. Which should have the latest.*/
            /*roadCheckInitiateView.setTrn(personBO.getTrnNbr());
            roadCheckInitiateView.setLastName(WordUtils.capitalize(personBO.getLastName().toLowerCase(), Constants.STRING_DELIM_ARRAY));
                    
            roadCheckInitiateView.setPhotoURL(this.getPictureFromBIMS(personBO.getTrnNbr(), roadCheckInitiateView));
            if (StringUtil.isSet(roadCheckInitiateView.getPhotoURL()))
               roadCheckInitiateView.setShowPhoto(true);
                    
            if (personBO.getFirstName() != null) {
               roadCheckInitiateView.setFirstName(WordUtils.capitalize(personBO.getFirstName().toLowerCase(), Constants.STRING_DELIM_ARRAY));
            }
            if (personBO.getMiddleName() != null) {
               roadCheckInitiateView.setMiddleName(WordUtils.capitalize(personBO.getMiddleName().toLowerCase(), Constants.STRING_DELIM_ARRAY));
            }*/
            roadCheckInitiateView.setTrn(trnDTO.getNbrTrn());
            roadCheckInitiateView.setLastName(
                    WordUtils.capitalize(trnDTO.getLastName().toLowerCase(), Constants.STRING_DELIM_ARRAY));

            roadCheckInitiateView
                    .setPhotoURL(this.getPictureFromBIMS(trnDTO.getNbrTrn(), roadCheckInitiateView));
            if (StringUtil.isSet(roadCheckInitiateView.getPhotoURL()))
                roadCheckInitiateView.setShowPhoto(true);

            if (trnDTO.getFirstName() != null) {
                roadCheckInitiateView.setFirstName(WordUtils.capitalize(trnDTO.getFirstName().toLowerCase(),
                        Constants.STRING_DELIM_ARRAY));
            }
            if (trnDTO.getMiddleName() != null) {
                roadCheckInitiateView.setMiddleName(WordUtils.capitalize(trnDTO.getMiddleName().toLowerCase(),
                        Constants.STRING_DELIM_ARRAY));
            }
        }
        roadCheckInitiateView.setFromSearch(false);
        context.getFlowScope().put("initiateView", roadCheckInitiateView);
        return success();

    } catch (NumberFormatException e) {
        addErrorMessageText(context, "Invalid TRN");
        e.printStackTrace();
        return error();
    } catch (InvalidTrnBranchException_Exception e) {
        addErrorMessage(context, "Norecordfound");
        e.printStackTrace();
        return error();
    } catch (NotValidTrnTypeException_Exception e) {
        addErrorMessage(context, "Norecordfound");
        e.printStackTrace();
        return error();
    } catch (SystemErrorException_Exception e) {
        addErrorMessage(context, "search.failure");
        e.printStackTrace();
        return error();
    } catch (TaxPayerClosedException e) {
        addErrorMessage(context, "TRN.Status.Closed");
        e.printStackTrace();
        return error();
    } catch (TaxPayerUnintendedException e) {
        addErrorMessage(context, "TRN.Status.Invalid");
        e.printStackTrace();
        return error();
    } catch (TaxPayerDeceasedException e) {
        addErrorMessage(context, "TRN.Status.Deceased");
        e.printStackTrace();
        return error();
    } catch (TaxPayerRetiredException e) {
        addErrorMessage(context, "TRN.Status.Retired");
        e.printStackTrace();
        return error();
    } catch (InvalidTaxPayerException e) {
        addErrorMessage(context, "TRN.Status.Invalid");
        e.printStackTrace();
        return error();
    }

    catch (Exception e) {
        e.printStackTrace();
        addErrorMessage(context, "search.failure");
        return error();
        // TODO: handle exception
    }
}

From source file:org.fsl.roms.service.action.RoadCheckServiceAction.java

public Event verifyJP(RequestContext context) {

    RoadCheckReviewSummaryBean roadCheckReviewSummaryBean = (RoadCheckReviewSummaryBean) context.getFlowScope()
            .get("roadCheckReviewSummaryBean");

    /*ONLY done when reprint reason is needed*/
    if (roadCheckReviewSummaryBean.isReprintReasonNeeded()) {
        if (!validateForReprint(context)) {
            logger.info("error");
            roadCheckReviewSummaryBean.setShouldYouPrint(false);
            return error();
        }//from  www  .j a va 2 s.  com
    }
    /*Ricardo Thompson
     * 3/3/2015 
     *This block was commented out as requested in Ticket Request 148231
     *
     */
    if (this.isHandHeld(context) && !roadCheckReviewSummaryBean.allSelectedSummonsSigned) {
        AuthorizationBO auth = new AuthorizationBO();
        if (roadCheckReviewSummaryBean.getjPIdNum() != null) {
            //System.err.println("JP PIN " + roadCheckReviewSummaryBean.getjPIdNum().toString());
            auth.setUsername(roadCheckReviewSummaryBean.getjPIdNum().toString());
        } else {
            auth.setUsername("");
        }

        //auth.setPassword(roadCheckReviewSummaryBean.getjPPin());

        if (validateJPAuth(auth.getUsername(), auth.getPassword(), context)) {
            roadCheckReviewSummaryBean.setShouldYouPrint(false);
            return error();
        } else {
            auth.setUsername(roadCheckReviewSummaryBean.jPIdNum.toString());
            auth.setPersonType("jp");
            try {
                this.printAllDocuments(roadCheckReviewSummaryBean, context);
                roadCheckReviewSummaryBean.setAlreadyPrinted(true);
                roadCheckReviewSummaryBean.setShouldYouPrint(true);

            } catch (NumberFormatException e) {
                this.addErrorMessage(context, "SystemError");
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                this.addErrorMessage(context, "SystemError");
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                this.addErrorMessage(context, "SystemError");
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                this.addErrorMessage(context, "SystemError");
                e.printStackTrace();
            } catch (ErrorSavingException e) {
                this.addErrorMessage(context, "SystemError");
                e.printStackTrace();
            } catch (NoRecordFoundException e) {
                this.addErrorMessage(context, "SystemError");
                e.printStackTrace();
                /*} catch (RequiredFieldMissingException e) {
                   this.addErrorMessage(context, "SystemError");
                   e.printStackTrace();*/
            } catch (Exception e) {
                this.addErrorMessageText(context, "An error has occured while printing document(s).");
                e.printStackTrace();
            }
        }

        /*   try {
              // jreid 2014-07-01
              // QA advised that message is required when no pin is entered
              if (StringUtils.isBlank(roadCheckReviewSummaryBean.getjPPin())) {
                 this.addErrorMessageText(context, "JP pin is required.");
              } else {
                 boolean correctPin = this.getAuthorizationPortProxy().validatePerson(auth);
                
                 if (correctPin) {
          this.printAllDocuments(roadCheckReviewSummaryBean, context);
                
          roadCheckReviewSummaryBean.setAlreadyPrinted(true);
          roadCheckReviewSummaryBean.setShouldYouPrint(true);
                
                 } else {
          roadCheckReviewSummaryBean.setShouldYouPrint(false);
          this.addErrorMessageText(context, "The pin entered is not correct.");
                 }
              }
           } catch (fsl.ta.toms.roms.webservices.authorization.NoRecordFoundException e) {
              this.addErrorMessageText(context, "JP and JP PIN required.");
              e.printStackTrace();
           } catch (Exception e) {
              this.addErrorMessageText(context, "An error has occured while printing document(s).");
              e.printStackTrace();
           }*/
    } else {

        try {
            this.printAllDocuments(roadCheckReviewSummaryBean, context);
            roadCheckReviewSummaryBean.setShouldYouPrint(true);
            // In house do not validate the JP
        } catch (NumberFormatException e) {
            this.addErrorMessage(context, "SystemError");
        } catch (IllegalAccessException e) {
            this.addErrorMessage(context, "SystemError");

        } catch (InvocationTargetException e) {
            this.addErrorMessage(context, "SystemError");

        } catch (NoSuchMethodException e) {
            this.addErrorMessage(context, "SystemError");
        } catch (ErrorSavingException e) {
            this.addErrorMessage(context, "SystemError");
        } catch (NoRecordFoundException e) {
            this.addErrorMessage(context, "SystemError");

        } catch (RequiredFieldMissingException e) {
            this.addErrorMessage(context, "FieldsWithAnAsterisk");
        }

    } //End bracket for jp pin validation else block 

    roadCheckReviewSummaryBean.setAlreadyPrinted(true);
    context.getFlowScope().put("roadCheckReviewSummaryBean", roadCheckReviewSummaryBean);
    return success();

}

From source file:me.camerongray.teamlocker.server.Server.java

public static void main(String[] args) throws PropertyVetoException, SQLException {
    ConnectionManager.initialise("localhost", "teamlocker", "teamlocker", "teamlocker");

    before((request, response) -> {/* w  ww  .j  a v  a2s . c  o  m*/
        // Log request
        StringBuilder sb = new StringBuilder();
        sb.append(request.requestMethod());
        sb.append(" " + request.url());
        sb.append(" " + request.body());
        System.out.println(sb);

        if (request.headers("Authorization") == null) {
            response.header("WWW-Authenticate", "Basic");
            halt(401);
        }
        RequestCredentials credentials = new RequestCredentials(request);
        if (!Auth.checkCredentials(credentials.username, credentials.password)) {
            ResponseBuilder.errorHalt(response, 401, "Incorrect username/password");
        }
    });

    get("/check_auth/", (request, response) -> {
        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    get("/users/:userId/", (request, response) -> {
        DynaBean user = null;
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            if (request.params(":userId").equals("self")) {
                try {
                    user = database.getUser((new RequestCredentials(request)).getUsername());
                } catch (ObjectNotFoundException e) {
                    ResponseBuilder.errorHalt(response, 404, "User not found");
                }
            } else {
                Auth.enforceAdmin(request, response);
                try {
                    user = database.getUser(Integer.parseInt(request.params(":userId")));
                } catch (NumberFormatException e) {
                    ResponseBuilder.errorHalt(response, 400, "User ID must be a number");
                } catch (ObjectNotFoundException e) {
                    ResponseBuilder.errorHalt(response, 404, "User not found");
                }
            }
        }

        return ResponseBuilder.build(response,
                ResponseBuilder.objectOf("user", ResponseBuilder.objectOf("id", (int) user.get("id"),
                        "full_name", (String) user.get("full_name"), "username", (String) user.get("username"),
                        "email", (String) user.get("email"), "auth_hash", (String) user.get("auth_hash"),
                        "encrypted_private_key", (String) user.get("encrypted_private_key"), "public_key",
                        (String) user.get("public_key"), "admin", (boolean) user.get("admin"), "pbkdf2_salt",
                        (String) user.get("pbkdf2_salt"), "aes_iv", (String) user.get("aes_iv"))));
    });

    get("/users/:userId/encrypted_aes_keys/", (request, response) -> {
        int userId;
        if (request.params(":userId").equals("self")) {
            userId = Auth.getCurrentUserId(request);
        } else {
            Auth.enforceAdmin(request, response);
            userId = Integer.parseInt(request.params(":userId"));
        }

        List<DynaBean> accountData;
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            accountData = database.getUserAccountData(userId);
        }

        ArrayList<JSONObject> aesKeyObjects = new ArrayList<>();
        for (DynaBean accountDataItem : accountData) {
            aesKeyObjects.add(ResponseBuilder.objectOf("account_id", (int) accountDataItem.get("account_id"),
                    "encrypted_aes_key", (String) accountDataItem.get("encrypted_aes_key")));
        }

        return ResponseBuilder.build(response,
                ResponseBuilder.objectOf("encrypted_aes_keys", ResponseBuilder.fromArrayList(aesKeyObjects)));
    });

    get("/users/:userId/permissions/", (request, response) -> {
        Auth.enforceAdmin(request, response);

        List<DynaBean> permissions = new ArrayList<>();
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                permissions = database.getUserPermissions(Integer.parseInt(request.params(":userId")));
            } catch (NumberFormatException ex) {
                ResponseBuilder.errorHalt(response, 400, "User ID must be a number");
            }
        }

        ArrayList<JSONObject> responseObjects = new ArrayList<>();
        for (DynaBean permission : permissions) {
            responseObjects.add(ResponseBuilder.objectOf("folder_id", (int) permission.get("folder_id"), "read",
                    (boolean) permission.get("read"), "write", (boolean) permission.get("write")));
        }
        return ResponseBuilder.build(response,
                ResponseBuilder.objectOf("permissions", ResponseBuilder.fromArrayList(responseObjects)));
    });

    delete("/users/:userId/permissions/", (request, response) -> {
        Auth.enforceAdmin(request, response);

        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                database.deleteUserPermissions(Integer.parseInt(request.params(":userId")));
            } catch (NumberFormatException ex) {
                ResponseBuilder.errorHalt(response, 400, "User ID must be a number");
            }
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    post("/users/:userId/", (request, response) -> {
        Auth.enforceAdmin(request, response);

        int userId = -1;
        try {
            userId = Integer.parseInt(request.params(":userId"));
        } catch (NumberFormatException ex) {
            ResponseBuilder.errorHalt(response, 400, "User ID must be a number");
        }

        JSONObject requestJson = null;
        try {
            requestJson = RequestJson.getValidated(request, "postUsers");
        } catch (JSONValidationException ex) {
            // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library
            ResponseBuilder.errorHalt(response, 400, ex.getMessage());
        }

        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            boolean usernameExists = true;
            try {
                DynaBean user = database.getUser(requestJson.getString("username"));
                if ((Integer) user.get("id") == userId) {
                    usernameExists = false;
                }
            } catch (ObjectNotFoundException ex) {
                usernameExists = false;
            }

            if (usernameExists) {
                ResponseBuilder.errorHalt(response, 409, "A user with that username already exists");
            }

            database.updateUser(userId, requestJson.getString("username"), requestJson.getString("full_name"),
                    requestJson.getString("email"), requestJson.getBoolean("admin"));
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    get("/users/", (request, response) -> {
        Auth.enforceAdmin(request, response);
        ArrayList<JSONObject> userObjects = new ArrayList<>();
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            List<DynaBean> users = database.getAllUsers();

            for (DynaBean user : users) {
                userObjects.add(ResponseBuilder.objectOf("id", (int) user.get("id"), "full_name",
                        (String) user.get("full_name"), "username", (String) user.get("username"), "email",
                        (String) user.get("email"), "auth_hash", (String) user.get("auth_hash"),
                        "encrypted_private_key", (String) user.get("encrypted_private_key"), "public_key",
                        (String) user.get("public_key"), "admin", (boolean) user.get("admin"), "pbkdf2_salt",
                        (String) user.get("pbkdf2_salt"), "aes_iv", (String) user.get("aes_iv")));
            }
        }

        return ResponseBuilder.build(response,
                ResponseBuilder.objectOf("users", ResponseBuilder.fromArrayList(userObjects)));
    });

    put("/users/", (request, response) -> {
        JSONObject requestJson = null;
        try {
            requestJson = RequestJson.getValidated(request, "putUsers");
        } catch (JSONValidationException ex) {
            // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library
            ResponseBuilder.errorHalt(response, 400, ex.getMessage());
        }

        int userId = -1;
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            boolean userExists = true;
            try {
                database.getUser(requestJson.getString("username"));
            } catch (ObjectNotFoundException ex) {
                userExists = false;
            }

            if (userExists) {
                ResponseBuilder.errorHalt(response, 409, "A user with that username already exists");
            }

            userId = database.addUser(requestJson.getString("full_name"), requestJson.getString("username"),
                    requestJson.getString("email"),
                    BCrypt.hashpw(requestJson.getString("auth_key"), BCrypt.gensalt()),
                    requestJson.getString("encrypted_private_key"), requestJson.getString("public_key"),
                    requestJson.getBoolean("admin"), requestJson.getString("pbkdf2_salt"),
                    requestJson.getString("aes_iv"));
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("user_id", userId));
    });

    get("/folders/", (request, response) -> {
        ArrayList<JSONObject> folderObjects = new ArrayList<>();
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            List<DynaBean> folders = database.getFolders((int) Auth.getCurrentUser(request).get("id"));
            for (DynaBean folder : folders) {
                folderObjects.add(ResponseBuilder.objectOf("id", (int) folder.get("id"), "name",
                        (String) folder.get("name"), "read", (boolean) folder.get("read"), "write",
                        (boolean) folder.get("write")));
            }
        }
        return ResponseBuilder.build(response,
                ResponseBuilder.objectOf("folders", ResponseBuilder.fromArrayList(folderObjects)));
    });

    put("/folders/", (request, response) -> {
        JSONObject requestJson = null;
        try {
            requestJson = RequestJson.getValidated(request, "putFolder");
        } catch (JSONValidationException ex) {
            // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library
            ResponseBuilder.errorHalt(response, 400, ex.getMessage());
        }
        Auth.enforceAdmin(request, response);

        int folderId = -1;
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                database.getFolder(requestJson.getString("name"));
                ResponseBuilder.errorHalt(response, 409, "A folder with that name already exists");
            } catch (ObjectNotFoundException ex) {
                // We don't care if it doesn't exist, we actually want this exception to be thrown!
            }

            folderId = database.addFolder(requestJson.getString("name"));
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("folder_id", folderId));
    });

    post("/folders/:folderId/", (request, response) -> {
        int folderId = -1;
        try {
            folderId = Integer.parseInt(request.params(":folderId"));
        } catch (NumberFormatException ex) {
            ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number");
        }
        Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_WRITE);

        JSONObject requestJson = null;
        try {
            requestJson = RequestJson.getValidated(request, "postFolders");
        } catch (JSONValidationException ex) {
            // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library
            ResponseBuilder.errorHalt(response, 400, ex.getMessage());
        }

        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                database.updateFolder(folderId, requestJson.getString("name"));
            } catch (ObjectNotFoundException ex) {
                ResponseBuilder.errorHalt(response, 404, "Folder not found");
            }
        }
        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    // TODO - Replace with generic update user method
    post("/users/self/update_password/", (request, response) -> {
        JSONObject requestJson = null;
        try {
            requestJson = RequestJson.getValidated(request, "postUsersUpdatePassword");
        } catch (JSONValidationException ex) {
            // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library
            ResponseBuilder.errorHalt(response, 400, ex.getMessage());
        }

        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                database.updateUserPassword(Auth.getCurrentUserId(request),
                        requestJson.getString("encrypted_private_key"), requestJson.getString("aes_iv"),
                        requestJson.getString("pbkdf2_salt"),
                        BCrypt.hashpw(requestJson.getString("auth_key"), BCrypt.gensalt()));
            } catch (ObjectNotFoundException ex) {
                ResponseBuilder.errorHalt(response, 404, "User not found");
            }
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    delete("/folders/:folderId/", (request, response) -> {
        int folderId = -1;
        try {
            folderId = Integer.parseInt(request.params(":folderId"));
        } catch (NumberFormatException ex) {
            ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number");
        }
        Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_WRITE);

        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                database.deleteFolder(folderId);
            } catch (ObjectNotFoundException ex) {
                ResponseBuilder.errorHalt(response, 404, "Folder not found");
            }
        }
        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    get("/folders/:folderId/accounts/", (request, response) -> {
        int folderId = -1;
        try {
            folderId = Integer.parseInt(request.params(":folderId"));
        } catch (NumberFormatException ex) {
            ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number");
        }
        Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_READ);

        ArrayList<JSONObject> accountObjects = new ArrayList<>();
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            List<DynaBean> accounts = new ArrayList<>();
            accounts = database.getFolderAccounts(folderId, Auth.getCurrentUserId(request));

            for (DynaBean account : accounts) {
                accountObjects.add(ResponseBuilder.objectOf("id", (int) account.get("account_id"),
                        "account_metadata", (String) account.get("account_metadata"), "encrypted_aes_key",
                        (String) account.get("encrypted_aes_key")));
            }
        }
        return ResponseBuilder.build(response,
                ResponseBuilder.objectOf("accounts", ResponseBuilder.fromArrayList(accountObjects)));
    });

    get("/folders/:folderId/permissions/", (request, response) -> {
        Auth.enforceAdmin(request, response);

        List<DynaBean> permissions = new ArrayList<>();
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                permissions = database.getFolderPermissions(Integer.parseInt(request.params(":folderId")));
            } catch (NumberFormatException ex) {
                ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number");
            }
        }

        ArrayList<JSONObject> responseObjects = new ArrayList<>();
        for (DynaBean permission : permissions) {
            responseObjects.add(ResponseBuilder.objectOf("user_id", (int) permission.get("user_id"), "read",
                    (boolean) permission.get("read"), "write", (boolean) permission.get("write")));
        }
        return ResponseBuilder.build(response,
                ResponseBuilder.objectOf("permissions", ResponseBuilder.fromArrayList(responseObjects)));
    });

    post("/folders/:folderId/permissions/", (request, response) -> {
        Auth.enforceAdmin(request, response);
        int folderId = -1;
        try {
            folderId = Integer.parseInt(request.params(":folderId"));
        } catch (NumberFormatException ex) {
            ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number");
        }

        JSONObject requestJson = RequestJson.getValidated(request, "postFoldersPermissions");

        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                database.getFolder(folderId);
            } catch (ObjectNotFoundException ex) {
                ResponseBuilder.errorHalt(response, 404, "Folder not found!");
            }
            TransactionInterface transaction;
            try {
                transaction = new Transaction(database.getWrappedConnection());
            } catch (ExistingOpenTransactionException ex) {
                transaction = new NullTransaction();
            }

            try {
                database.deleteFolderPermissions(folderId);

                JSONArray permissions = requestJson.getJSONArray("permissions");
                for (int i = 0; i < permissions.length(); i++) {
                    JSONObject permission = permissions.getJSONObject(i);
                    int userId = permission.getInt("user_id");
                    boolean read = permission.getBoolean("read");
                    boolean write = permission.getBoolean("write");
                    try {
                        DynaBean user = database.getUser(userId);
                        if ((boolean) user.get("admin")) {
                            transaction.rollback();
                            ResponseBuilder.errorHalt(response, 400, "Trying to set permissions "
                                    + "for an administrator, administrators already have full permission.");
                        }
                    } catch (ObjectNotFoundException ex) {
                        transaction.rollback();
                        ResponseBuilder.errorHalt(response, 404, "User not found!");
                    }

                    if (write && !read) {
                        transaction.rollback();
                        ResponseBuilder.errorHalt(response, 400,
                                "Users must be able " + "to read a folder if they are to write to it");
                    }

                    if (!(write || read)) {
                        database.deleteAccountDataForFolder(folderId, userId);
                    } else {
                        database.addPermission(folderId, userId, read, write);
                    }
                }
            } catch (SQLException ex) {
                transaction.rollback();
                ResponseBuilder.errorHalt(response, 500, "Error updating permissions - " + ex);
            }
            transaction.commit();
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    get("/folders/:folderId/public_keys/", (request, response) -> {
        int folderId = -1;
        try {
            folderId = Integer.parseInt(request.params(":folderId"));
        } catch (NumberFormatException ex) {
            ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number");
        }
        Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_WRITE);

        List<DynaBean> users;
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            users = database.getFolderUsers(folderId);
        }

        ArrayList<JSONObject> publicKeyObjects = new ArrayList<>();
        for (DynaBean user : users) {
            publicKeyObjects.add(ResponseBuilder.objectOf("user_id", (int) user.get("id"), "public_key",
                    (String) user.get("public_key")));
        }
        return ResponseBuilder.build(response,
                ResponseBuilder.objectOf("public_keys", ResponseBuilder.fromArrayList(publicKeyObjects)));
    });

    get("/accounts/:accountId/", (request, response) -> {
        int accountId = -1;
        try {
            accountId = Integer.parseInt(request.params(":accountId"));
        } catch (NumberFormatException ex) {
            ResponseBuilder.errorHalt(response, 400, "Account ID must be a number");
        }
        Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_READ);

        DynaBean account = null;
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                account = database.getAccountData(accountId, Auth.getCurrentUserId(request));
            } catch (ObjectNotFoundException ex) {
                ResponseBuilder.errorHalt(response, 404, "Account not found");
            }
        }
        return ResponseBuilder.build(response,
                ResponseBuilder.objectOf("account",
                        ResponseBuilder.objectOf("account_metadata", (String) account.get("account_metadata"),
                                "encrypted_aes_key", (String) account.get("encrypted_aes_key"))));
    });

    delete("/accounts/:accountId/", (request, response) -> {
        int accountId = -1;
        try {
            accountId = Integer.parseInt(request.params(":accountId"));
        } catch (NumberFormatException ex) {
            ResponseBuilder.errorHalt(response, 400, "Account ID must be a number");
        }
        Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_WRITE);

        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                database.deleteAccount(accountId);
            } catch (ObjectNotFoundException ex) {
                ResponseBuilder.errorHalt(response, 404, "Account not found");
            }
        }
        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    post("/accounts/:accountId/", (request, response) -> {
        JSONObject requestJson = null;
        try {
            requestJson = RequestJson.getValidated(request, "postAccountsSingle");
        } catch (JSONValidationException ex) {
            // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library
            ResponseBuilder.errorHalt(response, 400, "JSON Validation Error - " + ex.getMessage());
        }

        int accountId = -1;
        try {
            accountId = Integer.parseInt(request.params(":accountId"));
        } catch (NumberFormatException ex) {
            ResponseBuilder.errorHalt(response, 400, "Account ID must be a number");
        }

        Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_WRITE);

        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                database.getAccount(accountId);
            } catch (ObjectNotFoundException ex) {
                ResponseBuilder.errorHalt(response, 404, "Account not found");
            }
            try {
                database.getFolder(requestJson.getInt("folder_id"));
            } catch (ObjectNotFoundException ex) {
                ResponseBuilder.errorHalt(response, 404, "Folder not found");
            }
            TransactionInterface transaction;
            try {
                transaction = new Transaction(database.getWrappedConnection());
            } catch (ExistingOpenTransactionException ex) {
                transaction = new NullTransaction();
            }
            try {
                database.updateAccount(accountId, requestJson.getInt("folder_id"));

                JSONArray accountDataItems = requestJson.getJSONArray("encrypted_account_data");
                for (int i = 0; i < accountDataItems.length(); i++) {
                    JSONObject accountDataItem = accountDataItems.getJSONObject(i);
                    int userId = accountDataItem.getInt("user_id");
                    database.deleteAccountData(accountId, userId);
                    database.addAccountDataItem(accountId, userId,
                            accountDataItem.getString("account_metadata"),
                            accountDataItem.getString("password"),
                            accountDataItem.getString("encrypted_aes_key"));
                }
            } catch (SQLException ex) {
                transaction.rollback();
                ResponseBuilder.errorHalt(response, 500, "Error saving account - " + ex);
            } catch (ObjectNotFoundException ex) {
                transaction.rollback();
                ResponseBuilder.errorHalt(response, 404, "Error saving account - Object Not Found");
            }

            transaction.commit();
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    post("/accounts/", (request, response) -> {
        JSONObject requestJson = RequestJson.getValidated(request, "postAccountsBatch");
        JSONArray accounts = requestJson.getJSONArray("accounts");

        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            TransactionInterface transaction;
            try {
                transaction = new Transaction(database.getWrappedConnection());
            } catch (ExistingOpenTransactionException ex) {
                transaction = new NullTransaction();
            }
            try {
                for (int i = 0; i < accounts.length(); i++) {
                    JSONObject account = accounts.getJSONObject(i);
                    int accountId = account.getInt("account_id");
                    try {
                        if (!Auth.getAccountPermission(request, response, accountId, Auth.PERMISSION_WRITE)) {
                            transaction.rollback();
                            ResponseBuilder.errorHalt(response, 403,
                                    "You do not have write permission for account " + accountId);
                        }
                    } catch (ObjectNotFoundException ex) {
                        transaction.rollback();
                        ex.printStackTrace();
                        ResponseBuilder.errorHalt(response, 404, "Account not found");
                    }

                    JSONArray accountDataItems = account.getJSONArray("encrypted_account_data");
                    for (int j = 0; j < accountDataItems.length(); j++) {
                        JSONObject accountDataItem = accountDataItems.getJSONObject(j);
                        int userId = accountDataItem.getInt("user_id");
                        database.deleteAccountData(accountId, userId);
                        database.addAccountDataItem(accountId, userId,
                                accountDataItem.getString("account_metadata"),
                                accountDataItem.getString("password"),
                                accountDataItem.getString("encrypted_aes_key"));
                    }
                }
            } catch (SQLException ex) {
                transaction.rollback();
                ResponseBuilder.errorHalt(response, 500, "Error saving accounts - " + ex);
            }
            transaction.commit();
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    put("/accounts/", (request, response) -> {
        JSONObject requestJson = null;
        try {
            requestJson = RequestJson.getValidated(request, "putAccounts");
        } catch (JSONValidationException ex) {
            // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library
            ResponseBuilder.errorHalt(response, 400, ex.getMessage());
        }
        Auth.enforceFolderPermission(request, response, requestJson.getInt("folder_id"), Auth.PERMISSION_WRITE);

        int accountId = -1;
        WrappedConnection connection = ConnectionManager.getConnection(request);
        try (Database database = new Database(connection)) {
            try {
                database.getFolder(requestJson.getInt("folder_id"));
            } catch (ObjectNotFoundException ex) {
                ResponseBuilder.errorHalt(response, 404, "Folder not found");
            }

            TransactionInterface transaction;
            try {
                transaction = new Transaction(connection);
            } catch (ExistingOpenTransactionException ex) {
                transaction = new NullTransaction();
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }

            try {
                accountId = database.addAccount(requestJson.getInt("folder_id"));
                JSONArray accountDataItems = requestJson.getJSONArray("encrypted_account_data");
                for (int i = 0; i < accountDataItems.length(); i++) {
                    JSONObject accountDataItem = accountDataItems.getJSONObject(i);
                    database.addAccountDataItem(accountId, accountDataItem.getInt("user_id"),
                            accountDataItem.getString("account_metadata"),
                            accountDataItem.getString("password"),
                            accountDataItem.getString("encrypted_aes_key"));
                }
            } catch (SQLException ex) {
                transaction.rollback();
                ResponseBuilder.errorHalt(response, 500, "Error adding account - " + ex);
            }

            transaction.commit();
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("account_id", accountId));
    });

    get("/accounts/:accountId/password/", (request, response) -> {
        int accountId = -1;
        try {
            accountId = Integer.parseInt(request.params(":accountId"));
        } catch (NumberFormatException ex) {
            ResponseBuilder.errorHalt(response, 400, "Account ID must be a number");
        }
        Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_READ);

        DynaBean account = null;
        try (Database database = new Database(ConnectionManager.getConnection(request))) {
            try {
                account = database.getAccountData(accountId, Auth.getCurrentUserId(request));
            } catch (ObjectNotFoundException ex) {
                ResponseBuilder.errorHalt(response, 404, "Account not found");
            }
        }
        return ResponseBuilder.build(response,
                ResponseBuilder.objectOf("password",
                        ResponseBuilder.objectOf("encrypted_password", (String) account.get("password"),
                                "encrypted_aes_key", (String) account.get("encrypted_aes_key"))));
    });

    put("/transaction/", (request, response) -> {
        Transaction transaction = TransactionStore.getTransaction();

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("transaction_id", transaction.getId()));
    });

    post("/transaction/:transactionId/commit/", (request, response) -> {
        String transactionId = request.params(":transactionId");

        try {
            Transaction transaction = TransactionStore.getTransaction(transactionId);
            transaction.commit();
            transaction.getWrappedConnection().getConnection().close();
            TransactionStore.forgetTransaction(transactionId);
        } catch (TransactionNotFoundException ex) {
            ResponseBuilder.errorHalt(response, 404, "Transaction not found!");
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    post("/transaction/:transactionId/rollback/", (request, response) -> {
        String transactionId = request.params(":transactionId");

        try {
            Transaction transaction = TransactionStore.getTransaction(transactionId);
            transaction.rollback();
            transaction.getWrappedConnection().getConnection().close();
            TransactionStore.forgetTransaction(transactionId);
        } catch (TransactionNotFoundException ex) {
            ResponseBuilder.errorHalt(response, 404, "Transaction not found!");
        }

        return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true));
    });

    exception(Exception.class, (e, request, response) -> {
        if (e.getClass().equals(TransactionNotFoundException.class)) {
            response.status(404);
            response.body(ResponseBuilder.objectOf("error", true, "message", "Transaction not found", "type",
                    "transaction_not_found").toString());
        } else {
            System.out.println("An unhandled exception occurred!");
            System.out.println(e.toString());
            e.printStackTrace();
            response.status(500);
            response.type("application/json");
            response.body(ResponseBuilder
                    .objectOf("error", true, "message", "An unhandled server error occurred! - " + e.toString())
                    .toString());
        }
    });

    //TODO - Disable this in production!
    //        spark.debug.DebugScreen.enableDebugScreen();
}

From source file:at.alladin.rmbt.controlServer.RegistrationResource.java

@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    final String secret = getContext().getParameters().getFirstValue("RMBT_SECRETKEY");

    addAllowOrigin();/*from   w  w w  .  j a  v  a  2  s .c om*/

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();
    String answerString;

    final String clientIpRaw = getIP();
    final InetAddress clientAddress = InetAddresses.forString(clientIpRaw);
    final String clientIpString = InetAddresses.toAddrString(clientAddress);

    System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST"), clientIpRaw));

    final String geoIpCountry = GeoIPHelper.lookupCountry(clientAddress);
    // public_ip_asn
    final Long asn = Helperfunctions.getASN(clientAddress);
    // public_ip_as_name 
    // country_asn (2 digit country code of AS, eg. AT or EU)
    final String asName;
    final String asCountry;
    if (asn == null) {
        asName = null;
        asCountry = null;
    } else {
        asName = Helperfunctions.getASName(asn);
        asCountry = Helperfunctions.getAScountry(asn);
    }

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            int typeId = 0;

            final String lang = request.optString("language");

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            }

            //                System.out.println(request.toString(4));

            if (conn != null) {

                final Client clientDb = new Client(conn);

                if (!request.optString("type").isEmpty()) {
                    typeId = clientDb.getTypeId(request.getString("type"));
                    if (clientDb.hasError())
                        errorList.addError(clientDb.getError());
                }

                final List<String> clientNames = Arrays
                        .asList(settings.getString("RMBT_CLIENT_NAME").split(",\\s*"));
                final List<String> clientVersions = Arrays
                        .asList(settings.getString("RMBT_VERSION_NUMBER").split(",\\s*"));

                if (clientNames.contains(request.optString("client"))
                        && clientVersions.contains(request.optString("version")) && typeId > 0) {

                    UUID uuid = null;
                    final String uuidString = request.optString("uuid", "");
                    if (uuidString.length() != 0)
                        uuid = UUID.fromString(uuidString);

                    final String clientName = request.getString("client");
                    final String clientVersion = request.getString("version");

                    String timeZoneId = request.getString("timezone");
                    // String tmpTimeZoneId = timeZoneId;

                    final long clientTime = request.getLong("time");
                    final Timestamp clientTstamp = java.sql.Timestamp
                            .valueOf(new Timestamp(clientTime).toString());

                    final JSONObject location = request.optJSONObject("location");

                    long geotime = 0;
                    double geolat = 0;
                    double geolong = 0;
                    float geoaccuracy = 0;
                    double geoaltitude = 0;
                    float geobearing = 0;
                    float geospeed = 0;
                    String geoprovider = "";

                    if (!request.isNull("location")) {
                        geotime = location.optLong("time", 0);
                        geolat = location.optDouble("lat", 0);
                        geolong = location.optDouble("long", 0);
                        geoaccuracy = (float) location.optDouble("accuracy", 0);
                        geoaltitude = location.optDouble("altitude", 0);
                        geobearing = (float) location.optDouble("bearing", 0);
                        geospeed = (float) location.optDouble("speed", 0);
                        geoprovider = location.optString("provider", "");
                    }

                    Calendar timeWithZone = null;

                    if (timeZoneId.isEmpty()) {
                        timeZoneId = Helperfunctions.getTimezoneId();
                        timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);
                    } else
                        timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);

                    long clientUid = 0;
                    /*
                     * if (uuid == null) {
                     * clientDb.setTimeZone(timeWithZone);
                     * clientDb.setTime(tstamp);
                     * clientDb.setClient_type_id(typeId); uuid =
                     * clientDb.storeClient(); if (clientDb.hasError()) {
                     * errorList.addError(clientDb.getError()); } else {
                     * answer.put("uuid", uuid.toString()); } }
                     */

                    if (errorList.getLength() == 0 && uuid != null) {
                        clientUid = clientDb.getClientByUuid(uuid);
                        if (clientDb.hasError())
                            errorList.addError(clientDb.getError());
                    }

                    if (clientUid > 0) {

                        final String testUuid = UUID.randomUUID().toString();
                        final String testOpenUuid = UUID.randomUUID().toString();

                        boolean testServerEncryption = true; // default is
                                                             // true

                        // hack for android api <= 10 (2.3.x)
                        // using encryption with test doesn't work
                        if (request.has("plattform") && request.optString("plattform").equals("Android"))
                            if (request.has("api_level")) {
                                final String apiLevelString = request.optString("api_level");
                                try {
                                    final int apiLevel = Integer.parseInt(apiLevelString);
                                    if (apiLevel <= 10)
                                        testServerEncryption = false;
                                } catch (final NumberFormatException e) {
                                }
                            }

                        final String serverType;
                        if (request.optString("client").equals("RMBTws"))
                            serverType = "RMBTws";
                        else
                            serverType = "RMBT";

                        final Boolean ipv6;
                        if (clientAddress instanceof Inet6Address)
                            ipv6 = true;
                        else if (clientAddress instanceof Inet4Address)
                            ipv6 = false;
                        else // should never happen, unless ipv > 6 is available
                            ipv6 = null;

                        final TestServer server = getNearestServer(errorList, geolat, geolong, geotime,
                                clientIpString, asCountry, geoIpCountry, serverType, testServerEncryption,
                                ipv6);

                        try {
                            if (server == null)
                                throw new JSONException("could not find server");

                            if (timeZoneId.isEmpty()) {
                                timeZoneId = Helperfunctions.getTimezoneId();
                                timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);
                            } else
                                timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);

                            answer.put("test_server_address", server.address);
                            answer.put("test_server_port", server.port);
                            answer.put("test_server_name", server.name);
                            answer.put("test_server_encryption", testServerEncryption);

                            answer.put("test_duration", getSetting("rmbt_duration"));
                            answer.put("test_numthreads", getSetting("rmbt_num_threads"));
                            answer.put("test_numpings", getSetting("rmbt_num_pings"));

                            answer.put("client_remote_ip", clientIpString);

                            final String resultUrl = new Reference(getURL(),
                                    settings.getString("RMBT_RESULT_PATH")).getTargetRef().toString();

                            // System.out.println(resultUrl);

                            answer.put("result_url", resultUrl);

                            final String resultQoSUrl = new Reference(getURL(),
                                    settings.getString("RMBT_QOS_RESULT_PATH")).getTargetRef().toString();

                            // System.out.println(resultUrl);

                            answer.put("result_qos_url", resultQoSUrl);
                        } catch (final JSONException e) {
                            System.out.println("Error generating Answer " + e.toString());
                            errorList.addError("ERROR_RESPONSE_JSON");

                        }

                        if (errorList.getLength() == 0)
                            try {

                                PreparedStatement st;
                                st = conn.prepareStatement(
                                        "INSERT INTO test(time, uuid, open_test_uuid, client_id, client_name, client_version, client_software_version, client_language, client_public_ip, client_public_ip_anonymized, country_geoip, server_id, port, use_ssl, timezone, client_time, duration, num_threads_requested, status, software_revision, client_test_counter, client_previous_test_status, public_ip_asn, public_ip_as_name, country_asn, public_ip_rdns, run_ndt)"
                                                + "VALUES(NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                                        Statement.RETURN_GENERATED_KEYS);

                                int i = 1;
                                // uuid
                                st.setObject(i++, UUID.fromString(testUuid));
                                // open_test_uuid
                                st.setObject(i++, UUID.fromString(testOpenUuid));
                                // client_id
                                st.setLong(i++, clientUid);
                                // client_name
                                st.setString(i++, clientName);
                                // client_version
                                st.setString(i++, clientVersion);
                                // client_software_version
                                st.setString(i++, request.optString("softwareVersion", null));
                                // client_language
                                st.setString(i++, lang);
                                // client_public_ip
                                st.setString(i++, clientIpString);
                                // client_public_ip_anonymized
                                st.setString(i++, Helperfunctions.anonymizeIp(clientAddress));
                                // country_geoip (2digit country code derived from public IP of client)
                                st.setString(i++, geoIpCountry);
                                // server_id
                                st.setInt(i++, server.id);
                                // port
                                st.setInt(i++, server.port);
                                // use_ssl
                                st.setBoolean(i++, testServerEncryption);
                                // timezone (of client)
                                st.setString(i++, timeZoneId);
                                // client_time (local time of client)
                                st.setTimestamp(i++, clientTstamp, timeWithZone);
                                // duration (requested)
                                st.setInt(i++, Integer.parseInt(getSetting("rmbt_duration")));
                                // num_threads_requested 
                                st.setInt(i++, Integer.parseInt(getSetting("rmbt_num_threads")));
                                // status (of test)
                                st.setString(i++, "STARTED"); //was "RUNNING" before
                                // software_revision (of client)
                                st.setString(i++, request.optString("softwareRevision", null));
                                // client_test_counter (number of tests the client has performed)
                                final int testCounter = request.optInt("testCounter", -1);
                                if (testCounter == -1) // older clients did not support testCounter
                                    st.setNull(i++, Types.INTEGER);
                                else
                                    st.setLong(i++, testCounter);
                                // client_previous_test_status (outcome of previous test)
                                st.setString(i++, request.optString("previousTestStatus", null));
                                // AS name
                                if (asn == null)
                                    st.setNull(i++, Types.BIGINT);
                                else
                                    st.setLong(i++, asn);
                                if (asName == null)
                                    st.setNull(i++, Types.VARCHAR);
                                else
                                    st.setString(i++, asName);
                                // AS country
                                if (asCountry == null)
                                    st.setNull(i++, Types.VARCHAR);
                                else
                                    st.setString(i++, asCountry);
                                //public_ip_rdns
                                String reverseDNS = Helperfunctions.reverseDNSLookup(clientAddress);
                                if (reverseDNS == null || reverseDNS.isEmpty())
                                    st.setNull(i++, Types.VARCHAR);
                                else {
                                    reverseDNS = reverseDNS.replaceFirst("\\.$", "");
                                    st.setString(i++, reverseDNS); // cut off last dot (#332)
                                }
                                // run_ndt
                                if (request.has("ndt"))
                                    st.setBoolean(i++, request.getBoolean("ndt"));
                                else
                                    st.setNull(i++, Types.BOOLEAN);

                                final int affectedRows = st.executeUpdate();
                                if (affectedRows == 0)
                                    errorList.addError("ERROR_DB_STORE_TEST");
                                else {
                                    long key = 0;
                                    final ResultSet rs = st.getGeneratedKeys();
                                    if (rs.next())
                                        // Retrieve the auto generated
                                        // key(s).
                                        key = rs.getLong(1);
                                    rs.close();

                                    final PreparedStatement getProviderSt = conn
                                            .prepareStatement("SELECT rmbt_set_provider_from_as(?)");
                                    getProviderSt.setLong(1, key);
                                    String provider = null;
                                    if (getProviderSt.execute()) {
                                        final ResultSet rs2 = getProviderSt.getResultSet();
                                        if (rs2.next())
                                            provider = rs2.getString(1);
                                    }

                                    if (provider != null)
                                        answer.put("provider", provider);

                                    final PreparedStatement testSlotStatement = conn
                                            .prepareStatement("SELECT rmbt_get_next_test_slot(?)");
                                    testSlotStatement.setLong(1, key);
                                    int testSlot = -1;
                                    if (testSlotStatement.execute()) {
                                        final ResultSet rs2 = testSlotStatement.getResultSet();
                                        if (rs2.next())
                                            testSlot = rs2.getInt(1);
                                    }

                                    if (testSlot < 0)
                                        errorList.addError("ERROR_DB_STORE_GENERAL");
                                    else {
                                        final String data = testUuid + "_" + testSlot;
                                        final String hmac = Helperfunctions.calculateHMAC(secret, data);
                                        if (hmac.length() == 0)
                                            errorList.addError("ERROR_TEST_TOKEN");
                                        final String token = data + "_" + hmac;

                                        final PreparedStatement updateSt = conn
                                                .prepareStatement("UPDATE test SET token = ? WHERE uid = ?");
                                        updateSt.setString(1, token);
                                        updateSt.setLong(2, key);
                                        updateSt.executeUpdate();

                                        answer.put("test_token", token);

                                        answer.put("test_uuid", testUuid);
                                        answer.put("test_id", key);

                                        final long now = System.currentTimeMillis();
                                        int wait = testSlot - (int) (now / 1000);
                                        if (wait < 0)
                                            wait = 0;

                                        answer.put("test_wait", wait);

                                        if (geotime != 0 && geolat != 0 && geolong != 0) {

                                            final GeoLocation clientLocation = new GeoLocation(conn);

                                            clientLocation.setTest_id(key);

                                            final Timestamp geotstamp = java.sql.Timestamp
                                                    .valueOf(new Timestamp(geotime).toString());
                                            clientLocation.setTime(geotstamp, timeZoneId);

                                            clientLocation.setAccuracy(geoaccuracy);
                                            clientLocation.setAltitude(geoaltitude);
                                            clientLocation.setBearing(geobearing);
                                            clientLocation.setSpeed(geospeed);
                                            clientLocation.setProvider(geoprovider);
                                            clientLocation.setGeo_lat(geolat);
                                            clientLocation.setGeo_long(geolong);

                                            clientLocation.storeLocation();

                                            if (clientLocation.hasError())
                                                errorList.addError(clientLocation.getError());
                                        }
                                    }
                                }

                                st.close();
                            } catch (final SQLException e) {
                                errorList.addError("ERROR_DB_STORE_GENERAL");
                                e.printStackTrace();

                            }

                    } else
                        errorList.addError("ERROR_CLIENT_UUID");

                } else
                    errorList.addError("ERROR_CLIENT_VERSION");

            } else
                errorList.addError("ERROR_DB_CONNECTION");
            //                System.out.println(answer.toString(4));
        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    answerString = answer.toString();
    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:ispyb.client.mx.results.ViewResultsAction.java

/**
 * To display all the parameters linked to a dataCollectionId.
 * //from   w  ww  . j a  va 2  s . co  m
 * @param mapping
 * @param actForm
 * @param request
 * @param in_reponse
 * @return
 */
public ActionForward display(ActionMapping mapping, ActionForm actForm, HttpServletRequest request,
        HttpServletResponse in_reponse) {

    ActionMessages errors = new ActionMessages();
    boolean redirectToError = true;
    boolean displayOutputParam = false;

    try {

        dataCollectionIdst = request.getParameter(Constants.DATA_COLLECTION_ID);
        Integer dataCollectionId = null;
        if (dataCollectionIdst != null) {
            try {
                dataCollectionId = new Integer(dataCollectionIdst);
            } catch (NumberFormatException e) {

            }
        }
        if (dataCollectionId == null && BreadCrumbsForm.getIt(request).getSelectedDataCollection() != null) {
            dataCollectionId = BreadCrumbsForm.getIt(request).getSelectedDataCollection().getDataCollectionId();
        }

        request.getSession().setAttribute(Constants.DATA_COLLECTION_ID, dataCollectionId);
        ViewResultsForm form = (ViewResultsForm) actForm;
        form.setDataCollectionId(dataCollectionId);

        DataCollection3VO dc = dataCollectionService.findByPk(dataCollectionId, false, true);
        DataCollectionGroup3VO dataCollectionGroup = null;
        if (dc != null) {
            dataCollectionGroup = dataCollectionGroupService.findByPk(dc.getDataCollectionGroupVOId(), false,
                    true);
        }

        Screening3VO[] screeningList = null;

        Integer sessionId = null;
        if (dataCollectionGroup != null)
            sessionId = new Integer(dataCollectionGroup.getSessionVOId());
        Session3VO sessionlv = null;
        if (sessionId != null)
            sessionlv = sessionService.findByPk(sessionId, false, false, false);
        form.setSession(sessionlv);

        if (sessionlv == null) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("errors.detail", "No session retrieved"));
            saveErrors(request, errors);
            return (mapping.findForward("error"));
        }

        // Confidentiality (check if object proposalId and session proposalId match)
        if (!Confidentiality.isAccessAllowed(request, sessionlv.getProposalVO().getProposalId())) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", "Access denied"));
            saveErrors(request, errors);
            return (mapping.findForward("error"));
        }

        if (sessionlv.getBeamLineSetupVOId() != null && sessionlv.getBeamLineSetupVOId().intValue() != 0) {
            Integer beamLineId = new Integer(sessionlv.getBeamLineSetupVOId());
            BeamLineSetup3VO beamLinelv = beamLineSetupService.findByPk(beamLineId);
            form.setBeamLine(beamLinelv);
            form.setUndulatorTypes(beamLinelv.getUndulatorType1(), beamLinelv.getUndulatorType2(),
                    beamLinelv.getUndulatorType3());
        }

        String rMerge = request.getParameter(Constants.RSYMM);
        String iSigma = request.getParameter(Constants.ISIGMA);
        request.getSession().setAttribute(Constants.RSYMM, rMerge);
        request.getSession().setAttribute(Constants.ISIGMA, iSigma);

        Screening3VO[] screenings = dataCollectionGroup.getScreeningsTab();

        if (screenings.length > 0) {

            displayOutputParam = true;// there is at least 1 screening so we display the output params

            int length = screenings.length;
            screeningList = screenings;
            // if many screenings, only use the last one

            ScreeningRank3VO srlv = new ScreeningRank3VO();
            ScreeningOutput3VO sov = new ScreeningOutput3VO();
            ScreeningRankSet3VO srsv = new ScreeningRankSet3VO();
            ScreeningOutputLattice3VO solav = new ScreeningOutputLattice3VO();

            ScreeningStrategy3VO[] screeningStrategyList;
            List<ScreeningStrategyValueInfo> screeningInfoList = new ArrayList<ScreeningStrategyValueInfo>();

            // ScreeningValue sv = screening.findByPrimaryKey(screeningId);
            Screening3VO sv = screeningList[length - 1];
            // sv = screeningService.loadEager(sv);

            ScreeningRank3VO[] screeningRanks = sv.getScreeningRanksTab();
            if (screeningRanks.length > 0) {
                srlv = screeningRanks[0];
                srsv = srlv.getScreeningRankSetVO();
            }

            ScreeningOutput3VO[] screeningOutputs = sv.getScreeningOutputsTab();
            if (screeningOutputs.length > 0) {
                sov = screeningOutputs[0];
                // sov = screeningOutputService.loadEager(sov);
            }

            ScreeningOutputLattice3VO[] screeningOutputLattices = sov.getScreeningOutputLatticesTab();
            if (screeningOutputLattices != null && screeningOutputLattices.length > 0) {

                solav = screeningOutputLattices[0];
                form.setScreeningOutputLattice(solav);
            }
            ScreeningStrategy3VO[] screeningStrategys = sov.getScreeningStrategysTab();
            if (screeningStrategys.length > 0) {

                screeningStrategyList = screeningStrategys;
                List<ScreeningStrategyWedge3VO> wedgeList = new ArrayList<ScreeningStrategyWedge3VO>();

                for (int j = 0; j < screeningStrategyList.length; j++) {
                    ScreeningStrategy3VO ss = screeningStrategyService
                            .findByPk(screeningStrategyList[j].getScreeningStrategyId(), true);
                    ScreeningStrategyValueInfo ssvi = new ScreeningStrategyValueInfo(ss);
                    ssvi.setProgramLog(dc);
                    screeningInfoList.add(ssvi);

                    ArrayList<ScreeningStrategyWedge3VO> list = ss.getScreeningStrategyWedgesList();
                    if (list != null)
                        wedgeList.addAll(list);
                }
                form.setScreeningStrategyList(screeningStrategyList);
                form.setListStrategiesInfo(screeningInfoList);

                // strategy wedge
                ScreeningStrategyWedge3VO[] screeningStrategyWedgeList;
                List<ScreeningStrategyWedgeValueInfo> screeningWedgeInfoList;

                int nb = wedgeList.size();
                screeningStrategyWedgeList = new ScreeningStrategyWedge3VO[nb];
                for (int j = 0; j < nb; j++) {
                    screeningStrategyWedgeList[j] = wedgeList.get(j);
                }

                screeningWedgeInfoList = new ArrayList<ScreeningStrategyWedgeValueInfo>();
                for (int k = 0; k < screeningStrategyWedgeList.length; k++) {
                    ScreeningStrategyWedgeValueInfo sw = new ScreeningStrategyWedgeValueInfo(
                            screeningStrategyWedgeService.findByPk(
                                    screeningStrategyWedgeList[k].getScreeningStrategyWedgeId(), true));
                    screeningWedgeInfoList.add(sw);
                }
                form.setScreeningStrategyWedgeList(screeningStrategyWedgeList);
                form.setListStrategiesWedgeInfo(screeningWedgeInfoList);

                // strategy sub wedge
                ScreeningStrategySubWedge3VO[][] screeningStrategySubWedgeListAll;
                List<ScreeningStrategySubWedgeValueInfo>[] screeningSubWedgeInfoListAll;
                screeningStrategySubWedgeListAll = new ScreeningStrategySubWedge3VO[screeningStrategyWedgeList.length][];
                screeningSubWedgeInfoListAll = new ArrayList[screeningStrategyWedgeList.length];
                for (int j = 0; j < screeningStrategyWedgeList.length; j++) {
                    ScreeningStrategySubWedge3VO[] screeningStrategysSubWedge = screeningStrategyWedgeService
                            .findByPk(screeningStrategyWedgeList[j].getScreeningStrategyWedgeId(), true)
                            .getScreeningStrategySubWedgesTab();

                    screeningStrategySubWedgeListAll[j] = screeningStrategysSubWedge;
                    screeningSubWedgeInfoListAll[j] = new ArrayList<ScreeningStrategySubWedgeValueInfo>();
                    if (screeningStrategySubWedgeListAll[j] != null) {
                        for (int k = 0; k < screeningStrategySubWedgeListAll[j].length; k++) {
                            ScreeningStrategySubWedgeValueInfo ssw = new ScreeningStrategySubWedgeValueInfo(
                                    screeningStrategySubWedgeService
                                            .findByPk(screeningStrategySubWedgeListAll[j][k]
                                                    .getScreeningStrategySubWedgeId()));
                            screeningSubWedgeInfoListAll[j].add(ssw);
                        }
                    }
                }
                form.setScreeningStrategySubWedgeListAll(screeningStrategySubWedgeListAll);
                form.setListStrategiesSubWedgeInfoAll(screeningSubWedgeInfoListAll);

                // strategy sub wedge
                String screeningStrategyWedgeSelIdst = request.getParameter("screeningStrategyWedgeSel");
                Integer screeningStrategyWedgeSelId = -1;
                try {
                    screeningStrategyWedgeSelId = new Integer(screeningStrategyWedgeSelIdst);
                } catch (NumberFormatException ex) {

                }
                ScreeningStrategySubWedge3VO[] screeningStrategySubWedgeList;
                screeningStrategySubWedgeList = new ScreeningStrategySubWedge3VO[0];
                List<ScreeningStrategySubWedgeValueInfo> screeningSubWedgeInfoList;
                screeningSubWedgeInfoList = new ArrayList<ScreeningStrategySubWedgeValueInfo>();
                if (screeningStrategyWedgeSelId != -1) {
                    ScreeningStrategySubWedge3VO[] screeningStrategysSubWedge = new ScreeningStrategyWedgeValueInfo(
                            screeningStrategyWedgeService
                                    .findByPk(screeningStrategyWedgeList[screeningStrategyWedgeSelId]
                                            .getScreeningStrategyWedgeId(), true))
                                                    .getScreeningStrategySubWedgesTab();

                    screeningStrategySubWedgeList = screeningStrategysSubWedge;
                    for (int k = 0; k < screeningStrategySubWedgeList.length; k++) {
                        ScreeningStrategySubWedgeValueInfo sw = new ScreeningStrategySubWedgeValueInfo(
                                screeningStrategySubWedgeService.findByPk(
                                        screeningStrategySubWedgeList[k].getScreeningStrategySubWedgeId()));
                        screeningSubWedgeInfoList.add(sw);
                    }
                }
                form.setScreeningStrategySubWedgeList(screeningStrategySubWedgeList);
                form.setListStrategiesSubWedgeInfo(screeningSubWedgeInfoList);

            }

            // Populate form
            form.setScreeningRank(srlv);
            form.setScreeningRankSet(srsv);
            form.setScreeningOutput(sov);

        }
        if (dataCollectionGroup.getBlSampleVOId() != null
                && dataCollectionGroup.getBlSampleVOId().intValue() != 0) {
            BLSample3VO bslv = sampleService.findByPk(dataCollectionGroup.getBlSampleVOId(), false, false);
            BreadCrumbsForm.getIt(request).setSelectedSample(bslv);

            Crystal3VO clv = bslv.getCrystalVO();

            Protein3VO plv = clv.getProteinVO();

            form.setCrystal(clv);
            form.setProtein(plv);
            form.setSample(bslv);

        } else {
            BreadCrumbsForm.getIt(request).setSelectedSample(null);
        }
        // --- Get Image List
        LOG.debug("get image list");
        List<ImageValueInfo> imageList = FileUtil.GetImageList(dataCollectionId, null, null, null, null,
                request);
        LOG.debug("get image list done");

        // Snapshot Image present ?
        // DataCollection3VO dcValue = dataCollectionService.findByPk(dataCollectionId, false, false, false, false);
        List<SnapshotInfo> listSnapshots = FileUtil.GetFullSnapshotPath(dc);
        String expectedSnapshotPath = (listSnapshots.get(SNAPSHOT_EXPECTED_NUMBER)).getFileLocation();
        form.setListSnapshots(listSnapshots);
        form.setExpectedSnapshotPath(expectedSnapshotPath);

        // --- Populate Form ---

        form.setDisplayOutputParam(displayOutputParam);

        form.setDataCollectionId(dataCollectionId);
        form.setDataCollection(dc);
        form.setListInfo(imageList);
        FormUtils.setFormDisplayMode(request, actForm, FormUtils.INSPECT_MODE);

        // Fill the BreadCrumbs
        BreadCrumbsForm.getIt(request).setSelectedImage(null);
        BreadCrumbsForm.getIt(request).setSelectedDataCollection(dc);
        BreadCrumbsForm.getIt(request).setSelectedDataCollectionGroup(dc.getDataCollectionGroupVO());
        if (dc.getDataCollectionGroupVO().getWorkflowVO() != null) {
            BreadCrumbsForm.getIt(request).setSelectedWorkflow(dc.getDataCollectionGroupVO().getWorkflowVO());
        }

        displayEDNA(mapping, actForm, request, in_reponse, errors);

    } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.results.view"));
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString()));
        e.printStackTrace();
    }

    if (!errors.isEmpty() && redirectToError) {
        saveErrors(request, errors);
        return (mapping.findForward("error"));
    } else {
        // return mapping.findForward("success");
        RoleDO roleObject = (RoleDO) request.getSession().getAttribute(Constants.CURRENT_ROLE);
        String role = roleObject.getName();
        if (role.equals(Constants.FXMANAGE_ROLE_NAME)) {
            return mapping.findForward("fedexmanagerResultsViewPage");
        } else if (role.equals(Constants.ROLE_MANAGER)) {
            return mapping.findForward("managerResultsViewPage");
        } else if (role.equals(Constants.ROLE_LOCALCONTACT)) {
            return mapping.findForward("localcontactResultsViewPage");
        } else {
            return mapping.findForward("success");
        }
    }
}

From source file:edu.ucsd.library.xdre.web.CollectionOperationController.java

public static String handleProcesses(Map<String, String[]> paramsMap, HttpSession session) throws Exception {

    String message = "";
    String returnMessage = "";
    DAMSClient damsClient = null;//from   w ww  .ja va2 s.  c om
    String collectionId = getParameter(paramsMap, "category");

    boolean[] operations = new boolean[20];
    operations[0] = getParameter(paramsMap, "validateFileCount") != null;
    operations[1] = getParameter(paramsMap, "validateChecksums") != null;
    operations[2] = getParameter(paramsMap, "rdfImport") != null;
    operations[3] = getParameter(paramsMap, "createDerivatives") != null;
    operations[4] = getParameter(paramsMap, "collectionRelease") != null;
    operations[5] = getParameter(paramsMap, "externalImport") != null;
    operations[6] = getParameter(paramsMap, "marcModsImport") != null
            || getParameter(paramsMap, "excelImport") != null;
    operations[7] = getParameter(paramsMap, "luceneIndex") != null
            || getParameter(paramsMap, "solrDump") != null
            || getParameter(paramsMap, "solrRecordsDump") != null;
    operations[8] = getParameter(paramsMap, "sendToCDL") != null;
    operations[9] = getParameter(paramsMap, "dataConvert") != null;
    operations[10] = getParameter(paramsMap, "ingest") != null;
    operations[11] = getParameter(paramsMap, "serialize") != null;
    operations[12] = getParameter(paramsMap, "tsSyn") != null;
    operations[13] = getParameter(paramsMap, "createJson") != null;
    operations[14] = getParameter(paramsMap, "cacheJson") != null;
    operations[15] = getParameter(paramsMap, "fileUpload") != null;
    operations[16] = getParameter(paramsMap, "jsonDiffUpdate") != null;
    operations[17] = getParameter(paramsMap, "validateManifest") != null;
    operations[18] = getParameter(paramsMap, "metadataExport") != null;
    operations[19] = getParameter(paramsMap, "jhoveReport") != null;

    int submissionId = (int) System.currentTimeMillis();
    String logLink = "https://"
            + (Constants.CLUSTER_HOST_NAME.indexOf("localhost") >= 0 ? "localhost:8443"
                    : Constants.CLUSTER_HOST_NAME.indexOf("lib-ingest") >= 0
                            ? Constants.CLUSTER_HOST_NAME + ".ucsd.edu:8443"
                            : Constants.CLUSTER_HOST_NAME + ".ucsd.edu")
            + "/damsmanager/downloadLog.do?submissionId=" + submissionId;
    String dataLink = "";

    String ds = getParameter(paramsMap, "ts");
    String dsDest = null;
    if ((ds == null || (ds = ds.trim()).length() == 0) && !(operations[15] || operations[16]))
        ds = Constants.DEFAULT_TRIPLESTORE;
    else if (operations[12]) {
        dsDest = getParameter(paramsMap, "dsDest");
        if (dsDest == null)
            throw new ServletException("No destination triplestore data source provided...");
        else if (ds.equals(dsDest) || !dsDest.startsWith("ts/"))
            throw new ServletException("Can't sync triplestore from " + ds + " to destination " + dsDest + ".");
    }

    String fileStore = getParameter(paramsMap, "fs");
    damsClient = new DAMSClient(Constants.DAMS_STORAGE_URL);
    damsClient.setTripleStore(ds);
    damsClient.setFileStore(fileStore);
    damsClient.setUser((String) session.getAttribute("user"));

    String clientVersion = session.getServletContext().getInitParameter("src-version");
    String clientTool = "Custom";

    if (message.length() == 0) {
        int userId = -1;
        String userIdAttr = (String) session.getAttribute("employeeId");
        if (userIdAttr != null && userIdAttr.length() > 0) {
            try {
                userId = Integer.parseInt(userIdAttr);
            } catch (NumberFormatException e) {
                userId = -1;
            }
        }

        CollectionHandler handler = null;
        OutputStream fileOut = null;

        try {

            boolean successful = true;
            for (int i = 0; i < operations.length; i++) {
                handler = null;
                String exeInfo = "";

                if (operations[i]) {
                    String opMessage = "Preparing procedure ";
                    RequestOrganizer.setProgressPercentage(session, 0);
                    message = "";

                    if (i == 0) {
                        session.setAttribute("status",
                                opMessage + "File Count Validation for FileStore " + fileStore + " ...");
                        boolean ingestFile = getParameter(paramsMap, "ingestFile") != null;
                        boolean dams4FileRename = getParameter(paramsMap, "dams4FileRename") != null;
                        handler = new FileCountValidaionHandler(damsClient, collectionId);
                        ((FileCountValidaionHandler) handler).setDams4FileRename(dams4FileRename);
                        if (ingestFile) {
                            String[] filesPaths = getParameter(paramsMap, "filesLocation").split(";");
                            List<String> ingestFiles = new ArrayList<String>();
                            for (int j = 0; j < filesPaths.length; j++)
                                ingestFiles.add(new File(Constants.DAMS_STAGING + "/" + filesPaths[j])
                                        .getAbsolutePath());
                            ((FileCountValidaionHandler) handler).setIngestFile(ingestFile);
                            ((FileCountValidaionHandler) handler)
                                    .setFilesPaths(ingestFiles.toArray(new String[ingestFiles.size()]));
                        }
                    } else if (i == 1) {
                        session.setAttribute("status",
                                opMessage + "Checksum Validation for FileStore " + fileStore + " ...");
                        handler = new ChecksumsHandler(damsClient, collectionId, null);
                    } else if (i == 2) {
                        session.setAttribute("status", opMessage + "Importing metadata ...");
                        String dataFormat = getParameter(paramsMap, "dataFormat");
                        String importMode = getParameter(paramsMap, "importMode");
                        handler = new MetadataImportHandler(damsClient, collectionId,
                                getParameter(paramsMap, "data"), dataFormat, importMode);
                    } else if (i == 3) {
                        session.setAttribute("status", opMessage + "Derivatives Creation ...");
                        boolean derReplace = getParameter(paramsMap, "derReplace") == null ? false : true;

                        String reqSize = getParameter(paramsMap, "size");
                        String[] sizes = null;
                        if (reqSize != null && reqSize.length() > 0)
                            sizes = reqSize.split(",");
                        handler = new DerivativeHandler(damsClient, collectionId, sizes, derReplace);

                    } else if (i == 4) {
                        session.setAttribute("status",
                                opMessage + " release collection " + collectionId + " ...");
                        String releaseState = getParameter(paramsMap, "releaseState");
                        String releaseOption = getParameter(paramsMap, "releaseOption");
                        String collectionToMerge = getParameter(paramsMap, "collectionToMerge");

                        log.info("Collection release:  category =>" + collectionId + ", releaseState => "
                                + releaseState + ", releaseOption => " + releaseOption
                                + ", collectionToMerge => " + collectionToMerge);

                        handler = new CollectionReleaseHandler(damsClient, collectionId, releaseState,
                                releaseOption);
                        ((CollectionReleaseHandler) handler).setCollectionToMerge(collectionToMerge);
                    } else if (i == 5) {
                        session.setAttribute("status", opMessage + "Importing objects ...");
                        String[] dataPaths = getParameter(paramsMap, "dataPath").split(";");
                        String[] filesPaths = getParameter(paramsMap, "filesPath").split(";");
                        String importOption = getParameter(paramsMap, "importOption");
                        boolean replace = getParameter(paramsMap, "externalImportReplace") != null;
                        List<File> dFiles = new ArrayList<File>();
                        for (int j = 0; j < dataPaths.length; j++) {
                            String dataPath = dataPaths[j];
                            if (dataPath != null && (dataPath = dataPath.trim()).length() > 0) {
                                File file = new File(Constants.DAMS_STAGING + "/" + dataPath);
                                CollectionHandler.listFiles(dFiles, file);
                            }
                        }

                        List<String> ingestFiles = new ArrayList<String>();
                        for (int j = 0; j < filesPaths.length; j++) {
                            if ((filesPaths[j] = filesPaths[j].trim()).length() > 0)
                                ingestFiles.add(new File(Constants.DAMS_STAGING + "/" + filesPaths[j])
                                        .getAbsolutePath());
                        }

                        String[] excelExts = { "xls", "xlsx" };
                        List<File> excelFiles = FileUtils.filterFiles(dFiles, excelExts);

                        if (excelFiles.size() > 0) {
                            // Remove the Excel source that need conversion from the file list
                            dFiles.removeAll(excelFiles);

                            // Pre-processing
                            boolean preprocessing = importOption.equalsIgnoreCase("pre-processing");
                            Element rdfPreview = null;
                            StringBuilder errorMessage = new StringBuilder();
                            StringBuilder duplicatRecords = new StringBuilder();
                            List<String> ids = new ArrayList<String>();
                            if (preprocessing) {
                                Document doc = new DocumentFactory().createDocument();
                                rdfPreview = TabularRecord.createRdfRoot(doc);
                            }
                            handler = new MetadataImportHandler(damsClient, null);
                            handler.setSubmissionId(submissionId);
                            handler.setSession(session);
                            handler.setUserId(userId);

                            // Directory to hold the converted rdf/xml
                            File tmpDir = new File(Constants.TMP_FILE_DIR + File.separatorChar + "converted");
                            if (!tmpDir.exists())
                                tmpDir.mkdir();

                            // Convert Excel source files to DAMS4 rdf/xml
                            int filesCount = 0;
                            for (File f : excelFiles) {
                                filesCount++;
                                RecordSource src = new ExcelSource(f);

                                for (Record rec = null; (rec = src.nextRecord()) != null;) {
                                    String id = rec.recordID();
                                    handler.logMessage("Pre-processing record with ID " + id + " ... ");

                                    if (ids.indexOf(id) < 0) {
                                        ids.add(id);
                                    } else {
                                        duplicatRecords.append(id + ", ");
                                        handler.logError("Found duplicated record with ID " + id + ".");
                                    }

                                    try {

                                        Document doc = rec.toRDFXML();
                                        if (duplicatRecords.length() == 0 && errorMessage.length() == 0) {
                                            if (preprocessing) {
                                                // preview when there are no error reported
                                                rdfPreview.add(rec.toRDFXML().selectSingleNode("//dams:Object")
                                                        .detach());
                                            } else {
                                                File convertedFile = new File(tmpDir.getAbsolutePath(),
                                                        id.replaceAll("[\\//:.*]+", "") + ".rdf.xml");
                                                try {
                                                    writeXml(convertedFile, doc.asXML());
                                                } finally {
                                                    convertedFile.deleteOnExit();
                                                    if (dFiles.indexOf(convertedFile) < 0) {
                                                        dFiles.add(convertedFile);
                                                        handler.logMessage("Added converted RDF/XML file "
                                                                + convertedFile.getAbsolutePath());
                                                    }
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        log.warn("Excel Input Stream error", e);
                                        errorMessage.append("-" + e.getMessage() + "\n");
                                        handler.logMessage(e.getMessage() + "\n");
                                    }
                                }
                                handler.setProgressPercentage(filesCount * 100 / excelFiles.size());
                            }

                            if (errorMessage.length() == 0 && duplicatRecords.length() == 0) {

                                if (preprocessing) {
                                    File destFile = new File(Constants.TMP_FILE_DIR,
                                            "preview-" + submissionId + "-rdf.xml");
                                    writeXml(destFile, rdfPreview.getDocument().asXML());

                                    successful = true;
                                    message = "\nPre-processing passed. ";
                                    message += "\nThe converted RDF/XML is ready for <a href=\"" + logLink
                                            + "&file=" + destFile.getName() + "\">download</a>.";
                                    //handler.logMessage(message);
                                    handler.release();
                                    handler = null;
                                } else {
                                    handler.release();
                                    // Initiate the ingest task for Excel AND/OR RDF/XML files
                                    handler = new RDFDAMS4ImportTsHandler(damsClient,
                                            dFiles.toArray(new File[dFiles.size()]), importOption);
                                    ((RDFDAMS4ImportTsHandler) handler)
                                            .setFilesPaths(ingestFiles.toArray(new String[ingestFiles.size()]));
                                    ((RDFDAMS4ImportTsHandler) handler).setReplace(replace);
                                }
                            } else {
                                successful = false;
                                message = "\nPre-processing issues found:";
                                if (duplicatRecords.length() > 0)
                                    message += "\nDuplicated records: " + duplicatRecords
                                            .substring(0, duplicatRecords.length() - 2).toString();
                                if (errorMessage.length() > 0)
                                    message += "\nOther Errors: \n" + errorMessage.toString();
                                //handler.logMessage(message);
                                handler.release();
                                handler = null;
                            }
                        } else {
                            // Ingest for RDF/XML files
                            handler = new RDFDAMS4ImportTsHandler(damsClient,
                                    dFiles.toArray(new File[dFiles.size()]), importOption);
                            ((RDFDAMS4ImportTsHandler) handler)
                                    .setFilesPaths(ingestFiles.toArray(new String[ingestFiles.size()]));
                            ((RDFDAMS4ImportTsHandler) handler).setReplace(replace);
                        }
                    } else if (i == 6) {
                        session.setAttribute("status",
                                opMessage + "Importing from Standard Input Stream source ...");
                        log.info(opMessage + "Importing from Standard Input Stream source ...");

                        String unit = getParameter(paramsMap, "unit");
                        String source = getParameter(paramsMap, "source");
                        String bibNumber = getParameter(paramsMap, "bibInput");
                        String modsXml = getParameter(paramsMap, "modsInput");
                        String copyrightStatus = getParameter(paramsMap, "copyrightStatus");
                        String copyrightJurisdiction = getParameter(paramsMap, "countryCode");
                        String copyrightOwner = getParameter(paramsMap, "copyrightOwner");
                        String program = getParameter(paramsMap, "program");
                        String access = getParameter(paramsMap, "accessOverride");
                        String beginDate = getParameter(paramsMap, "licenseBeginDate");
                        String endDate = getParameter(paramsMap, "licenseEndDate");
                        String[] dataPaths = getParameter(paramsMap, "dataPath").split(";");
                        String[] filesPaths = getParameter(paramsMap, "filesPath").split(";");
                        String importOption = getParameter(paramsMap, "importOption");
                        List<String> ingestFiles = new ArrayList<String>();
                        for (int j = 0; j < filesPaths.length; j++) {
                            if ((filesPaths[j] = filesPaths[j].trim()).length() > 0)
                                ingestFiles.add(new File(Constants.DAMS_STAGING + "/" + filesPaths[j])
                                        .getAbsolutePath());
                        }

                        List<File> dataFiles = new ArrayList<File>();
                        for (int j = 0; j < dataPaths.length; j++) {
                            String dataPath = dataPaths[j];
                            if (dataPath != null && (dataPath = dataPath.trim()).length() > 0) {
                                File file = new File(Constants.DAMS_STAGING + "/" + dataPath);
                                CollectionHandler.listFiles(dataFiles, file);
                            }
                        }

                        // initiate the source metadata
                        List<Object> sources = new ArrayList<Object>();
                        if (source != null && source.equalsIgnoreCase("bib")) {
                            String[] bibs = bibNumber.split(",");
                            for (int j = 0; j < bibs.length; j++) {
                                if (bibs[j] != null && (bibs[j] = bibs[j].trim()).length() > 0)
                                    sources.add(bibs[j]);
                            }
                        } else {
                            List<String> filters = new ArrayList<>();
                            if (getParameter(paramsMap, "excelImport") != null) {
                                // Excel Input Stream
                                source = "excel";
                                filters.add("xls");
                                filters.add("xlsx");
                            } else {
                                // MARC/MODS source
                                filters.add("xml");
                            }

                            dataFiles = FileUtils.filterFiles(dataFiles,
                                    filters.toArray(new String[filters.size()]));
                            sources.addAll(dataFiles);
                            dataFiles.clear();
                        }

                        // Handling pre-processing request
                        Element rdfPreview = null;
                        StringBuilder duplicatRecords = new StringBuilder();
                        List<String> ids = new ArrayList<String>();
                        boolean preprocessing = importOption.equalsIgnoreCase("pre-processing");
                        boolean ingestWithFiles = importOption.equalsIgnoreCase("metadataAndFiles");

                        if (preprocessing) {
                            Document doc = new DocumentFactory().createDocument();
                            rdfPreview = TabularRecord.createRdfRoot(doc);
                        }

                        boolean preSuccessful = true;
                        StringBuilder proMessage = new StringBuilder();
                        if (source != null && (source.equalsIgnoreCase("bib") || source.equalsIgnoreCase("mods")
                                || source.equalsIgnoreCase("excel"))) {
                            // Initiate the logging handler 
                            handler = new MetadataImportHandler(damsClient, null);
                            handler.setSubmissionId(submissionId);
                            handler.setSession(session);
                            handler.setUserId(userId);

                            Map<String, String> collections = new HashMap<String, String>();
                            if (StringUtils.isNotBlank(collectionId)) {
                                String collType = damsClient.getCollectionType(collectionId);
                                collections.put(collectionId, collType);
                            }

                            for (int j = 0; j < sources.size(); j++) {
                                InputStream in = null;
                                String sourceID = null;

                                Object srcRecord = sources.get(j);
                                sourceID = (srcRecord instanceof File ? ((File) srcRecord).getName()
                                        : srcRecord.toString());
                                if (preprocessing)
                                    handler.setStatus("Pre-processing record " + sourceID + " ... ");
                                else
                                    handler.setStatus("Processing record " + sourceID + " ... ");

                                RecordSource recordSource = null;
                                InputStreamRecord record = null;

                                try {
                                    if (source.equalsIgnoreCase("excel")) {
                                        clientTool = "Excel";
                                        // Handling Excel Input Stream records
                                        recordSource = new ExcelSource((File) srcRecord);

                                        // Report for Excel column name validation
                                        List<String> invalidColumns = ((ExcelSource) recordSource)
                                                .getInvalidColumns();

                                        if (invalidColumns != null && invalidColumns.size() > 0) {
                                            successful = false;
                                            preSuccessful = false;

                                            proMessage.append("Excel source " + sourceID + " - failed - "
                                                    + CollectionHandler.damsDateFormat.format(new Date())
                                                    + ": \n");

                                            if (invalidColumns != null && invalidColumns.size() > 0) {
                                                // Report invalid columns
                                                proMessage.append("* Found the following invalid column name"
                                                        + (invalidColumns.size() > 1 ? "s" : "") + ": ");
                                                for (int k = 0; k < invalidColumns.size(); k++) {
                                                    proMessage.append(invalidColumns.get(k));
                                                    if (k == invalidColumns.size() - 1)
                                                        proMessage.append("\n");
                                                    else
                                                        proMessage.append("; ");
                                                }
                                            }
                                        }
                                    } else {
                                        // Handling AT/Roger records
                                        try {
                                            if (source.equalsIgnoreCase("bib")) {

                                                clientTool = "MARC";
                                                String url = Constants.DAMS_STORAGE_URL.substring(0,
                                                        Constants.DAMS_STORAGE_URL.indexOf("/dams/"))
                                                        + "/jollyroger/get?type=bib&mods=true&ns=true&value="
                                                        + sourceID;

                                                log.info("Getting MARC XML for Roger record " + sourceID
                                                        + " from URL: " + url);
                                                HttpGet req = new HttpGet(url);
                                                Document doc = damsClient.getXMLResult(req);
                                                modsXml = doc.asXML();
                                                in = new ByteArrayInputStream(modsXml.getBytes("UTF-8"));
                                            } else {
                                                // METS/MODS XML from staging area
                                                clientTool = "AT";
                                                File srcFile = (File) sources.get(j);
                                                in = new FileInputStream(srcFile);
                                            }

                                            File xsl = new File(session.getServletContext()
                                                    .getRealPath("files/mets2dams.xsl"));
                                            recordSource = new XsltSource(xsl, sourceID.replaceAll("\\..*", ""),
                                                    in);
                                        } finally {
                                            CollectionHandler.close(in);
                                            in = null;
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    successful = false;
                                    preSuccessful = false;
                                    String error = e.getMessage() != null ? e.getMessage()
                                            : e.getCause() != null ? e.getCause().getMessage()
                                                    : e.getClass().getName();
                                    handler.setStatus(error);
                                    log.error("Error metadata source " + sourceID + ": " + error);
                                    proMessage.append(sourceID + " - failed - "
                                            + CollectionHandler.damsDateFormat.format(new Date()) + " - "
                                            + error);
                                }

                                String id = "";
                                String info = "";
                                if (recordSource != null && preSuccessful) {
                                    for (Record rec = null; (rec = recordSource.nextRecord()) != null;) {

                                        String objTitle = "";
                                        id = rec.recordID();
                                        StringBuilder errorMessage = new StringBuilder();
                                        try {

                                            record = new InputStreamRecord(rec, collections, unit,
                                                    copyrightStatus, copyrightJurisdiction, copyrightOwner,
                                                    program, access, beginDate, endDate);

                                            objTitle = getTitle(record.toRDFXML());
                                            info = "Pre-processing record with ID " + id + " ... ";
                                            handler.setStatus(info);
                                            log.info(info);

                                            if (ids.indexOf(id) < 0) {
                                                ids.add(id);
                                            } else {
                                                duplicatRecords.append(rec + ", ");
                                                String error = "Duplicated record with ID " + id;
                                                handler.setStatus(error);
                                                log.error(info);
                                                errorMessage.append("\n* " + error);
                                            }

                                            // Add master file(s) for the bib/Roger record: a PDF or a TIFF, or a PDF + ZIP
                                            List<File> filesToIngest = null;
                                            if (source.equalsIgnoreCase("bib") && ingestWithFiles) {
                                                filesToIngest = getRogerFiles((String) srcRecord, ingestFiles);
                                                // Processing the master file(s) with error report. 
                                                if (filesToIngest.size() == 0) {
                                                    errorMessage.append("\n* Roger record " + srcRecord
                                                            + " has no master file(s) for \"Ingest metadata and files\" option.");
                                                } else if (filesToIngest.size() > 2
                                                        || (filesToIngest.size() == 2 && !filesToIngest.get(1)
                                                                .getName().endsWith(".zip"))) {
                                                    errorMessage
                                                            .append("\n* Unexpected file(s) for Roger record "
                                                                    + srcRecord + ": ");
                                                    for (File file : filesToIngest) {
                                                        errorMessage.append(
                                                                (filesToIngest.indexOf(file) > 0 ? ", " : "")
                                                                        + file.getName());
                                                    }
                                                } else {
                                                    // Handle the use property for the file(s)
                                                    Map<String, String> fileUseMap = getFileUse(filesToIngest);

                                                    record.addFiles(0, filesToIngest, fileUseMap);
                                                }
                                            } else if (source.equalsIgnoreCase("excel")) {
                                                // Report for invalid Excel control values validation
                                                List<Map<String, String>> invalidValues = ((ExcelSource) recordSource)
                                                        .getInvalidValues();
                                                if (invalidValues != null && invalidValues.size() > 0) {

                                                    // process to retrieve control values errors for the record since it will parse the row for the next record
                                                    StringBuilder cvErrors = new StringBuilder();
                                                    for (int k = 0; k < invalidValues.size(); k++) {
                                                        Map<String, String> m = invalidValues.get(k);
                                                        if (m.containsKey(TabularRecord.OBJECT_ID)
                                                                && m.get(TabularRecord.OBJECT_ID)
                                                                        .equals(String.valueOf(id))) {
                                                            cvErrors.append(
                                                                    "* Row index " + m.get("row") + " [");

                                                            // don't count for the row number and the record id
                                                            m.remove("row");
                                                            m.remove(TabularRecord.OBJECT_ID);
                                                            int l = 0;
                                                            for (String key : m.keySet()) {
                                                                if (l++ > 0)
                                                                    cvErrors.append(" | ");
                                                                cvErrors.append(key + " => " + m.get(key));
                                                            }
                                                            cvErrors.append("]\n");
                                                        }
                                                    }

                                                    if (cvErrors.length() > 0) {
                                                        errorMessage.append("Invalid control value(s)" + " - \n"
                                                                + cvErrors.toString());
                                                    }
                                                }
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            info = "Error: " + e.getMessage();
                                            handler.setStatus(info);
                                            log.warn(info);
                                            errorMessage.append("\n* " + e.getMessage());
                                        }

                                        objTitle = StringUtils.isEmpty(objTitle) ? "[Object]" : objTitle;
                                        if (errorMessage.length() == 0) {

                                            info = objTitle + " - " + id + " - " + " successful - "
                                                    + CollectionHandler.damsDateFormat.format(new Date());
                                            proMessage.append("\n\n" + info);
                                            log.info(info);

                                            if (preprocessing) {
                                                // Pre-processing with rdf preview
                                                rdfPreview.add(record.toRDFXML()
                                                        .selectSingleNode("//dams:Object").detach());
                                            } else {
                                                // Write the converted rdf/xml to file system
                                                File tmpDir = new File(Constants.TMP_FILE_DIR
                                                        + File.separatorChar + "converted");
                                                if (!tmpDir.exists())
                                                    tmpDir.mkdir();
                                                File convertedFile = new File(tmpDir.getAbsolutePath(),
                                                        id.replaceAll("[\\//:.*]+", "") + ".rdf.xml");
                                                try {
                                                    writeXml(convertedFile, record.toRDFXML().asXML());
                                                } finally {
                                                    convertedFile.deleteOnExit();
                                                    dataFiles.add(convertedFile);
                                                }
                                            }
                                        } else {
                                            preSuccessful = false;

                                            info = objTitle + " - " + id + " - " + " failed - "
                                                    + CollectionHandler.damsDateFormat.format(new Date())
                                                    + " - " + errorMessage.toString();
                                            proMessage.append("\n\n" + info);
                                            log.error(info);
                                        }

                                        handler.setProgressPercentage(j * 100 / sources.size());
                                    }
                                }
                            }

                            // Logging the result for pre-processing
                            if (preprocessing || !preSuccessful) {
                                message = "\nPre-processing " + (preSuccessful ? "successful" : "failed")
                                        + ": \n"
                                        + (proMessage.length() == 0 ? "" : "\n " + proMessage.toString());
                                handler.logMessage(message);
                            }
                            handler.release();
                            handler = null;

                            if (preSuccessful) {
                                // Write the converted RDF/xml for preview
                                if (preprocessing) {
                                    File destFile = new File(Constants.TMP_FILE_DIR,
                                            "preview-" + submissionId + "-rdf.xml");
                                    writeXml(destFile, rdfPreview.getDocument().asXML());

                                    dataLink = "\nThe converted RDF/XML is ready for <a href=\"" + logLink
                                            + "&file=" + destFile.getName() + "\">download</a>.\n";

                                } else {
                                    // Ingest the converted RDF/XML files
                                    handler = new RDFDAMS4ImportTsHandler(damsClient,
                                            dataFiles.toArray(new File[dataFiles.size()]), importOption);
                                    ((RDFDAMS4ImportTsHandler) handler)
                                            .setFilesPaths(ingestFiles.toArray(new String[ingestFiles.size()]));
                                    ((RDFDAMS4ImportTsHandler) handler).setReplace(true);
                                }
                            } else {
                                successful = false;
                            }
                        } else {
                            successful = false;
                            message += "\nUnknown source type: " + source;
                        }
                    } else if (i == 7) {
                        session.setAttribute("status", opMessage + "SOLR Index ...");
                        boolean update = getParameter(paramsMap, "indexReplace") != null;
                        if (getParameter(paramsMap, "solrRecordsDump") != null) {
                            // Handle single records submission
                            List<String> items = new ArrayList<String>();
                            String txtInput = getParameter(paramsMap, "textInput");
                            String fileInputValue = getParameter(paramsMap, "data");
                            if (txtInput != null && (txtInput = txtInput.trim()).length() > 0) {
                                String[] subjects = txtInput.split(",");
                                for (String subject : subjects) {
                                    subject = subject.trim();
                                    if (subject.length() > 0) {
                                        items.add(subject);
                                    }
                                }
                            }

                            // Handle records submitted in file with csv format, in lines or mixed together
                            if (fileInputValue != null
                                    && (fileInputValue = fileInputValue.trim()).length() > 0) {
                                // Handle record with line input
                                String[] lines = fileInputValue.split("\n");
                                for (String line : lines) {
                                    // Handle CSV encoding records and records delimited by comma, whitespace etc.
                                    if (line != null && (line = line.trim().replace("\"", "")).length() > 0) {
                                        String[] tokens = line.split(",");
                                        for (String token : tokens) {
                                            String[] records = token.split(" ");
                                            for (String record : records) {
                                                record = record.trim();
                                                if (record.length() > 0) {
                                                    items.add(record);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            // Initiate SOLRIndexHandler to index the records
                            handler = new SOLRIndexHandler(damsClient, null, update);
                            handler.setItems(items);
                            handler.setCollectionTitle("SOLR Records");
                        } else {
                            // Handle solr update for collections
                            if (collectionId.indexOf(",") > 0) {
                                String collIDs = collectionId;
                                String[] collArr = collectionId.split(",");
                                List<String> items = new ArrayList<String>();
                                String collNames = "";
                                for (int j = 0; j < collArr.length; j++) {
                                    if (collArr[j] != null && (collArr[j] = collArr[j].trim()).length() > 0) {
                                        collectionId = collArr[j];
                                        if (collectionId.equalsIgnoreCase("all")) {
                                            items.addAll(damsClient.listAllRecords());
                                            collNames += "All Records (" + items.size() + "), ";
                                        } else {
                                            try {
                                                handler = new SOLRIndexHandler(damsClient, collectionId);
                                                items.addAll(handler.getItems());
                                                collNames += handler.getCollectionTitle() + "("
                                                        + handler.getFilesCount() + "), ";
                                                if (j > 0 && j % 5 == 0)
                                                    collNames += "\n";
                                            } finally {
                                                if (handler != null) {
                                                    handler.release();
                                                    handler = null;
                                                }
                                            }
                                        }
                                    }
                                }
                                handler = new SOLRIndexHandler(damsClient, null, update);
                                handler.setItems(items);
                                handler.setCollectionTitle(collNames.substring(0, collNames.lastIndexOf(",")));
                                handler.setCollectionId(collIDs);
                            } else {
                                if (collectionId.equalsIgnoreCase("all")) {
                                    handler = new SOLRIndexHandler(damsClient, null, update);
                                    handler.setItems(damsClient.listAllRecords());
                                } else
                                    handler = new SOLRIndexHandler(damsClient, collectionId, update);
                            }
                        }
                    } /*else if (i == 8){   
                           //session.setAttribute("status", opMessage + "CDL Sending ...");
                           int operationType = 0;
                              boolean resend = getParameter(paramsMap, "cdlResend") != null;
                              if(resend){
                                 operationType = 1;
                              }else{
                                 resend = getParameter(paramsMap, "cdlResendMets") != null;
                                 if(resend)
                                    operationType = 2;
                              }
                             //handler = new CdlIngestHandler(tsUtils, collectionId, userId, operationType);
                              
                           String feeder = getParameter(paramsMap, "feeder");
                           session.setAttribute("status", opMessage + "CDL " + feeder.toUpperCase() + " METS feeding ...");
                           boolean includeEmbargoed = (getParameter(paramsMap, "includeEmbargoed")!=null);
                           if(feeder.equals("merritt")){
                              String account = getParameter(paramsMap, "account");
                              String password = getParameter(paramsMap, "password");
                              //String accessGroupId = getParameter(paramsMap, "accessGroup");
                              handler = new CdlIngestHandler(damsClient, collectionId, userId, operationType, feeder, account, password);
                           }else
                              handler = new CdlIngestHandler(damsClient, collectionId, userId, operationType);
                           if(!includeEmbargoed)
                              handler.excludeEmbargoedObjects();
                      }else if (i == 9){   
                           session.setAttribute("status", opMessage + "Metadata Converting and populating ...");
                           String tsOperation = getParameter(paramsMap, "sipOption");
                                   
                           if(tsOperation == null || tsOperation.length() == 0)
                              tsOperation = "tsNew";
                                   
                           int operationType = MetadataImportController.getOperationId(tsOperation);
                           String srcFile = (String) session.getAttribute("source");
                           String srcFormat = (String) session.getAttribute("format");
                           String pathMap = (String) session.getAttribute("pathMap");
                           int sheetNo = 0;
                           if(session.getAttribute("sheetNo") != null)
                              sheetNo = ((Integer)session.getAttribute("sheetNo")).intValue();
                                   
                           String rdfFileToWrite = Constants.TMP_FILE_DIR + "tmpRdf_" + session.getId() + ".xml";
                           if("excel".equalsIgnoreCase(srcFormat)){
                              handler = new ExcelConverter(damsClient, collectionId, srcFile, sheetNo, pathMap, operationType);
                             ExcelConverter converter = (ExcelConverter)handler;
                             converter.setUseArk(true);
                             converter.setRdfFileToWrite(rdfFileToWrite);
                           }else
                              throw new ServletException("Unsupported data format: " + srcFormat);
                              
                      }*/else if (i == 10) {
                        session.setAttribute("status", opMessage + "Stage Ingesting ...");

                        String unit = getParameter(paramsMap, "unit");
                        String arkSetting = getParameter(paramsMap, "arkSetting").trim();
                        String filePath = getParameter(paramsMap, "filePath").trim();
                        String fileFilter = getParameter(paramsMap, "fileFilter").trim();
                        String preferedOrder = getParameter(paramsMap, "preferedOrder");
                        String fileSuffixes = getParameter(paramsMap, "fileSuffixes");
                        String fileUse = getParameter(paramsMap, "fileUse");
                        if (fileSuffixes != null && fileSuffixes.length() > 0)
                            fileSuffixes = fileSuffixes.trim();

                        String coDelimiter = "p";
                        if (arkSetting.equals("1")) {
                            if (preferedOrder == null || preferedOrder.equalsIgnoreCase("cofDelimiter")) {
                                coDelimiter = getParameter(paramsMap, "cofDelimiter").trim();
                            } else if (preferedOrder.equals("suffix"))
                                coDelimiter = getParameter(paramsMap, "coDelimiter").trim();
                            else
                                coDelimiter = null;
                        } else {
                            if (arkSetting.equals("5")) {
                                coDelimiter = getParameter(paramsMap, "coDelimiter").trim();
                            }
                        }

                        String[] fileOrderSuffixes = null;
                        if (fileSuffixes != null && fileSuffixes.length() > 0)
                            fileOrderSuffixes = fileSuffixes.split(",");

                        String[] fileUses = null;
                        if (fileUse != null && (fileUse = fileUse.trim()).length() > 0) {
                            fileUses = fileUse.split(",");
                            for (int j = 0; j < fileUses.length; j++) {
                                if (fileUses[j] != null)
                                    fileUses[j] = fileUses[j].trim();
                            }
                        }

                        session.setAttribute("category", collectionId);
                        session.setAttribute("unit", unit);
                        session.setAttribute("arkSetting", arkSetting);
                        session.setAttribute("filePath", filePath);
                        session.setAttribute("fileFilter", fileFilter);
                        session.setAttribute("preferedOrder", preferedOrder);
                        session.setAttribute("fileSuffixes", fileSuffixes);
                        session.setAttribute("fileUse", fileUse);

                        String[] dirArr = filePath.split(";");
                        List<String> fileList = new ArrayList<String>();
                        String dir = null;
                        for (int j = 0; j < dirArr.length; j++) {
                            dir = dirArr[j];
                            if (dir != null && (dir = dir.trim()).length() > 0) {
                                if ((dir.startsWith("/") || dir.startsWith("\\"))
                                        && (Constants.DAMS_STAGING.endsWith("/")
                                                || Constants.DAMS_STAGING.endsWith("\\")))
                                    dir = dir.substring(1);
                                fileList.add(Constants.DAMS_STAGING + dir);
                            }
                        }

                        handler = new FileIngestionHandler(damsClient, fileList, Integer.parseInt(arkSetting),
                                collectionId, fileFilter, coDelimiter);
                        ((FileIngestionHandler) handler).setFileOrderSuffixes(fileOrderSuffixes);
                        ((FileIngestionHandler) handler).setPreferedOrder(preferedOrder);
                        ((FileIngestionHandler) handler).setUnit(unit);
                        ((FileIngestionHandler) handler).setFileUses(fileUses);

                    } else if (i == 11) {
                        session.setAttribute("status",
                                opMessage + "Serialize records as RDF/XML to filestore ...");
                        if (collectionId.indexOf(",") > 0) {
                            String collIDs = collectionId;
                            String[] collArr = collectionId.split(",");
                            List<String> items = new ArrayList<String>();
                            String collNames = "";
                            for (int j = 0; j < collArr.length; j++) {
                                if (collArr[j] != null && (collArr[j] = collArr[j].trim()).length() > 0) {
                                    collectionId = collArr[j];
                                    if (collectionId.equalsIgnoreCase("all")) {
                                        items.addAll(damsClient.listAllRecords());
                                        collNames += "All Records (" + items.size() + "), ";
                                    } else {
                                        try {
                                            handler = new SOLRIndexHandler(damsClient, collectionId);
                                            items.addAll(handler.getItems());
                                            collNames += handler.getCollectionTitle() + "("
                                                    + handler.getFilesCount() + "), ";
                                            if (j > 0 && j % 5 == 0)
                                                collNames += "\n";
                                        } finally {
                                            if (handler != null) {
                                                handler.release();
                                                handler = null;
                                            }
                                        }
                                    }
                                }
                            }
                            handler = new FilestoreSerializationHandler(damsClient, null);
                            handler.setItems(items);
                            handler.setCollectionTitle(collNames.substring(0, collNames.lastIndexOf(",")));
                            handler.setCollectionId(collIDs);
                        } else {
                            if (collectionId.equalsIgnoreCase("all")) {
                                handler = new FilestoreSerializationHandler(damsClient, null);
                                handler.setItems(damsClient.listAllRecords());
                            } else
                                handler = new FilestoreSerializationHandler(damsClient, collectionId);
                        }
                    } else if (i == 15) {
                        session.setAttribute("status", opMessage + "Uploading files from dams-staging to "
                                + damsClient.getFileStore() + " ...");
                        Map<String, String> filesMap = new TreeMap<String, String>();
                        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                            String key = it.next();
                            if (key.startsWith("f-")) {
                                String file = paramsMap.get(key)[0];
                                String fileURI = paramsMap.get(key.replaceFirst("f-", "fid-"))[0];

                                if (fileURI != null && fileURI.startsWith(Constants.DAMS_ARK_URL_BASE))
                                    filesMap.put(file, fileURI.trim());
                                else
                                    message += "Invalid fileURL for file " + file + " (" + fileURI + "). \n";
                            }
                        }
                        handler = new FileUploadHandler(damsClient, filesMap);
                        handler.setItems(Arrays.asList(filesMap.keySet().toArray(new String[filesMap.size()])));
                    } else if (i == 18) {
                        boolean components = getParameter(paramsMap, "exComponents") == null;
                        String exFormat = getParameter(paramsMap, "exportFormat");
                        String xslSource = getParameter(paramsMap, "xsl");
                        if (xslSource == null || (xslSource = xslSource.trim()).length() == 0) {
                            xslSource = "/pub/data1/import/apps/glossary/xsl/dams/convertToCSV.xsl";
                            if (!new File(xslSource).exists())
                                xslSource = Constants.CLUSTER_HOST_NAME + "glossary/xsl/dams/convertToCSV.xsl";
                        }
                        session.setAttribute("status",
                                opMessage + (exFormat.equalsIgnoreCase("csv") ? "CSV"
                                        : exFormat.equalsIgnoreCase("N-TRIPLE") ? "N-TRIPLE" : "RDF XML ")
                                        + " Metadata Export ...");
                        File outputFile = new File(Constants.TMP_FILE_DIR,
                                "export-" + DAMSClient.stripID(collectionId) + "-" + System.currentTimeMillis()
                                        + "-rdf.xml");
                        String nsInput = getParameter(paramsMap, "nsInput");
                        List<String> nsInputs = new ArrayList<String>();
                        boolean componentsIncluded = true;
                        if (nsInput != null && (nsInput = nsInput.trim()).length() > 0) {
                            String[] nsInputArr = nsInput.split(",");
                            for (int j = 0; j < nsInputArr.length; j++) {
                                if (nsInputArr[j] != null
                                        && (nsInputArr[j] = nsInputArr[j].trim()).length() > 0)
                                    nsInputs.add(nsInputArr[j]);
                            }
                        }
                        fileOut = new FileOutputStream(outputFile);
                        handler = new MetadataExportHandler(damsClient, collectionId, nsInputs,
                                componentsIncluded, exFormat, fileOut);
                        ((MetadataExportHandler) handler).setFileUri(logLink + "&file=" + outputFile.getName());
                        ((MetadataExportHandler) handler).setComponents(components);

                    } else if (i == 19) {
                        session.setAttribute("status", opMessage + "Jhove report ...");
                        boolean bytestreamFilesOnly = getParameter(paramsMap, "bsJhoveReport") != null;
                        boolean update = getParameter(paramsMap, "bsJhoveUpdate") != null;
                        handler = new JhoveReportHandler(damsClient, collectionId, bytestreamFilesOnly);
                        if (update)
                            ((JhoveReportHandler) handler)
                                    .setJhoveUpdate(getParameter(paramsMap, "jhoveUpdate"));

                    } else
                        throw new ServletException("Unhandle operation index: " + i);

                    if (handler != null) {
                        try {
                            damsClient.setClientInfo(clientTool
                                    + (StringUtils.isNotBlank(clientVersion) ? " " + clientVersion : ""));
                            handler.setSubmissionId(submissionId);
                            handler.setDamsClient(damsClient);
                            handler.setSession(session);
                            handler.setUserId(userId);
                            if (handler.getCollectionId() == null
                                    && (collectionId != null && collectionId.length() > 0))
                                handler.setCollectionId(collectionId);

                            successful = handler.execute();
                        } catch (InterruptedException e) {
                            successful = false;
                            exeInfo += e.getMessage();
                            e.printStackTrace();
                        } catch (Exception e) {
                            successful = false;
                            exeInfo += "\n" + e.getMessage();
                            e.printStackTrace();
                        } finally {
                            String collectionName = handler.getCollectionId();
                            if (collectionName != null && collectionName.length() > 0
                                    && logLink.indexOf("&category=") < 0)
                                logLink += "&category=" + collectionName.replace(" ", "");
                            handler.setExeResult(successful);
                            exeInfo += handler.getExeInfo();
                            handler.release();
                            if (fileOut != null) {
                                CollectionHandler.close(fileOut);
                                fileOut = null;
                            }
                        }
                    }
                } else
                    continue;

                message += exeInfo;
                if (!successful) {
                    String errors = "Execution failed:\n" + message + "\n";
                    returnMessage += errors;
                    break;
                } else {
                    returnMessage += "\n" + message;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnMessage += e.getMessage();
        } finally {
            if (damsClient != null)
                damsClient.close();
            if (fileOut != null) {
                CollectionHandler.close(fileOut);
                fileOut = null;
            }
        }
    } else
        returnMessage = message;

    String logMessage = "For details, please download " + "<a href=\"" + logLink + "\">log</a>" + ".";
    if (returnMessage.length() > 1000) {
        returnMessage = returnMessage.substring(0, 1000);
        int idx = returnMessage.lastIndexOf("\n");
        if (idx > 0)
            returnMessage = returnMessage.substring(0, idx);
        else {
            idx = returnMessage.lastIndexOf("</a>");
            if (idx < returnMessage.lastIndexOf("<a "))
                returnMessage = returnMessage.substring(0, idx);
        }
        returnMessage = "\n" + returnMessage + "\n    ...     ";
    }
    returnMessage += "\n" + dataLink + "\n" + logMessage;
    RequestOrganizer.addResultMessage(session, returnMessage.replace("\n", "<br />") + "<br />");
    return returnMessage;
}