Example usage for org.dom4j Attribute getValue

List of usage examples for org.dom4j Attribute getValue

Introduction

In this page you can find the example usage for org.dom4j Attribute getValue.

Prototype

String getValue();

Source Link

Document

Returns the value of the attribute.

Usage

From source file:org.craftercms.search.service.impl.TokenizedElementParser.java

License:Open Source License

@Override
public boolean parse(Element element, String fieldName, String parentFieldName, SolrInputDocument solrDoc,
        ElementParserService parserService) {
    Attribute tokenizedAttribute = element.attribute(tokenizedAttributeName);
    if (tokenizedAttribute != null && BooleanUtils.toBoolean(tokenizedAttribute.getValue())) {
        logger.debug("Parsing element '{}' marked to tokenize", fieldName);

        // Remove the attribute so that at the end the element can be parsed as a normal attribute.
        element.remove(tokenizedAttribute);

        String elementName = element.getName();

        for (Map.Entry<String, String> mapping : fieldSuffixMappings.entrySet()) {
            if (elementName.endsWith(mapping.getKey())) {
                String newElementName = StringUtils.substringBefore(elementName, mapping.getKey())
                        + mapping.getValue();

                Element tokenizedElement = element.createCopy(newElementName);

                if (logger.isDebugEnabled()) {
                    logger.debug("Created new element for tokenized search: " + tokenizedElement.getName());
                }//w  w w.  j a  v  a2 s  . c  o  m

                parserService.parse(tokenizedElement, parentFieldName, solrDoc);

                break;
            }
        }

        parserService.parse(element, parentFieldName, solrDoc);

        return true;
    } else {
        return false;
    }
}

From source file:org.dentaku.gentaku.tools.cgen.visitor.LocalDefaultElement.java

License:Apache License

public String toString() {
    StringBuffer sb = new StringBuffer();
    if (getPath().length() > 75) {
        sb.append("..." + getPath().substring(getPath().length() - 75));
    } else {/*w w w  . j a va 2 s .  c o  m*/
        sb.append(getPath());
    }
    for (Iterator attrIter = attributes().iterator(); attrIter.hasNext();) {
        Attribute attribute = (Attribute) attrIter.next();
        sb.append("[" + attribute.getName() + "=" + attribute.getValue() + "] ");
    }
    return sb.toString();
}

From source file:org.dom4j.samples.LinkChecker.java

License:Open Source License

protected void process(Document document) throws Exception {

    List list = document.selectNodes("//*[local-name()='a']/@href");

    System.out.println("Found: " + list.size() + " links(s)");

    for (Iterator iter = list.iterator(); iter.hasNext();) {
        Attribute attribute = (Attribute) iter.next();
        System.out.println("href = " + attribute.getValue());
    }/*from   w  ww  . j a  v a2  s .  c o  m*/
}

From source file:org.etudes.component.app.melete.MeleteImportServiceImpl.java

License:Apache License

private void processManageItems(Element rootEle, String unZippedDirPath, String fromSiteId, Document document)
        throws Exception {
    List elements = rootEle.elements();
    for (Iterator iter = elements.iterator(); iter.hasNext();) {
        Element element = (Element) iter.next();
        // for next steps file don't bring in as unreferrrenced material
        if (element.attributeValue("identifier").startsWith("NEXTSTEPS"))
            continue;

        Attribute resHrefAttr = element.attribute("href");

        if (resHrefAttr != null) {
            String hrefVal = resHrefAttr.getValue();
            hrefVal = hrefVal.trim();/*from   w w w .  j  av a2 s . c  o  m*/

            //for old melete packages which don't have identifier starting with NEXTSTEPS 
            if (hrefVal != null && hrefVal.indexOf("module_") != -1 && hrefVal.endsWith("nextsteps.html"))
                continue;

            // for files already imported
            Set recordFiles = (Set) importThreadLocal.get("MeleteIMSImportFiles");
            if (recordFiles != null && recordFiles.contains(hrefVal))
                continue;

            String melResourceName = null;
            String melResourceDescription = null;
            String contentType = "typeUpload";
            List resElements = element.elements();

            //typeLink resource
            if (hrefVal.startsWith("http://") || hrefVal.startsWith("https://")
                    || hrefVal.startsWith("mailto:")) {
                melResourceName = readTitlefromElement(resElements, true, hrefVal);
                contentType = "typeLink";
            } else {
                melResourceName = hrefVal.substring(hrefVal.lastIndexOf("/") + 1);
                // if starts with Section then ignore it
                if (hrefVal.substring(hrefVal.lastIndexOf('/') + 1).startsWith("Section_"))
                    continue;
                // LTI RESOURCE
                //Load up the resource to look at it
                //      String fileName = ((Element)resElements.get(0)).attributeValue("href");
                String fileName = getFileNamefromElement(resElements, melResourceName);
                byte[] data = readData(unZippedDirPath, fileName);
                if (data == null)
                    continue;
                String contentEditor = new String(data);
                if (isLTIDocument(contentEditor))
                    contentType = "typeLTI";

                //else uploaded file
                String fileTitle = readTitlefromElement(resElements, false, null);
                if (fileTitle != null)
                    melResourceName = fileTitle;
                melResourceDescription = readDescriptionFromElement(resElements);
            }
            checkAndAddResource(hrefVal, contentType, fromSiteId, resElements, unZippedDirPath, false);
        }
    } //for end
}

