Example usage for java.lang Integer compareTo

List of usage examples for java.lang Integer compareTo

Introduction

In this page you can find the example usage for java.lang Integer compareTo.

Prototype

public int compareTo(Integer anotherInteger) 

Source Link

Document

Compares two Integer objects numerically.

Usage

From source file:org.kuali.ole.select.document.service.impl.OleInvoiceServiceImpl.java

public void createPaymentRequestDocument(OleInvoiceDocument inv, List<OleInvoiceItem> items, boolean flag) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating Payment Request document");
    }/*w  w  w  .  jav a  2 s. c o  m*/

    KNSGlobalVariables.getMessageList().clear();

    //   validateInvoiceOrderValidForPREQCreation(inv);

    if (LOG.isDebugEnabled()) {
        if (inv.isInvoiceCancelIndicator()) {
            LOG.debug("Not possible to convert cancelled Invoice details into payment request");
        } else {
            LOG.debug("Payment request document creation validation succeeded");
        }
    }

    if (inv.isInvoiceCancelIndicator()) {
        LOG.debug("Invoice Cancelled, Payment Request not created");
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Total Dollar Amount above line items >>>>" + inv.getTotalDollarAmountAboveLineItems());
    }
    Integer invId = inv.getPurapDocumentIdentifier();
    Integer poId = 0;
    List<Integer> poList = new ArrayList();

    List<OleInvoiceItem> oleInvoiceItemList = items;
    KualiDecimal invItemCount = new KualiDecimal(0);
    for (OleInvoiceItem oleInvoiceItem : oleInvoiceItemList) {
        if (oleInvoiceItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
            invItemCount = invItemCount.add(oleInvoiceItem.getItemQuantity());
        }
        if ((!(poList.contains(oleInvoiceItem.getPurchaseOrderIdentifier())))
                && oleInvoiceItem.getExtendedPrice().isNonZero()) {
            poList.add(oleInvoiceItem.getPurchaseOrderIdentifier());
        }
    }

    String prorateBy = inv.getProrateBy();

    OlePaymentRequestDocument preqDoc = null;
    Integer invPoId = 0;
    for (Integer purchaseOrderId : poList) {
        if (purchaseOrderId != null && invPoId.compareTo(purchaseOrderId) != 0) {
            try {
                preqDoc = (OlePaymentRequestDocument) SpringContext.getBean(DocumentService.class)
                        .getNewDocument("OLE_PREQ");
                preqDoc.setImmediatePaymentIndicator(inv.getImmediatePaymentIndicator());
                preqDoc.setInvoiceDate(inv.getInvoiceDate());
                preqDoc.setInvoiceNumber(inv.getInvoiceNumber());
                preqDoc.setVendorInvoiceAmount(inv.getVendorInvoiceAmount().abs());
                preqDoc.setVendorDetail(inv.getVendorDetail());
                preqDoc.setVendorName(inv.getVendorName());
                preqDoc.setVendorHeaderGeneratedIdentifier(inv.getVendorHeaderGeneratedIdentifier());
                preqDoc.setVendorDetailAssignedIdentifier(inv.getVendorDetailAssignedIdentifier());
                preqDoc.setVendorNumber(inv.getVendorNumber());
                preqDoc.setVendorHeaderGeneratedIdentifier(inv.getVendorHeaderGeneratedIdentifier());
                preqDoc.setVendorDetailAssignedIdentifier(inv.getVendorDetailAssignedIdentifier());
                preqDoc.setVendorPaymentTerms(inv.getVendorPaymentTerms());
                if (inv.getVendorPaymentTerms() != null) {
                    preqDoc.setVendorPaymentTermsCode(inv.getVendorPaymentTerms().getVendorPaymentTermsCode());
                }
                preqDoc.setVendorShippingTitleCode(inv.getVendorShippingTitleCode());
                preqDoc.setVendorShippingPaymentTerms(inv.getVendorShippingPaymentTerms());
                preqDoc.setVendorCityName(inv.getVendorCityName());
                preqDoc.setVendorLine1Address(inv.getVendorLine1Address());
                preqDoc.setVendorLine2Address(inv.getVendorLine2Address());
                preqDoc.setVendorAttentionName(inv.getVendorAttentionName());
                preqDoc.setVendorPostalCode(inv.getVendorPostalCode());
                preqDoc.setVendorStateCode(inv.getVendorStateCode());
                preqDoc.setVendorAttentionName(inv.getVendorAttentionName());
                preqDoc.setVendorAddressInternationalProvinceName(
                        inv.getVendorAddressInternationalProvinceName());
                preqDoc.setVendorCountryCode(inv.getVendorCountryCode());
                preqDoc.setVendorCountry(inv.getVendorCountry());
                preqDoc.setVendorCustomerNumber(inv.getVendorCustomerNumber());
                preqDoc.setAccountsPayableProcessorIdentifier(inv.getAccountsPayableProcessorIdentifier());
                preqDoc.setProcessingCampusCode(inv.getProcessingCampusCode());
                preqDoc.setPurchaseOrderIdentifier(purchaseOrderId);
                //
                //preqDoc.setClosePurchaseOrderIndicator(oleInvoiceItem.isClosePurchaseOrderIndicator());
                preqDoc.setPaymentRequestPayDate(inv.getInvoicePayDate());
                preqDoc.setImmediatePaymentIndicator(inv.getImmediatePaymentIndicator());
                preqDoc.setPaymentRequestCostSource(inv.getInvoiceCostSource());
                preqDoc.setProrateBy(inv.getProrateBy());
                preqDoc.setProrateDollar(inv.isProrateDollar());
                preqDoc.setProrateQty(inv.isProrateQty());
                preqDoc.setProrateManual(inv.isProrateManual());
                preqDoc.setNoProrate(inv.isNoProrate());
                preqDoc.setForeignVendorInvoiceAmount(inv.getForeignVendorInvoiceAmount());

                if (inv.getPaymentMethodId() != null) {
                    OlePaymentMethod olePaymentMethod = SpringContext.getBean(BusinessObjectService.class)
                            .findBySinglePrimaryKey(OlePaymentMethod.class, inv.getPaymentMethodId());
                    preqDoc.setPaymentMethod(olePaymentMethod);
                    preqDoc.getPaymentMethod().setPaymentMethodId(olePaymentMethod.getPaymentMethodId());
                    preqDoc.setPaymentMethodId(olePaymentMethod.getPaymentMethodId());
                }

                preqDoc.setInvoiceIdentifier(inv.getPurapDocumentIdentifier());
                preqDoc.setBankCode(inv.getBankCode());
                preqDoc.setBank(inv.getBank());
            } catch (WorkflowException e) {
                String extraDescription = "Error=" + e.getMessage();
                LOG.error("Exception creating Payment request document - " + e.getMessage());
            }

            Map invItemMap = new HashMap();
            invItemMap.put(PurapConstants.PRQSDocumentsStrings.PUR_ID, inv.getPurapDocumentIdentifier());
            invItemMap.put(PurapConstants.PRQSDocumentsStrings.PO_ID, purchaseOrderId);
            List<OleInvoiceItem> invoiceItems = (List<OleInvoiceItem>) businessObjectService
                    .findMatchingOrderBy(OleInvoiceItem.class, invItemMap,
                            PurapConstants.PRQSDocumentsStrings.PO_ID, true);

            KualiDecimal itemCount = new KualiDecimal(0);
            KualiDecimal itemPrice = new KualiDecimal(0);
            PurchaseOrderDocument poDoc = inv.getPurchaseOrderDocument(purchaseOrderId);
            if (poDoc == null) {
                throw new RuntimeException(
                        "Purchase Order document (invPoId=" + invPoId + ") does not exist in the system");
            }

            preqDoc.getDocumentHeader().setDocumentDescription(
                    createPreqDocumentDescription(poDoc.getPurapDocumentIdentifier(), inv.getVendorName()));

            try {
                preqDoc.updateAndSaveAppDocStatus(PurapConstants.PaymentRequestStatuses.APPDOC_IN_PROCESS);
            } catch (WorkflowException we) {
                throw new RuntimeException(
                        "Unable to save route status data for document: " + preqDoc.getDocumentNumber(), we);
            }

            SpringContext.getBean(KualiRuleService.class)
                    .applyRules(new AttributedCalculateAccountsPayableEvent(preqDoc));

            SpringContext.getBean(PaymentRequestService.class).calculatePaymentRequest(preqDoc, false);
            HashMap<String, ExpiredOrClosedAccountEntry> expiredOrClosedAccountList = SpringContext
                    .getBean(AccountsPayableService.class).expiredOrClosedAccountsList(poDoc);
            if (expiredOrClosedAccountList == null) {
                expiredOrClosedAccountList = new HashMap();
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug(expiredOrClosedAccountList.size() + " accounts has been found as Expired or Closed");
            }
            List<OlePaymentRequestItem> olePaymentRequestItems = new ArrayList<>();
            // int itemLineNumberCount = 0;
            for (OleInvoiceItem invoiceItem : invoiceItems) {
                if ((flag || invoiceItem.isDebitItem()) && invoiceItem.getExtendedPrice().isNonZero()) {
                    OlePaymentRequestItem olePaymentRequestItem = new OlePaymentRequestItem(invoiceItem,
                            preqDoc, expiredOrClosedAccountList);
                    if (flag && !invoiceItem.isDebitItem()) {
                        olePaymentRequestItem
                                .setItemListPrice(olePaymentRequestItem.getItemListPrice().negated());
                        olePaymentRequestItem
                                .setItemUnitPrice(olePaymentRequestItem.getItemUnitPrice().negate());
                        olePaymentRequestItem
                                .setExtendedPrice(olePaymentRequestItem.getExtendedPrice().negated());
                        for (PurApAccountingLine purApAccountingLine : olePaymentRequestItem
                                .getSourceAccountingLines()) {
                            purApAccountingLine.setAmount(purApAccountingLine.getAmount().negated());
                        }
                    }
                    olePaymentRequestItems.add(olePaymentRequestItem);
                    if (invoiceItem.isReopenPurchaseOrderIndicator()) {
                        preqDoc.setReopenPurchaseOrderIndicator(invoiceItem.isReopenPurchaseOrderIndicator());
                    }
                    if (invoiceItem.isClosePurchaseOrderIndicator()) {
                        preqDoc.setClosePurchaseOrderIndicator(invoiceItem.isClosePurchaseOrderIndicator());
                    }
                    if (preqDoc.getAccountsPayablePurchasingDocumentLinkIdentifier() == null) {
                        preqDoc.setAccountsPayablePurchasingDocumentLinkIdentifier(
                                invoiceItem.getAccountsPayablePurchasingDocumentLinkIdentifier());
                    }
                    preqDoc.setReceivingDocumentRequiredIndicator(
                            invoiceItem.isReceivingDocumentRequiredIndicator());
                }
            }

            invPoId = purchaseOrderId;
            preqDoc.setItems(olePaymentRequestItems);

            try {
                SpringContext.getBean(PaymentRequestService.class).populateAndSavePaymentRequest(preqDoc);

                SpringContext.getBean(PaymentRequestService.class).autoApprovePaymentRequest(preqDoc);
            } catch (WorkflowException e) {
                e.printStackTrace();
            } catch (ValidationException e) {
                String extraDescription = GlobalVariables.getMessageMap().toString();
            }
        }

        if (GlobalVariables.getMessageMap().hasErrors()) {

            LOG.error("***************Error in rules processing - " + GlobalVariables.getMessageMap());
            Map<String, AutoPopulatingList<ErrorMessage>> errorMessages = GlobalVariables.getMessageMap()
                    .getErrorMessages();

            String errors = errorMessages.toString();
        }

        if (KNSGlobalVariables.getMessageList().size() > 0) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Payment request contains " + KNSGlobalVariables.getMessageList().size()
                        + " warning message(s)");
                for (int i = 0; i < KNSGlobalVariables.getMessageList().size(); i++) {
                    LOG.debug("Warning " + i + "  - " + KNSGlobalVariables.getMessageList().get(i));
                }
            }
        }

        String routingAnnotation = null;
        if (!inv.isInvoiceCancelIndicator()) {
            routingAnnotation = "Routed by New Invoice Creation";
        }
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.util.TcgaVcfFileDataLineValidatorImpl.java

