Example usage for java.lang NumberFormatException getCause

List of usage examples for java.lang NumberFormatException getCause

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:xtrememp.playlist.PlaylistIO.java

/**
 * Saves playlist in XSPF format.//from  w w w .java2s .  co m
 * 
 * @param playlist
 * @param location
 * @return <code>true</code> if playlist is successfully saved, else <code>false</code>.
 */
public static boolean saveXSPF(Playlist playlist, String location) throws PlaylistException {
    if (playlist != null) {
        File xspfFile = new File(location);

        // Create a xspf playlist
        XspfPlaylist xspfPlaylist = new XspfPlaylist();
        xspfPlaylist.setVersion("1");
        xspfPlaylist.setTitle("Playlist");
        xspfPlaylist.setLocation(xspfFile.toURI().toString());

        // Create track list
        XspfPlaylistTrackList tracks = new XspfPlaylistTrackList();
        for (PlaylistItem pli : playlist.listAllItems()) {
            // Create a track and add to list
            XspfTrack track = new XspfTrack();
            track.setIdentifier(String.valueOf(playlist.indexOf(pli)));
            if (pli.isFile()) {
                track.setLocation(new File(pli.getLocation()).toURI().toString());
            } else {
                track.setLocation(pli.getLocation());
            }
            if (pli.isFile()) {
                TagInfo tagInfo = pli.getTagInfo();
                if (tagInfo != null) {
                    String title = tagInfo.getTitle();
                    if (!Utilities.isNullOrEmpty(title)) {
                        track.setTitle(title);
                    }
                    String artist = tagInfo.getArtist();
                    if (!Utilities.isNullOrEmpty(artist)) {
                        track.setCreator(artist);
                    }
                    String album = tagInfo.getAlbum();
                    if (!Utilities.isNullOrEmpty(album)) {
                        track.setAlbum(album);
                    }
                    String trackNum = tagInfo.getTrack();
                    if (!Utilities.isNullOrEmpty(trackNum)) {
                        try {
                            track.setTrackNum(new BigInteger(trackNum));
                        } catch (NumberFormatException ex) {
                            logger.debug("{} is not a valid number", trackNum, ex);
                        }
                    }
                    String genre = tagInfo.getGenre();
                    if (!Utilities.isNullOrEmpty(genre)) {
                        track.setAnnotation(genre);
                    }
                    long duration = pli.getDuration();
                    if (duration >= 0) {
                        try {
                            track.setDuration(new BigInteger(String.valueOf(duration)));
                        } catch (NumberFormatException ex) {
                            logger.debug("{} is not a valid number", duration, ex);
                        }
                    }
                }
            } else {
                String name = pli.getFormattedName();
                if (!Utilities.isNullOrEmpty(name)) {
                    track.setTitle(name.trim());
                }
            }
            tracks.addTrack(track);
        }
        // add track to playlist
        xspfPlaylist.setPlaylistTrackList(tracks);

        // save to file
        OutputFormat format = OutputFormat.createPrettyPrint();
        FileWriter fw = null;
        Document doc = null;
        try {
            fw = new FileWriter(xspfFile);
            XMLWriter xmlWriter = new XMLWriter(fw, format);
            doc = DocumentHelper.parseText(xspfPlaylist.makeTextDocument());
            xmlWriter.write(doc);
            return true;
        } catch (Exception ex) {
            logger.error("Can't save playlist in XSPF format", ex);
            throw new PlaylistException(ex.getMessage(), ex.getCause());
        } finally {
            IOUtils.closeQuietly(fw);
        }
    }
    return false;
}

From source file:com.kenshoo.freemarker.util.DataModelParser.java