From source file:org.etudes.component.app.melete.MeleteImportServiceImpl.java

License:Apache License

private void buildWhatsNext(Element eleItem, Document document, Module module, String unZippedDirPath)
        throws Exception {
    Attribute identifierref = eleItem.attribute("identifierref");
    Element eleRes;//from  ww  w.j a  v  a  2 s. c  o  m

    if (identifierref != null) {
        eleRes = getResource(identifierref.getValue(), document);
        String hrefVal = eleRes.attributeValue("href");
        String nextsteps = new String(readData(unZippedDirPath, hrefVal));
        module.setWhatsNext(nextsteps);
        ModuleDateBean mdbean = new ModuleDateBean();
        mdbean.setModuleId(module.getModuleId().intValue());
        mdbean.setModule(module);
        mdbean.setModuleShdate(module.getModuleshdate());
        ArrayList mdbeanList = new ArrayList();
        mdbeanList.add(mdbean);
        moduleDB.updateModuleDateBeans(mdbeanList);
    }

}

From source file:org.etudes.component.app.melete.MeleteImportServiceImpl.java

License:Apache License

private void mergeWhatsNext(Element eleItem, Document document, Module module, String unZippedDirPath)
        throws Exception {
    Attribute identifierref = eleItem.attribute("identifierref");
    Element eleRes;//ww w . j av a2 s . com

    if (identifierref != null) {
        eleRes = getMergeResource(identifierref.getValue(), document);
        String hrefVal = eleRes.attributeValue("href");
        String nextsteps = new String(readData(unZippedDirPath, hrefVal));
        module.setWhatsNext(nextsteps);
        moduleDB.updateModule(module);
    }

}

From source file:org.etudes.component.app.melete.MeleteImportServiceImpl.java

License:Apache License

/**
 * Builds section for each item under module item
 * @param eleItem item element/*from   w ww  .  j a  v  a2  s  .c  o m*/
 * @param document document
 * @param module Module
 * @throws Exception
 */
