Example usage for java.lang Long compareTo

List of usage examples for java.lang Long compareTo

Introduction

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

Prototype

public int compareTo(Long anotherLong) 

Source Link

Document

Compares two Long objects numerically.

Usage

From source file:org.finra.dm.dao.impl.S3DaoImpl.java

@Override
public void validateS3File(S3FileTransferRequestParamsDto params, Long fileSizeInBytes)
        throws RuntimeException {
    ObjectMetadata objectMetadata = getObjectMetadata(params);

    if (objectMetadata == null) {
        throw new ObjectNotFoundException(String.format("File not found at s3://%s/%s location.",
                params.getS3BucketName(), params.getS3KeyPrefix()));
    }/*w  ww .j  av a  2  s  .c  om*/

    Assert.isTrue(fileSizeInBytes == null || fileSizeInBytes.compareTo(objectMetadata.getContentLength()) == 0,
            String.format(
                    "Specified file size (%d bytes) does not match to the actual file size (%d bytes) reported by S3 for s3://%s/%s file.",
                    fileSizeInBytes, objectMetadata.getContentLength(), params.getS3BucketName(),
                    params.getS3KeyPrefix()));
}

From source file:mil.jpeojtrs.sca.util.AnyUtils.java

/**
 * Attempts to convert the string value to the appropriate Java type.
 * //  w  w  w  . ja  v a  2s  .  c o m
 * @param stringValue the string form of the value
 * @param type the string form of the TypeCode
 * @return A Java object of theString corresponding to the typecode
 */
private static Object primitiveConvertString(final String stringValue, final String type) {
    if (stringValue == null) {
        return null;
    }
    if ("string".equals(type)) {
        return stringValue;
    } else if ("wstring".equals(type)) {
        return stringValue;
    } else if ("boolean".equals(type)) {
        if ("true".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue)) {
            return Boolean.parseBoolean(stringValue);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid boolean value");
    } else if ("char".equals(type)) {
        switch (stringValue.length()) {
        case 1:
            return stringValue.charAt(0);
        case 0:
            return null;
        default:
            throw new IllegalArgumentException(stringValue + " is not a valid char value");
        }
    } else if ("wchar".equals(type)) {
        return stringValue.charAt(0);
    } else if ("double".equals(type)) {
        return Double.parseDouble(stringValue);
    } else if ("float".equals(type)) {
        return Float.parseFloat(stringValue);
    } else if ("short".equals(type)) {
        return Short.decode(stringValue);
    } else if ("long".equals(type)) {
        return Integer.decode(stringValue);
    } else if ("longlong".equals(type)) {
        return Long.decode(stringValue);
    } else if ("ulong".equals(type)) {
        final long MAX_UINT = 2L * Integer.MAX_VALUE + 1L;
        final Long retVal = Long.decode(stringValue);
        if (retVal < 0 || retVal > MAX_UINT) {
            throw new IllegalArgumentException(
                    "ulong value must be greater than '0' and less than " + MAX_UINT);
        }
        return retVal;
    } else if ("ushort".equals(type)) {
        final int MAX_USHORT = 2 * Short.MAX_VALUE + 1;
        final Integer retVal = Integer.decode(stringValue);
        if (retVal < 0 || retVal > MAX_USHORT) {
            throw new IllegalArgumentException(
                    "ushort value must be greater than '0' and less than " + MAX_USHORT);
        }
        return retVal;
    } else if ("ulonglong".equals(type)) {
        final BigInteger MAX_ULONG_LONG = BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2))
                .add(BigInteger.ONE);
        final BigInteger retVal = AnyUtils.bigIntegerDecode(stringValue);
        if (retVal.compareTo(BigInteger.ZERO) < 0 || retVal.compareTo(MAX_ULONG_LONG) > 0) {
            throw new IllegalArgumentException(
                    "ulonglong value must be greater than '0' and less than " + MAX_ULONG_LONG.toString());
        }
        return retVal;
    } else if ("objref".equals(type)) {
        if ("".equals(stringValue)) {
            return null;
        }
        final List<String> objrefPrefix = Arrays.asList("IOR:", "corbaname:", "corbaloc:");
        for (final String prefix : objrefPrefix) {
            if (stringValue.startsWith(prefix)) {
                return stringValue;
            }
        }
        throw new IllegalArgumentException(stringValue + " is not a valid objref value");
    } else if ("octet".equals(type)) {
        final short MIN_OCTET = 0;
        final short MAX_OCTET = 0xFF;
        final short val = Short.decode(stringValue);
        if (val <= MAX_OCTET && val >= MIN_OCTET) {
            return Short.valueOf(val);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid octet value");
    } else {
        throw new IllegalArgumentException("Unknown CORBA Type: " + type);
    }
}

From source file:org.kuali.kpme.tklm.leave.calendar.validation.LeaveCalendarValidationUtil.java