private static Object parseValue(String value, TimeZone timeZone) throws DataModelParsingException {
    // Note: Because we fall back to interpret the input as a literal string value when it doesn't look like
    // anything else (like a number, boolean, etc.), it's important to avoid misunderstandings, and throw exception
    // in suspicious situations. The user can always quote the string value if we are "too smart". But he will
    // be confused about the rules of FreeMarker if what he believes to be a non-string is misinterpreted by this
    // parser as a string. Getting sometimes an error and then quoting the string is better than that.

    if (value.endsWith(";")) { // Tolerate this habit of Java and JavaScript programmers
        value = value.substring(value.length() - 1).trim();
    }//ww w  .j a  v  a  2  s  . co  m

    if (NUMBER_LIKE.matcher(value).matches()) {
        try {
            return new BigDecimal(value);
        } catch (NumberFormatException e) {
            // Maybe it's a ISO 8601 Date/time/datetime
            CalendarFieldsToDateConverter calToDateConverter = new TrivialCalendarFieldsToDateConverter();

            DateParseException attemptedTemportalPExc = null;
            String attemptedTemporalType = null;
            final int dashIdx = value.indexOf('-');
            final int colonIdx = value.indexOf(':');
            if (value.indexOf('T') > 1 || (dashIdx > 1 && colonIdx > dashIdx)) {
                try {
                    return new Timestamp(
                            DateUtil.parseISO8601DateTime(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "date-time";
                    attemptedTemportalPExc = pExc;
                }
            } else if (dashIdx > 1) {
                try {
                    return new java.sql.Date(
                            DateUtil.parseISO8601Date(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "date";
                    attemptedTemportalPExc = pExc;
                }
            } else if (colonIdx > 1) {
                try {
                    return new Time(DateUtil.parseISO8601Time(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "time";
                    attemptedTemportalPExc = pExc;
                }
            }
            if (attemptedTemportalPExc == null) {
                throw new DataModelParsingException("Malformed number: " + value, e);
            } else {
                throw new DataModelParsingException("Malformed ISO 8601 " + attemptedTemporalType
                        + " (or malformed number): " + attemptedTemportalPExc.getMessage(), e.getCause());
            }
        }
    } else if (value.startsWith("\"")) {
        try {
            return JSON_MAPPER.readValue(value, String.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed quoted string (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("\'")) {
        throw new DataModelParsingException(
                "Malformed quoted string (using JSON syntax): Use \" character for quotation, not \' character.");
    } else if (value.startsWith("[")) {
        try {
            return JSON_MAPPER.readValue(value, List.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed list (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("{")) {
        try {
            return JSON_MAPPER.readValue(value, LinkedHashMap.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed list (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("<")) {
        try {
            DocumentBuilder builder = NodeModel.getDocumentBuilderFactory().newDocumentBuilder();
            ErrorHandler errorHandler = NodeModel.getErrorHandler();
            if (errorHandler != null)
                builder.setErrorHandler(errorHandler);
            final Document doc = builder.parse(new InputSource(new StringReader(value)));
            NodeModel.simplify(doc);
            return doc;
        } catch (SAXException e) {
            final String saxMsg = e.getMessage();
            throw new DataModelParsingException("Malformed XML: " + (saxMsg != null ? saxMsg : e), e);
        } catch (Exception e) {
            throw new DataModelParsingException("XML parsing has failed with internal error: " + e, e);
        }
    } else if (value.equalsIgnoreCase(KEYWORD_TRUE)) {
        checkKeywordCase(value, KEYWORD_TRUE);
        return Boolean.TRUE;
    } else if (value.equalsIgnoreCase(KEYWORD_FALSE)) {
        checkKeywordCase(value, KEYWORD_FALSE);
        return Boolean.FALSE;
    } else if (value.equalsIgnoreCase(KEYWORD_NULL)) {
        checkKeywordCase(value, KEYWORD_NULL);
        return null;
    } else if (value.equalsIgnoreCase(KEYWORD_NAN)) {
        checkKeywordCase(value, KEYWORD_NAN);
        return Double.NaN;
    } else if (value.equalsIgnoreCase(KEYWORD_INFINITY)) {
        checkKeywordCase(value, KEYWORD_INFINITY);
        return Double.POSITIVE_INFINITY;
    } else if (value.equalsIgnoreCase(KEYWORD_POSITIVE_INFINITY)) {
        checkKeywordCase(value, KEYWORD_POSITIVE_INFINITY);
        return Double.POSITIVE_INFINITY;
    } else if (value.equalsIgnoreCase(KEYWORD_NEGATIVE_INFINITY)) {
        checkKeywordCase(value, KEYWORD_NEGATIVE_INFINITY);
        return Double.NEGATIVE_INFINITY;
    } else if (value.length() == 0) {
        throw new DataModelParsingException(
                "Empty value. (If you indeed wanted a 0 length string, quote it, like \"\".)");
    } else {
        return value;
    }
}

From source file:com.ssbusy.controller.checkout.CheckoutController.java

@RequestMapping(value = "/checkout/alipaySucessOrFailed")
public String alipayCheckout(HttpServletRequest request, HttpServletResponse response, Model model,
        MyBillingInfoForm billingForm, BindingResult result, String orderNum, String returnInfo,
        String total_fee) {/*w ww .  ja v  a  2  s  .  c o  m*/
    LOG.info("this is our alipayCheckout function:");
    /*
     * String orderNum = (String) request.getAttribute("order_id"); String
     * returnInfo = (String) request.getAttribute("return_info"); String
     * total_fee = (String) request.getAttribute("total_fee");
     */
    BigDecimal alipay = null;
    if ("".equals(total_fee) || total_fee == null) {
        LOG.error("total_fee is null");
    } else {
        alipay = new BigDecimal(total_fee);
    }

    if (orderNum == null || returnInfo == null || alipay == null || orderNum.length() < 13
            || !"success".equals(returnInfo)) {
        LOG.error("orderNum or retutnInfo or alipay is error");
        return getCartPageRedirect();
    }

    Long orderId;
    try {
        orderId = Long.parseLong(orderNum.substring(12));
    } catch (NumberFormatException e) {
        LOG.error("substring orderNum throws an exception" + orderNum, e);
        return getCartPageRedirect();
    }
    Order cart = orderService.findOrderById(orderId);
    if (cart != null && OrderStatus.IN_PROCESS.equals(cart.getStatus())) {
        if (alipay.compareTo(cart.getTotal().getAmount()) < 0) {
            billingForm.setAlipay(alipay);
            LOG.info("a part of the order is used alipay");
            String ret = "";
            try {
                ret = complexCheckout(request, response, model, billingForm, result,
                        MyPaymentInfoType.Payment_Alipay, orderId);
            } catch (CheckoutException e) {
                if (e.getCause() instanceof InventoryUnavailableException) {
                    LOG.info("InventoryUnavailableException so we pay balance to the customer");
                    return aplipayFailedRollBack2Banlance(alipay, cart);
                } else {
                    LOG.info("not know exception", e);
                }
            }
            if (OrderStatus.IN_PROCESS.equals(cart.getStatus())) {
                return aplipayFailedRollBack2Banlance(alipay, cart);
            } else {
                LOG.info("alipay pay the part of the order is success");
                return ret;
            }
        }
        copyShippingAddressToBillingAddress(cart, billingForm);
        billingInfoFormValidator.validate(billingForm, result);
        if (result.hasErrors()) {
            LOG.error("result.hasErrors() orderid=" + orderId);
            populateModelWithShippingReferenceData(request, model);
            return getCheckoutView();
        }
        // ??
        cart.getPaymentInfos().clear();
        PaymentInfo alipayInfo = alipayPaymentInfoFactory.constructPaymentInfo(cart);
        alipayInfo.setAddress(billingForm.getMyAddress());
        cart.getPaymentInfos().add(alipayInfo);
        AlipayPaymentInfo alipayReference = (AlipayPaymentInfo) alipaySecurePaymentInfoService
                .create(MyPaymentInfoType.Payment_Alipay);
        alipayReference.setMessage("success");
        alipayReference.setReferenceNumber("try");
        Map<PaymentInfo, Referenced> payments = new HashMap<PaymentInfo, Referenced>(1);
        payments.put(alipayInfo, alipayReference);
        CheckoutResponse checkoutResponse = null;
        try {
            checkoutResponse = checkoutService.performCheckout(cart, payments);
        } catch (CheckoutException e) {
            if (e.getCause() instanceof InventoryUnavailableException) {
                LOG.info("InventoryUnavailableException in all pay by alipay");
                return aplipayFailedRollBack2Banlance(alipay, cart);
            } else {
                LOG.info("not know exception in all pay by alipay", e);
            }
        }
        if (!checkoutResponse.getPaymentResponse().getResponseItems().get(alipayInfo).getTransactionSuccess()) {

            LOG.error("alipay is finished but the order is not success because some problems");
            // ????????
            return aplipayFailedRollBack2Banlance(alipay, cart);
        }
        LOG.info("alipay success, the order is success order id=" + orderId);
        return getConfirmationView(cart.getOrderNumber());
    } else {

        LOG.error("alipay failed, the order is not normal order invalid: id=" + orderId);
        if (cart != null) {
            LOG.error("alipay failed OrderStatus is " + cart.getStatus());
        }
    }
    return getCartPageRedirect();

}

From source file:xtrememp.playlist.PlaylistIO.java

/**
 * Load playlist in PLS format.//from  w  ww . j a  v  a2 s.  c  o  m
 *
 * @param location
 * @return a list of playlist items.
 */
protected static List<PlaylistItem> loadPLS(String location) throws PlaylistException {
    List<PlaylistItem> itemList = new ArrayList<PlaylistItem>();
    BufferedReader br = null;
    try {
        // Playlist from URL ? (http:, ftp:, file: ....)
        if (Utilities.startWithProtocol(location)) {
            br = new BufferedReader(new InputStreamReader((new URL(location)).openStream()));
        } else {
            br = new BufferedReader(new FileReader(location));
        }
        String line = null;
        boolean markerFound = false;
        int numberOfEntries = -1;
        int lineNumber = 0;
        while ((line = br.readLine()) != null) {
            line = line.trim();
            lineNumber++;
            if (line.length() > 0) {
                // Header
                // The PLS marker string
                if (!markerFound) {
                    if (!line.equalsIgnoreCase("[playlist]")) {
                        logger.warn("Not a PLS playlist format");
                    }
                    markerFound = true;
                    continue;
                }

                if (line.indexOf('=') <= 0) {
                    logger.error("Malformed PLS playlist {}", location);
                    break;
                }

                StringTokenizer st = new StringTokenizer(line, "=");
                String key = st.nextToken().trim();
                String value = st.nextToken().trim();
                if (key.equalsIgnoreCase("numberofentries")) {
                    int tmpValue;
                    try {
                        tmpValue = Integer.parseInt(value);
                    } catch (NumberFormatException ex) {
                        logger.error("Error on parsing NumberOfEntries in PLS playlist: {} at line {}",
                                location, lineNumber);
                        break;
                    }

                    if (tmpValue < 0) {
                        logger.warn("Invalid NumberOfEntries in PLS playlist: {} at line {}", location,
                                lineNumber);
                    }

                    // Test if already found.
                    if ((numberOfEntries >= 0) && (numberOfEntries != tmpValue)) {
                        logger.warn("PLS playlist number of entries already specified with a different value");
                    }
                    numberOfEntries = tmpValue;
                } // Track entry
                else if (key.toLowerCase().startsWith("file")) {
                    PlaylistItem pli = null;
                    if (Utilities.startWithProtocol(value)) {
                        // URL.
                        pli = new PlaylistItem(value, value, -1, false);
                    } else {
                        // File.
                        File f = new File(value);
                        if (f.exists()) {
                            pli = new PlaylistItem(value, value, -1, true);
                        } else {
                            // Try relative path.
                            String parent = new File(location).getParent();
                            f = new File(parent, value);
                            if (f.exists()) {
                                pli = new PlaylistItem(value, f.getAbsolutePath(), -1, true);
                            }
                        }
                    }
                    if (pli != null) {
                        itemList.add(pli);
                    }
                } else if (key.toLowerCase().startsWith("title")) {
                    try {
                        int index = Integer.parseInt(key.substring(5)) - 1;
                        PlaylistItem pli = itemList.get(index);
                        pli.setFormattedName(value);
                    } catch (Exception ex) {
                        logger.warn("Corrupted PLS playlist {} at line {}", location, lineNumber);
                        continue;
                    }
                } else if (key.toLowerCase().startsWith("length")) {
                    try {
                        int duration = Integer.parseInt(value);
                        int index = Integer.parseInt(key.substring(6)) - 1;
                        PlaylistItem pli = itemList.get(index);
                        pli.setDuration(duration);
                    } catch (Exception ex) {
                        logger.warn("Corrupted PLS playlist {} at line {}", location, lineNumber);
                        continue;
                    }
                } // Footer
                else if (key.equalsIgnoreCase("version")) {
                    // If present, shall be "2".
                    if (!value.equals("2")) {
                        logger.error("Unknown PLS version " + value);
                        break;
                    }
                }
            }
        }
        if (numberOfEntries < 0) {
            logger.warn("No number of entries in PLS playlist");
        }
    } catch (Exception ex) {
        logger.error("Can't load PLS playlist", ex);
        throw new PlaylistException(ex.getMessage(), ex.getCause());
    } finally {
        IOUtils.closeQuietly(br);
    }
    return itemList;
}

From source file:com.virtusa.akura.common.controller.GradeSubjectController.java

/**
 * Save or update grade subjects./*from  w w w  . j  a  v a  2 s .co  m*/
 *
 * @param model the model
 * @param gradeSubject the grade subject
 * @param result the result
 * @param request the request
 * @return the string
 * @param errorMsgLoader - error massage
 * @throws AkuraException the akura app exception
 */
@RequestMapping(REQ_MAP_UPDATE_GRADE_SUBJECT)
public String saveOrUpdateGradeSubjects(final ModelMap model,
        @ModelAttribute(MODEL_ATT_GRADE_SUBJECT) final GradeSubject gradeSubject, BindingResult result,
        HttpServletRequest request, ErrorMsgLoader errorMsgLoader) throws AkuraException {

    String selectedSubjects = null;
    if (request.getParameter(ALL_SUBJECT_IDS) != null && !request.getParameter(ALL_SUBJECT_IDS).isEmpty()) {
        selectedSubjects = request.getParameter(ALL_SUBJECT_IDS);
    }

    gradeSubjectValidator.validate(gradeSubject, result);

    if (result.hasErrors()) {

        setRequestParameters(request);

        return VIEW_GET_MANAGE_SUBJECT_GRADE;
    } else {
        if (selectedSubjects == null) {

            String message = new ErrorMsgLoader().getErrorMessage(ERROR_MESSAGE_MANDATORY_FIELD_REQUIRED);
            model.addAttribute(VAR_MESSAGE, message);
            request.setAttribute(DISPLAY_EDIT_PANEL, true);

            setRequestParameters(request);
            return VIEW_GET_MANAGE_SUBJECT_GRADE;

        } else {

            String maxM = request.getParameter(MAXIMUM_MARK);
            String[] maxArray = maxM.split(COMMA);
            for (String maximumMarks : maxArray) {
                try {
                    int maxMa = Integer.parseInt(maximumMarks);
                    if (maxMa > MAX_MARK || maxMa < MIN_MARK) {
                        errorMsgLoader = new ErrorMsgLoader();
                        String message = errorMsgLoader.getErrorMessage(ERROR_MSG_KEY_INVALID_MAXIMUM_MARK);
                        model.addAttribute(AkuraConstant.MESSAGE, message);

                        setRequestParameters(request);
                        return VIEW_GET_MANAGE_SUBJECT_GRADE;
                    }
                } catch (NumberFormatException e) {
                    model.addAttribute(MESSAGE, AkuraWebConstant.MISMATCH_ERROR_MARKS);
                    setRequestParameters(request);
                    return VIEW_GET_MANAGE_SUBJECT_GRADE;
                }

            }

            String gradeDescription = request.getParameter(GRADE_DESCRIPTION);
            model.addAttribute(SELECTED_DESCRIPTION, gradeDescription);

            try {

                Grade grade = commonService.findGradeById(gradeSubject.getGrade().getGradeId());
                gradeSubject.setGrade(grade);
                String[] allSubjectIds = selectedSubjects.split(COMMA);
                String[] optionalSubjectIds = request.getParameterValues(OPTIONAL_SUBJECTS);

                if (EMPTY.equals(gradeDescription.trim())) {

                    // Check whether any subject already have assigned to the same grade.
                    if (commonService.hasAlreadyAssignedSubjectsForGrade(grade.getDescription())) {

                        errorMsgLoader = new ErrorMsgLoader();
                        String message = errorMsgLoader
                                .getErrorMessage(ERROR_MSG_KEY_SUBJECTS_ALREADY_ASSIGNED);
                        model.addAttribute(AkuraConstant.MESSAGE, message);

                        model.addAttribute(MODEL_ATT_SELECTED_GRADE_ID, grade.getGradeId());
                        setRequestParameters(request);
                        return VIEW_GET_MANAGE_SUBJECT_GRADE;

                    } else {

                        for (int k = 0; k < maxArray.length; k++) {
                            for (int j = 0; j < allSubjectIds.length;) {
                                handleSaveGradeSubject(gradeSubject, optionalSubjectIds, allSubjectIds[k],
                                        maxArray[k]);
                                break;
                            }
                        }

                    }

                } else {
                    List<GradeSubject> selectedSubjectsList = commonService
                            .findSubjectsByGrade(gradeDescription);
                    if (!selectedSubjectsList.isEmpty()) {

                        // Already assign subject ids for selected grade
                        String[] oldAllSubjectIds = new String[selectedSubjectsList.size()];
                        String[] oldOptionalSubjectIds = new String[selectedSubjectsList.size()];

                        int i = 0;
                        for (GradeSubject oldGradeSubject : selectedSubjectsList) {
                            oldAllSubjectIds[i] = oldGradeSubject.getSubject().getSubjectId()
                                    + String.valueOf(EMPTY);

                            if (oldGradeSubject.getIsOptionalSubject()) {
                                oldOptionalSubjectIds[i] = oldGradeSubject.getSubject().getSubjectId()
                                        + String.valueOf(EMPTY);
                            }

                            i++;
                        }

                        manageAddMoreGradeSubjects(gradeSubject, allSubjectIds, optionalSubjectIds,
                                oldAllSubjectIds, maxArray);

                        // Remove previously added grade subjects
                        manageRemoveAddedGradeSubjects(gradeDescription, allSubjectIds, oldAllSubjectIds,
                                request);

                        // edit maximum Marks
                        for (int k = 0; k < maxArray.length; k++) {
                            for (int j = 0; j < allSubjectIds.length;) {
                                editMaximumMarks(gradeDescription, allSubjectIds[k], maxArray[k]);
                                break;
                            }
                        }

                        updateMainSubjectAsOptional(gradeDescription, optionalSubjectIds, oldOptionalSubjectIds,
                                allSubjectIds);

                        updateOptionalSubjectAsMain(gradeDescription, optionalSubjectIds,
                                oldOptionalSubjectIds);
                    }
                }

            } catch (AkuraAppException e) {

                if (e.getCause() instanceof DataIntegrityViolationException) {
                    checkExistsGradeSubject(model, e);
                    setRequestParameters(request);
                    return VIEW_GET_MANAGE_SUBJECT_GRADE;
                } else {
                    errorMsgLoader = new ErrorMsgLoader();
                    String message = errorMsgLoader.getErrorMessage(ERROR_MSG_KEY_INVALID_MAXIMUM_MARK);
                    model.addAttribute(AkuraConstant.MESSAGE, message);
                    setRequestParameters(request);
                    return VIEW_GET_MANAGE_SUBJECT_GRADE;

                }

            }
            setRequestParameters(request);
            return VIEW_POST_MANAGE_SUBJECT_GRADE;
        }
    }
}

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 w  w . ja v a 2s .  co m*/
    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;
}