private void buildSection(Element eleItem, Document document, Module module, Element seqElement,
        String unZippedDirPath, Document seqDocument, String courseId) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("Entering buildSection...");

    Attribute identifier = eleItem.attribute("identifier");
    //   logger.debug("importing ITEM " + identifier.getValue());

    Attribute identifierref = eleItem.attribute("identifierref");
    Element eleRes;

    Section section = new Section();
    MeleteResource meleteResource = new MeleteResource();
    boolean sectionTitleFlag = false;
    boolean sectionCopyrightFlag = false;

    List elements = eleItem.elements();
    for (Iterator iter = elements.iterator(); iter.hasNext();) {
        Element element = (Element) iter.next();

        //title
        if (element.getQualifiedName().equalsIgnoreCase("title")) {
            section.setTitle(element.getTextTrim());
            sectionTitleFlag = true;
        }
        //item
        else if (element.getQualifiedName().equalsIgnoreCase("item")) {
            //call recursive here
            buildSection(element, document, module, addBlankSection(seqElement, seqDocument), unZippedDirPath,
                    seqDocument, courseId);
        }
        //metadata
        else if (element.getQualifiedName().equalsIgnoreCase("imsmd:lom")) {
            // section instructions
            Element DescElement = null;
            if (eleItem.selectNodes("./imsmd:lom/imsmd:general/imsmd:description") != null
                    && (eleItem.selectNodes("./imsmd:lom/imsmd:general/imsmd:description").size() != 0))
                DescElement = (Element) eleItem.selectNodes("./imsmd:lom/imsmd:general/imsmd:description")
                        .get(0);

            if (DescElement != null) {
                String instr = DescElement.selectSingleNode(".//imsmd:langstring").getText();
                section.setInstr(instr.trim());
            }

            //             read license information
            Element rightsElement = null;
            if (eleItem.selectNodes("./imsmd:lom/imsmd:rights") != null
                    && (eleItem.selectNodes("./imsmd:lom/imsmd:rights").size() != 0))
                rightsElement = (Element) eleItem.selectNodes("./imsmd:lom/imsmd:rights").get(0);

            if (rightsElement != null) {
                Element licenseElement = rightsElement.element("description");
                String licenseUrl = licenseElement.selectSingleNode(".//imsmd:langstring").getText();
                if (licenseUrl != null)
                    buildLicenseInformation(meleteResource, licenseUrl);
                sectionCopyrightFlag = true;
            }
        }
        // license end
    }
    // other attributes
    //   logger.debug("setting section attribs");
    String userId = UserDirectoryService.getCurrentUser().getEid();
    String firstName = UserDirectoryService.getCurrentUser().getFirstName();
    String lastName = UserDirectoryService.getCurrentUser().getLastName();

    section.setTextualContent(true);
    section.setCreatedByFname(firstName);
    section.setCreatedByLname(lastName);
    section.setContentType("notype");

    if (!sectionTitleFlag)
        section.setTitle("Untitled Section");

    //default to no license
    if (!sectionCopyrightFlag) {
        meleteResource.setLicenseCode(RESOURCE_LICENSE_CODE);
        meleteResource.setCcLicenseUrl(RESOURCE_LICENSE_URL);
    }
    // save section object
    Integer new_section_id = sectionDB.addSection(module, section, true);
    section.setSectionId(new_section_id);
    seqElement.addAttribute("id", new_section_id.toString());

    // now melete resource object
    if (identifierref != null) {
        eleRes = getResource(identifierref.getValue(), document);
        if (eleRes != null) {
            Attribute resHrefAttr = eleRes.attribute("href");

            if (resHrefAttr != null) {
                String hrefVal = resHrefAttr.getValue();
                // logger.debug("hrefVal:" + hrefVal);
                // check if file is missing
                if (hrefVal != null && hrefVal.length() != 0 && !(hrefVal.startsWith("http://")
                        || hrefVal.startsWith("https://") || hrefVal.startsWith("mailto:"))) {
                    hrefVal = getFileNamefromElement(eleRes.elements(), hrefVal);
                    if (!meleteUtil.checkFileExists(unZippedDirPath + File.separator + hrefVal)) {
                        logger.info("content file for section is missing so move ON");
                        return;
                    }
                }
                // end missing file check

                // create meleteResourceObject
                List resElements = eleRes.elements();
                createContentResource(module, section, meleteResource, hrefVal, resElements, unZippedDirPath,
                        courseId);

            } // resHrefAttr check end
        }
    }

    if (logger.isDebugEnabled())
        logger.debug("Exiting buildSection...");
}

From source file:org.etudes.component.app.melete.MeleteImportServiceImpl.java

License:Apache License

/**
 * Builds section for each item under module item
 * @param eleItem item element// ww w . ja va2s .co m
 * @param document document
 * @param module Module
 * @throws Exception
 */