public static List<String> validateTimeParametersForLeaveEntry(EarnCode selectedEarnCode,
        CalendarEntry leaveCalEntry, String startDateS, String endDateS, String startTimeS, String endTimeS,
        String selectedAssignment, String leaveBlockId, String spanningWeeks) {
    /**/*from   w  ww .  j a va 2s  .c  o  m*/
     * Cannot pull this method up to super until validateOverlap is refactored.
     */
    List<String> errors = new ArrayList<String>();
    //earn code is validate through the span of the leave entry, could the earn code's record method change between then and the leave period end date?
    //Why not use endDateS to retrieve the earn code?

    errors.addAll(CalendarValidationUtil.validateDates(startDateS, endDateS));
    errors.addAll(CalendarValidationUtil.validateTimes(startTimeS, endTimeS));
    if (errors.size() > 0)
        return errors;

    Long startTime;
    Long endTime;

    startTime = TKUtils.convertDateStringToDateTimeWithoutZone(startDateS, startTimeS).getMillis();
    endTime = TKUtils.convertDateStringToDateTimeWithoutZone(endDateS, endTimeS).getMillis();

    errors.addAll(CalendarValidationUtil.validateInterval(leaveCalEntry, startTime, endTime));
    if (errors.size() > 0)
        return errors;

    if (startTimeS == null)
        errors.add("The start time is blank.");
    if (endTimeS == null)
        errors.add("The end time is blank.");
    if (startTime - endTime == 0)
        errors.add("Start time and end time cannot be equivalent");

    if (errors.size() > 0)
        return errors;

    DateTime startTemp = new DateTime(startTime);
    DateTime endTemp = new DateTime(endTime);

    if (errors.size() == 0) {
        Hours hrs = Hours.hoursBetween(startTemp, endTemp);
        if (hrs.getHours() >= 24)
            errors.add("One leaveblock cannot exceed 24 hours");
    }
    if (errors.size() > 0)
        return errors;

    //KPME-2010
    if (spanningWeeks != null && !StringUtils.equalsIgnoreCase(spanningWeeks, "y")) {
        errors.addAll(validateSpanningWeeks(startTemp, endTemp));
    }

    //Check that assignment is valid for both days
    AssignmentDescriptionKey assignKey = HrServiceLocator.getAssignmentService()
            .getAssignmentDescriptionKey(selectedAssignment);
    Assignment assign = HrServiceLocator.getAssignmentService().getAssignmentForTargetPrincipal(assignKey,
            startTemp.toLocalDate());

    if ((startTime.compareTo(endTime) > 0 || endTime.compareTo(startTime) < 0)) {
        errors.add("The time or date is not valid.");
    }
    if (errors.size() > 0)
        return errors;

    //              boolean isRegularEarnCode = StringUtils.equals(assign.getJob().getPayTypeObj().getRegEarnCode(),selectedEarnCode);
    boolean isRegularEarnCode = true;
    errors.addAll(validateOverlap(startTime, endTime, startDateS, endTimeS, startTemp, endTemp, leaveCalEntry,
            leaveBlockId, isRegularEarnCode, selectedEarnCode.getRecordMethod()));
    if (errors.size() > 0)
        return errors;
    return errors;
}

From source file:org.opendatakit.common.persistence.engine.gae.TaskLockImpl.java

/**
 * Returns the entity for the lock with the earliest in-the-future expiration
 * timestamp. Whatever lock holds that is considered the winner of the mutex.
 * //from  w  ww  .  ja  v  a2s  .c  o m
 * Returning null means there is no active lock.
 * 
 * @param formId
 * @param taskType
 * @return
 * @throws ODKTaskLockException
 */
private Entity queryForLock(String formId, ITaskLockType taskType) throws ODKTaskLockException {
    int readCount = 0;
    try {
        Key entityGroupKey = createTaskGroupKey(formId, taskType);
        Query query = new Query(KIND, entityGroupKey);
        query.setAncestor(entityGroupKey);
        query.setFilter(new Query.CompositeFilter(CompositeFilterOperator.AND,
                Arrays.<Filter>asList(
                        new Query.FilterPredicate(FORM_ID_PROPERTY, Query.FilterOperator.EQUAL, formId),
                        new Query.FilterPredicate(TASK_TYPE_PROPERTY, Query.FilterOperator.EQUAL,
                                taskType.getName()))));
        PreparedQuery pquery = ds.prepare(query);
        Iterable<Entity> entities = pquery.asIterable();
        // There may be expired locks in the database.
        // Skip over those and find the active lock.
        Entity active = null;
        for (Entity e : entities) {
            ++readCount;
            if (!isExpired(e)) {
                if (active != null) {
                    Long timestamp1 = getTimestamp(active);
                    Long timestamp2 = getTimestamp(e);

                    // can't tell who won if we are within the settle interval.
                    if (Math.abs(timestamp1 - timestamp2) < taskType.getMinSettleTime()) {
                        throw new ODKTaskLockException(MULTIPLE_RESULTS_ERROR);
                    }

                    // otherwise, whichever holder held the lock first wins
                    int cmp = timestamp1.compareTo(timestamp2);
                    if (cmp > 0) {
                        active = e;
                    }
                } else {
                    active = e;
                }
            }
        }
        return active;
    } catch (ODKTaskLockException e) {
        throw e;
    } catch (TooManyResultsException e) {
        throw new ODKTaskLockException(MULTIPLE_RESULTS_ERROR, e);
    } catch (IllegalStateException e) {
        throw new ODKTaskLockException(NO_TRANSACTION_ACTIVE, e);
    } catch (Exception e) { // may catch datastore issues?
        e.printStackTrace();
        throw new ODKTaskLockException(OTHER_ERROR, e);
    } finally {
        dam.recordQueryUsage(KIND, readCount);
    }

}

From source file:org.sakaiproject.lessonbuildertool.ccexport.SamigoExport.java

