Example usage for java.lang Float floatValue

List of usage examples for java.lang Float floatValue

Introduction

In this page you can find the example usage for java.lang Float floatValue.

Prototype

@HotSpotIntrinsicCandidate
public float floatValue() 

Source Link

Document

Returns the float value of this Float object.

Usage

From source file:net.sf.fspdfs.chartthemes.simple.SimpleChartTheme.java

protected void setPlotBackground(Plot plot, JRChartPlot jrPlot) {
    PlotSettings plotSettings = getPlotSettings();
    Paint backgroundPaint = jrPlot.getOwnBackcolor();
    if (backgroundPaint == null && plotSettings.getBackgroundPaint() != null) {
        backgroundPaint = plotSettings.getBackgroundPaint().getPaint();
    }//from   w  w w.j av  a2s. co  m
    if (backgroundPaint == null) {
        backgroundPaint = ChartThemesConstants.TRANSPARENT_PAINT;
    }
    plot.setBackgroundPaint(backgroundPaint);

    Float backgroundAlpha = jrPlot.getBackgroundAlphaFloat();
    if (backgroundAlpha == null) {
        backgroundAlpha = plotSettings.getBackgroundAlpha();
    }
    if (backgroundAlpha != null)
        plot.setBackgroundAlpha(backgroundAlpha.floatValue());

    Float foregroundAlpha = jrPlot.getForegroundAlphaFloat();
    if (foregroundAlpha == null) {
        foregroundAlpha = plotSettings.getForegroundAlpha();
    }
    if (foregroundAlpha != null)
        plot.setForegroundAlpha(foregroundAlpha.floatValue());

    Image backgroundImage = plotSettings.getBackgroundImage() == null ? null
            : plotSettings.getBackgroundImage().getImage();
    if (backgroundImage != null) {
        plot.setBackgroundImage(backgroundImage);
        Integer backgroundImageAlignment = plotSettings.getBackgroundImageAlignment();
        if (backgroundImageAlignment != null) {
            plot.setBackgroundImageAlignment(backgroundImageAlignment.intValue());
        }
        Float backgroundImageAlpha = plotSettings.getBackgroundImageAlpha();
        if (backgroundImageAlpha != null) {
            plot.setBackgroundImageAlpha(backgroundImageAlpha.floatValue());
        }
    }
}

From source file:net.sf.fspdfs.chartthemes.spring.GenericChartTheme.java

protected void setChartBackgroundImage(JFreeChart jfreeChart, Image defaultBackgroundImage,
        Integer defaultBackgroundImageAlignment, Float defaultBackgroundImageAlpha)

{

    if (defaultBackgroundImage != null) {
        jfreeChart.setBackgroundImage(defaultBackgroundImage);
        if (defaultBackgroundImageAlignment != null) {
            jfreeChart.setBackgroundImageAlignment(defaultBackgroundImageAlignment.intValue());
        }//from ww  w . java  2s  .  com
        if (defaultBackgroundImageAlpha != null) {
            jfreeChart.setBackgroundImageAlpha(defaultBackgroundImageAlpha.floatValue());
        }
    }
}

From source file:net.sf.fspdfs.chartthemes.simple.SimpleChartTheme.java

protected void setChartBackgroundImage(JFreeChart jfreeChart) {
    ChartSettings chartSettings = getChartSettings();
    Image backgroundImage = chartSettings.getBackgroundImage() == null ? null
            : chartSettings.getBackgroundImage().getImage();
    if (backgroundImage != null) {
        jfreeChart.setBackgroundImage(backgroundImage);

        Integer backgroundImageAlignment = chartSettings.getBackgroundImageAlignment();
        if (backgroundImageAlignment != null) {
            jfreeChart.setBackgroundImageAlignment(backgroundImageAlignment.intValue());
        }//from  ww  w . j  a  v  a  2 s  .  c  o m
        Float backgroundImageAlpha = chartSettings.getBackgroundImageAlpha();
        //         if(getChart().getOwnMode() != null && getChart().getOwnMode().byteValue() == ModeEnum.TRANSPARENT)
        //         {
        //            backgroundImageAlpha = new Float(0);
        //         }
        if (backgroundImageAlpha != null) {
            jfreeChart.setBackgroundImageAlpha(backgroundImageAlpha.floatValue());
        }
    }
}

From source file:org.etudes.jforum.view.admin.ForumAction.java