private void mergeSection(Element eleItem, Document document, Module module, Element seqElement,
        String unZippedDirPath, Document seqDocument, String courseId) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("Entering mergeSection...");

    Attribute identifier = eleItem.attribute("identifier");
    // // logger.debug("importing ITEM " + identifier.getValue());

    Attribute identifierref = eleItem.attribute("identifierref");
    Element eleRes;

    Section section = new Section();
    MeleteResource meleteResource = new MeleteResource();
    boolean sectionTitleFlag = false;
    boolean sectionCopyrightFlag = false;

    List elements = eleItem.elements();
    for (Iterator iter = elements.iterator(); iter.hasNext();) {
        Element element = (Element) iter.next();

        // title
        if (element.getQualifiedName().equalsIgnoreCase("title")) {
            section.setTitle(element.getTextTrim());
            sectionTitleFlag = true;
        }
        // item
        else if (element.getQualifiedName().equalsIgnoreCase("item")) {
            // call recursive here
            buildSection(element, document, module, addBlankSection(seqElement, seqDocument), unZippedDirPath,
                    seqDocument, courseId);
        }
        // metadata
        else if (element.getName().equalsIgnoreCase("imsmd:lom")) {
            // section instructions
            List<Element> modulegeneralList = element.elements();
            List moduleMetadataList = modulegeneralList.get(0).elements();

            for (Iterator iter2 = moduleMetadataList.iterator(); iter2.hasNext();) {
                Element metaElement = (Element) iter2.next();

                if (metaElement.getName().equals("imsmd:description")
                        && metaElement.element("imsmd:langstring") != null) {
                    String instr = metaElement.element("imsmd:langstring").getText();
                    section.setInstr(instr.trim());
                }
            }

            // read license information
            if (modulegeneralList.size() > 1) {
                List rightList = modulegeneralList.get(1).elements();
                for (Iterator iter3 = rightList.iterator(); iter3.hasNext();) {
                    Element rightsElement = (Element) iter3.next();

                    if (rightsElement.getName().equals("imsmd:description")
                            && rightsElement.element("imsmd:langstring") != null) {
                        String licenseUrl = rightsElement.element("imsmd:langstring").getText();
                        if (licenseUrl != null) {
                            buildLicenseInformation(meleteResource, licenseUrl);
                            sectionCopyrightFlag = true;
                        }
                    }
                }
            }
        }
        // license end
    }
    // other attributes
    // logger.debug("setting section attribs");
    String userId = UserDirectoryService.getCurrentUser().getEid();
    String firstName = UserDirectoryService.getCurrentUser().getFirstName();
    String lastName = UserDirectoryService.getCurrentUser().getLastName();

    section.setTextualContent(true);
    section.setCreatedByFname(firstName);
    section.setCreatedByLname(lastName);
    section.setContentType("notype");

    if (!sectionTitleFlag)
        section.setTitle("Untitled Section");

    // default to no license
    if (!sectionCopyrightFlag) {
        meleteResource.setLicenseCode(RESOURCE_LICENSE_CODE);
        meleteResource.setCcLicenseUrl(RESOURCE_LICENSE_URL);
    }
    // save section object
    Integer new_section_id = sectionDB.addSection(module, section, true);
    section.setSectionId(new_section_id);
    seqElement.addAttribute("id", new_section_id.toString());

    // now melete resource object
    if (identifierref != null) {
        eleRes = getMergeResource(identifierref.getValue(), document);
        if (eleRes != null) {
            Attribute resHrefAttr = eleRes.attribute("href");

            if (resHrefAttr != null) {
                String hrefVal = resHrefAttr.getValue();

                // check if file is missing
                if (hrefVal != null && hrefVal.length() != 0 && !(hrefVal.startsWith("http://")
                        || hrefVal.startsWith("https://") || hrefVal.startsWith("mailto:"))) {
                    if (!meleteUtil.checkFileExists(unZippedDirPath + File.separator + hrefVal)) {
                        logger.info("content file for section is missing so move ON");
                        return;
                    }
                }
                // end missing file check

                // create meleteResourceObject
                List resElements = eleRes.elements();
                createContentResource(module, section, meleteResource, hrefVal, resElements, unZippedDirPath,
                        courseId);

            } // resHrefAttr check end
        }
    }

    if (logger.isDebugEnabled())
        logger.debug("Exiting mergeSection...");
}

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

License:Apache License

/**
 * create topic and first post/*from   w ww  .  j av  a2s  . c om*/
 * 
 * @param topicEle
 * @param forum
 */