/**
 * INFO part of data line contains an Integer value for DP
 * FORMAT part of the data line contains DP hence sample lines should have an integer value specified
 * In that case, if both INFO and FORMAT are specified, then the total across all samples for the data line
 * must be equal to the value specified in the INFO part.
 * @param dataLine A data line containing values for each of the columns in the data line
 * @param lineNum The line number of the data line for logging purposes
 * @param context The <code>QcContext</code> for logging purposes
 * @return <code>true</code> is validation was successful, <code>false</code> otherwise
 *//*from w  w  w.j av  a 2 s. c om*/
protected boolean validateDPKey(final String[] dataLine, final Integer lineNum, final QcContext context) {
    // since everything has checked out to this point, all keys and values should follow
    // proper syntax and all we do here is semantic validation
    boolean isValid = true;
    if (dataLine.length >= VcfFileDataLineValidatorImpl.VcfColumns.FORMAT.colPos() + 1) {
        final String infoValue = dataLine[VcfColumns.INFO_POS.colPos()];
        Integer dpValue = new Integer(0);
        final String infoDpValue = VcfFileValidatorUtil.getInfoValue(FORMAT_VALUE_DP, infoValue);
        if (!StringUtils.isEmpty(infoDpValue) && !isBlankDataValue(infoDpValue)) {
            try {
                dpValue = Integer.parseInt(infoDpValue);
            } catch (NumberFormatException nfe) {
                addErrorMessage(VcfFile.HEADER_TYPE_INFO, infoDpValue, "The value of DP must be an Integer",
                        lineNum, context);
                return false;
            }
        } else {
            return true; // cant validate something that does not exist
        }

        Integer sampleDpTotalValue = new Integer(0);
        final String formatValue = dataLine[VcfColumns.FORMAT.colPos()];
        if (!StringUtils.isEmpty(formatValue)) {
            if (VcfFileValidatorUtil.isExistsFormatKey(formatValue, FORMAT_VALUE_DP)) {
                final List<String> sampleValues = VcfFile.getSamplesColumns(Arrays.asList(dataLine));
                for (final String sampleValue : sampleValues) {
                    // validate only if sample column contains all data
                    if (isSampleColumnContainsAllData(sampleValue, formatValue)) {
                        final String sampleDpValue = VcfFileValidatorUtil.getSampleValue(FORMAT_VALUE_DP,
                                formatValue, sampleValue);
                        if (!isBlankDataValue(sampleDpValue)) {
                            try {
                                sampleDpTotalValue = sampleDpTotalValue + Integer.parseInt(sampleDpValue);
                            } catch (NumberFormatException nfe) {
                                // do not add the error message. It is already captured in validateSampleData
                                isValid = false;
                            }
                        } else {
                            // if any SAMPLE column has dp of '.' then we can't validate this, so just return true
                            return true;
                        }
                    } else {
                        // do not add the error message. It is already captured in validateSampleData
                        isValid = false;
                    }
                }
            } else {
                return true; // novalidation if DP not specified in FORMAT
            }
        } else {
            return true; // novalidation if DP not specified in FORMAT
        }
        if (isValid && dpValue != null && sampleDpTotalValue != null
                && !(dpValue.compareTo(sampleDpTotalValue) == 0)) {
            final String value = new StringBuilder().append(" DP of ").append(dpValue)
                    .append(" and sample DP total of ").append(sampleDpTotalValue).toString();
            addErrorMessage(VcfFile.HEADER_TYPE_INFO, value,
                    "The value for DP in INFO column and the total of the values for DP in the sample columns must be equal if DP is specified in FORMAT column",
                    lineNum, context);
            isValid = false;
        }
    }

    return isValid;
}

From source file:org.sakaiproject.tool.assessment.ui.listener.evaluation.HistogramListener.java

/**
 * calculates statistics for EMI questions
 *///from   w ww. j  a  v  a  2  s. c o m