public void editSave() throws Exception {
    boolean isfacilitator = JForumUserUtil.isJForumFacilitator(UserDirectoryService.getCurrentUser().getId())
            || SecurityService.isSuperUser();

    if (!isfacilitator) {
        this.context.put("message", I18n.getMessage("User.NotAuthorizedToManage"));
        this.setTemplateName(TemplateKeys.MANAGE_NOT_AUTHORIZED);
        return;/* w ww  . ja  v  a2 s .  c o m*/
    }

    JForumForumService jforumForumService = (JForumForumService) ComponentManager
            .get("org.etudes.api.app.jforum.JForumForumService");
    org.etudes.api.app.jforum.Forum forum = jforumForumService
            .getForum(this.request.getIntParameter("forum_id"));

    forum.setDescription(SafeHtml.escapeJavascript(this.request.getParameter("description")));
    forum.setCategoryId(this.request.getIntParameter("categories_id"));
    forum.setName(SafeHtml.escapeJavascript(this.request.getParameter("forum_name")));
    //forum.setType(Integer.parseInt(this.request.getParameter("forum_type")));
    //forum.setAccessType(Integer.parseInt(this.request.getParameter("access_type")));
    forum.setModifiedBySakaiUserId(UserDirectoryService.getCurrentUser().getId());
    String startDateParam = this.request.getParameter("start_date");

    // dates
    if (startDateParam != null && startDateParam.trim().length() > 0) {
        Date startDate;
        try {
            startDate = DateUtil.getDateFromString(startDateParam.trim());
        } catch (ParseException e) {
            this.context.put("errorMessage", I18n.getMessage("Forums.Forum.DateParseError"));
            this.edit();
            return;
        }
        forum.getAccessDates().setOpenDate(startDate);

        String hideUntilOpen = this.request.getParameter("hide_until_open");
        if (hideUntilOpen != null && "1".equals(hideUntilOpen)) {
            forum.getAccessDates().setHideUntilOpen(Boolean.TRUE);
        } else {
            forum.getAccessDates().setHideUntilOpen(Boolean.FALSE);
        }
    } else {
        forum.getAccessDates().setOpenDate(null);
        forum.getAccessDates().setHideUntilOpen(Boolean.FALSE);
    }

    // due date
    String endDateParam = this.request.getParameter("end_date");
    if (endDateParam != null && endDateParam.trim().length() > 0) {
        Date endDate;
        try {
            endDate = DateUtil.getDateFromString(endDateParam.trim());
        } catch (ParseException e) {
            this.context.put("errorMessage", I18n.getMessage("Forums.Forum.DateParseError"));
            this.edit();
            return;
        }
        forum.getAccessDates().setDueDate(endDate);

        /*String lockForum = this.request.getParameter("lock_forum");
        if (lockForum != null && "1".equals(lockForum))
        {
           forum.getAccessDates().setLocked(Boolean.TRUE);
        }
        else
        {
           forum.getAccessDates().setLocked(Boolean.FALSE);
        }*/
    } else {
        forum.getAccessDates().setDueDate(null);
        //forum.getAccessDates().setLocked(Boolean.FALSE);
    }

    // allow until
    String allowUntilDateParam = this.request.getParameter("allow_until_date");
    if (allowUntilDateParam != null && allowUntilDateParam.trim().length() > 0) {
        Date allowUntilDate;
        try {
            allowUntilDate = DateUtil.getDateFromString(allowUntilDateParam.trim());
        } catch (ParseException e) {
            this.context.put("errorMessage", I18n.getMessage("Forums.Forum.DateParseError"));
            this.edit();
            return;
        }
        forum.getAccessDates().setAllowUntilDate(allowUntilDate);
    } else {
        forum.getAccessDates().setAllowUntilDate(null);
    }

    // type - noraml, reply only, read only
    forum.setType(Integer.parseInt(this.request.getParameter("forum_type")));

    // access type - all site participants, deny access, selected groups
    forum.setAccessType(Integer.parseInt(this.request.getParameter("access_type")));
    if (forum.getAccessType() == org.etudes.api.app.jforum.Forum.ForumAccess.GROUPS.getAccessType()) {
        String selectedGroups[] = (String[]) this.request.getParameterValues("selectedGroups");
        if (logger.isDebugEnabled())
            logger.debug("selectedGroups[] " + selectedGroups);

        List selectedGroupsList = new ArrayList();

        if (selectedGroups != null && selectedGroups.length > 0) {
            for (int i = 0; i < selectedGroups.length; i++)
                selectedGroupsList.add(selectedGroups[i]);
        }
        forum.setGroups(selectedGroupsList);
    }

    if (this.request.getParameter("grading_enabled") != null
            && Integer.parseInt(this.request.getParameter("grading_enabled")) == 1) {
        forum.setGradeType(Integer.parseInt(this.request.getParameter("grading_type")));

        if (forum.getGradeType() == org.etudes.api.app.jforum.Grade.GradeType.FORUM.getType()) {
            // grade
            org.etudes.api.app.jforum.Grade grade = forum.getGrade();
            if (grade == null) {
                grade = jforumForumService.newGrade(forum);
            }

            try {
                Float points = Float.parseFloat(this.request.getParameter("points"));

                if (points.floatValue() < 0)
                    points = Float.valueOf(0.0f);
                if (points.floatValue() > 1000)
                    points = Float.valueOf(10000.0f);
                points = Float.valueOf(((float) Math.round(points.floatValue() * 100.0f)) / 100.0f);

                grade.setPoints(points);
            } catch (NumberFormatException ne) {
                grade.setPoints(0f);
            }

            String minPostsRequired = this.request.getParameter("min_posts_required");

            if ((minPostsRequired != null) && ("1".equals(minPostsRequired))) {
                try {
                    grade.setMinimumPostsRequired(true);
                    int minimumPosts = this.request.getIntParameter("min_posts");
                    grade.setMinimumPosts(minimumPosts);
                } catch (NumberFormatException ne) {
                    grade.setMinimumPosts(0);
                }
            } else {
                try {
                    grade.setMinimumPostsRequired(false);
                    grade.setMinimumPosts(0);
                } catch (NumberFormatException ne) {
                    grade.setMinimumPosts(0);
                }
            }

            grade.setType(Forum.GRADE_BY_FORUM);

            String sendToGradebook = this.request.getParameter("send_to_grade_book");
            Boolean addToGradeBook = Boolean.FALSE;
            if ((sendToGradebook != null) && (Integer.parseInt(sendToGradebook) == 1)) {
                addToGradeBook = Boolean.TRUE;
            }
            grade.setAddToGradeBook(addToGradeBook);
        } else if (forum.getGradeType() == org.etudes.api.app.jforum.Grade.GradeType.TOPIC.getType()) {
            forum.setGrade(null);
        }
    } else
        forum.setGradeType(org.etudes.api.app.jforum.Grade.GradeType.DISABLED.getType());

    try {
        jforumForumService.modifyForum(forum);

        if (forum.getGradeType() == org.etudes.api.app.jforum.Grade.GradeType.FORUM.getType()) {
            // if add to grade option unchecked after saving show the error that there is existing title in the gradebook
            String sendToGradebook = this.request.getParameter("send_to_grade_book");
            boolean addToGradeBook = false;
            if ((sendToGradebook != null) && (Integer.parseInt(sendToGradebook) == 1)) {
                addToGradeBook = true;
            }
            if (addToGradeBook) {
                /*JForumGBService jForumGBService = null;
                jForumGBService = (JForumGBService)ComponentManager.get("org.etudes.api.app.jforum.JForumGBService");
                        
                String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
                if (jForumGBService != null && jForumGBService.isAssignmentDefined(gradebookUid, forum.getName()))
                {
                   this.context.put("errorMessage", I18n.getMessage("Grade.AddEditForumGradeBookConflictingAssignmentNameException"));
                }*/
                org.etudes.api.app.jforum.Forum modForum = jforumForumService
                        .getForum(this.request.getIntParameter("forum_id"));

                if (!modForum.getGrade().isAddToGradeBook()) {
                    if (modForum.getGrade().getPoints() <= 0) {
                        this.context.put("errorMessage", I18n
                                .getMessage("Grade.AddEditForumGradeBookAssignmentHasIllegalPointsException"));
                    } else {
                        this.context.put("errorMessage", I18n
                                .getMessage("Grade.AddEditForumGradeBookConflictingAssignmentNameException"));
                    }
                    this.request.addParameter("forum_id", String.valueOf(forum.getId()));
                    this.edit();
                    return;
                }
            }

        }
    } catch (JForumAccessException e) {
        // already verified access
    } catch (JForumGradesModificationException e) {
        JForum.enableCancelCommit();
        this.context.put("errorMessage", I18n.getMessage("Forums.Forum.CannotEditForum"));
        this.request.addParameter("forum_id", String.valueOf(forum.getId()));
        this.edit();
        return;
    }

    /*addGradeTypesToContext();
            
    Forum f = new Forum(ForumRepository.getForum(this.request.getIntParameter("forum_id")));
    boolean moderated = f.isModerated();
    int categoryId = f.getCategoryId();
            
    f.setDescription(SafeHtml.escapeJavascript(this.request.getParameter("description")));
            
    Category c = DataAccessDriver.getInstance().newCategoryDAO().selectById(this.request.getIntParameter("categories_id"));
    int topicDatesCount = DataAccessDriver.getInstance().newTopicDAO().getTopicDatesCountByForum(f.getId());
            
    if ((c.getStartDate() == null && c.getEndDate() == null) && (topicDatesCount == 0))
    {
       String startDateParam = this.request.getParameter("start_date");
       if (startDateParam != null && startDateParam.trim().length() > 0)
       {
    Date startDate;
    try
    {
       startDate = DateUtil.getDateFromString(startDateParam.trim());
    }
    catch (ParseException e)
    {
       this.context.put("errorMessage", I18n.getMessage("Forums.Forum.DateParseError"));
       this.request.addParameter("forum_id", String.valueOf(f.getId()));
       this.edit();
       return;
    }
    f.setStartDate(startDate);
            
    if (startDate != null)
    {
       SimpleDateFormat df = new SimpleDateFormat(SakaiSystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));
       f.setStartDateFormatted(df.format(startDate));
    }
       }
       else
       {
    f.setStartDate(null);
       }
            
       String endDateParam = this.request.getParameter("end_date");
       if (endDateParam != null && endDateParam.trim().length() > 0)
       {
    Date endDate;
    try
    {
       endDate = DateUtil.getDateFromString(endDateParam.trim());
    }
    catch (ParseException e)
    {
       this.context.put("errorMessage", I18n.getMessage("Forums.Forum.DateParseError"));
       this.request.addParameter("forum_id", String.valueOf(f.getId()));
       this.edit();
       return;
    }
    f.setEndDate(endDate);
            
    String lockForum = this.request.getParameter("lock_forum");
    if (lockForum != null && "1".equals(lockForum))
    {
       f.setLockForum(true);
    }
    else
    {
       f.setLockForum(false);
    }
            
    if (endDate != null)
    {
       SimpleDateFormat df = new SimpleDateFormat(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));
       f.setEndDateFormatted(df.format(endDate));
    }
       }
       else
       {
    f.setEndDate(null);
    f.setLockForum(false);
       }
    }
    else
    {
       f.setStartDate(null);
       f.setEndDate(null);
       f.setLockForum(false);
    }
            
    // check if grading is enabled for forum category
    boolean forumCategoryChangedToGradeCategory = false;
    if ((f.getCategoryId() != this.request.getIntParameter("categories_id")) && (c.isGradeCategory()))
    {
       forumCategoryChangedToGradeCategory = true;
    }
            
    // check category special access
    boolean forumCategoryChanged = false;
    if (f.getCategoryId() != this.request.getIntParameter("categories_id"))
    {
       forumCategoryChanged = true;
    }
            
    f.setIdCategories(this.request.getIntParameter("categories_id"));
    f.setName(SafeHtml.escapeJavascript(this.request.getParameter("forum_name")));
    f.setModerated("1".equals(this.request.getParameter("moderate")));
    f.setType(Integer.parseInt(this.request.getParameter("forum_type")));
    f.setAccessType(Integer.parseInt(this.request.getParameter("access_type")));
            
    if (f.getAccessType() == Forum.ACCESS_GROUPS)
    {
       String selectedGroups[] = (String[]) this.request.getParameterValues("selectedGroups");
       if (logger.isDebugEnabled())
    logger.debug("selectedGroups[] " + selectedGroups);
       List selectedGroupsList = new ArrayList();
            
       if (selectedGroups != null && selectedGroups.length > 0)
       {
    for (int i = 0; i < selectedGroups.length; i++)
       selectedGroupsList.add(selectedGroups[i]);
       }
       f.setGroups(selectedGroupsList);
    }
            
    // check if grading is enabled for forum category
    if (c.isGradeCategory()
    && (this.request.getParameter("grading_enabled") != null && Integer.parseInt(this.request.getParameter("grading_enabled")) == 1))
    {
       JForum.enableCancelCommit();
       this.context.put("errorMessage", I18n.getMessage("Forums.Forum.CannotEditForumGrading"));
       this.request.addParameter("forum_id", String.valueOf(f.getId()));
       this.edit();
       return;
    }
            
    // grading - Once the forum is graded the forum "Grading" cannot be
    // changed to Not Enabled or Enabled - By Topic
    if ((f.getGradeType() == Forum.GRADE_BY_TOPIC) || (f.getGradeType() == Forum.GRADE_BY_FORUM))
    {
       boolean editForum = true;
       EvaluationDAO evaldao = DataAccessDriver.getInstance().newEvaluationDAO();
       int evalCount = 0;
            
       if (f.getGradeType() == Forum.GRADE_BY_TOPIC)
       {
    evalCount = evaldao.selectForumTopicEvaluationsCount(f.getId());
       }
       else if (f.getGradeType() == Forum.GRADE_BY_FORUM)
       {
    evalCount = evaldao.selectForumEvaluationsCount(f.getId());
       }
            
       if (this.request.getParameter("grading_enabled") == null)
       {
    if (evalCount > 0)
    {
       editForum = false;
    }
       }
       else
       {
    if (evalCount > 0)
    {
       if ((f.getGradeType() == Forum.GRADE_BY_TOPIC && (Integer.parseInt(this.request.getParameter("grading_type")) == Forum.GRADE_BY_FORUM))
             || (f.getGradeType() == Forum.GRADE_BY_FORUM && (Integer.parseInt(this.request.getParameter("grading_type")) == Forum.GRADE_BY_TOPIC))
             || ((f.getGradeType() == Forum.GRADE_BY_FORUM || f.getGradeType() == Forum.GRADE_BY_TOPIC) && (Integer
                   .parseInt(this.request.getParameter("grading_enabled")) == Forum.GRADE_DISABLED)))
       {
          editForum = false;
       }
    }
       }
            
       if (!editForum)
       {
            
    if (forumCategoryChangedToGradeCategory)
    {
       this.context.put("errorMessage", I18n.getMessage("Forums.Forum.CannotEditForumToGradableCategory"));
    }
    else
    {
       this.context.put("errorMessage", I18n.getMessage("Forums.Forum.CannotEditForum"));
    }
            
    JForum.enableCancelCommit();
    this.request.addParameter("forum_id", String.valueOf(f.getId()));
    this.edit();
    return;
       }
    }
            
    if (this.request.getParameter("grading_enabled") != null && Integer.parseInt(this.request.getParameter("grading_enabled")) == 1)
    {
       if (this.request.getParameter("grading_type") != null)
       {
    f.setGradeType(Integer.parseInt(this.request.getParameter("grading_type")));
       }
       else
       {
    f.setGradeType(Forum.GRADE_BY_TOPIC);
       }
    }
    else
    {
       f.setGradeType(Forum.GRADE_DISABLED);
    }
            
    // if category is changed delete forum special access.
    if (forumCategoryChanged)
    {
       List<SpecialAccess> forumSpecialAccessList = DataAccessDriver.getInstance().newSpecialAccessDAO().selectByForumId(f.getId());
       for (SpecialAccess exiSpecialAccess : forumSpecialAccessList)
       {
    DataAccessDriver.getInstance().newSpecialAccessDAO().delete(exiSpecialAccess.getId());
       }
    }
            
    DataAccessDriver.getInstance().newForumDAO().update(f);
            
    // remove existing special access if no dates
    if ((f.getStartDate() == null) && (f.getEndDate() == null))
    {
       deleteForumSpecialAccess(f);
    }
            
    if (moderated != f.isModerated())
    {
       new ModerationCommon().setTopicModerationStatus(f.getId(), f.isModerated());
    }
            
    // if grading type is forum update grade
    if (f.getGradeType() == Forum.GRADE_BY_FORUM)
    {
       // remove existing topic grades if any
       List<Grade> grades = DataAccessDriver.getInstance().newGradeDAO().selectForumTopicGradesByForumId(f.getId());
       for (Grade grade : grades)
       {
    Topic topic = DataAccessDriver.getInstance().newTopicDAO().selectById(grade.getTopicId());
    topic.setGradeTopic(false);
    DataAccessDriver.getInstance().newTopicDAO().update(topic);
    removeEntryFromGradeBook(grade);
    DataAccessDriver.getInstance().newGradeDAO().delete(grade.getId());
       }
       Grade exisGrade = DataAccessDriver.getInstance().newGradeDAO().selectByForumId(f.getId());
            
       // update existing forum grade or create grade
       if (exisGrade == null)
       {
    Grade grade = new Grade();
            
    grade.setContext(ToolManager.getCurrentPlacement().getContext());
    grade.setForumId(f.getId());
    try
    {
       Float points = Float.parseFloat(this.request.getParameter("points"));
            
       if (points.floatValue() < 0)
          points = Float.valueOf(0.0f);
       if (points.floatValue() > 1000)
          points = Float.valueOf(1000.0f);
       points = Float.valueOf(((float) Math.round(points.floatValue() * 100.0f)) / 100.0f);
            
       grade.setPoints(points);
    }
    catch (NumberFormatException ne)
    {
       grade.setPoints(0f);
    }
            
            
     * try { int minimumPosts =
     * this.request.getIntParameter("min_posts");
     * grade.setMinimumPosts(minimumPosts); } catch
     * (NumberFormatException ne) { grade.setMinimumPosts(0); }
             
    String minPostsRequired = this.request.getParameter("min_posts_required");
            
    if ((minPostsRequired != null) && ("1".equals(minPostsRequired)))
    {
       try
       {
          grade.setMinimumPostsRequired(true);
          int minimumPosts = this.request.getIntParameter("min_posts");
          grade.setMinimumPosts(minimumPosts);
       }
       catch (NumberFormatException ne)
       {
          grade.setMinimumPosts(0);
       }
    }
    else
    {
       try
       {
          grade.setMinimumPostsRequired(false);
          grade.setMinimumPosts(0);
       }
       catch (NumberFormatException ne)
       {
          grade.setMinimumPosts(0);
       }
    }
            
    grade.setType(Forum.GRADE_BY_FORUM);
            
    int gradeId = DataAccessDriver.getInstance().newGradeDAO().addNew(grade);
    grade.setId(gradeId);
            
    String sendToGradebook = this.request.getParameter("send_to_grade_book");
    boolean addToGradeBook = false;
    if ((sendToGradebook != null) && (Integer.parseInt(sendToGradebook) == 1))
    {
       addToGradeBook = true;
    }
            
    // if add to grade book is true then add the grade to grade book
    if (addToGradeBook)
    {
       grade.setAddToGradeBook(addToGradeBook);
               
        * if (f.getStartDate() != null) { Calendar calendar =
        * Calendar.getInstance();
        * 
        * Date startDate = f.getStartDate();
        * 
        * Date nowDate = calendar.getTime();
        * 
        * if (nowDate.before(startDate)) { addToGradeBook = false;
        * } else { addToGradeBook = updateGradebook(grade); } }
        * else { addToGradeBook = updateGradebook(grade); }
                
            
       Date endDate = f.getEndDate();
            
       if (endDate == null)
       {
          endDate = c.getEndDate();
       }
            
       addToGradeBook = updateGradebook(grade, endDate);
    }
    grade.setAddToGradeBook(addToGradeBook);
    DataAccessDriver.getInstance().newGradeDAO().updateAddToGradeBookStatus(gradeId, addToGradeBook);
       }
       else
       {
    try
    {
       Float points = Float.parseFloat(this.request.getParameter("points"));
            
       if (points.floatValue() < 0)
          points = Float.valueOf(0.0f);
       if (points.floatValue() > 1000)
          points = Float.valueOf(1000.0f);
       points = Float.valueOf(((float) Math.round(points.floatValue() * 100.0f)) / 100.0f);
       exisGrade.setPoints(points);
    }
    catch (NumberFormatException ne)
    {
       exisGrade.setPoints(0f);
    }
            
            
     * try { int minimumPosts =
     * this.request.getIntParameter("min_posts");
     * exisGrade.setMinimumPosts(minimumPosts); } catch
     * (NumberFormatException ne) { exisGrade.setMinimumPosts(0); }
             
    String minPostsRequired = this.request.getParameter("min_posts_required");
            
    if ((minPostsRequired != null) && ("1".equals(minPostsRequired)))
    {
       try
       {
          exisGrade.setMinimumPostsRequired(true);
          int minimumPosts = this.request.getIntParameter("min_posts");
          exisGrade.setMinimumPosts(minimumPosts);
       }
       catch (NumberFormatException ne)
       {
          exisGrade.setMinimumPosts(0);
       }
    }
    else
    {
       try
       {
          exisGrade.setMinimumPostsRequired(false);
          exisGrade.setMinimumPosts(0);
       }
       catch (NumberFormatException ne)
       {
          exisGrade.setMinimumPosts(0);
       }
    }
    exisGrade.setType(Forum.GRADE_BY_FORUM);
            
    String sendToGradebook = this.request.getParameter("send_to_grade_book");
    boolean addToGradeBook = false;
    if ((sendToGradebook != null) && (Integer.parseInt(sendToGradebook) == 1))
    {
       addToGradeBook = true;
    }
            
    DataAccessDriver.getInstance().newGradeDAO().updateForumGrade(exisGrade);
            
    exisGrade.setAddToGradeBook(addToGradeBook);
            
    // update title in gradebook if grades are released to gradebook
            
    if (addToGradeBook)
    {
               
        * if (f.getStartDate() != null) { Calendar calendar =
        * Calendar.getInstance();
        * 
        * Date startDate = f.getStartDate();
        * 
        * Date nowDate = calendar.getTime();
        * 
        * if (nowDate.before(startDate)) { // remove any existing
        * entry in the grade book
        * removeEntryFromGradeBook(exisGrade); addToGradeBook =
        * false; } else { addToGradeBook =
        * updateGradebook(exisGrade); } } else { addToGradeBook =
        * updateGradebook(exisGrade); }
                
            
       Date endDate = f.getEndDate();
            
       if (endDate == null)
       {
          endDate = c.getEndDate();
       }
            
       addToGradeBook = updateGradebook(exisGrade, endDate);
    }
    else
    {
       // remove any existing entry in the grade book
       removeEntryFromGradeBook(exisGrade);
    }
    exisGrade.setAddToGradeBook(addToGradeBook);
    DataAccessDriver.getInstance().newGradeDAO().updateAddToGradeBookStatus(exisGrade.getId(), addToGradeBook);
       }
    }
    else if (f.getGradeType() == Forum.GRADE_BY_TOPIC)
    {
       updateGradebookTopics(c, f);
    }
    else
    {
       // delete forum or topic grades if existing
       List<Grade> grades = DataAccessDriver.getInstance().newGradeDAO().selectForumTopicGradesByForumId(f.getId());
       for (Grade grade : grades)
       {
    Topic topic = DataAccessDriver.getInstance().newTopicDAO().selectById(grade.getTopicId());
    topic.setGradeTopic(false);
    DataAccessDriver.getInstance().newTopicDAO().update(topic);
            
    removeEntryFromGradeBook(grade);
            
    DataAccessDriver.getInstance().newGradeDAO().delete(grade.getId());
       }
            
       Grade grade = DataAccessDriver.getInstance().newGradeDAO().selectByForumId(f.getId());
            
       removeEntryFromGradeBook(grade);
            
       if (grade != null)
    DataAccessDriver.getInstance().newGradeDAO().delete(grade.getId());
    }
            
    if (categoryId != f.getCategoryId())
    {
       f.setIdCategories(categoryId);
       ForumRepository.removeForum(f);
            
       f.setIdCategories(this.request.getIntParameter("categories_id"));
       ForumRepository.addForum(f);
    }
    else
    {
       ForumRepository.reloadForum(f.getId());
    }
     */

    // auto save navigation
    autoSaveNavigation();
}