void outputQuestions(List<ItemDataIfc> itemList, String assessmentSeq, String assessmentTitle,
        ZipPrintStream out, PrintStream errStream, CCExport ccExport, CCExport.Resource resource, int version) {

    int seq = 1;/*w  ww  .  ja va 2s.  c  om*/

    // feedback:
    // item: Map<String, String> where keys are org.sakaiproject.tool.assessment.data.ifc.assessment.ItemFeedbackIfc.
    //  CORRECT_FEEDBACK = "Correct Feedback";
    //  INCORRECT_FEEDBACK = "InCorrect Feedback";
    //  GENERAL_FEEDBACK = "General Feedback";
    // but may be easiest to use item.getItemFeedback(type)
    //   or getCorrectItemFeedback, getInCorrectItemFeedback, getGeneralItemFeedback
    //  for individual answers,
    //  answer: Set, 
    //  org.sakaiproject.tool.assessment.data.ifc.assessment.AnswerFeedbackIfc.
    //  CORRECT_FEEDBACK = "Correct Feedback";
    //  INCORRECT_FEEDBACK = "InCorrect Feedback";
    //   GENERAL_FEEDBACK = "General Feedback";
    //  ANSWER_FEEDBACK = "answerfeedback";
    // matching has correct and/or incorrect for each answer
    // multiple choice has general feedback for each answer
    // answer_feedback doesn't seem to be used
    // probably easier to use answer.getAnswerFeedback(type)
    // or answer.getCorrectAnswerFeedback, getInCorrectAnswerFeedback, getGeneralAnswerFeedback, getTheAnswerFeedback

    for (ItemDataIfc item : itemList) {

        SectionDataIfc section = item.getSection();
        String itemId = null;
        String title = null;

        List<Feedback> feedbacks = new ArrayList<Feedback>();

        if (section != null) {
            itemId = item.getSection().getSequence() + "_" + item.getSequence();
            title = item.getSection().getSequence() + "." + item.getSequence();
        } else {
            itemId = assessmentSeq + "_" + seq;
            title = assessmentTitle + " " + (seq++);
        }

        Set<ItemTextIfc> texts = item.getItemTextSet();
        List<ItemTextIfc> textlist = new ArrayList<ItemTextIfc>();
        textlist.addAll(texts);

        // for FIB we have a textlist rather than just one text
        if (textlist.size() > 1) {
            Collections.sort(textlist, new Comparator() {
                public int compare(Object o1, Object o2) {
                    Long v1 = ((ItemTextIfc) o1).getSequence();
                    Long v2 = ((ItemTextIfc) o2).getSequence();
                    return v1.compareTo(v2);
                }
            });
        }

        Set<AnswerIfc> answers = null;
        if (textlist.size() > 0)
            answers = textlist.get(0).getAnswerSet();
        else
            answers = new HashSet<AnswerIfc>();
        List<AnswerIfc> answerlist = new ArrayList<AnswerIfc>();
        answerlist.addAll(answers);

        if (answerlist.size() > 1) {
            Collections.sort(answerlist, new Comparator() {
                public int compare(Object o1, Object o2) {
                    Long v1 = ((AnswerIfc) o1).getSequence();
                    Long v2 = ((AnswerIfc) o2).getSequence();
                    return v1.compareTo(v2);
                }
            });
        }

        String profile = "cc.multiple_choice.v0p1";
        Long type = item.getTypeId();
        boolean survey = false;

        if (type.equals(TypeIfc.MULTIPLE_CHOICE) || type.equals(TypeIfc.MULTIPLE_CHOICE_SURVEY)
                || type.equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION)) {
            if (type.equals(TypeIfc.MULTIPLE_CHOICE_SURVEY))
                survey = true;
            type = TypeIfc.MULTIPLE_CHOICE; // normalize it
            profile = "cc.multiple_choice.v0p1";
        } else if (type.equals(TypeIfc.MULTIPLE_CORRECT)) {
            profile = "cc.multiple_response.v0p1";
        } else if (type.equals(TypeIfc.TRUE_FALSE)) {
            profile = "cc.true_false.v0p1";
        } else if (type.equals(TypeIfc.ESSAY_QUESTION)) {
            profile = "cc.essay.v0p1";
        } else if (type.equals(TypeIfc.FILL_IN_BLANK) || type.equals(TypeIfc.FILL_IN_NUMERIC)) {
            String answerString = "";
            if (answerlist.size() > 0)
                answerString = answerlist.get(0).getText();
            // only limited pattern match is supported. It has to be just one alternative, and
            // it can only be a substring. I classify anything starting or ending in *, and with one
            // alternative as pattern match, otherwise FIB, and give error except for the one proper case
            if (answerString.indexOf("*") >= 0 && answerString.indexOf("|") < 0)
                profile = "cc.pattern_match.v0p1";
            else
                profile = "cc.fib.v0p1";
            type = TypeIfc.FILL_IN_BLANK; // normalize

        } else {
            errStream.println(messageLocator.getMessage("simplepage.exportcc-sam-undefinedtype")
                    .replace("{1}", title).replace("{2}", assessmentTitle));
            continue;
        }

        //ignore
        // MATCHING
        // FILE_UPLOAD:
        // AUDIO_RECORDING:
        // MATRIX_CHOICES_SURVEY:

        String cardinality = "Single";
        if (type.equals(TypeIfc.MULTIPLE_CORRECT) || type.equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION))
            cardinality = "Multiple";
        Set<Long> correctSet = new HashSet<Long>();
        String correctItem = "";

        // CC doesn't have survey questoins. We treat them as multiple correct single selection
        if (answerlist.size() > 0) {
            for (AnswerIfc answer : answerlist) {
                if (survey || answer.getIsCorrect() != null && answer.getIsCorrect()) {
                    if (type.equals(TypeIfc.TRUE_FALSE))
                        correctItem = answer.getText().toLowerCase();
                    else
                        correctItem = "QUE_" + itemId + "_" + answer.getSequence();
                    correctSet.add(answer.getSequence());
                }
            }
        }

        out.println("      <item ident=\"QUE_" + itemId + "\" title=\"" + StringEscapeUtils.escapeXml(title)
                + "\">");
        out.println("        <itemmetadata>");
        out.println("          <qtimetadata>");
        out.println("            <qtimetadatafield>");
        out.println("              <fieldlabel>cc_profile</fieldlabel>");
        out.println("              <fieldentry>" + profile + "</fieldentry>");
        out.println("            </qtimetadatafield>");
        if (type.equals(TypeIfc.ESSAY_QUESTION)) {
            out.println("            <qtimetadatafield>");
            out.println("              <fieldlabel>qmd_scoringpermitted</fieldlabel>");
            out.println("              <fieldentry>Yes</fieldentry>");
            out.println("            </qtimetadatafield>");
            out.println("            <qtimetadatafield>");
            out.println("              <fieldlabel>qmd_computerscored</fieldlabel>");
            out.println("              <fieldentry>No</fieldentry>");
            out.println("            </qtimetadatafield>");
        }
        out.println("          </qtimetadata>");
        out.println("        </itemmetadata>");

        out.println("        <presentation>");
        out.println("          <material>");
        String text = "";
        if (type.equals(TypeIfc.FILL_IN_BLANK) || type.equals(TypeIfc.FILL_IN_NUMERIC)) {
            // gettext replaces {} with ____. The problem is that some of the CC samples tests have
            // an actual ____ in the text. Thus it's best to work with the original {}.
            for (ItemTextIfc it : textlist) {
                text += "" + it.getText();
            }
            text = text.trim();
            // If there's more than one {} we'll get a weird result, but there's not a lot we can do about that.
            int index = 0;
            int blanks = 0;
            while (true) {
                index = text.indexOf("{}", index + 2);
                if (index >= 0)
                    blanks++;
                else
                    break;
            }

            if (blanks > 1) {
                errStream.println(messageLocator.getMessage("simplepage.exportcc-sam-too-many-blanks")
                        .replace("{1}", title).replace("{2}", assessmentTitle).replace("{3}", "" + blanks));
            }

            // now we have the whole string with {}. If the {} isn't at the end, replace
            // it with [____] so the student can see where the replacement actually is. The
            // CC subset won't allow the actual blank to be there.
            if (text.endsWith("{}"))
                text = text.substring(0, text.length() - 2);
            text = text.replaceAll("\\{\\}", "[____]");

        } else
            text = item.getText();

        out.println(
                "            <mattext texttype=\"text/html\">" + ccExport.fixup(text, resource) + "</mattext>");
        out.println("          </material>");

        if (type.equals(TypeIfc.MULTIPLE_CHOICE) || type.equals(TypeIfc.MULTIPLE_CORRECT)
                || type.equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || type.equals(TypeIfc.TRUE_FALSE)) {
            // mc has general for each item, correct and incorrect, survey has general

            out.println("          <response_lid ident=\"QUE_" + itemId + "_RL\" rcardinality=\"" + cardinality
                    + "\">");
            out.println("            <render_choice>");

            for (AnswerIfc answer : answerlist) {
                String answerId = "QUE_" + itemId + "_" + answer.getSequence();
                if (type.equals(TypeIfc.TRUE_FALSE))
                    answerId = answer.getText().toLowerCase();
                String atext = answer.getText();
                if (atext == null || atext.trim().equals(""))
                    continue;
                out.println("              <response_label ident=\"" + answerId + "\">");
                out.println("                <material>");
                out.println("                  <mattext texttype=\"text/html\">"
                        + ccExport.fixup(atext, resource) + "</mattext>");
                out.println("                </material>");
                out.println("              </response_label>");
            }

            out.println("            </render_choice>");
            out.println("          </response_lid>");
            out.println("        </presentation>");
            out.println("        <resprocessing>");
            out.println("          <outcomes>");
            out.println(
                    "            <decvar maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/>");
            out.println("          </outcomes>");

            if (item.getGeneralItemFeedback() != null) {
                out.println("          <respcondition continue=\"Yes\">");
                out.println("            <conditionvar><other/></conditionvar>");
                out.println(
                        "            <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\" />");
                out.println("          </respcondition>");
                Feedback feedback = new Feedback();
                feedback.id = "general_fb";
                feedback.text = item.getGeneralItemFeedback();
                feedbacks.add(feedback);
            }

            for (AnswerIfc answer : answerlist) {
                if (answer.getGeneralAnswerFeedback() != null) {
                    String atext = answer.getText();
                    if (atext == null || atext.trim().equals(""))
                        continue;

                    String answerId = "QUE_" + itemId + "_" + answer.getSequence();
                    if (type.equals(TypeIfc.TRUE_FALSE))
                        answerId = answer.getText().toLowerCase();
                    out.println("          <respcondition continue=\"Yes\">");
                    out.println("              <conditionvar>");
                    out.println("                <varequal respident=\"QUE_" + itemId + "_RL\">" + answerId
                            + "</varequal>");
                    out.println("              </conditionvar>");
                    out.println("              <displayfeedback feedbacktype=\"Response\" linkrefid=\""
                            + answerId + "_fb\" />");
                    out.println("          </respcondition>");
                    Feedback feedback = new Feedback();
                    feedback.id = answerId + "_fb";
                    feedback.text = answer.getGeneralAnswerFeedback();
                    feedbacks.add(feedback);
                }
            }

            out.println("          <respcondition continue=\"No\">");
            out.println("            <conditionvar>");
            if (type.equals(TypeIfc.MULTIPLE_CHOICE) || type.equals(TypeIfc.TRUE_FALSE)) {
                int remaining = -1; // default to allow all correct answers
                if (correctSet.size() > 1) {
                    if (version < CCExport.V12) {
                        errStream.println(messageLocator.getMessage("simplepage.exportcc-sam-mcss")
                                .replace("{1}", title).replace("{2}", assessmentTitle));
                        remaining = 1;
                    } else
                        out.println("              <or>");
                }
                for (AnswerIfc answer : answerlist) {
                    String answerId = "QUE_" + itemId + "_" + answer.getSequence();
                    if (type.equals(TypeIfc.TRUE_FALSE))
                        answerId = answer.getText().toLowerCase();
                    if (correctSet.contains(answer.getSequence()) && remaining != 0) {
                        out.println("              <varequal case=\"Yes\" respident=\"QUE_" + itemId + "_RL\">"
                                + answerId + "</varequal>");
                        remaining--;
                    }
                }
                if (correctSet.size() > 1 && remaining < 0)
                    out.println("              </or>");
            } else if (type.equals(TypeIfc.MULTIPLE_CORRECT)
                    || type.equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION)) {
                if (type.equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION))
                    errStream.println(messageLocator.getMessage("simplepage.exportcc-sam-mcss")
                            .replace("{1}", title).replace("{2}", assessmentTitle));
                out.println("              <and>");
                for (AnswerIfc answer : answerlist) {
                    String answerId = itemId + "_" + answer.getSequence();
                    String atext = answer.getText();
                    if (atext == null || atext.trim().equals(""))
                        continue;
                    if (correctSet.contains(answer.getSequence())) {
                        out.println("              <varequal case=\"Yes\" respident=\"QUE_" + itemId
                                + "_RL\">QUE_" + itemId + "_" + answer.getSequence() + "</varequal>");
                    } else {
                        out.println("              <not>");
                        out.println("                <varequal case=\"Yes\" respident=\"QUE_" + itemId
                                + "_RL\">QUE_" + itemId + "_" + answer.getSequence() + "</varequal>");
                        out.println("              </not>");
                    }
                }
                out.println("              </and>");
            }
            out.println("            </conditionvar>");
            out.println("            <setvar action=\"Set\" varname=\"SCORE\">100</setvar>");
            if (item.getCorrectItemFeedback() != null) {
                out.println(
                        "            <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/>");
                Feedback feedback = new Feedback();
                feedback.id = "correct_fb";
                feedback.text = item.getCorrectItemFeedback();
                feedbacks.add(feedback);
            }
            out.println("          </respcondition>");
            if (item.getInCorrectItemFeedback() != null) {
                out.println("         <respcondition>");
                out.println("           <conditionvar><other/></conditionvar>");
                out.println(
                        "           <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\" />");
                out.println("         </respcondition>");
                Feedback feedback = new Feedback();
                feedback.id = "general_incorrect_fb";
                feedback.text = item.getInCorrectItemFeedback();
                feedbacks.add(feedback);
            }
            out.println("        </resprocessing>");
        }

        if (type.equals(TypeIfc.FILL_IN_BLANK) || type.equals(TypeIfc.ESSAY_QUESTION)) {
            // FIB has correct or incorrect, essay has general

            out.println("          <response_str ident=\"QUE_" + itemId + "_RL\">");
            out.println("            <render_fib columns=\"30\" rows=\"1\"/>");
            out.println("          </response_str>");
            out.println("        </presentation>");

            if (type.equals(TypeIfc.FILL_IN_BLANK) && answerlist.size() > 0) {
                out.println("        <resprocessing>");
                out.println("          <outcomes>");
                out.println(
                        "            <decvar maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/>");
                out.println("          </outcomes>");

                if (item.getGeneralItemFeedback() != null) {
                    out.println("          <respcondition continue=\"Yes\">");
                    out.println("            <conditionvar><other/></conditionvar>");
                    out.println(
                            "            <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\" />");
                    out.println("          </respcondition>");
                    Feedback feedback = new Feedback();
                    feedback.id = "general_fb";
                    feedback.text = item.getGeneralItemFeedback();
                    feedbacks.add(feedback);
                }

                out.println("          <respcondition continue=\"No\">");
                out.println("            <conditionvar>");

                String answerId = "QUE_" + itemId + "_RL";
                String answerString = answerlist.get(0).getText();
                String[] answerArray = answerString.split("\\|");
                boolean toomanystars = false;
                if (answerString.indexOf("*") >= 0 && answerString.indexOf("|") >= 0) {
                    errStream.println(messageLocator.getMessage("simplepage.exportcc-sam-fib-too-many-star")
                            .replace("{1}", title).replace("{2}", assessmentTitle)
                            .replace("{3}", answerString));
                    toomanystars = true;
                }

                for (String answer : answerArray) {
                    boolean substr = false;
                    boolean hasStar = answer.indexOf("*") >= 0;
                    String orig = answer;

                    // this isn't a perfect test. Not much we can do with * in the middle of a string
                    // and just at the end or just at the beginning isn't a perfect match to this.
                    // if more than one alternative, don't treat as matching, since that format isn't legal

                    if (!toomanystars) {
                        if (answer.startsWith("*")) {
                            answer = answer.substring(1);
                            substr = true;
                        }
                        if (answer.endsWith("*")) {
                            answer = answer.substring(0, answer.length() - 1);
                            substr = true;
                        }
                    }

                    if (hasStar) {
                        if (substr)
                            errStream.println(messageLocator.getMessage("simplepage.exportcc-sam-fib-star")
                                    .replace("{1}", title).replace("{2}", assessmentTitle).replace("{3}", orig)
                                    .replace("{4}", answer));
                        else
                            errStream.println(messageLocator.getMessage("simplepage.exportcc-sam-fib-bad-star")
                                    .replace("{1}", title).replace("{2}", assessmentTitle)
                                    .replace("{3}", orig));
                    }

                    if (substr)
                        out.println("              <varsubstring case=\"No\" respident=\"" + answerId + "\">"
                                + StringEscapeUtils.escapeXml(answer) + "</varsubstring>");
                    else
                        out.println("              <varequal case=\"No\" respident=\"" + answerId + "\">"
                                + StringEscapeUtils.escapeXml(answer) + "</varequal>");
                }

                out.println("            </conditionvar>");
                out.println("            <setvar action=\"Set\" varname=\"SCORE\">100</setvar>");
                if (item.getCorrectItemFeedback() != null) {
                    out.println(
                            "            <displayfeedback feedbacktype=\"Response\" linkrefid=\"correct_fb\"/>");
                    Feedback feedback = new Feedback();
                    feedback.id = "correct_fb";
                    feedback.text = item.getCorrectItemFeedback();
                    feedbacks.add(feedback);
                }
                out.println("          </respcondition>");
                if (item.getInCorrectItemFeedback() != null) {
                    out.println("         <respcondition>");
                    out.println("           <conditionvar><other/></conditionvar>");
                    out.println(
                            "           <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_incorrect_fb\" />");
                    out.println("         </respcondition>");
                    Feedback feedback = new Feedback();
                    feedback.id = "general_incorrect_fb";
                    feedback.text = item.getInCorrectItemFeedback();
                    feedbacks.add(feedback);
                }
                out.println("        </resprocessing>");
            }
        }

        if (type.equals(TypeIfc.ESSAY_QUESTION)) {
            // essay has no resprocessing except if there is general feedback
            if (item.getGeneralItemFeedback() != null) {
                out.println("        <resprocessing>");
                out.println("          <outcomes>");
                out.println(
                        "            <decvar maxvalue=\"100\" minvalue=\"0\" varname=\"SCORE\" vartype=\"Decimal\"/>");
                out.println("          </outcomes>");
                out.println("          <respcondition continue=\"No\">");
                out.println("            <conditionvar><other/></conditionvar>");
                out.println(
                        "            <displayfeedback feedbacktype=\"Response\" linkrefid=\"general_fb\" />");
                out.println("          </respcondition>");
                out.println("        </resprocessing>");
                Feedback feedback = new Feedback();
                feedback.id = "general_fb";
                feedback.text = item.getGeneralItemFeedback();
                feedbacks.add(feedback);
            }
        }

        if (feedbacks.size() > 0) {
            for (Feedback feedback : feedbacks) {
                out.println("        <itemfeedback ident=\"" + feedback.id + "\">");
                out.println("          <material>");
                out.println("            <mattext texttype=\"text/html\">"
                        + ccExport.fixup(feedback.text, resource) + "</mattext>");
                out.println("          </material>");
                out.println("        </itemfeedback>");
            }
        }
        out.println("      </item>");
    }
}