private void getEMIScores(HashMap publishedItemHash, HashMap publishedAnswerHash,
        HashMap emiRequiredCorrectAnswersCount, List scores, HistogramQuestionScoresBean qbean, List answers) {
    ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");

    // Answers keyed by answer-id
    HashMap answersById = new HashMap();

    //keys the number of student responses selecting a particular answer
    //by the Answer ID
    HashMap results = new HashMap();

    //keys Answer-IDs by subQuestion/ItemTextSequence-answerSequence (concatenated)
    HashMap sequenceMap = new HashMap();

    //list of answers for each sub-question/ItemText
    ArrayList subQuestionAnswers = null;

    //Map which keys above lists by the sub-question/ItemText sequence
    HashMap subQuestionAnswerMap = new HashMap();

    //Create a Map where each Sub-Question's Answers-ArrayList 
    //is keyed by sub-question and answer sequence 
    Iterator iter = answers.iterator();
    while (iter.hasNext()) {
        AnswerIfc answer = (AnswerIfc) iter.next();
        answersById.put(answer.getId(), answer);
        results.put(answer.getId(), Integer.valueOf(0));
        sequenceMap.put(answer.getItemText().getSequence() + "-" + answer.getSequence(), answer.getId());
        Long subQuestionSequence = answer.getItemText().getSequence();
        Object subSeqAns = subQuestionAnswerMap.get(subQuestionSequence);
        if (subSeqAns == null) {
            subQuestionAnswers = new ArrayList();
            subQuestionAnswerMap.put(subQuestionSequence, subQuestionAnswers);
        } else {
            subQuestionAnswers = (ArrayList) subSeqAns;
        }
        subQuestionAnswers.add(answer);
    }

    //Iterate through the student answers (ItemGradingData)
    iter = scores.iterator();
    //Create a map that keys all the responses/answers (ItemGradingData) 
    //for this question from a specific student (assessment)
    //by the id of that assessment (AssessmentGradingData)
    HashMap responsesPerStudentPerQuestionMap = new HashMap();
    //and do the same for seperate sub-questions
    HashMap responsesPerStudentPerSubQuestionMap = new HashMap();
    while (iter.hasNext()) {
        ItemGradingData data = (ItemGradingData) iter.next();
        //Get the published answer that corresponds to the student's reponse
        AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId());
        //This should always be the case as only valid responses 
        //from the list of available options are allowed 
        if (answer != null) {
            // log.info("Gopal: looking for " + answer.getId());
            // found a response
            Integer num = null;
            // num is a counter for the number of responses that select this published answer
            try {
                // we found a response, now get existing count from the
                // hashmap
                num = (Integer) results.get(answer.getId());

            } catch (Exception e) {
                log.warn("No results for " + answer.getId());
            }

            //If this published answer has not been selected before
            if (num == null)
                num = Integer.valueOf(0);

            //Now create a map that keys all the responses (ItemGradingData) 
            //for this question from a specific student (or assessment)
            //by the id of that assessment (AssessmentGradingData)
            ArrayList studentResponseList = (ArrayList) responsesPerStudentPerQuestionMap
                    .get(data.getAssessmentGradingId());
            if (studentResponseList == null) {
                studentResponseList = new ArrayList();
            }
            studentResponseList.add(data);
            responsesPerStudentPerQuestionMap.put(data.getAssessmentGradingId(), studentResponseList);

            //Do the same for the sub-questions
            String key = data.getAssessmentGradingId() + "-" + answer.getItemText().getId();
            ArrayList studentResponseListForSubQuestion = (ArrayList) responsesPerStudentPerSubQuestionMap
                    .get(key);
            if (studentResponseListForSubQuestion == null) {
                studentResponseListForSubQuestion = new ArrayList();
            }
            studentResponseListForSubQuestion.add(data);
            responsesPerStudentPerSubQuestionMap.put(key, studentResponseListForSubQuestion);

            results.put(answer.getId(), Integer.valueOf(num.intValue() + 1));
        }
    }

    HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()];
    int[] numarray = new int[results.keySet().size()];

    //List of "ItemText.sequence-Answer.sequence"
    List<String> sequenceList = new ArrayList<String>();
    iter = answers.iterator();
    while (iter.hasNext()) {
        AnswerIfc answer = (AnswerIfc) iter.next();
        sequenceList.add(answer.getItemText().getSequence() + "-" + answer.getSequence());
    }
    // sort the sequence
    Collections.sort(sequenceList, new Comparator<String>() {

        public int compare(String o1, String o2) {
            Integer a1 = Integer.valueOf(o1.substring(0, o1.indexOf("-")));
            Integer a2 = Integer.valueOf(o2.substring(0, o1.indexOf("-")));
            int val = a1.compareTo(a2);
            if (val != 0) {
                return val;
            }
            a1 = Integer.valueOf(o1.substring(o1.indexOf("-") + 1));
            a2 = Integer.valueOf(o2.substring(o1.indexOf("-") + 1));
            return a1.compareTo(a2);
        }
    });
    // iter = results.keySet().iterator();
    iter = sequenceList.iterator();
    int i = 0;
    int responses = 0;
    int correctresponses = 0;
    while (iter.hasNext()) {
        String sequenceId = (String) iter.next();
        Long answerId = (Long) sequenceMap.get(sequenceId);
        AnswerIfc answer = (AnswerIfc) answersById.get(answerId);
        int num = ((Integer) results.get(answerId)).intValue();
        numarray[i] = num;
        bars[i] = new HistogramBarBean();
        if (answer != null) {
            bars[i].setSubQuestionSequence(answer.getItemText().getSequence());
            if (answer.getItem().getIsAnswerOptionsSimple()) {
                bars[i].setLabel(answer.getItemText().getSequence() + ". " + answer.getLabel() + "  "
                        + answer.getText());
            } else { //rich text or attachment options
                bars[i].setLabel(answer.getItemText().getSequence() + ". " + answer.getLabel());
            }

            if (answer.getLabel().equals("A")) {
                String title = rb.getString("item") + " " + answer.getItemText().getSequence();
                String text = answer.getItemText().getText();
                if (text != null && !text.equals(null)) {
                    title += " : " + text;
                    bars[i].setTitle(title);
                }
            }
            bars[i].setIsCorrect(answer.getIsCorrect());
        }

        bars[i].setNumStudentsText(num + " " + rb.getString("responses"));
        bars[i].setNumStudents(num);
        i++;
    } // end while

    responses = responsesPerStudentPerQuestionMap.size();

    //Determine the number of students with all correct responses for the whole question
    for (Iterator it = responsesPerStudentPerQuestionMap.entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        ArrayList resultsForOneStudent = (ArrayList) entry.getValue();

        boolean hasIncorrect = false;
        Iterator listiter = resultsForOneStudent.iterator();

        // iterate through the results for one student
        // for this question (qbean)
        while (listiter.hasNext()) {
            ItemGradingData item = (ItemGradingData) listiter.next();

            // only answered choices are created in the
            // ItemGradingData_T, so we need to check
            // if # of checkboxes the student checked is == the number
            // of correct answers
            // otherwise if a student only checked one of the multiple
            // correct answers,
            // it would count as a correct response
            try {
                int corranswers = 0;
                Iterator answeriter = answers.iterator();
                while (answeriter.hasNext()) {
                    AnswerIfc answerchoice = (AnswerIfc) answeriter.next();
                    if (answerchoice.getIsCorrect().booleanValue()) {
                        corranswers++;
                    }
                }
                if (resultsForOneStudent.size() != corranswers) {
                    hasIncorrect = true;
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("error calculating emi question.");
            }

            // now check each answer
            AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(item.getPublishedAnswerId());
            if (answer != null && (answer.getIsCorrect() == null || (!answer.getIsCorrect().booleanValue()))) {
                hasIncorrect = true;
                break;
            }
        }

        if (!hasIncorrect) {
            correctresponses = correctresponses + 1;
            qbean.addStudentWithAllCorrect(((ItemGradingData) resultsForOneStudent.get(0)).getAgentId());
        }
        qbean.addStudentResponded(((ItemGradingData) resultsForOneStudent.get(0)).getAgentId());
    } // end for - number of students with all correct responses for the whole question

    // NEW
    int[] heights = calColumnHeight(numarray, responses);
    // int[] heights = calColumnHeight(numarray);
    for (i = 0; i < bars.length; i++) {
        try {
            bars[i].setColumnHeight(Integer.toString(heights[i]));
        } catch (NullPointerException npe) {
            log.warn("null column height " + npe);
        }
    }

    qbean.setHistogramBars(bars);
    qbean.setNumResponses(responses);
    if (responses > 0)
        qbean.setPercentCorrect(
                Integer.toString((int) (((double) correctresponses / (double) responses) * 100)));

    HashMap numStudentsWithAllCorrectPerSubQuestion = new HashMap();
    HashMap studentsWithAllCorrectPerSubQuestion = new HashMap();
    HashMap studentsRespondedPerSubQuestion = new HashMap();
    Iterator studentSubquestionResponseKeyIter = responsesPerStudentPerSubQuestionMap.keySet().iterator();
    while (studentSubquestionResponseKeyIter.hasNext()) {
        String key = (String) studentSubquestionResponseKeyIter.next();
        ArrayList studentResponseListForSubQuestion = (ArrayList) responsesPerStudentPerSubQuestionMap.get(key);
        if (studentResponseListForSubQuestion != null && !studentResponseListForSubQuestion.isEmpty()) {
            ItemGradingData response1 = (ItemGradingData) studentResponseListForSubQuestion.get(0);
            Long subQuestionId = ((AnswerIfc) publishedAnswerHash.get(response1.getPublishedAnswerId()))
                    .getItemText().getId();

            Set studentsResponded = (Set) studentsRespondedPerSubQuestion.get(subQuestionId);
            if (studentsResponded == null)
                studentsResponded = new TreeSet();
            studentsResponded.add(response1.getAgentId());
            studentsRespondedPerSubQuestion.put(subQuestionId, studentsResponded);

            boolean hasIncorrect = false;
            //numCorrectSubQuestionAnswers = (Integer) correctAnswersPerSubQuestion.get(subQuestionId);
            Integer numCorrectSubQuestionAnswers = (Integer) emiRequiredCorrectAnswersCount.get(subQuestionId);

            if (studentResponseListForSubQuestion.size() < numCorrectSubQuestionAnswers.intValue()) {
                hasIncorrect = true;
                continue;
            }
            //now check each answer
            Iterator studentResponseIter = studentResponseListForSubQuestion.iterator();
            while (studentResponseIter.hasNext()) {
                ItemGradingData response = (ItemGradingData) studentResponseIter.next();
                AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(response.getPublishedAnswerId());
                if (answer != null
                        && (answer.getIsCorrect() == null || (!answer.getIsCorrect().booleanValue()))) {
                    hasIncorrect = true;
                    break;
                }
            }
            if (hasIncorrect)
                continue;
            Integer numWithAllCorrect = (Integer) numStudentsWithAllCorrectPerSubQuestion.get(subQuestionId);
            if (numWithAllCorrect == null) {
                numWithAllCorrect = Integer.valueOf(0);
            }
            numStudentsWithAllCorrectPerSubQuestion.put(subQuestionId,
                    Integer.valueOf(numWithAllCorrect.intValue() + 1));

            Set studentsWithAllCorrect = (Set) studentsWithAllCorrectPerSubQuestion.get(subQuestionId);
            if (studentsWithAllCorrect == null)
                studentsWithAllCorrect = new TreeSet();
            studentsWithAllCorrect.add(response1.getAgentId());
            studentsWithAllCorrectPerSubQuestion.put(subQuestionId, studentsWithAllCorrect);

        }

    }

    //Map ItemText sequences to Ids
    HashMap itemTextSequenceIdMap = new HashMap();
    Iterator answersIter = answers.iterator();
    while (answersIter.hasNext()) {
        AnswerIfc answer = (AnswerIfc) answersIter.next();
        itemTextSequenceIdMap.put(answer.getItemText().getSequence(), answer.getItemText().getId());
    }

    //Now select the the bars for each sub-questions   
    Set subQuestionKeySet = subQuestionAnswerMap.keySet();
    ArrayList subQuestionKeyList = new ArrayList();
    subQuestionKeyList.addAll(subQuestionKeySet);
    Collections.sort(subQuestionKeyList);
    Iterator subQuestionIter = subQuestionKeyList.iterator();
    ArrayList subQuestionInfo = new ArrayList(); //List of sub-question HistogramQuestionScoresBeans - for EMI sub-questions
    // Iterate through the assessment questions (items)
    while (subQuestionIter.hasNext()) {
        Long subQuestionSequence = (Long) subQuestionIter.next();

        //While qbean is the HistogramQuestionScoresBean for the entire question
        //questionScores are the HistogramQuestionScoresBeans for each sub-question
        HistogramQuestionScoresBean questionScores = new HistogramQuestionScoresBean();
        questionScores.setSubQuestionSequence(subQuestionSequence);

        // Determine the number of bars (possible answers) for this sub-question
        int numBars = 0;
        for (int j = 0; j < bars.length; j++) {
            if (bars[j].getSubQuestionSequence().equals(subQuestionSequence)) {
                numBars++;
            }
        }
        //Now create an array of that size
        //and populate it with the bars for this sub-question
        HistogramBarBean[] subQuestionBars = new HistogramBarBean[numBars];
        int subBar = 0;
        for (int j = 0; j < bars.length; j++) {
            if (bars[j].getSubQuestionSequence().equals(subQuestionSequence)) {
                subQuestionBars[subBar++] = bars[j];
            }
        }

        questionScores.setShowIndividualAnswersInDetailedStatistics(true);
        questionScores.setHistogramBars(subQuestionBars);
        questionScores.setNumberOfParts(qbean.getNumberOfParts());
        //if this part is a randompart , then set randompart = true
        questionScores.setRandomType(qbean.getRandomType());

        questionScores.setPartNumber(qbean.getPartNumber());
        questionScores.setQuestionNumber(qbean.getQuestionNumber() + "-" + subQuestionSequence);

        questionScores.setQuestionText(qbean.getQuestionText());

        questionScores.setQuestionType(qbean.getQuestionType());

        questionScores.setN(qbean.getN());
        questionScores.setItemId(qbean.getItemId());

        //This boild down to the number of AssessmentGradingData
        //So should be the same for whole and sub questions
        questionScores.setNumResponses(qbean.getNumResponses());

        Long subQuestionId = (Long) itemTextSequenceIdMap.get(subQuestionSequence);
        if (questionScores.getNumResponses() > 0) {
            Integer numWithAllCorrect = (Integer) numStudentsWithAllCorrectPerSubQuestion.get(subQuestionId);
            if (numWithAllCorrect != null)
                correctresponses = numWithAllCorrect.intValue();
            questionScores.setPercentCorrect(
                    Integer.toString((int) (((double) correctresponses / (double) responses) * 100)));
        }
        Set studentsWithAllCorrect = (Set) studentsWithAllCorrectPerSubQuestion.get(subQuestionId);
        questionScores.setStudentsWithAllCorrect(studentsWithAllCorrect);

        Set studentsResponded = (Set) studentsRespondedPerSubQuestion.get(subQuestionId);
        questionScores.setStudentsResponded(studentsResponded);

        subQuestionAnswers = (ArrayList) subQuestionAnswerMap.get(subQuestionSequence);
        Iterator answerIter = subQuestionAnswers.iterator();
        Double totalScore = new Double(0);
        while (answerIter.hasNext()) {
            AnswerIfc subQuestionAnswer = (AnswerIfc) answerIter.next();
            totalScore += (subQuestionAnswer == null || subQuestionAnswer.getScore() == null ? 0.0
                    : subQuestionAnswer.getScore());

        }
        questionScores.setTotalScore(totalScore.toString());

        HistogramScoresBean histogramScores = (HistogramScoresBean) ContextUtil.lookupBean("histogramScores");

        Iterator keys = responsesPerStudentPerSubQuestionMap.keySet().iterator();
        int numSubmissions = 0;
        while (keys.hasNext()) {
            String assessmentAndSubquestionId = (String) keys.next();
            if (assessmentAndSubquestionId.endsWith("-" + subQuestionId))
                numSubmissions++;
        }
        int percent27 = numSubmissions * 27 / 100; // rounded down
        if (percent27 == 0)
            percent27 = 1;

        studentsWithAllCorrect = questionScores.getStudentsWithAllCorrect();
        studentsResponded = questionScores.getStudentsResponded();
        if (studentsWithAllCorrect == null || studentsResponded == null || studentsWithAllCorrect.isEmpty()
                || studentsResponded.isEmpty()) {
            questionScores.setPercentCorrectFromUpperQuartileStudents("0");
            questionScores.setPercentCorrectFromLowerQuartileStudents("0");
            questionScores.setDiscrimination("0.0");
        } else {
            int numStudentsWithAllCorrectFromUpperQuartile = 0;
            int numStudentsWithAllCorrectFromLowerQuartile = 0;
            Iterator studentsIter = studentsWithAllCorrect.iterator();
            while (studentsIter.hasNext()) {
                String agentId = (String) studentsIter.next();
                if (histogramScores.isUpperQuartileStudent(agentId)) {
                    numStudentsWithAllCorrectFromUpperQuartile++;
                }
                if (histogramScores.isLowerQuartileStudent(agentId)) {
                    numStudentsWithAllCorrectFromLowerQuartile++;
                }
            }
            int numStudentsRespondedFromUpperQuartile = 0;
            int numStudentsRespondedFromLowerQuartile = 0;
            studentsIter = studentsResponded.iterator();
            while (studentsIter.hasNext()) {
                String agentId = (String) studentsIter.next();
                if (histogramScores.isUpperQuartileStudent(agentId)) {
                    numStudentsRespondedFromUpperQuartile++;
                }
                if (histogramScores.isLowerQuartileStudent(agentId)) {
                    numStudentsRespondedFromLowerQuartile++;
                }
            }

            double percentCorrectFromUpperQuartileStudents = ((double) numStudentsWithAllCorrectFromUpperQuartile
                    / (double) percent27) * 100d;

            double percentCorrectFromLowerQuartileStudents = ((double) numStudentsWithAllCorrectFromLowerQuartile
                    / (double) percent27) * 100d;

            questionScores.setPercentCorrectFromUpperQuartileStudents(
                    Integer.toString((int) percentCorrectFromUpperQuartileStudents));
            questionScores.setPercentCorrectFromLowerQuartileStudents(
                    Integer.toString((int) percentCorrectFromLowerQuartileStudents));

            double numResponses = (double) questionScores.getNumResponses();

            double discrimination = ((double) numStudentsWithAllCorrectFromUpperQuartile
                    - (double) numStudentsWithAllCorrectFromLowerQuartile) / (double) percent27;

            // round to 2 decimals
            if (discrimination > 999999 || discrimination < -999999) {
                questionScores.setDiscrimination("NaN");
            } else {
                discrimination = ((int) (discrimination * 100.00)) / 100.00;
                questionScores.setDiscrimination(Double.toString(discrimination));
            }
        }

        subQuestionInfo.add(questionScores);
    } // end-while - items
    qbean.setInfo(subQuestionInfo);

}