//private void createTopic(Element topicEle, Category category, Forum forum, Document document, String unZippedDirPath) throws Exception
private void createTopic(Element topicEle, org.etudes.api.app.jforum.Category category,
        org.etudes.api.app.jforum.Forum forum, Document document, String unZippedDirPath) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Entering createTopic......");
    }

    List eleTopicTitles = (List) topicEle.elements("title");

    if (eleTopicTitles == null || eleTopicTitles.size() == 0) {
        return;
    }

    Element titleEle = (Element) topicEle.elements("title").get(0);

    int topicGrade = 0;
    float gradePoints = 0f;
    int topicType = 0;
    Date startDate = null, endDate = null, allowUntilDate = null;
    //int lockEndDate = 0;
    int hideUntilOpen = 0;
    int addToGradebook = 0;
    int minPostsRequired = 0;
    int minPosts = 0;

    String parameters = topicEle.attributeValue("parameters");
    if (parameters != null && parameters.trim().length() > 0) {
        String param[] = parameters.split("&");
        for (int i = 0; i < param.length; i++) {
            if (param[i].startsWith("topictype")) {
                try {
                    if (param[i].indexOf('=') != -1) {
                        topicType = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1));
                    }
                } catch (NumberFormatException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
            } else if (param[i].startsWith("gradetopic")) {
                try {
                    if (param[i].indexOf('=') != -1) {
                        topicGrade = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1));
                    }
                } catch (NumberFormatException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e);
                    }
                }
            } else if (param[i].startsWith("gradepoints")) {
                try {
                    if (param[i].indexOf('=') != -1) {
                        gradePoints = Float.parseFloat(param[i].substring(param[i].indexOf('=') + 1));
                    }
                } catch (NumberFormatException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
            } else if (param[i].startsWith("startdate")) {
                try {
                    if (param[i].indexOf('=') != -1) {

                        try {
                            startDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1));
                        } catch (ParseException e) {
                        }
                    }
                } catch (NumberFormatException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
            } else if (param[i].startsWith("hideuntilopen")) {
                try {
                    if (param[i].indexOf('=') != -1) {
                        hideUntilOpen = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1));
                    }
                } catch (NumberFormatException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
            } else if (param[i].startsWith("enddate")) {
                try {
                    if (param[i].indexOf('=') != -1) {

                        try {
                            endDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1));
                        } catch (ParseException e) {
                        }
                    }
                } catch (NumberFormatException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
            }
            /*else if (param[i].startsWith("lockenddate"))
            {
               try
               {
                  if (param[i].indexOf('=') != -1)
                  {
             lockEndDate = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1));
                  }
               }
               catch (NumberFormatException e)
               {
                  if (logger.isErrorEnabled())
                  {
             logger.error(e, e);
                  }
               }
            }*/
            else if (param[i].startsWith("allowuntildate")) {
                try {
                    if (param[i].indexOf('=') != -1) {

                        try {
                            allowUntilDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1));
                        } catch (ParseException e) {
                        }
                    }
                } catch (NumberFormatException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
            } else if (param[i].startsWith("addtogradebook")) {
                try {
                    if (param[i].indexOf('=') != -1) {
                        addToGradebook = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1));
                    }
                } catch (NumberFormatException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
            } else if (param[i].startsWith("minpostsrequired")) {
                try {
                    if (param[i].indexOf('=') != -1) {
                        minPostsRequired = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1));
                    }
                } catch (NumberFormatException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
            } else if (param[i].startsWith("minposts")) {
                try {
                    if (param[i].indexOf('=') != -1) {
                        minPosts = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1));
                    }
                } catch (NumberFormatException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }
            }
        }
    }

    /* create new topic and it is a first post */
    JForumPostService jforumPostService = (JForumPostService) ComponentManager
            .get("org.etudes.api.app.jforum.JForumPostService");
    org.etudes.api.app.jforum.Topic t = jforumPostService.newTopic();

    t.setTitle(titleEle.getText());

    t.setForumId(forum.getId());

    if (topicType == org.etudes.api.app.jforum.Topic.TopicType.NORMAL.getType()
            || topicType == org.etudes.api.app.jforum.Topic.TopicType.ANNOUNCE.getType()
            || topicType == org.etudes.api.app.jforum.Topic.TopicType.STICKY.getType()) {
        t.setType(topicType);
    } else {
        t.setType(org.etudes.api.app.jforum.Topic.TopicType.NORMAL.getType());
    }

    t.setGradeTopic((topicGrade == 1) ? true : false);
    t.setExportTopic(true);

    if ((category.getAccessDates().getOpenDate() == null && category.getAccessDates().getDueDate() == null
            && category.getAccessDates().getAllowUntilDate() == null)
            && (forum.getAccessDates().getOpenDate() == null && forum.getAccessDates().getDueDate() == null
                    && forum.getAccessDates().getAllowUntilDate() == null)) {
        t.getAccessDates().setOpenDate(startDate);

        if (startDate != null) {
            t.getAccessDates().setHideUntilOpen((hideUntilOpen == 1) ? true : false);
        }

        t.getAccessDates().setDueDate(endDate);

        t.getAccessDates().setAllowUntilDate(allowUntilDate);

        /*if (endDate != null)
        {
           t.getAccessDates().setLocked((lockEndDate == 1) ? true : false);
        }*/
    } else {
        t.getAccessDates().setOpenDate(null);
        t.getAccessDates().setDueDate(null);
    }

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

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

    // TODO: topic grades
    // create grade if forum is grade by topic and topic is grade topic
    if (forum.getGradeType() == Forum.GRADE_BY_TOPIC && t.isGradeTopic()) {

        org.etudes.api.app.jforum.Grade grade = t.getGrade();

        grade.setContext(ToolManager.getCurrentPlacement().getContext());
        grade.setForumId(forum.getId());
        grade.setTopicId(t.getId());
        try {
            grade.setPoints(gradePoints);
        } catch (NumberFormatException ne) {
            grade.setPoints(0f);
        }
        grade.setType(Forum.GRADE_BY_TOPIC);

        Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());

        if (site.getToolForCommonId(SakaiSystemGlobals.getValue(ConfigKeys.GRADEBOOK_TOOL_ID)) != null) {
            if (forum.getAccessType() != Forum.ACCESS_DENY) {
                grade.setAddToGradeBook((addToGradebook == 1) ? true : false);
            } else {
                grade.setAddToGradeBook(false);
            }
        } else {
            grade.setAddToGradeBook(false);
        }

        if (minPostsRequired == 1) {
            grade.setMinimumPostsRequired(true);
            grade.setMinimumPosts(minPosts);
        }
    }

    // Set the Post
    org.etudes.api.app.jforum.Post p = jforumPostService.newPost();
    p.setTime(new Date());
    p.setSubject(titleEle.getText());
    p.setBbCodeEnabled(false);
    p.setSmiliesEnabled(true);
    p.setSignatureEnabled(true);
    p.setUserIp(JForum.getRequest().getRemoteAddr());
    p.setUserId(SessionFacade.getUserSession().getUserId());
    p.setPostedBy(postedBy);

    p.setHtmlEnabled(false);

    // get text
    Attribute identifierref = topicEle.attribute("identifierref");
    Element eleRes = getResource(identifierref.getValue(), document);
    String hrefVal = eleRes.attributeValue("href");
    String message = null;

    try {
        message = readFromFile(new File(unZippedDirPath + File.separator + hrefVal));
    } catch (Exception e1) {
        if (logger.isWarnEnabled()) {
            logger.warn("site : " + ToolManager.getCurrentPlacement().getContext() + " : " + e1.toString(), e1);
        }
        return;
    }

    // parse and update embedded references path and save the embedded references if not in the resource tool
    message = parseAndUpdateImportUrls(message, unZippedDirPath);

    if (p.isHtmlEnabled()) {
        p.setText(SafeHtml.makeSafe(message));
    } else {
        p.setText(message);
    }

    t.getPosts().clear();
    t.getPosts().add(p);

    try {
        //processAttachments(eleRes, forum, document, unZippedDirPath, postId);
        processAttachments(eleRes, document, unZippedDirPath, p, jforumPostService);
    } catch (Exception e) {
        if (logger.isWarnEnabled()) {
            logger.warn("site : " + ToolManager.getCurrentPlacement().getContext() + " : " + e.toString(), e);
        }
    }

    try {
        jforumPostService.createTopicWithAttachments(t);
    } catch (JForumAccessException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("site : " + ToolManager.getCurrentPlacement().getContext() + " : " + e.toString(), e);
        }
    } catch (JForumAttachmentOverQuotaException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("site : " + ToolManager.getCurrentPlacement().getContext() + " : " + e.toString(), e);
        }
    } catch (JForumAttachmentBadExtensionException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("site : " + ToolManager.getCurrentPlacement().getContext() + " : " + e.toString(), e);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Exiting createTopic......");
    }
}

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