From source file:org.etudes.jforum.view.forum.PostAction.java

/**
 * save the post//from  w w w. j  a v a  2  s .c om
 * 
 * @throws Exception
 */
public void insertSave() throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("starting insertSave()");

    int forumId = this.request.getIntParameter("forum_id");

    try {

        boolean facilitator = JForumUserUtil.isJForumFacilitator(UserDirectoryService.getCurrentUser().getId());

        boolean participant = JForumUserUtil.isJForumParticipant(UserDirectoryService.getCurrentUser().getId());

        if (!(facilitator || participant)) {
            this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized"));
            this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED);
            return;
        }

        JForumForumService jforumForumService = (JForumForumService) ComponentManager
                .get("org.etudes.api.app.jforum.JForumForumService");

        org.etudes.api.app.jforum.Forum forum = null;
        try {
            forum = jforumForumService.getForum(forumId, UserDirectoryService.getCurrentUser().getId());
        } catch (JForumAccessException e) {
            this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized"));
            this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED);
            return;
        }

        JForumPostService jforumPostService = (JForumPostService) ComponentManager
                .get("org.etudes.api.app.jforum.JForumPostService");

        if (this.request.getParameter("topic_id") != null) {
            int topicId = Integer.parseInt(this.request.getParameter("topic_id"));
            // posting reply
            org.etudes.api.app.jforum.Topic topic = jforumPostService.getTopic(topicId);

            JForumUserService jforumUserService = (JForumUserService) ComponentManager
                    .get("org.etudes.api.app.jforum.JForumUserService");

            org.etudes.api.app.jforum.User postedBy = jforumUserService
                    .getBySakaiUserId(SessionFacade.getUserSession().getSakaiUserId());
            topic.setPostedBy(postedBy);

            org.etudes.api.app.jforum.Post post = jforumPostService.newPost();

            fillPost(post, false);

            if (post.getSubject() == null || post.getSubject().trim() == "") {
                post.setSubject(topic.getTitle());
            }

            processPostAttachments(jforumPostService, post);

            topic.getPosts().clear();
            topic.getPosts().add(post);

            try {
                jforumPostService.createPost(topic);
            } catch (JForumAccessException e) {
                this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized"));
                this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED);
                return;
            } catch (JForumAttachmentOverQuotaException e) {
                JForum.enableCancelCommit();
                this.request.addParameter("topic_id", this.request.getParameter("topic_id"));
                this.context.put("errorMessage", e.getMessage());
                this.context.put("post", post);
                this.insert();
                return;
            } catch (JForumAttachmentBadExtensionException e) {
                JForum.enableCancelCommit();
                this.request.addParameter("topic_id", this.request.getParameter("topic_id"));
                this.context.put("errorMessage", e.getMessage());
                this.context.put("post", post);
                this.insert();
                return;
            }

            // Topic watch
            if (this.request.getParameter("notify") != null) {
                jforumPostService.subscribeUserToTopic(topic.getId(), post.getPostedBy().getSakaiUserId());
            }

            String path = this.request.getContextPath() + "/posts/list/";
            int start = ViewCommon.getStartPage();

            path += this.startPage(topic, start) + "/";
            path += topic.getId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) + "#" + post.getId();

            JForum.setRedirect(path);
            //this.response.setIntHeader("X-XSS-Protection", 0);
        } else {
            // creating new topic
            //topic type, forum id, title(subject), dates, postedBy if topic is gradable grade information.
            org.etudes.api.app.jforum.Topic topic = jforumPostService.newTopic();

            if (this.request.getParameter("topic_type") != null) {
                topic.setType(this.request.getIntParameter("topic_type"));
            }

            topic.setForumId(forumId);

            topic.setTitle(this.request.getParameter("subject"));

            // topic - mark for export
            if (this.request.getParameter("topic_export") != null) {
                topic.setExportTopic(true);
            } else {
                topic.setExportTopic(false);
            }

            String startDateParam = this.request.getParameter("start_date");

            // dates
            if (startDateParam != null && startDateParam.trim().length() > 0) {
                Date startDate = null;
                try {
                    startDate = DateUtil.getDateFromString(startDateParam.trim());
                } catch (ParseException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
                topic.getAccessDates().setOpenDate(startDate);

                String hideUntilOpen = this.request.getParameter("hide_until_open");
                if (hideUntilOpen != null && "1".equals(hideUntilOpen)) {
                    topic.getAccessDates().setHideUntilOpen(Boolean.TRUE);
                } else {
                    topic.getAccessDates().setHideUntilOpen(Boolean.FALSE);
                }
            } else {
                topic.getAccessDates().setOpenDate(null);
                topic.getAccessDates().setHideUntilOpen(Boolean.FALSE);
            }

            // due date
            String endDateParam = this.request.getParameter("end_date");
            if (endDateParam != null && endDateParam.trim().length() > 0) {
                Date endDate = null;
                try {
                    endDate = DateUtil.getDateFromString(endDateParam.trim());
                } catch (ParseException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
                topic.getAccessDates().setDueDate(endDate);
            } else {
                topic.getAccessDates().setDueDate(null);
            }

            // allow until
            String allowUntilDateParam = this.request.getParameter("allow_until_date");
            if (allowUntilDateParam != null && allowUntilDateParam.trim().length() > 0) {
                Date allowUntilDate = null;
                try {
                    allowUntilDate = DateUtil.getDateFromString(allowUntilDateParam.trim());
                } catch (ParseException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
                topic.getAccessDates().setAllowUntilDate(allowUntilDate);
            } else {
                topic.getAccessDates().setAllowUntilDate(null);
            }

            //grade topic
            if (facilitator && this.request.getParameter("grade_topic") != null) {
                org.etudes.api.app.jforum.Grade grade = topic.getGrade();
                if (this.request.getIntParameter("grade_topic") == Topic.GRADE_NO) {
                    topic.setGradeTopic(false);
                } else if (this.request.getIntParameter("grade_topic") == Topic.GRADE_YES) {
                    topic.setGradeTopic(true);
                }

                try {
                    Float points = Float.parseFloat(this.request.getParameter("point_value"));

                    if (points.floatValue() < 0)
                        points = Float.valueOf(0.0f);
                    if (points.floatValue() > 1000)
                        points = Float.valueOf(1000.0f);
                    points = Float.valueOf(((float) Math.round(points.floatValue() * 100.0f)) / 100.0f);
                    grade.setPoints(points);
                } catch (NumberFormatException ne) {
                    grade.setPoints(0f);
                    if (logger.isWarnEnabled()) {
                        logger.warn(ne.toString(), ne);
                    }
                }

                String minPostsRequired = this.request.getParameter("min_posts_required");

                if ((minPostsRequired != null) && ("1".equals(minPostsRequired))) {
                    grade.setMinimumPostsRequired(true);
                    try {
                        int minimumPosts = this.request.getIntParameter("min_posts");
                        grade.setMinimumPosts(minimumPosts);
                    } catch (NumberFormatException e) {
                        if (logger.isWarnEnabled()) {
                            logger.warn(e.toString(), e);
                        }
                    }
                }

                String sendToGradebook = this.request.getParameter("send_to_grade_book");
                boolean addToGradeBook = false;
                if ((sendToGradebook != null) && (Integer.parseInt(sendToGradebook) == 1)) {
                    addToGradeBook = true;
                }
                grade.setAddToGradeBook(addToGradeBook);
            }

            JForumUserService jforumUserService = (JForumUserService) ComponentManager
                    .get("org.etudes.api.app.jforum.JForumUserService");

            org.etudes.api.app.jforum.User postedBy = jforumUserService
                    .getBySakaiUserId(SessionFacade.getUserSession().getSakaiUserId());
            topic.setPostedBy(postedBy);

            org.etudes.api.app.jforum.Post post = jforumPostService.newPost();

            fillPost(post, false);

            processPostAttachments(jforumPostService, post);

            topic.getPosts().add(post);

            try {
                jforumPostService.createTopicWithAttachments(topic);
            } catch (JForumAccessException e) {
                this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized"));
                this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED);
                return;
            } catch (JForumAttachmentOverQuotaException e) {
                JForum.enableCancelCommit();
                this.context.put("errorMessage", e.getMessage());
                this.context.put("post", post);
                this.insert();
                return;
            } catch (JForumAttachmentBadExtensionException e) {
                JForum.enableCancelCommit();
                this.context.put("errorMessage", e.getMessage());
                this.context.put("post", post);
                this.insert();
                return;
            }

            // Topic watch
            if (this.request.getParameter("notify") != null) {
                jforumPostService.subscribeUserToTopic(topic.getId(), post.getPostedBy().getSakaiUserId());
            }

            if (facilitator) {
                org.etudes.api.app.jforum.Post newPost = jforumPostService.getPost(post.getId());
                org.etudes.api.app.jforum.Topic newTopic = null;
                newTopic = newPost.getTopic();

                if (newTopic.isGradeTopic() && newTopic.getFirstPostId() == post.getId()) {
                    String sendToGradebook = this.request.getParameter("send_to_grade_book");
                    boolean addToGradeBook = false;
                    if ((sendToGradebook != null) && (Integer.parseInt(sendToGradebook) == 1)) {
                        addToGradeBook = true;
                    }

                    if (addToGradeBook) {
                        if (newTopic.isGradeTopic() && !newTopic.getGrade().isAddToGradeBook()) {
                            if (newTopic.getGrade().getPoints() <= 0) {
                                this.context.put("errorMessage", I18n.getMessage(
                                        "Grade.AddEditTopicGradeBookAssignmentHasIllegalPointsException"));
                            } else {
                                this.context.put("errorMessage", I18n.getMessage(
                                        "Grade.AddEditTopicGradeBookConflictingAssignmentNameException"));
                            }

                            this.request.addParameter("post_id", String.valueOf(post.getId()));
                            this.request.addParameter("start", "0");
                            this.edit();
                            return;
                        }

                    }
                }
            }

            String path = this.request.getContextPath() + "/posts/list/";
            path += topic.getId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION);

            JForum.setRedirect(path);
        }
    } catch (Exception e) {
        if (logger.isErrorEnabled()) {
            logger.error(e.toString(), e);
        }

        throw e;

        /*String path = this.request.getContextPath() +"/forums/show/"+ forumId + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION);
                
        JForum.setRedirect(path);*/
    }
}