From source file:org.kitodo.production.metadata.MetadataProcessor.java

/**
 * alle Seiten des aktuellen Strukturelements ermitteln.
 *///w  w  w .j a  v  a 2  s .co  m
private void determinePagesStructure(LegacyDocStructHelperInterface inStrukturelement) {
    if (inStrukturelement == null) {
        return;
    }
    List<LegacyReferenceHelper> references = inStrukturelement.getAllReferences("to");
    int zaehler = 0;
    int imageNr = 0;
    if (references != null) {
        references.sort((firstObject, secondObject) -> {
            Integer firstPage = 0;
            int secondPage = 0;

            LegacyMetadataTypeHelper mdt = this.myPrefs.getMetadataTypeByName("physPageNumber");
            List<? extends LegacyMetadataHelper> listMetadata = firstObject.getTarget()
                    .getAllMetadataByType(mdt);
            if (Objects.nonNull(listMetadata) && !listMetadata.isEmpty()) {
                LegacyMetadataHelper page = listMetadata.get(0);
                firstPage = Integer.parseInt(page.getValue());
            }
            listMetadata = secondObject.getTarget().getAllMetadataByType(mdt);
            if (Objects.nonNull(listMetadata) && !listMetadata.isEmpty()) {
                LegacyMetadataHelper page = listMetadata.get(0);
                secondPage = Integer.parseInt(page.getValue());
            }
            return firstPage.compareTo(secondPage);
        });

        /* die Gre der Arrays festlegen */
        this.structSeiten = new SelectItem[references.size()];
        this.structurePageNew = new MetadataImpl[references.size()];

        /* alle Referenzen durchlaufen und deren Metadaten ermitteln */
        for (LegacyReferenceHelper ref : references) {
            LegacyDocStructHelperInterface target = ref.getTarget();
            determineSecondPagesStructure(target, zaehler);
            if (imageNr == 0) {
                imageNr = determineThirdPagesStructure(target);
            }
            zaehler++;
        }

    }

    /*
     * Wenn eine Verknpfung zwischen Strukturelement und Bildern sein soll,
     * das richtige Bild anzeigen
     */
    if (this.imageToStructuralElement) {
        identifyImage(imageNr - this.imageNumber);
    }
}