License:Apache License

/**
 * process attachments//from   ww  w.j  a va  2 s . c  om
 * 
 * @param eleRes
 * @param forum
 * @param document
 * @param unZippedDirPath
 * @param postId
 * @throws Exception
 */
/*private void processAttachments(Element eleRes, Forum forum, Document document, String unZippedDirPath, int postId) throws Exception
{
   int total_files = 0;
        
   long totalSize = 0;
   int userId = SessionFacade.getUserSession().getUserId();
   AttachmentDAO am = DataAccessDriver.getInstance().newAttachmentDAO();
   Map extensions = am.extensionsForSecurity();
   // resource elements - <file>
   List resElements = eleRes.elements();
   Attribute resHrefAttr = eleRes.attribute("href");
   for (Iterator iter = resElements.iterator(); iter.hasNext();)
   {
 Element element = (Element) iter.next();
 if (element.getQualifiedName().equalsIgnoreCase("file"))
 {
    Attribute hrefAttr = element.attribute("href");
    // if (total_files >= SystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_MAX_POST))
    if (total_files >= SakaiSystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_MAX_POST))
    {
       if (logger.isWarnEnabled())
          logger.warn("Total number of files attached exceeding maximum " + "allowed.... for site : "
                + ToolManager.getCurrentPlacement().getContext() + " - and for forum : " + forum.getName());
       return;
    }
    String fileext = hrefAttr.getValue().trim().substring(hrefAttr.getValue().trim().lastIndexOf('.') + 1);
    // if (!fileext.equalsIgnoreCase("html")){
    if (!hrefAttr.getValue().trim().equalsIgnoreCase(resHrefAttr.getValue().trim()))
    {
       // create as attachment
       try
       {
          // if (logger.isDebugEnabled())
          // logger.debug("extensions.entrySet() : "+
          // extensions.entrySet());
          // Check if the extension is allowed
          if (extensions.containsKey(fileext))
          {
             if (!((Boolean) extensions.get(fileext)).booleanValue())
             {
                throw new BadExtensionException(I18n.getMessage("Attachments.badExtension", new String[] { fileext }));
             }
          }
          else
          {
             if (logger.isWarnEnabled())
                logger.warn("site - " + ToolManager.getCurrentPlacement().getContext() + " - Attachment with this extension '"
                      + fileext + "' is not allowed ");
             continue;
          }
       }
       catch (BadExtensionException e)
       {
          if (logger.isWarnEnabled())
             logger.warn("site - " + ToolManager.getCurrentPlacement().getContext() + " - " + e.toString());
          continue;
       }
       Attachment a = new Attachment();
       a.setUserId(userId);
        
       AttachmentInfo info = new AttachmentInfo();
       File attachmentFile = new File(unZippedDirPath + File.separator + hrefAttr.getValue());
       if (!attachmentFile.exists())
       {
          if (logger.isErrorEnabled())
             logger.error("Error while import for site - " + ToolManager.getCurrentPlacement().getContext() + " - Attachment : "
                   + attachmentFile.getAbsolutePath() + " doesn't exist.");
          continue;
       }
        
       try
       {
          // Check for total attachments size limit
          // long quotaSize = SystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_QUOTA_LIMIT) * 1024 * 1024;
          long quotaSize = SakaiSystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_QUOTA_LIMIT) * 1024 * 1024;
          totalSize = totalSize + attachmentFile.length();
          if (quotaSize < totalSize)
          {
             throw new AttachmentSizeTooBigException(I18n.getMessage("Attachments.tooBig", new Integer[] {
                   new Integer((int) quotaSize / 1024), new Integer((int) totalSize / 1024) }));
          }
       }
       catch (AttachmentSizeTooBigException e)
       {
          if (logger.isWarnEnabled())
             logger.warn("site - " + ToolManager.getCurrentPlacement().getContext() + " - " + e.toString());
          break;
       }
        
       info.setFilesize(attachmentFile.length());
       info.setComment("");
       info.setMimetype("");
       // description
       List genElements = element.selectNodes("./imsmd:lom/imsmd:general");
       if (genElements != null && genElements.size() > 0)
       {
          Element generalElement = (Element) genElements.get(0);
          Element descElement = generalElement.element("description");
          String description = descElement.selectSingleNode(".//imsmd:langstring").getText();
          if (description != null)
             info.setComment(description.trim());
       }
        
       String filename = null;
       String hrefVal = hrefAttr.getValue().trim();
       if (hrefVal.lastIndexOf('/') != -1)
          filename = hrefVal.substring(hrefVal.lastIndexOf('/') + 1);
       else if (hrefVal.lastIndexOf('\\') != -1)
          filename = hrefVal.substring(hrefVal.lastIndexOf('\\') + 1);
        
       if (filename.startsWith("post_"))
          filename = filename.substring(filename.indexOf("_", 5) + 1);
        
       info.setRealFilename(filename);
       info.setUploadTimeInMillis(System.currentTimeMillis());
        
       AttachmentExtension ext = am.selectExtension(fileext);
        
       info.setExtension(ext);
       String savePath = makeStoreFilename(info);
       info.setPhysicalFilename(savePath);
       a.setInfo(info);
       a.setPostId(postId);
       // String path = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + a.getInfo().getPhysicalFilename();
       String path = SakaiSystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + a.getInfo().getPhysicalFilename();
       am.addAttachment(a);
        
       saveAttachmentFile(path, attachmentFile);
        
       total_files++;
    }
 }
   }
}*/