From source file:org.etudes.jforum.view.forum.PostAction.java

/**
 * save the edited post/*w w  w  .  j a  v  a 2 s  . c o m*/
 * @throws Exception
 */
public void editSave() throws Exception {
    boolean facilitator = false;

    //facilitator can add all type of topics 
    if (JForumUserUtil.isJForumFacilitator(UserDirectoryService.getCurrentUser().getId())
            || SecurityService.isSuperUser()) {
        facilitator = true;
    }

    boolean participant = JForumUserUtil.isJForumParticipant(UserDirectoryService.getCurrentUser().getId());

    if (!(facilitator || participant)) {
        this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized"));
        this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED);
        return;
    }

    int postId = this.request.getIntParameter("post_id");

    JForumPostService jforumPostService = (JForumPostService) ComponentManager
            .get("org.etudes.api.app.jforum.JForumPostService");

    org.etudes.api.app.jforum.Post post = jforumPostService.getPost(postId);

    if (post == null) {
        this.postNotFound();
        return;
    }

    org.etudes.api.app.jforum.Topic topic = null;

    try {
        topic = jforumPostService.getTopic(post.getTopicId(), UserDirectoryService.getCurrentUser().getId());
    } catch (JForumAccessException e) {
        this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized"));
        this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED);
        return;
    }

    if (topic == null) {
        this.topicNotFound();
        return;
    }

    int userId = SessionFacade.getUserSession().getUserId();
    boolean canAccess = (facilitator || post.getUserId() == userId);

    if (!canAccess) {
        this.setTemplateName(TemplateKeys.POSTS_EDIT_CANNOTEDIT);
        this.context.put("message", I18n.getMessage("CannotEditPost"));
        return;
    }

    if (participant && !topic.mayPost()) {
        this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized"));
        this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED);
        return;
    }

    if (facilitator) {
        org.etudes.api.app.jforum.Topic apiTopic = null;
        apiTopic = post.getTopic();

        if (apiTopic.getFirstPostId() == post.getId()) {
            apiTopic.setType(this.request.getIntParameter("topic_type"));

            // topic - mark for export
            if (this.request.getParameter("topic_export") != null) {
                apiTopic.setExportTopic(true);
            } else {
                apiTopic.setExportTopic(false);
            }

            // star and end dates
            /*String startDateParam = this.request.getParameter("start_date");
            if (startDateParam != null && startDateParam.trim().length() > 0)
            {
               Date startDate = null;
               try
               {
                  startDate = DateUtil.getDateFromString(startDateParam.trim());
               } catch (ParseException e)
               {
                          
               }
               apiTopic.getAccessDates().setOpenDate(startDate);
            }
            else
            {
               apiTopic.getAccessDates().setOpenDate(null);
            }
                    
            String endDateParam = this.request.getParameter("end_date");
            if (endDateParam != null && endDateParam.trim().length() > 0)
            {
               Date endDate = null;
               try
               {
                  endDate = DateUtil.getDateFromString(endDateParam.trim());
               } catch (ParseException e)
               {
                  logger.error(e);            
               }
                           
               apiTopic.getAccessDates().setDueDate(endDate);
                       
               String lockTopic = this.request.getParameter("lock_topic");
               if (lockTopic != null && "1".equals(lockTopic)){
                  apiTopic.getAccessDates().setLocked(true);
               }
               else
               {
                  apiTopic.getAccessDates().setLocked(false);
               }
            }
            else
            {
               apiTopic.getAccessDates().setDueDate(null);
               apiTopic.getAccessDates().setLocked(false);
            }*/

            String startDateParam = this.request.getParameter("start_date");

            // dates
            if (startDateParam != null && startDateParam.trim().length() > 0) {
                Date startDate = null;
                try {
                    startDate = DateUtil.getDateFromString(startDateParam.trim());
                } catch (ParseException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
                apiTopic.getAccessDates().setOpenDate(startDate);

                String hideUntilOpen = this.request.getParameter("hide_until_open");
                if (hideUntilOpen != null && "1".equals(hideUntilOpen)) {
                    apiTopic.getAccessDates().setHideUntilOpen(Boolean.TRUE);
                } else {
                    apiTopic.getAccessDates().setHideUntilOpen(Boolean.FALSE);
                }
            } else {
                apiTopic.getAccessDates().setOpenDate(null);
                apiTopic.getAccessDates().setHideUntilOpen(Boolean.FALSE);
            }

            // due date
            String endDateParam = this.request.getParameter("end_date");
            if (endDateParam != null && endDateParam.trim().length() > 0) {
                Date endDate = null;
                try {
                    endDate = DateUtil.getDateFromString(endDateParam.trim());
                } catch (ParseException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
                apiTopic.getAccessDates().setDueDate(endDate);
            } else {
                apiTopic.getAccessDates().setDueDate(null);
            }

            // allow until
            String allowUntilDateParam = this.request.getParameter("allow_until_date");
            if (allowUntilDateParam != null && allowUntilDateParam.trim().length() > 0) {
                Date allowUntilDate = null;
                try {
                    allowUntilDate = DateUtil.getDateFromString(allowUntilDateParam.trim());
                } catch (ParseException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
                apiTopic.getAccessDates().setAllowUntilDate(allowUntilDate);
            } else {
                apiTopic.getAccessDates().setAllowUntilDate(null);
            }

            if (this.request.getParameter("grade_topic") != null) {
                if (this.request.getIntParameter("grade_topic") == Topic.GRADE_NO) {
                    apiTopic.setGradeTopic(false);
                } else if (this.request.getIntParameter("grade_topic") == Topic.GRADE_YES) {
                    apiTopic.setGradeTopic(true);
                }

                if (apiTopic.isGradeTopic()) {
                    if (apiTopic.getGrade() != null) {

                    } else {
                        jforumPostService.newTopicGrade(apiTopic);
                    }

                    //org.etudes.api.app.jforum.Grade grade = topic.getGrade();
                    try {
                        Float points = Float.parseFloat(this.request.getParameter("point_value"));

                        if (points.floatValue() < 0)
                            points = Float.valueOf(0.0f);
                        if (points.floatValue() > 1000)
                            points = Float.valueOf(1000.0f);
                        points = Float.valueOf(((float) Math.round(points.floatValue() * 100.0f)) / 100.0f);
                        apiTopic.getGrade().setPoints(points);
                    } catch (NumberFormatException ne) {
                        apiTopic.getGrade().setPoints(0f);
                    }

                    String minPostsRequired = this.request.getParameter("min_posts_required");

                    if ((minPostsRequired != null) && ("1".equals(minPostsRequired))) {
                        apiTopic.getGrade().setMinimumPostsRequired(true);

                        try {
                            int minimumPosts = this.request.getIntParameter("min_posts");
                            apiTopic.getGrade().setMinimumPosts(minimumPosts);
                        } catch (NumberFormatException e) {
                            if (logger.isWarnEnabled()) {
                                logger.warn(e.toString(), e);
                            }
                        }
                    } else {
                        apiTopic.getGrade().setMinimumPostsRequired(false);
                        apiTopic.getGrade().setMinimumPosts(0);
                    }

                    String sendToGradebook = this.request.getParameter("send_to_grade_book");
                    boolean addToGradeBook = false;
                    if ((sendToGradebook != null) && (Integer.parseInt(sendToGradebook) == 1)) {
                        addToGradeBook = true;
                    }
                    apiTopic.getGrade().setAddToGradeBook(addToGradeBook);
                }

            }
        }
    }

    fillPost(post, true);

    processPostAttachments(jforumPostService, post);
    editPostAttachments(jforumPostService, post);

    try {
        jforumPostService.modifyTopicPost(post);
    } catch (JForumAccessException e) {
        this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized"));
        this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED);
        return;
    } catch (JForumAttachmentOverQuotaException e) {
        JForum.enableCancelCommit();
        this.context.put("errorMessage", e.getMessage());
        this.context.put("post", post);
        this.edit(post);
        return;
    } catch (JForumAttachmentBadExtensionException e) {
        JForum.enableCancelCommit();
        this.context.put("errorMessage", e.getMessage());
        this.context.put("post", post);
        this.edit(post);
        return;
    } catch (JForumGradesModificationException e) {
        JForum.enableCancelCommit();
        this.context.put("errorMessage", I18n.getMessage("PostShow.CannotEditTopic"));
        this.context.put("post", post);
        this.edit(post);
        return;
    }

    String path = this.request.getContextPath() + "/posts/list/";
    String start = this.request.getParameter("start");
    if (start != null && !start.equals("0")) {
        path += start + "/";
    }

    if (facilitator) {
        org.etudes.api.app.jforum.Post modPost = jforumPostService.getPost(postId);
        org.etudes.api.app.jforum.Topic modTopic = null;
        modTopic = modPost.getTopic();

        if (modTopic.isGradeTopic() && modTopic.getFirstPostId() == post.getId()) {
            String sendToGradebook = this.request.getParameter("send_to_grade_book");
            boolean addToGradeBook = false;
            if ((sendToGradebook != null) && (Integer.parseInt(sendToGradebook) == 1)) {
                addToGradeBook = true;
            }

            if (addToGradeBook) {
                if (modTopic.isGradeTopic() && !modTopic.getGrade().isAddToGradeBook()) {
                    if (modTopic.getGrade().getPoints() <= 0) {
                        this.context.put("errorMessage", I18n
                                .getMessage("Grade.AddEditTopicGradeBookAssignmentHasIllegalPointsException"));
                    } else {
                        this.context.put("errorMessage", I18n
                                .getMessage("Grade.AddEditTopicGradeBookConflictingAssignmentNameException"));
                    }

                    this.request.addParameter("post_id", String.valueOf(postId));
                    this.edit();
                    return;
                }

            }
        }
    }

    path += post.getTopicId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) + "#" + post.getId();
    JForum.setRedirect(path);
}