From source file:org.kuali.ole.select.document.service.impl.OleInvoiceServiceImpl.java

protected void updatePaymentTotalsOnPurchaseOrder(OleInvoiceDocument invoiceDocument) {
    LOG.debug("Inside updatePaymentTotalsOnPurchaseOrder");
    List<Integer> poList = new ArrayList();
    Integer invPoId = 0;
    for (OleInvoiceItem invoiceItem : (List<OleInvoiceItem>) invoiceDocument.getItems()) {
        if (!(poList.contains(invoiceItem.getPurchaseOrderIdentifier()))) {
            poList.add(invoiceItem.getPurchaseOrderIdentifier());
        }//from  w  w w .ja v  a  2s .com
    }
    for (OleInvoiceItem invoiceItem : (List<OleInvoiceItem>) invoiceDocument.getItems()) {
        for (Integer purchaseOrderId : poList) {
            if (invoiceItem.getItemType() != null && invoiceItem.getItemType().getItemTypeCode() != null
                    && StringUtils.equalsIgnoreCase(invoiceItem.getItemType().getItemTypeCode(),
                            PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)
                    && purchaseOrderId != null && invPoId != null && invPoId.compareTo(purchaseOrderId) != 0
                    && invoiceItem.getPurchaseOrderIdentifier().compareTo(purchaseOrderId) == '0') {
                PurchaseOrderDocument poDoc = invoiceDocument.getPurchaseOrderDocument(purchaseOrderId);
                OlePurchaseOrderItem poItem = (OlePurchaseOrderItem) poDoc
                        .getItemByLineNumber(invoiceItem.getItemLineNumber());

                if (ObjectUtils.isNotNull(poItem)) {

                    KualiDecimal poItemReceivedTotal = poItem.getOutstandingQuantity();

                    KualiDecimal itemQuantity = invoiceItem.getItemQuantity();

                    if (ObjectUtils.isNull(itemQuantity)) {
                        itemQuantity = KualiDecimal.ZERO;
                    }
                    if (ObjectUtils.isNull(poItemReceivedTotal)) {
                        poItemReceivedTotal = KualiDecimal.ZERO;
                    }
                    /* Modified for OLE - 2516
                      poItem.setItemQuantity(itemQuantity);
                    */
                    // poItem.setItemUnitPrice(invoiceItem.getItemUnitPrice());
                }
                purapService.saveDocumentNoValidation(poDoc);
            }
            invPoId = purchaseOrderId;
        }

    }
    LOG.debug("Leaving updatePaymentTotalsOnPurchaseOrder");
}

From source file:de.juwimm.cms.remote.EditionServiceSpringImpl.java