From source file:org.sakaiproject.contentreview.impl.urkund.UrkundReviewServiceImpl.java

@Override
public String getIconUrlforScore(Long score, Long warnings) {

    String urlBase = "/sakai-contentreview-tool-urkund/images/";
    String suffix = ".gif";

    if (warnings > 0) {
        return urlBase + "w" + suffix;
    }//www . j  av  a  2 s  .  com

    if (score.equals((long) 0)) {
        return urlBase + "0" + suffix;
    } else if (score.compareTo(Long.valueOf(12)) < 0) {
        return urlBase + "1" + suffix;
    } else if (score.compareTo(Long.valueOf(25)) < 0) {
        return urlBase + "2" + suffix;
    } else if (score.compareTo(Long.valueOf(38)) < 0) {
        return urlBase + "3" + suffix;
    } else if (score.compareTo(Long.valueOf(50)) < 0) {
        return urlBase + "4" + suffix;
    } else if (score.compareTo(Long.valueOf(62)) < 0) {
        return urlBase + "5" + suffix;
    } else if (score.compareTo(Long.valueOf(75)) < 0) {
        return urlBase + "6" + suffix;
    } else if (score.compareTo(Long.valueOf(88)) < 0) {
        return urlBase + "7" + suffix;
    } else {
        return urlBase + "8" + suffix;
    }

}