From source file:uk.ac.ebi.orchem.search.SimilaritySearch.java

/**
 * Performs a similarity search between a query molecule and the orchem fingerprint table.
 *
 * @param queryFp fingerprint of the query molecule
 * @param _cutOff tanimoto score below which to stop searching
 * @param _topN top N results after which to stop searching
 * @param debugYN Y or N to debug output back
 * @param idsOnlyYN Y or N to indicate to just return IDs of results (faster)
 * @param extraWhereClause option to include an extra SQL where clause refering to the base compound table
 * @return array of {@link uk.ac.ebi.orchem.bean.OrChemCompound compounds}
 * @throws Exception//from  w ww  . ja  va2s. c om
 */
private static oracle.sql.ARRAY search(BitSet queryFp, Float _cutOff, Integer _topN, String debugYN,
        String idsOnlyYN, String extraWhereClause) throws Exception {

    /*
     * 
    The comment block below describes the search algorithm.
    From:
     "Bounds and Algorithms for Fast Exact Searches of Chemical Fingerprints in Linear and Sub-Linear Time"
      S.Joshua Swamidass and Pierre Baldi
      http://dx.doi.org/10.1021/ci600358f
            
     Top K Hits
     ----------
     We can search for the top K hits by starting from the maximum (where A=B), and exploring discrete possible
     values of B right and left of the maximum.
            
     More precisely, for binary fingerprints, we first
     index the molecules in the database by their fingerprint "bit count"
     to enable efficient referencing
     of a particular bit count bin.
            
     Next, with respect to a particular query, we calculate the bound
     on the similarity for every bit count in the database.
            
     Then we sort these bit counts by their associated bound and iterate over the
     molecules in the database, in order of decreasing bound.
            
     As we iterate, we calculate the similarity between the query and the database molecule and use
     a heap to efficiently track the top hits. The algorithm terminates when
     "the lowest similarity value in the heap is greater than the bound associated with the current database bin"
            
     Algorithm 1 Top K Search
     Require: database of fingerprints binned by bit count Bs
     Ensure: hits contains top K hits which satisfy SIMILARITY( ) > T
            
     1:  hits <- MINHEAP()
     2:  bounds <- LIST()
     3:  for all B in database do //iterate over bins
     4:    tuple <- TUPLE(BOUND(A,B),B)
     5:    LISTAPPEND(bounds, tuple)
     6:  end for
     7:  QUICKSORT(bounds) //NOTE: the length of bounds is constant
     8:  for all bound, B in bounds do //iterate in order of decreasing bound
     9:    if bound < T then
     10:      break //threshold stopping condition
     11:   end if
     12:   if K  HEAPSIZE(hits) and bound < MINSIMILARITY(hits) then
     13:     break //top-K stopping condition
     14:   end if
     15:   for all in database[B] do
     16:     S=SIMILARITY( )
     17:     tuple <- TUPLE(S, )
     18:     if S  T then
     19:        continue //ignore this and continue to next
     20:     else if LENGTH(hits)< K then
     21:        HEAPPUSH(hits, tuple)
     22:     else if S > MINSIMILARITY(hits) then
     23:       HEAPPOPMIN(hits)
     24:       HEAPPUSH(hits,tuple)
     25:     end if
     26:   end for
     27: end for
     28: return hits
     */

    boolean debugging = false;
    if (debugYN.toLowerCase().equals("y"))
        debugging = true;

    debug("started", debugging);

    /**********************************************************************
     * Similarity search algorithm section                                *
     *                                                                    *
     **********************************************************************/
    Comparator heapComparator = new SimHeapElementTanimComparator();
    PriorityBuffer heap = null;
    OracleConnection conn = null;
    PreparedStatement pstmtFp = null;
    PreparedStatement pstmLookup = null;

    String query = " select bit_count, id, fp from orchem_fingprint_simsearch s where  bit_count = ? ";

    float cutOff = _cutOff.floatValue();
    int topN = -1;
    if (_topN == null) {
        debug("No topN breakout specified.. searching until lower bound reached", debugging);
    } else {
        topN = _topN.intValue();
        debug("topN is " + topN + ", result set size limited.", debugging);
    }

    try {
        conn = (OracleConnection) new OracleDriver().defaultConnection();

        String compoundTableName = OrChemParameters.getParameterValue(OrChemParameters.COMPOUND_TABLE, conn);
        String compoundTablePkColumn = OrChemParameters.getParameterValue(OrChemParameters.COMPOUND_PK, conn);
        String compoundTableMolfileColumn = OrChemParameters.getParameterValue(OrChemParameters.COMPOUND_MOL,
                conn);

        if (extraWhereClause != null) {
            query = " select s.bit_count, s.id, s.fp from " + " orchem_fingprint_simsearch s , "
                    + compoundTableName + " c " + " where  s.bit_count = ? " + " and s.id = c."
                    + compoundTablePkColumn + " " + " and " + extraWhereClause;
            debug("QUERY is " + query, debugging);
        }

        float queryBitCount = queryFp.cardinality();
        byte[] queryBytes = Utils.toByteArray(queryFp, extFpSize);
        int queryByteArrLen = queryBytes.length;

        float lowBucketNum = queryBitCount - 1;
        float highBucketNum = queryBitCount + 1;
        float currBucketNum = queryBitCount;

        pstmtFp = conn.prepareStatement(query);
        pstmtFp.setFetchSize(250);

        ResultSet resFp = null;
        boolean done = false;
        byte[] dbByteArray = null;
        float tanimotoCoeff = 0f;
        heap = new PriorityBuffer(true, heapComparator);
        int bucksSearched = 0;
        int loopCount = 0;

        while (!done) {
            debug("bucket is " + currBucketNum, debugging);
            loopCount++;
            pstmtFp.setFloat(1, currBucketNum);
            bucksSearched++;
            resFp = pstmtFp.executeQuery();

            float bound = 0f;
            if (currBucketNum < queryBitCount)
                bound = currBucketNum / queryBitCount;
            else
                bound = queryBitCount / currBucketNum;

            /* Algorithm step 9..11
               Here we can break out because the tanimoto score is becoming to low */
            if (bound < cutOff) {
                debug("bound < cutOff, done", debugging);
                done = true;
            }

            if (!done) {
                //Algorithm 15-26
                while (resFp.next()) {
                    dbByteArray = resFp.getBytes("fp");
                    tanimotoCoeff = calcTanimoto(queryBytes, queryByteArrLen, dbByteArray, queryBitCount,
                            currBucketNum);

                    if (tanimotoCoeff >= cutOff) {
                        SimHeapElement elm = new SimHeapElement();
                        elm.setID(resFp.getString("id"));
                        elm.setTanimotoCoeff(new Float(tanimotoCoeff));

                        if (heap.size() < topN || topN == -1) {
                            heap.add(elm);
                            debug("add elem " + elm.getID(), debugging);

                        } else if (tanimotoCoeff > ((SimHeapElement) (heap.get())).getTanimotoCoeff()
                                .floatValue()) {
                            heap.remove();
                            heap.add(elm);
                            debug("remove + add elem " + elm.getID(), debugging);
                        }
                    }
                }
                resFp.close();
                /* Algorithm 12-14:
                 * When top N hits is reached, and the lowest score of the
                 * hits is greater than the current bucket bound, stop.
                 * If not, the next bucket may contain a better score, so go on.
                 */

                if (topN != -1 && heap.size() >= topN
                        && ((SimHeapElement) (heap.get())).getTanimotoCoeff().floatValue() > bound) {
                    done = true;
                    debug("topN reached, done", debugging);

                } else {
                    // calculate new currBucket
                    float up = queryBitCount / highBucketNum;
                    float down = lowBucketNum / queryBitCount;

                    if (up > down) {
                        currBucketNum = highBucketNum;
                        highBucketNum++;
                    } else {
                        currBucketNum = lowBucketNum;
                        lowBucketNum--;
                    }

                    if (lowBucketNum < 1 && highBucketNum > extFpSize)
                        done = true;
                }
            }
        }
        debug("searched bit_count buckets: " + loopCount, debugging);

        /********************************************************************
         * Search completed.                                                *
         *                                                                  *
         * Next section is just looking up the compounds by ID and          *
         * returning the results, sorted by Tanimoto coefficient            *
         *                                                                  *
         *******************************************************************/
        String lookupCompoundQuery = " select " + compoundTableMolfileColumn + " from " + " "
                + compoundTableName + " where " + " " + compoundTablePkColumn + " =?";

        pstmLookup = conn.prepareStatement(lookupCompoundQuery);
        List compounds = new ArrayList();

        while (heap.size() != 0) {
            SimHeapElement bElm = (SimHeapElement) heap.remove();

            if (idsOnlyYN.equals("N")) {
                // return structure to user
                pstmLookup.setString(1, bElm.getID());
                ResultSet resLookup = pstmLookup.executeQuery();
                if (resLookup.next()) {
                    OrChemCompound c = new OrChemCompound();
                    c.setId(bElm.getID());
                    c.setScore(bElm.getTanimotoCoeff().floatValue());
                    c.setMolFileClob(resLookup.getClob(compoundTableMolfileColumn));
                    compounds.add(c);
                }
                resLookup.close();
            } else {
                // only return ID and score to user
                OrChemCompound c = new OrChemCompound();
                c.setId(bElm.getID());
                c.setScore(bElm.getTanimotoCoeff().floatValue());
                compounds.add(c);
            }
        }
        pstmLookup.close();
        long befSort = System.currentTimeMillis();
        Collections.sort(compounds, new OrChemCompoundTanimComparator());
        debug("sorting time (ms) " + (System.currentTimeMillis() - befSort), debugging);

        OrChemCompound[] output = new OrChemCompound[compounds.size()];
        for (int i = 0; i < compounds.size(); i++) {
            output[i] = (OrChemCompound) (compounds.get(i));
        }
        ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor("ORCHEM_COMPOUND_LIST", conn);
        debug("#compounds in result list : " + compounds.size(), debugging);
        debug("ended", debugging);
        return new ARRAY(arrayDescriptor, conn, output);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw (ex);
    } finally {
        if (pstmLookup != null)
            pstmLookup.close();
        if (pstmtFp != null)
            pstmtFp.close();
        if (conn != null)
            conn.close();
    }
}