@Override
public void handleImportEdition(Integer siteId, Integer editionId, String editionFileName, Integer rootVcId,
        boolean useNewIds) throws Exception {
    this.editionCronService.logEditionStatusInfo(LiveserverDeployStatus.ImportStarted, editionId);
    mappingUnits = new Hashtable<Integer, Integer>();
    mappingUnitsReverse = new Hashtable<Integer, Integer>();
    mappingVDs = new Hashtable<Integer, Integer>();
    mappingVCs = new Hashtable<Integer, Integer>();
    mappingPics = new Hashtable<Integer, Integer>();
    mappingDocs = new Hashtable<Integer, Integer>();
    mappingAddresses = new Hashtable<Integer, Long>();
    mappingDepartments = new Hashtable<Integer, Long>();
    mappingPersons = new Hashtable<Integer, Long>();
    mappingTalktime = new Hashtable<Integer, Long>();
    startPageBackup = new Hashtable<String, Integer>();
    mappingRealmsSimplePw = new Hashtable<Integer, Integer>();
    mappingRealmsJdbc = new Hashtable<Integer, Integer>();
    mappingRealmsLdap = new Hashtable<Integer, Integer>();
    mappingRealmsJaas = new Hashtable<Integer, Integer>();
    loginPagesRealmsSimplePw = new Hashtable<Integer, Integer>();
    loginPagesRealmsJdbc = new Hashtable<Integer, Integer>();
    loginPagesRealmsLdap = new Hashtable<Integer, Integer>();
    loginPagesRealmsJaas = new Hashtable<Integer, Integer>();
    loginPagesRealm2vc = new Hashtable<Integer, Integer>();
    File preparsedXMLfile = null;
    EditionHbm edition = null;/* w ww. j  a va  2s . c om*/
    try {
        if (log.isInfoEnabled()) {
            if (rootVcId == null) {
                log.info("processFileImport for Site: " + siteId);
            } else {
                log.info("processFileImport for Site: " + siteId + " in the RootVCId: " + rootVcId);
            }
        }
        edition = getEditionHbmDao().load(editionId);
        UnitHbm rootUnit = null;
        Integer rootUnitId = null;
        ViewComponentHbm viewComponent = null;
        if (edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_PAGE) == 0
                || edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_UNIT) == 0) {
            try {
                log.info("try to load ViewComponent: " + rootVcId);
                viewComponent = getViewComponentHbmDao().load(rootVcId);
                rootUnit = viewComponent.getAssignedUnit();
                //               if (viewComponent.isRoot()) {
                //                  rootVcId = null;
                //                  // context.setRollbackOnly();
                //                  //                  throw new RuntimeException("You can't import an Unit-Deploy as Root-Unit at this moment");
                //               }
            } catch (Exception e) {
                if (log.isInfoEnabled())
                    log.info("The given rootVcId " + rootVcId + " does not belong to any viewcomponent");
            }
        }

        if (log.isInfoEnabled())
            log.info("Finished writing Edition to File, starting to import it as GZIP-InputStream...");
        preparsedXMLfile = File.createTempFile("edition_import_preparsed_", ".xml");
        Document doc = getDocumentFromFile(preparsedXMLfile, editionFileName);
        /*
         * DOMParser parser = new DOMParser(); parser.parse(domIn); org.w3c.dom.Document doc = parser.getDocument();
         */

        /*
         * #################################################################################### 
         * S T E P 0.5 create/update Site 
         * ####################################################################################
         */
        SiteHbm importSite = null;
        try {
            importSite = getSiteHbmDao().load(siteId);
        } catch (Exception e) {
            if (log.isDebugEnabled())
                log.debug("Could not find site with Id: " + siteId + " will create it now");
        }
        boolean siteIsNew = false;
        if (importSite == null) {
            importSite = SiteHbm.Factory.newInstance();
            siteIsNew = true;
            importSite.setSiteId(siteId);
        } else {
            if (log.isDebugEnabled())
                log.debug("Site with id: " + siteId + " found - updating it now");
        }
        Element node = (Element) XercesHelper.findNode(doc, "/edition/site");
        importSite.setName(getNValNotNull(node, "name"));
        importSite.setShortName(getNValNotNull(node, "shortName"));
        importSite.setConfigXML(getNValNotNull(node, "siteConfig"));
        importSite.setMandatorDir(getNValNotNull(node, "mandatorDir"));
        importSite.setCacheExpire(new Integer(getNVal(node, "cacheExpire")));
        importSite.setWysiwygImageUrl(getNValNotNull(node, "wysiwygImageUrl"));
        importSite.setHelpUrl(getNValNotNull(node, "helpUrl"));
        importSite.setDcfUrl(getNValNotNull(node, "dcfUrl"));
        importSite.setPreviewUrlWorkServer(getNValNotNull(node, "previewUrlWorkServer"));
        importSite.setPreviewUrlLiveServer(getNValNotNull(node, "previewUrlLiveServer"));
        importSite.setPageNameFull(getNValNotNull(node, "pageNameFull"));
        importSite.setPageNameContent(getNValNotNull(node, "pageNameContent"));
        importSite.setPageNameSearch(getNValNotNull(node, "pageNameSearch"));
        importSite.setLastModifiedDate(new Long(getNVal(node, "lastModifiedDate")));

        String str = getNVal(node, "rootUnitId");
        Integer defaultViewDocumentId_import = null;
        Integer siteGroupId_import = null;
        if (str != null) {
            rootUnitId = Integer.decode(str);
        }
        str = getNVal(node, "defaultViewDocumentId");
        if (str != null) {
            defaultViewDocumentId_import = Integer.decode(str);
        }
        str = getNVal(node, "siteGroupId");
        if (str != null) {
            siteGroupId_import = new Integer(str);
        }
        if (siteIsNew) {
            getSiteHbmDao().create(importSite);
        }
        // set this site as active site for user 
        // in case the site was new it could not be done at login
        getUserHbmDao().load(AuthenticationHelper.getUserName()).setActiveSite(importSite);
        if (rootUnit != null) {
            // if provided a unit import, we will fillup the mapping for this unit
            Integer newUnitId = rootUnit.getUnitId();
            Element unitNode = (Element) XercesHelper.findNode(doc, "/edition/units/unit");
            Integer oldUnitId = new Integer(unitNode.getAttribute("id"));
            if (log.isDebugEnabled())
                log.debug("mapping for unit-import: OLD:" + oldUnitId + " NEW:" + newUnitId);
            mappingUnits.put(oldUnitId, newUnitId);
            mappingUnitsReverse.put(newUnitId, oldUnitId);
        }

        /*
         * #################################################################################### 
         * S T E P 1 Clean the complete Database
         * ####################################################################################
         */
        //TODO: on UnitDeploy delete just unit relevant stuff, for rootImport site stuff too
        this.editionCronService.logEditionStatusInfo(LiveserverDeployStatus.ImportCleanDatabase, editionId);
        if (log.isDebugEnabled())
            log.debug("Starting with STEP 1/6");

        if (edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_ROOT) == 0
                || edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_FULL) == 0) {
            Collection vdocs = getViewDocumentHbmDao().findAll(siteId);
            Iterator vdocsIt = vdocs.iterator();
            while (vdocsIt.hasNext()) {
                ViewDocumentHbm viewDocument = (ViewDocumentHbm) vdocsIt.next();
                if (log.isDebugEnabled())
                    log.debug("Found VDocument to remove: " + viewDocument.getLanguage() + " "
                            + viewDocument.getViewType());
                ViewComponentHbm rootViewComponent = viewDocument.getViewComponent();
                if (log.isDebugEnabled())
                    log.debug("Removing rootVC: " + rootViewComponent.getViewComponentId());
                getViewComponentHbmDao().remove(rootViewComponent);
                getViewDocumentHbmDao().remove(viewDocument);
                if (log.isDebugEnabled())
                    log.debug("Removing SUCC!");
            }
            Collection units = getUnitHbmDao().findAll(siteId);
            getUnitHbmDao().remove(units);
        }

        if (edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_UNIT) == 0
                || edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_FULL) == 0
                || edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_ROOT) == 0) {
            ViewComponentHbm rootViewComponent = getViewComponentHbmDao().find4Unit(edition.getUnitId(),
                    edition.getViewDocumentId());
            if (rootViewComponent != null) {
                Collection vComps = rootViewComponent.getChildren();
                while (vComps.iterator().hasNext()) {
                    ViewComponentHbm vc = (ViewComponentHbm) vComps.iterator().next();
                    if (vc.getAssignedUnit().equals(rootUnit)) {
                        Realm2viewComponentHbm r2vc = getRealm2viewComponentHbmDao()
                                .findByViewComponent(vc.getViewComponentId());
                        if (r2vc != null) {
                            if (r2vc.getJaasRealm() != null)
                                getRealmJaasHbmDao().remove(r2vc.getJaasRealm());
                            if (r2vc.getJdbcRealm() != null)
                                getRealmJdbcHbmDao().remove(r2vc.getJdbcRealm());
                            if (r2vc.getLdapRealm() != null)
                                getRealmLdapHbmDao().remove(r2vc.getLdapRealm());
                            if (r2vc.getSimplePwRealm() != null)
                                getRealmSimplePwHbmDao().remove(r2vc.getSimplePwRealm());
                        }
                    }
                    //vc.getChildren();
                }
                if (log.isDebugEnabled())
                    log.debug("Removing rootVC: " + rootViewComponent.getViewComponentId());
                //getViewComponentHbmDao().remove(rootViewComponent);
                if (log.isDebugEnabled())
                    log.debug("Removing SUCC!");
            } else {
                if (log.isDebugEnabled())
                    log.debug("RootVC: " + edition.getViewDocumentId() + " not found - first deploy?");

            }

        }

        if (edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_PAGE) == 0) {
            ViewComponentHbm vc = getViewComponentHbmDao().load(edition.getViewComponentId());
            Realm2viewComponentHbm r2vc = getRealm2viewComponentHbmDao()
                    .findByViewComponent(vc.getViewComponentId());
            if (r2vc != null) {
                if (r2vc.getJaasRealm() != null)
                    getRealmJaasHbmDao().remove(r2vc.getJaasRealm());
                if (r2vc.getJdbcRealm() != null)
                    getRealmJdbcHbmDao().remove(r2vc.getJdbcRealm());
                if (r2vc.getLdapRealm() != null)
                    getRealmLdapHbmDao().remove(r2vc.getLdapRealm());
                if (r2vc.getSimplePwRealm() != null)
                    getRealmSimplePwHbmDao().remove(r2vc.getSimplePwRealm());
            }

            if (log.isDebugEnabled())
                log.debug("Removing vC: " + vc.getViewComponentId());
            getViewComponentHbmDao().remove(vc);
            if (log.isDebugEnabled())
                log.debug("Removing SUCC!");
        }

        /*
         * #################################################################################### 
         * S T E P 2 Import Units WITHOUT IMAGEID, ViewDocuments WITHOUT rootVC, Hosts WITHOUT vcId
         * ####################################################################################
         */
        this.editionCronService.logEditionStatusInfo(LiveserverDeployStatus.ImportUnits, editionId);
        if (log.isDebugEnabled())
            log.debug("Starting with STEP 2/6");
        if (edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_FULL) == 0
                || edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_ROOT) == 0) {
            importUnitsAndViewDocumentsAndRealms(doc, siteId, useNewIds);
        } else {
            // perhaps protected pages should stay protected after an import?
            importRealms(doc, siteId, useNewIds);
        }
        /*
         * #################################################################################### 
         * S T E P 3 Import Pic / Docs, UPDATE Units
         * ####################################################################################
         */
        this.editionCronService.logEditionStatusInfo(LiveserverDeployStatus.ImportResources, editionId);
        if (log.isDebugEnabled())
            log.debug("Starting with STEP 3/6");
        importDocumentsAndPictures(doc, rootUnit, useNewIds, preparsedXMLfile);
        // pics and docs are in full, unit and root
        if (edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_PAGE) != 0) {
            Collection units = getUnitHbmDao().findAll(siteId);
            Iterator unitsIt = units.iterator();
            while (unitsIt.hasNext()) {
                UnitHbm unit = (UnitHbm) unitsIt.next();
                Integer newId = unit.getUnitId();
                if (edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_UNIT) == 0 && rootUnit != null
                        && newId.compareTo(rootUnit.getUnitId()) != 0)
                    continue;
                Element unitNode = null;
                if (useNewIds) {
                    unitNode = (Element) XercesHelper.findNode(doc,
                            "/edition/units/unit[@id='" + mappingUnitsReverse.get(newId) + "']");
                    if (log.isDebugEnabled())
                        log.debug("newId " + newId + " mappingUnitsReverse.get(newId)"
                                + mappingUnitsReverse.get(newId) + " unitNode " + unitNode);
                } else {
                    unitNode = (Element) XercesHelper.findNode(doc, "/edition/units/unit[@id='" + newId + "']");
                    if (log.isDebugEnabled())
                        log.debug("newId " + newId + " mappingUnitsReverse.get(newId)" + newId + " unitNode "
                                + unitNode);

                }
                String imageIdstr = unitNode.getAttribute("imageId");
                if (imageIdstr != null && !imageIdstr.equalsIgnoreCase("")
                        && !imageIdstr.equalsIgnoreCase("null")) {
                    Integer newImageId = new Integer(imageIdstr);
                    if (useNewIds) {
                        newImageId = mappingPics.get(newImageId);
                    }
                    unit.setImageId(newImageId);
                }
                String logoIdstr = unitNode.getAttribute("logoId");
                if (logoIdstr != null && !logoIdstr.equalsIgnoreCase("")
                        && !logoIdstr.equalsIgnoreCase("null")) {
                    Integer newLogoId = new Integer(logoIdstr);
                    if (useNewIds) {
                        newLogoId = mappingPics.get(newLogoId);
                    }
                    unit.setLogoId(newLogoId);
                }
            }
        }
        /*
         * #################################################################################### 
         * S T E P 3 U Import Database Components
         * ####################################################################################
         */
        this.editionCronService.logEditionStatusInfo(LiveserverDeployStatus.ImportDatabaseComponents,
                editionId);
        Iterator it = XercesHelper.findNodes(doc, "/edition/units/unit");
        while (it.hasNext()) {
            Element unitNode = (Element) it.next();
            Integer newUnitId = new Integer(unitNode.getAttribute("id"));
            if (useNewIds) {
                newUnitId = mappingUnits.get(newUnitId);
            }
            if (log.isDebugEnabled())
                log.debug("Import Database Components for UnitId: " + newUnitId + " (old was:"
                        + unitNode.getAttribute("id") + ")");
            UnitHbm unit = getUnitHbmDao().load(newUnitId);
            importDatabaseComponents(unitNode, unit, useNewIds);
        }
        /*
         * #################################################################################### 
         * S T E P 4+5 Import ViewComponents. DONT UPDATE InternalLink IDs Update ViewDocument rootVCIDs
         * ####################################################################################
         */
        this.editionCronService.logEditionStatusInfo(LiveserverDeployStatus.ImportViewComponents, editionId);
        if (log.isDebugEnabled())
            log.debug("Starting with STEP 4+5(6)/6");
        if (XercesHelper.findNode(doc, "/edition/viewcomponent") != null) {
            //if (edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_FULL) == 0) {
            if (viewComponent == null) {
                Iterator vcNodeIt = XercesHelper.findNodes(doc, "/edition/viewcomponent");
                while (vcNodeIt.hasNext()) {
                    Element vcNode = (Element) vcNodeIt.next();
                    String oldVcId = vcNode.getAttribute("id");
                    String oldVdId = null;
                    try {
                        oldVdId = ((Element) XercesHelper.findNode(doc,
                                "/edition/viewDocuments/viewDocument[@rootViewComponentId='" + oldVcId + "']"))
                                        .getAttribute("id");
                    } catch (Exception e) {
                        oldVdId = XercesHelper.getNodeValue(vcNode, "./viewDocumentId");
                        new Integer(oldVdId);
                        //                     Integer tempParent = Integer.decode(vcNode.getAttribute("parent"));
                        //                     oldVdId = getViewComponentHbmDao().load(tempParent).getViewDocument().getViewDocumentId().toString();
                    }
                    Integer newVdlId = new Integer(oldVdId);
                    if (useNewIds) {
                        newVdlId = mappingVDs.get(newVdlId);
                    }
                    if (log.isDebugEnabled())
                        log.debug("Importing one of the Root-ViewComponents with oldVcId:" + oldVcId
                                + " oldVdId:" + oldVdId + " newVdlId:" + newVdlId);
                    ViewDocumentHbm viewDocument = getViewDocumentHbmDao().load(newVdlId);
                    ViewComponentHbm parentVc = null;
                    ViewComponentHbm prevVc = null;
                    Integer id = null;

                    if ((id = getIntegerAttributeValue(vcNode, "parent")) != null) {
                        parentVc = getViewComponentHbmDao().load(id);
                    }
                    if ((id = getIntegerAttributeValue(vcNode, "prev")) != null) {
                        prevVc = getViewComponentHbmDao().load(id);
                    }

                    ViewComponentHbm rootViewComponent = createViewComponent(null, viewDocument, null, vcNode,
                            parentVc, prevVc, false, 1, useNewIds);

                    //getViewComponentHbmDao().remove(viewDocument.getViewComponent());
                    //viewDocument.setViewComponent(rootViewComponent);
                }
            } else {
                // Unit-Import or Unit-Deploy!
                {
                    // backing-up hosts with startpage
                    Collection hosts = getHostHbmDao().findAllWithStartPage4Site(siteId);
                    Iterator<HostHbm> hostIt = hosts.iterator();
                    while (hostIt.hasNext()) {
                        HostHbm currHost = hostIt.next();
                        this.startPageBackup.put(currHost.getHostName(),
                                currHost.getStartPage().getViewComponentId());
                    }
                }
                Element vcNode = (Element) XercesHelper.findNode(doc, "/edition/viewcomponent");

                ViewComponentHbm prev = null;
                ViewComponentHbm next = null;
                ViewComponentHbm parent = null;

                ViewDocumentHbm viewDocument = null;

                boolean wasFirstChild = false;
                // After removing we need this information to localize the ViewComponent to reimport
                prev = viewComponent.getPrevNode();
                next = viewComponent.getNextNode();
                parent = viewComponent.getParent();
                viewDocument = viewComponent.getViewDocument();

                if (parent != null && parent.getFirstChild().getViewComponentId()
                        .equals(viewComponent.getViewComponentId()))
                    wasFirstChild = true;
                // REMOVE
                if (log.isDebugEnabled()) {
                    log.debug("Removing ViewComponent for clean Import: " + viewComponent.getLinkDescription()
                            + " PREV" + viewComponent.getPrevNode() + " NEXT" + viewComponent.getNextNode()
                            + " PARENT" + viewComponent.getParent());
                }
                ViewComponentHbm temp, temp2;
                if (viewComponent.getPrevNode() == null && viewComponent.getNextNode() == null) {
                    viewComponent.getParent().setFirstChild(null);
                } else if (viewComponent.getPrevNode() == null) {
                    viewComponent.getParent().setFirstChild(viewComponent.getNextNode());
                    viewComponent.getNextNode().setPrevNode(null);
                } else if (viewComponent.getNextNode() != null) {
                    temp2 = viewComponent.getNextNode();
                    temp = viewComponent.getPrevNode();
                    temp2.setPrevNode(temp);
                    temp.setNextNode(viewComponent.getNextNode());
                } else {
                    viewComponent.getPrevNode().setNextNode(null);
                }
                if (log.isDebugEnabled())
                    log.debug("Trying to remove Unit-ViewComponent " + viewComponent.getViewComponentId());
                getViewComponentHbmDao().remove(viewComponent);
                if (log.isDebugEnabled())
                    log.debug("SUCC remove!");
                Integer myOldUnitId = new Integer(vcNode.getAttribute("unitId"));
                //FIXME useNewIds or not
                ViewComponentHbm rootview = createViewComponent(myOldUnitId, viewDocument, null, vcNode, parent,
                        prev, false, 2, useNewIds);
                if (log.isDebugEnabled())
                    log.debug("rootview " + rootview + " next " + next);
                // Linkname check begin
                try {
                    String linkname = rootview.getUrlLinkName();
                    rootview.setUrlLinkName(UUID.randomUUID().toString());
                    if (rootview.hasSiblingsWithLinkName(linkname)) {
                        int id = 0;
                        String tempText = "";
                        while (true) {
                            id++;
                            tempText = linkname + id;
                            if (!rootview.hasSiblingsWithLinkName(tempText)) {
                                rootview.setUrlLinkName(tempText);
                                break;
                            }
                        }
                    } else {
                        rootview.setUrlLinkName(linkname);
                    }
                } catch (Exception exe) {
                    log.error("Error occured", exe);
                }
                // Linkname check end
                rootview.setNextNode(next);
                if (next != null) {
                    next.setPrevNode(rootview);
                }
                rootview.setAssignedUnit(rootUnit);
                if (wasFirstChild) {
                    parent.setFirstChild(rootview);
                }
                if (log.isDebugEnabled())
                    log.debug("Starting with STEP 6/6 for Unit-Import");
                reparseViewComponent(rootview);
            }
        }
        /*
         * #################################################################################### 
         * S T E P 6 Reparse ViewComponents / Content for Internal Links, Pics, Docs Must be done in a second
         * 'while', because there could be Internal Links from other languages/viewtypes as well
         * 
         * Importing Hosts, there is no other dependency on them 
         * ####################################################################################
         */
        this.editionCronService.logEditionStatusInfo(LiveserverDeployStatus.ImportHosts, editionId);
        if (log.isDebugEnabled())
            log.debug("Starting with STEP 6/6");
        // hosts are only depoyed with full and root
        if (edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_FULL) == 0
                || edition.getDeployType().compareTo(Constants.DEPLOY_TYPE_ROOT) == 0) {
            Collection vdocs = getViewDocumentHbmDao().findAll(siteId);
            Iterator vdocsIt = vdocs.iterator();
            while (vdocsIt.hasNext()) {
                ViewDocumentHbm vdl = (ViewDocumentHbm) vdocsIt.next();
                reparseViewComponent(vdl.getViewComponent());
            }
            if (log.isDebugEnabled())
                log.debug("Root-Deploy, importing Hosts");
            importHosts(doc, siteId);
        } else {
            if (log.isDebugEnabled())
                log.debug("Unit-Import, restoring Hosts");
            {
                Enumeration<String> hosts = this.startPageBackup.keys();
                while (hosts.hasMoreElements()) {
                    try {
                        String hostName = hosts.nextElement();
                        Integer startPageId = this.startPageBackup.get(hostName);
                        HostHbm currHost = getHostHbmDao().load(hostName);
                        ViewComponentHbm currStartPage = getViewComponentHbmDao().load(startPageId);
                        currHost.setStartPage(currStartPage);
                    } catch (Exception e) {
                        log.warn("Error restoring startpage ", e);
                    }
                }
            }
        }
        this.restoreSafeguardLoginPages(true);
    } catch (Exception exe) {
        // context.setRollbackOnly();
        if (exe.getMessage() != null) {
            editionCronService.logEditionStatusException(editionId, exe.getMessage());
        } else {
            editionCronService.logEditionStatusException(editionId, exe.getClass().toString());
        }
        log.error("Error occured processFileImport", exe);
        throw exe;
    } finally {
        //         try {
        //            new File(editionFileName).delete();
        //         } catch (Exception exe) {
        //         }
        //         try {
        //            preparsedXMLfile.delete();
        //         } catch (Exception exe) {
        //         }
        System.gc();
    }
    this.editionCronService.logEditionStatusInfo(LiveserverDeployStatus.ImportSuccessful, editionId);
    if (log.isInfoEnabled())
        log.info("End processFileImport");
}