protected void processAttachments(Element eleRes, Document document, String unZippedDirPath,
        org.etudes.api.app.jforum.Post post, JForumPostService jforumPostService) throws Exception {
    // resource elements - <file>
    List resElements = eleRes.elements();
    Attribute resHrefAttr = eleRes.attribute("href");
    for (Iterator iter = resElements.iterator(); iter.hasNext();) {
        Element element = (Element) iter.next();
        if (element.getQualifiedName().equalsIgnoreCase("file")) {
            Attribute hrefAttr = element.attribute("href");

            String fileext = hrefAttr.getValue().trim()
                    .substring(hrefAttr.getValue().trim().lastIndexOf('.') + 1);

            if (!hrefAttr.getValue().trim().equalsIgnoreCase(resHrefAttr.getValue().trim())) {
                File attachmentFile = new File(unZippedDirPath + File.separator + hrefAttr.getValue());
                if (!attachmentFile.exists()) {
                    if (logger.isErrorEnabled()) {
                        logger.error("Error while import for site - "
                                + ToolManager.getCurrentPlacement().getContext() + " - Attachment : "
                                + attachmentFile.getAbsolutePath() + " doesn't exist.");
                    }
                    continue;
                }

                // String fileName = null;
                String contentType = null;
                String comments = null;
                byte[] fileContent = null;

                // description
                List genElements = element.selectNodes("./imsmd:lom/imsmd:general");
                if (genElements != null && genElements.size() > 0) {
                    Element generalElement = (Element) genElements.get(0);
                    Element descElement = generalElement.element("description");
                    String description = descElement.selectSingleNode(".//imsmd:langstring").getText();
                    if (description != null) {
                        comments = description.trim();
                    }
                }

                String fileName = null;
                String hrefVal = hrefAttr.getValue().trim();
                if (hrefVal.lastIndexOf('/') != -1)
                    fileName = hrefVal.substring(hrefVal.lastIndexOf('/') + 1);
                else if (hrefVal.lastIndexOf('\\') != -1)
                    fileName = hrefVal.substring(hrefVal.lastIndexOf('\\') + 1);

                if (fileName.startsWith("post_"))
                    fileName = fileName.substring(fileName.indexOf("_", 5) + 1);

                //contentType = new MimetypesFileTypeMap().getContentType(attachmentFile);
                FileNameMap fileNameMap = URLConnection.getFileNameMap();
                contentType = fileNameMap.getContentTypeFor(fileName);

                fileContent = getBytesFromFile(attachmentFile);

                org.etudes.api.app.jforum.Attachment attachment = jforumPostService.newAttachment(fileName,
                        contentType, comments, fileContent);
                if (attachment != null) {
                    post.getAttachments().add(attachment);
                    post.setHasAttachments(true);
                }
            }
        }
    }
}