From source file:com.sonymobile.android.media.internal.ISOBMFFParser.java

@Override
public float getFloat(String key) {
    if (mMetaDataValues.containsKey(key)) {
        Float val = (Float) (mMetaDataValues.get(key));
        return val.floatValue();
    }/*from  www .  ja v a  2  s .  c  o m*/
    return Float.MIN_VALUE;
}

From source file:de.innovationgate.wgpublisher.webtml.form.TMLForm.java

private void attachSingleFile(WGDocument doc, String altFileName, String keepRatio, String width, String height,
        Float fCompression, File file) throws NumberFormatException, IOException, WGException {

    // Determine if image file is of valid format
    String fileExt = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".") + 1);
    if (!fileExt.equalsIgnoreCase("jpg") && !fileExt.equalsIgnoreCase("jpeg")
            && !fileExt.equalsIgnoreCase("bmp") && !fileExt.equalsIgnoreCase("gif")
            && !fileExt.equalsIgnoreCase("png") && !fileExt.equalsIgnoreCase("tif")
            && !fileExt.equalsIgnoreCase("tiff") && !fileExt.equalsIgnoreCase("fpx")) {
        WGFactory.getLogger().error("WGA Imaging API Error: wrong file type!");
        return;/*from www . j ava  2  s.c  om*/
    }

    // Determine target file
    String targetFileName = null;
    if (altFileName != null && !altFileName.equals("") && !file.getName().equals(altFileName)) {
        targetFileName = altFileName;
    } else {
        String fileName = file.getName();
        targetFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".jpg";
    }

    TemporaryFile tempTargetFile = new TemporaryFile(targetFileName, null, WGFactory.getTempDir());
    tempTargetFile.deleteOnEviction(doc.getDatabase().getSessionContext());
    File targetFile = tempTargetFile.getFile();

    ImageScaler scaler = TMLContext.getThreadMainContext().createimagescaler(file);
    scaler.useJPEGForOutput();
    scaler.setQuality(fCompression.floatValue());

    scaler.scaleToSize(Integer.parseInt(width), Integer.parseInt(height),
            new Boolean(keepRatio).booleanValue());

    // Write scaled image to target file
    scaler.writeImage(targetFile);

    doc.attachFile(targetFile);
}

From source file:org.etudes.mneme.impl.SubmissionServiceImpl.java

/**
 * Check if the candidate has a better score than the best so far.
 * /*ww w  .  j  av  a2  s.  c  o  m*/
 * @param bestSubmission
 *        The best so far.
 * @param candidateSub
 *        The candidate.
 * @return true if the candidate is better, false if not.
 */
protected boolean sameScores(SubmissionImpl bestSubmission, SubmissionImpl candidateSub) {
    Float best = bestSubmission.getTotalScore();
    Float candidate = candidateSub.getTotalScore();
    if ((best == null) && (candidate == null))
        return true;
    if ((candidate == null) || (best == null))
        return false;
    if (best.floatValue() == candidate.floatValue())
        return true;
    return false;
}