From source file:org.telegram.ui.ChatActivity.java

@Override
public void didSelectDialog(MessagesActivity activity, long did) {
    if (dialog_id != 0 && (forwaringMessage != null || !selectedMessagesIds.isEmpty())) {
        if (did != dialog_id) {
            int lower_part = (int) did;
            if (lower_part != 0) {
                ActionBarActivity inflaterActivity = parentActivity;
                if (inflaterActivity == null) {
                    inflaterActivity = (ActionBarActivity) getActivity();
                }//from  w ww.  jav  a  2  s . c  om
                activity.removeSelfFromStack();
                ChatActivity fragment = new ChatActivity();
                Bundle bundle = new Bundle();
                if (lower_part > 0) {
                    bundle.putInt("user_id", lower_part);
                    fragment.setArguments(bundle);
                    fragment.scrollToTopOnResume = true;
                    ActionBarActivity act = (ActionBarActivity) getActivity();
                    if (inflaterActivity != null) {
                        ((ApplicationActivity) inflaterActivity).presentFragment(fragment,
                                "chat" + Math.random(), false);
                    }
                } else if (lower_part < 0) {
                    bundle.putInt("chat_id", -lower_part);
                    fragment.setArguments(bundle);
                    fragment.scrollToTopOnResume = true;
                    if (inflaterActivity != null) {
                        ((ApplicationActivity) inflaterActivity).presentFragment(fragment,
                                "chat" + Math.random(), false);
                    }
                }
                removeSelfFromStack();
                if (forwaringMessage != null) {
                    if (forwaringMessage.messageOwner.id > 0) {
                        MessagesController.Instance.sendMessage(forwaringMessage, did);
                    }
                    forwaringMessage = null;
                } else {
                    ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesIds.keySet());
                    Collections.sort(ids);
                    for (Integer id : ids) {
                        if (id > 0) {
                            MessagesController.Instance.sendMessage(selectedMessagesIds.get(id), did);
                        }
                    }
                    selectedMessagesIds.clear();
                }
            } else {
                activity.finishFragment();
            }
        } else {
            activity.finishFragment();
            if (forwaringMessage != null) {
                MessagesController.Instance.sendMessage(forwaringMessage, did);
                forwaringMessage = null;
            } else {
                ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesIds.keySet());
                Collections.sort(ids, new Comparator<Integer>() {
                    @Override
                    public int compare(Integer lhs, Integer rhs) {
                        return lhs.compareTo(rhs);
                    }
                });
                for (Integer id : ids) {
                    MessagesController.Instance.sendMessage(selectedMessagesIds.get(id), did);
                }
                selectedMessagesIds.clear();
            }
            chatListView.setSelection(messages.size() + 1);
            scrollToTopOnResume = true;
        }
    }
}