From source file:org.apache.ranger.patch.PatchPersmissionModel_J10003.java

public void assignPermissionToExistingUsers() {
    int countUserPermissionUpdated = 0;
    Long userCount = daoManager.getXXPortalUser().getAllCount();
    List<XXPortalUser> xXPortalUsers = null;
    Long patchModeMaxLimit = Long.valueOf(500L);
    try {//from  ww  w. j a v a  2  s.co m
        if (userCount != null && userCount > 0) {
            List<String> loginIdList = readUserNamesFromFile(usersListFileName);
            if (!CollectionUtils.isEmpty(loginIdList)) {
                xXPortalUsers = new ArrayList<XXPortalUser>();
                XXPortalUser xXPortalUser = null;
                for (String loginId : loginIdList) {
                    try {
                        xXPortalUser = daoManager.getXXPortalUser().findByLoginId(loginId);
                        if (xXPortalUser != null) {
                            xXPortalUsers.add(xXPortalUser);
                        } else {
                            logger.info("User " + loginId + " doesn't exist!");
                        }
                    } catch (Exception ex) {
                    }
                }
                countUserPermissionUpdated = assignPermissions(xXPortalUsers);
                logger.info(
                        "Permissions assigned to " + countUserPermissionUpdated + " of " + loginIdList.size());
            } else if (userCount.compareTo(Long.valueOf(patchModeMaxLimit)) < 0 || grantAllUsers) {
                xXPortalUsers = daoManager.getXXPortalUser().findAllXPortalUser();
                if (!CollectionUtils.isEmpty(xXPortalUsers)) {
                    countUserPermissionUpdated = assignPermissions(xXPortalUsers);
                    logger.info("Permissions assigned to " + countUserPermissionUpdated + " of "
                            + xXPortalUsers.size());
                }
            } else {
                //if total no. of users are more than 500 then process ADMIN and KEY_ADMIN users only to avoid timeout
                xXPortalUsers = daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_SYS_ADMIN);
                if (!CollectionUtils.isEmpty(xXPortalUsers)) {
                    countUserPermissionUpdated = assignPermissions(xXPortalUsers);
                    logger.info("Permissions assigned to users having role:" + RangerConstants.ROLE_SYS_ADMIN
                            + ". Processed:" + countUserPermissionUpdated + " of total "
                            + xXPortalUsers.size());
                }
                xXPortalUsers = daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_KEY_ADMIN);
                if (!CollectionUtils.isEmpty(xXPortalUsers)) {
                    countUserPermissionUpdated = assignPermissions(xXPortalUsers);
                    logger.info("Permissions assigned to users having role:" + RangerConstants.ROLE_KEY_ADMIN
                            + ". Processed:" + countUserPermissionUpdated + " of total "
                            + xXPortalUsers.size());
                }
                logger.info(
                        "Please execute this patch separately with argument 'ALL' to assign permission to remaining users ");
                System.out.println(
                        "Please execute this patch separately with argument 'ALL' to assign module permissions to remaining users!!");
            }
        }
    } catch (Exception ex) {
    }
}

From source file:org.hyperic.hq.bizapp.server.session.EventsBossImpl.java

/**
 * Search recent alerts given a set of criteria
 * @param sessionID the session token//www  . j a v a2  s.  c om
 * @param count the maximum number of alerts to return
 * @param priority allowable values: 0 (all), 1, 2, or 3
 * @param timeRange the amount of time from current time to include
 * @param ids the IDs of resources to include or null for ALL
 * @return a list of {@link Escalatable}s
 * 
 */
@Transactional(readOnly = true)
public List<Escalatable> findRecentAlerts(int sessionID, int count, int priority, long timeRange,
        AppdefEntityID[] ids) throws SessionNotFoundException, SessionTimeoutException, PermissionException {
    AuthzSubject subject = sessionManager.getSubject(sessionID);
    long cur = System.currentTimeMillis();
    final boolean debug = log.isDebugEnabled();
    final StopWatch watch = new StopWatch();

    List<AppdefEntityID> appentResources = ids != null ? appentResources = Arrays.asList(ids) : null;

    // Assume if user can be alerted, then they can view resource,
    // otherwise, it'll be filtered out later anyways
    if (debug)
        watch.markTimeBegin("findEscalatables");
    List<Escalatable> alerts = alertManager.findEscalatables(subject, count, priority, timeRange, cur,
            appentResources);
    if (debug)
        watch.markTimeEnd("findEscalatables");

    // CheckAlertingScope now only used for galerts
    if (ids == null) {
        // find ALL alertable resources
        if (debug)
            watch.markTimeBegin("checkAlertingScope");
        appentResources = permissionManager.checkAlertingScope(subject);
        if (debug)
            watch.markTimeEnd("checkAlertingScope");
    }

    if (debug)
        watch.markTimeBegin("galertManager.findEscalatables");
    List<Escalatable> galerts = galertManager.findEscalatables(subject, count, priority, timeRange, cur,
            appentResources);
    if (debug)
        watch.markTimeEnd("galertManager.findEscalatables");
    alerts.addAll(galerts);

    Collections.sort(alerts, new Comparator<Escalatable>() {
        public int compare(Escalatable o1, Escalatable o2) {
            if (o1 == o2) {
                return 0;
            }
            Long l1 = o1.getAlertInfo().getTimestamp();
            Long l2 = o2.getAlertInfo().getTimestamp();
            // Reverse sort
            return l2.compareTo(l1);
        }
    });

    Set<AppdefEntityID> goodIds = new HashSet<AppdefEntityID>();
    Set<AppdefEntityID> badIds = new HashSet<AppdefEntityID>();

    List<Escalatable> res = new ArrayList<Escalatable>();
    if (debug)
        watch.markTimeBegin("loop");
    for (Iterator<Escalatable> i = alerts.iterator(); i.hasNext() && res.size() < count;) {
        Escalatable alert = i.next();
        PerformsEscalations def = alert.getDefinition();
        AlertDefinitionInterface defInfo = def.getDefinitionInfo();
        AppdefEntityID aeid;

        aeid = AppdefUtil.newAppdefEntityId(defInfo.getResource());

        if (badIds.contains(aeid))
            continue;

        // Check to see if we already have the resource in the hash map
        if (!goodIds.contains(aeid)) {
            AppdefEntityValue entVal = new AppdefEntityValue(aeid, subject);

            try {
                entVal.getName();
                goodIds.add(aeid);
            } catch (Exception e) {
                // Probably because the resource does not exist
                badIds.add(aeid);
                continue;
            }
        }

        res.add(alert);
    }
    if (debug)
        watch.markTimeEnd("loop");
    if (debug)
        log.debug(watch);

    return res;
}