From source file:de.sub.goobi.metadaten.Metadaten.java

/**
 * alle Seiten des aktuellen Strukturelements ermitteln.
 *///from  w  w  w . j a va  2  s .  c om
private void determinePagesStructure(DocStruct inStrukturelement) {
    if (inStrukturelement == null) {
        return;
    }
    List<Reference> listReferenzen = inStrukturelement.getAllReferences("to");
    int zaehler = 0;
    int imageNr = 0;
    if (listReferenzen != null) {
        /*
         * Referenzen sortieren
         */
        Collections.sort(listReferenzen, new Comparator<Reference>() {
            @Override
            public int compare(final Reference firstObject, final Reference secondObject) {
                final Reference firstReference = firstObject;
                final Reference secondReference = secondObject;
                Integer firstPage = 0;
                Integer secondPage = 0;

                MetadataType mdt = Metadaten.this.myPrefs.getMetadataTypeByName("physPageNumber");
                List<? extends Metadata> listMetadaten = firstReference.getTarget().getAllMetadataByType(mdt);
                if (listMetadaten != null && listMetadaten.size() > 0) {
                    Metadata meineSeite = listMetadaten.get(0);
                    firstPage = Integer.parseInt(meineSeite.getValue());
                }
                listMetadaten = secondReference.getTarget().getAllMetadataByType(mdt);
                if (listMetadaten != null && listMetadaten.size() > 0) {
                    Metadata meineSeite = listMetadaten.get(0);
                    secondPage = Integer.parseInt(meineSeite.getValue());
                }
                return firstPage.compareTo(secondPage);
            }
        });

        /* die Gre der Arrays festlegen */
        this.structSeiten = new SelectItem[listReferenzen.size()];
        this.structSeitenNeu = new MetadatumImpl[listReferenzen.size()];

        /* alle Referenzen durchlaufen und deren Metadaten ermitteln */
        for (Reference ref : listReferenzen) {
            DocStruct target = ref.getTarget();
            determineSecondPagesStructure(target, zaehler);
            if (imageNr == 0) {
                imageNr = determineThirdPagesStructure(target);
            }
            zaehler++;
        }

    }

    /*
     * Wenn eine Verknpfung zwischen Strukturelement und Bildern sein soll,
     * das richtige Bild anzeigen
     */
    if (this.imageToStructuralElement) {
        identifyImage(imageNr - this.imageNumber);
    }
}

From source file:ffsutils.TaskUtils.java

public static ArrayList<Tasks> TaskFile(Connection conn, String tranid, String diaryid, UserAccount userName)
        throws SQLException, FileNotFoundException, IOException {
    String tranid2;// w w w .j a  v  a 2s . c  o m
    Integer comp = 2;
    Integer tranlen = tranid.length();
    int retval = comp.compareTo(tranlen);
    if (retval > 0) {
        tranid2 = "0" + tranid;
    } else if (retval < 0) {
        tranid2 = tranid.substring(tranid.length() - 2);
    } else {
        tranid2 = tranid;
    }

    System.out.println("tranid2 " + tranid2 + " diaryid " + diaryid + " tranid " + tranid);

    String sql = "Select * from " + userName.getcompany() + ".taskimag" + tranid2
            + " where tranid = ? and taskid = ?";

    PreparedStatement pstm = conn.prepareStatement(sql);
    pstm.setString(1, diaryid);
    pstm.setString(2, tranid);

    ResultSet rs = pstm.executeQuery();
    ArrayList<Tasks> list = new ArrayList<Tasks>();
    if (rs.next()) {
        String thisFile = rs.getString("imagedesc") + rs.getString("imagetype");
        String filename = "C:/java-app/group1/ffsint3/ffsint2/build/web/resources/" + rs.getString("imagedesc")
                + rs.getString("imagetype");

        File file = new File(filename);

        FileOutputStream output = new FileOutputStream(file);
        InputStream input = rs.getBinaryStream("imag1");
        byte[] buffer = new byte[1024];
        while (input.read(buffer) > 0) {
            output.write(buffer);
        }

        Tasks tasks = new Tasks();
        tasks.setTaskfrom(thisFile);
        list.add(tasks);

    }
    return list;
}

From source file:ffsutils.TaskUtils.java

public static ArrayList<TaskImage> getTaskUpImag(Connection connconn, String tranid1, UserAccount userName,
        String Description, String filetype, FileItem thisfile) throws SQLException {

    String tranid2;/*w  w w .j  ava 2  s .  c om*/
    Integer comp = 2;
    Integer tranlen = tranid1.length();
    int retval = comp.compareTo(tranlen);
    if (retval > 0) {
        tranid2 = "0" + tranid1;
    } else if (retval < 0) {
        tranid2 = tranid1.substring(tranid1.length() - 2);
    } else {
        tranid2 = tranid1;
    }

    System.out.println(
            "getTaskUpImag " + userName + " size " + String.valueOf(thisfile.getSize()) + " " + tranid2);
    PreparedStatement pstm2 = null;
    FileInputStream fis;

    pstm2 = connconn.prepareStatement("insert into " + userName.getcompany() + ".taskimag" + tranid2
            + " (user, dateup,imagedesc, taskid, imagetype, imag1) values (?, current_timestamp, ? , '"
            + tranid1 + "' ,'" + filetype + "', ?)");
    //PreparedStatement pstm2 = connconn.prepareStatement(sql2);
    OutputStream inputstream = null;
    try {
        inputstream = thisfile.getOutputStream();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    pstm2.setString(1, userName.getUserName());
    pstm2.setString(2, Description);
    //pstm2.setBlob(3,inputstream);
    try {
        pstm2.setBinaryStream(3, thisfile.getInputStream(), (int) thisfile.getSize());
    } catch (IOException e) {
        e.printStackTrace();

    }
    // pstm2.setString(1, tranid1);

    Integer temp1 = pstm2.executeUpdate();

    String sql = "Select * from " + userName.getcompany() + ".taskimag" + tranid2 + " a where a.taskid =?";

    PreparedStatement pstm = connconn.prepareStatement(sql);
    pstm.setString(1, tranid1);

    ResultSet rs = pstm.executeQuery();
    ArrayList<TaskImage> list = new ArrayList<TaskImage>();
    while (rs.next()) {
        String Tranid = rs.getString("tranid");
        String User = rs.getString("user");
        String ImageDesc = rs.getString("imagedesc");
        String ImageType = rs.getString("imagetype");

        Date date = new Date();
        Calendar calendar = new GregorianCalendar();

        calendar.setTime(rs.getTimestamp("dateup"));
        String year = Integer.toString(calendar.get(Calendar.YEAR));
        String month = Integer.toString(calendar.get(Calendar.MONTH) + 1);
        String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
        String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
        String minute = Integer.toString(calendar.get(Calendar.MINUTE));
        int length = month.length();
        if (length == 1) {
            month = "0" + month;
        }
        int length2 = day.length();
        if (length2 == 1) {
            day = "0" + day;
        }
        int length3 = hour.length();
        if (length3 == 1) {
            hour = "0" + hour;
        }
        int length4 = minute.length();
        if (length4 == 1) {
            minute = "0" + minute;
        }
        String thistime = year + "/" + month + "/" + day + " " + hour + ":" + minute;
        String DateUp = thistime;

        TaskImage taskimage = new TaskImage();
        taskimage.setTranid(Tranid);
        taskimage.setUser(User);
        taskimage.setImageDesc(ImageDesc);

        taskimage.setImageType(ImageType);
        taskimage.setDateUp(DateUp);

        list.add(taskimage);
    }
    return list;
}