From source file:org.openbravo.client.myob.MyOpenbravoActionHandler.java

private void processWidgets(String strEventType, boolean isAdminMode, OBError message, JSONArray widgets,
        String availableAtLevel, String[] availableAtLevelValue) throws JSONException, OBException {
    log.debug(">> processing widgets");
    boolean hasRemovedInstances = false, hasAddedInstances = false, hasModifiedInstances = false;
    Role role = OBDal.getInstance().get(Role.class, OBContext.getOBContext().getRole().getId());
    User user = OBDal.getInstance().get(User.class, OBContext.getOBContext().getUser().getId());

    // Currently only 2 columns are supported, increase the array length if more columns are
    // supported.
    Long[] maxOpenbravoTypeInstanceRow = { 0L, 0L };
    Long[] minNotOpenbravoTypeInstanceRow = { null, null };

    List<WidgetInstance> currentWidgetInstances = Collections.emptyList();
    if (isAdminMode) {
        currentWidgetInstances = MyOBUtils.getDefaultWidgetInstances(availableAtLevel, availableAtLevelValue);
    } else {/*  w  w w .j a v  a 2s.  c  o  m*/
        currentWidgetInstances = MyOBUtils.getUserWidgetInstances();
    }
    for (int i = 0; i < widgets.length(); i++) {
        JSONObject widget = (JSONObject) widgets.get(i);
        final String newWidgetInstanceId = widget.getString("dbInstanceId");
        final Long newColNum = widget.getLong("colNum");
        final Long newRowNum = widget.getLong("rowNum");
        boolean isOpenbravoTypeInstance = false;
        log.debug(">> process widget id: " + newWidgetInstanceId + " colNum: " + newColNum + " rowNum: "
                + newRowNum);
        if (StringUtils.isNotEmpty(newWidgetInstanceId)) {
            WidgetInstance retrievedWidgetInstance = OBDal.getInstance().get(WidgetInstance.class,
                    newWidgetInstanceId);
            log.debug(">> existing widget, colNum: " + retrievedWidgetInstance.getColumnPosition() + " rowNum: "
                    + retrievedWidgetInstance.getSequenceInColumn());
            isOpenbravoTypeInstance = (retrievedWidgetInstance.getRelativePriority() != null
                    && retrievedWidgetInstance.getRelativePriority().compareTo(0L) == 0);

            currentWidgetInstances.remove(retrievedWidgetInstance);
            // Widget modified, check for colNum and rowNum changes.
            if (newColNum.compareTo(retrievedWidgetInstance.getColumnPosition()) != 0) {
                retrievedWidgetInstance.setColumnPosition(widget.getLong("colNum"));
                OBDal.getInstance().save(retrievedWidgetInstance);
                hasModifiedInstances = true;
            }
            if (newRowNum.compareTo(retrievedWidgetInstance.getSequenceInColumn()) != 0) {
                retrievedWidgetInstance.setSequenceInColumn(widget.getLong("rowNum"));
                OBDal.getInstance().save(retrievedWidgetInstance);
                hasModifiedInstances = true;
            }
        } else {
            // Added widget, create a new widget
            WidgetInstance newWidgetInstance = OBProvider.getInstance().get(WidgetInstance.class);
            newWidgetInstance.setColumnPosition(newColNum);
            newWidgetInstance.setSequenceInColumn(newRowNum);
            newWidgetInstance.setWidgetClass(
                    OBDal.getInstance().get(WidgetClass.class, widget.getString("widgetClassId")));
            if (!isAdminMode) {
                newWidgetInstance.setOrganization(OBDal.getInstance().get(Organization.class, "0"));
                newWidgetInstance.setVisibleAtRole(role);
                newWidgetInstance.setVisibleAtUser(user);
                newWidgetInstance.setRelativePriority(6L);
            } else if (availableAtLevel.equals("SYSTEM")) {
                newWidgetInstance.setRelativePriority(1L);
            } else if (availableAtLevel.equals("CLIENT")) {
                newWidgetInstance.setRelativePriority(2L);
                newWidgetInstance.setClient(OBDal.getInstance().get(Client.class, availableAtLevelValue[0]));
                newWidgetInstance.setOrganization(OBDal.getInstance().get(Organization.class, "0"));
            } else if (availableAtLevel.equals("ORG")) {
                newWidgetInstance.setRelativePriority(3L);
                newWidgetInstance
                        .setOrganization(OBDal.getInstance().get(Organization.class, availableAtLevelValue[0]));
            } else if (availableAtLevel.equals("ROLE")) {
                newWidgetInstance.setRelativePriority(4L);
                newWidgetInstance.setOrganization(OBDal.getInstance().get(Organization.class, "0"));
                newWidgetInstance
                        .setVisibleAtRole(OBDal.getInstance().get(Role.class, availableAtLevelValue[0]));
            }
            OBDal.getInstance().save(newWidgetInstance);
            widget.put("dbInstanceId", newWidgetInstance.getId());
            log.debug(">> new widget added: " + newWidgetInstance.getId());
            hasAddedInstances = true;

            // Process parameter values
            processParameters(newWidgetInstance);
        }
        if (isOpenbravoTypeInstance && maxOpenbravoTypeInstanceRow[newColNum.intValue()] < newRowNum) {
            maxOpenbravoTypeInstanceRow[newColNum.intValue()] = newRowNum;
        } else if (!isOpenbravoTypeInstance && minNotOpenbravoTypeInstanceRow[newColNum.intValue()] != null
                && minNotOpenbravoTypeInstanceRow[newColNum.intValue()] > newRowNum) {
            minNotOpenbravoTypeInstanceRow[newColNum.intValue()] = newRowNum;
        } else if (!isOpenbravoTypeInstance && minNotOpenbravoTypeInstanceRow[newColNum.intValue()] == null) {
            minNotOpenbravoTypeInstanceRow[newColNum.intValue()] = newRowNum;
        }
    }

    // Check Openbravo type instances remain on top, only for community instances.
    if (!ActivationKey.getInstance().isOPSInstance()) {
        for (int i = 0; i < minNotOpenbravoTypeInstanceRow.length; i++) {
            if (minNotOpenbravoTypeInstanceRow[i] != null
                    && minNotOpenbravoTypeInstanceRow[i] < maxOpenbravoTypeInstanceRow[i]) {
                throw new OBException("@OBKMO_OpenbravoTypeInstanceMustOnTop@");
            }
        }
    }

    if (!currentWidgetInstances.isEmpty()) {
        // Removed widget instance to delete.
        for (WidgetInstance widgetInstance : currentWidgetInstances) {
            log.debug(">> removed widget instance: " + widgetInstance.getId());
            if (widgetInstance.getCopiedFrom() != null) {
                widgetInstance.setActive(Boolean.FALSE);
                OBDal.getInstance().save(widgetInstance);
            } else {
                // Remove all instances of the widget instance that is to be removed
                OBQuery<WidgetInstance> widgetInstanceQuery = OBDal.getInstance()
                        .createQuery(WidgetInstance.class, "copiedFrom='" + widgetInstance.getId() + "'");
                widgetInstanceQuery.setFilterOnActive(false);
                for (WidgetInstance copiedWidgetInstance : widgetInstanceQuery.list()) {
                    OBDal.getInstance().remove(copiedWidgetInstance);
                }
                OBDal.getInstance().remove(widgetInstance);
            }
        }
        hasRemovedInstances = true;
    }
    if (hasRemovedInstances || hasAddedInstances || hasModifiedInstances) {
        OBDal.getInstance().flush();
    }
    if (strEventType.equals(WIDGET_ADDED) && !hasAddedInstances) {
        message.setType("Warning");
        message.setMessage("@OBKMO_NoWidgetsAdded@");
    } else if (strEventType.equals(WIDGET_REMOVED) && !hasRemovedInstances) {
        message.setType("Warning");
        message.setMessage("@OBKMO_NoWidgetsRemoved@");
    } else if (strEventType.equals(WIDGET_MOVED) && !hasModifiedInstances) {
        message.setType("Info");
        message.setMessage("@OBKMO_NoWidgetsMoved@");
    }
}

From source file:org.sakaiproject.contentreview.compilatio.CompilatioReviewServiceImpl.java

@Override
public String getIconUrlforScore(Long score) {
    String urlBase = "/library/content-review/score_";
    String suffix = ".gif";

    //TODO : check this (compilatio original)
    /*if (score.compareTo(Long.valueOf(5)) <= 0) {
       return urlBase + "green" + suffix;
    } else if (score.compareTo(Long.valueOf(20)) <= 0) {
       return urlBase + "orange" + suffix;
    } else {//from w w w. j  av a 2s.c  om
       return urlBase + "red" + suffix;
    }*/

    //TODO : check this (turnitin)
    if (score.equals(Long.valueOf(0))) {
        return urlBase + "blue" + suffix;
    } else if (score.compareTo(Long.valueOf(25)) < 0) {
        return urlBase + "green" + suffix;
    } else if (score.compareTo(Long.valueOf(50)) < 0) {
        return urlBase + "yellow" + suffix;
    } else if (score.compareTo(Long.valueOf(75)) < 0) {
        return urlBase + "orange" + suffix;
    } else {
        return urlBase + "red" + suffix;
    }
}