Example usage for com.liferay.portal.kernel.xml Element elements

List of usage examples for com.liferay.portal.kernel.xml Element elements

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.xml Element elements.

Prototype

public List<Element> elements(String name);

Source Link

Usage

From source file:com.liferay.knowledgebase.admin.lar.AdminPortletDataHandlerImpl.java

License:Open Source License

protected void importKBArticleAttachments(PortletDataContext portletDataContext, long importId,
        Map<String, String> dirNames, Element rootElement) throws Exception {

    List<Element> kbArticleAttachmentsElements = rootElement.elements("kb-article-attachments");

    for (Element kbArticleAttachmentsElement : kbArticleAttachmentsElements) {

        String resourcePrimKey = kbArticleAttachmentsElement.attributeValue("resource-prim-key");

        String dirName = "knowledgebase/temp/import/" + importId + StringPool.SLASH + resourcePrimKey;

        DLStoreUtil.addDirectory(portletDataContext.getCompanyId(), CompanyConstants.SYSTEM, dirName);

        List<Element> fileElements = kbArticleAttachmentsElement.elements("file");

        ServiceContext serviceContext = new ServiceContext();

        serviceContext.setCompanyId(portletDataContext.getCompanyId());
        serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());

        for (Element fileElement : fileElements) {
            String shortFileName = fileElement.attributeValue("short-file-name");

            String fileName = dirName + StringPool.SLASH + shortFileName;
            byte[] bytes = portletDataContext.getZipEntryAsByteArray(fileElement.attributeValue("path"));

            DLStoreUtil.addFile(portletDataContext.getCompanyId(), CompanyConstants.SYSTEM, fileName, bytes);
        }/*from   ww w . ja  va 2  s . c  o m*/

        dirNames.put(resourcePrimKey, dirName);
    }
}

From source file:com.liferay.knowledgebase.admin.lar.AdminPortletDataHandlerImpl.java

License:Open Source License

protected void importKBArticles(PortletDataContext portletDataContext, Element rootElement) throws Exception {

    long importId = CounterLocalServiceUtil.increment();

    Map<String, String> dirNames = new HashMap<String, String>();

    try {/*from w w w.  j a  v  a  2  s  .c o  m*/
        DLStoreUtil.addDirectory(portletDataContext.getCompanyId(), CompanyConstants.SYSTEM,
                "knowledgebase/temp/import/" + importId);

        importKBArticleAttachments(portletDataContext, importId, dirNames, rootElement);

        List<Element> kbArticleElements = rootElement.elements("kb-article");

        for (Element kbArticleElement : kbArticleElements) {
            String path = kbArticleElement.attributeValue("path");

            if (!portletDataContext.isPathNotProcessed(path)) {
                continue;
            }

            KBArticle kbArticle = (KBArticle) portletDataContext.getZipEntryAsObject(path);

            importKBArticle(portletDataContext, dirNames, kbArticleElement, kbArticle);
        }
    } finally {
        DLStoreUtil.deleteDirectory(portletDataContext.getCompanyId(), CompanyConstants.SYSTEM,
                "knowledgebase/temp/import/" + importId);
    }
}

From source file:com.liferay.knowledgebase.admin.lar.AdminPortletDataHandlerImpl.java

License:Open Source License

protected KBArticle importKBArticleVersions(PortletDataContext portletDataContext, String uuid,
        long parentResourcePrimKey, String dirName, Element kbArticleElement) throws Exception {

    Element versionsElement = kbArticleElement.element("versions");

    List<Element> kbArticleElements = versionsElement.elements("kb-article");

    KBArticle importedKBArticle = null;//  ww w .j a  va 2  s  .c o  m

    for (Element curKBArticleElement : kbArticleElements) {
        KBArticle curKBArticle = (KBArticle) portletDataContext
                .getZipEntryAsObject(curKBArticleElement.attributeValue("path"));

        long curUserId = portletDataContext.getUserId(curKBArticle.getUserUuid());
        String[] curSections = AdminUtil.unescapeSections(curKBArticle.getSections());
        String curDirName = StringPool.BLANK;

        if (curKBArticle.isMain()) {
            curDirName = dirName;
        }

        ServiceContext serviceContext = portletDataContext.createServiceContext(curKBArticleElement,
                curKBArticle, _NAMESPACE);

        if (importedKBArticle == null) {
            serviceContext.setUuid(uuid);

            importedKBArticle = KBArticleLocalServiceUtil.addKBArticle(curUserId, parentResourcePrimKey,
                    curKBArticle.getTitle(), curKBArticle.getContent(), curKBArticle.getDescription(),
                    curSections, curDirName, serviceContext);
        } else {
            importedKBArticle = KBArticleLocalServiceUtil.updateKBArticle(curUserId,
                    importedKBArticle.getResourcePrimKey(), curKBArticle.getTitle(), curKBArticle.getContent(),
                    curKBArticle.getDescription(), curSections, curDirName, serviceContext);
        }
    }

    return importedKBArticle;
}

From source file:com.liferay.knowledgebase.admin.lar.AdminPortletDataHandlerImpl.java

License:Open Source License

protected void importKBComments(PortletDataContext portletDataContext, Element rootElement) throws Exception {

    List<Element> kbCommentElements = rootElement.elements("kb-comment");

    for (Element kbCommentElement : kbCommentElements) {
        String path = kbCommentElement.attributeValue("path");

        if (!portletDataContext.isPathNotProcessed(path)) {
            continue;
        }/*from  w  ww.j a v  a  2s.c  om*/

        KBComment kbComment = (KBComment) portletDataContext.getZipEntryAsObject(path);

        importKBComment(portletDataContext, kbCommentElement, kbComment);
    }
}

From source file:com.liferay.knowledgebase.admin.lar.AdminPortletDataHandlerImpl.java

License:Open Source License

protected void importKBTemplates(PortletDataContext portletDataContext, Element rootElement) throws Exception {

    for (Element kbTemplateElement : rootElement.elements("kb-template")) {
        String path = kbTemplateElement.attributeValue("path");

        if (!portletDataContext.isPathNotProcessed(path)) {
            continue;
        }/*from w w w  .j av a  2 s  . co m*/

        KBTemplate kbTemplate = (KBTemplate) portletDataContext.getZipEntryAsObject(path);

        importKBTemplate(portletDataContext, kbTemplateElement, kbTemplate);
    }
}

From source file:com.liferay.lms.service.impl.LearningActivityResultLocalServiceImpl.java

License:Open Source License

public LearningActivityResult update(long latId, String tryResultData, long userId)
        throws SystemException, PortalException {
    System.out.println("update");
    LearningActivityTry learningActivityTry = learningActivityTryLocalService.getLearningActivityTry(latId);
    if (userId != learningActivityTry.getUserId()) {
        throw new PortalException();
    }/*w w w.ja  v a 2s . c  om*/

    LearningActivity learningActivity = learningActivityLocalService
            .getLearningActivity(learningActivityTry.getActId());
    String assetEntryId = learningActivityLocalService.getExtraContentValue(learningActivityTry.getActId(),
            "assetEntry");
    AssetEntry assetEntry = AssetEntryLocalServiceUtil.getAssetEntry(Long.valueOf(assetEntryId));

    List<String> manifestItems = new ArrayList<String>();
    Map<String, String> recursos = new HashMap<String, String>();

    Map<String, String> manifestResources = new HashMap<String, String>();

    try {
        String urlString = assetEntry.getUrl();
        if (Validator.isNotNull(urlString)) {
            Document imsdocument = null;
            URL url = new URL(urlString);
            if (urlString.startsWith("http://") || urlString.startsWith("https://")) {
                imsdocument = SAXReaderUtil.read(new URL(urlString).openStream());
            }
            if (urlString.startsWith("file://")) {
                imsdocument = SAXReaderUtil.read(new File(URLDecoder.decode(url.getFile(), "UTF-8")));
            }
            List<Element> resources = new ArrayList<Element>();
            resources = imsdocument.getRootElement().element("resources").elements("resource");
            for (Element resource : resources) {
                String identifier = resource.attributeValue("identifier");
                String type = resource.attributeValue("scormType");
                String type2 = resource.attributeValue("scormtype");
                manifestResources.put(identifier, type != null ? type : type2);
            }

            List<Element> items = new ArrayList<Element>();
            items.addAll(imsdocument.getRootElement().element("organizations").elements("organization").get(0)
                    .elements("item"));
            for (int i = 0; i < items.size(); i++) {
                Element item = items.get(i);
                String identifier = item.attributeValue("identifier");
                String identifierref = item.attributeValue("identifierref");
                manifestItems.add(identifier);
                recursos.put(identifier, identifierref);
                items.addAll(item.elements("item"));
            }
        }
    } catch (DocumentException e) {
    } catch (Exception e) {
        e.printStackTrace();
    }

    Long master_score = new Integer(learningActivity.getPasspuntuation()).longValue();

    JSONObject scorm = JSONFactoryUtil.createJSONObject();
    scorm = JSONFactoryUtil.createJSONObject(tryResultData);

    JSONObject organizations = scorm.getJSONObject("organizations");
    JSONArray organizationNames = organizations.names();
    JSONObject organization = organizations.getJSONObject(organizationNames.getString(0));

    JSONObject cmis = organization.getJSONObject("cmi");
    JSONArray cmiNames = cmis.names();

    List<String> completion_statuses = new ArrayList<String>();
    List<String> success_statuses = new ArrayList<String>();
    List<Long> scores = new ArrayList<Long>();

    String total_completion_status = "not attempted";
    String total_lesson_status = "unknown";
    Double total_score = 0.0;

    for (int i = 0; i < cmiNames.length(); i++) {
        JSONObject cmi = cmis.getJSONObject(cmiNames.getString(0));
        String typeCmi = manifestResources.get(recursos.get(cmiNames.getString(i)));

        String completion_status = null;
        String success_status = null;
        Double max_score = null;
        Double min_score = null;
        Double raw_score = null;
        Double scaled_score = null;
        Long scaled_score_long = null;
        String suspend_data = cmi.getJSONObject("cmi.suspend_data").getString("value");

        if (cmi.getJSONObject("cmi.core.lesson_status") != null) { // 1.2
            String lesson_status = cmi.getJSONObject("cmi.core.lesson_status").getString("value");
            //"passed", "completed", "failed", "incomplete", "browsed", "not attempted"
            if ("passed".equals(lesson_status)) {
                success_status = "passed";
                completion_status = "completed";
            } else if ("failed".equals(lesson_status)) {
                success_status = "failed";
                completion_status = "completed";
            } else if ("completed".equals(lesson_status)) {
                success_status = "passed"; // or passed
                completion_status = "completed";
            } else if ("browsed".equals(lesson_status)) {
                success_status = "passed";
                completion_status = "completed";
            } else if ("incomplete".equals(lesson_status)) {
                success_status = "unknown";
                completion_status = "incomplete";
            } else if ("not attempted".equals(lesson_status)) {
                success_status = "unknown";
                completion_status = "not attempted";
                if (suspend_data.contains("1")) {
                    completion_status = "completed";
                    if (suspend_data.contains("0")) {
                        completion_status = "incomplete";
                    }
                    tryResultData.replaceAll("\"not attempted\"", "\"" + completion_status + "\"");
                }
            }
            max_score = cmi.getJSONObject("cmi.core.score.max").getDouble("value", 100);
            min_score = cmi.getJSONObject("cmi.core.score.min").getDouble("value", 0);
            raw_score = cmi.getJSONObject("cmi.core.score.raw").getDouble("value",
                    "asset".equals(typeCmi) ? 100 : 0);
            scaled_score = new Double(Math.round((raw_score * 100) / (max_score - min_score)));
            scaled_score_long = Math.round(scaled_score);
        } else { // 1.3
            //"completed", "incomplete", "not attempted", "unknown"
            completion_status = cmi.getJSONObject("cmi.completion_status").getString("value");
            //"passed", "failed", "unknown"
            success_status = cmi.getJSONObject("cmi.success_status").getString("value");
            max_score = cmi.getJSONObject("cmi.score.max").getDouble("value", 100);
            min_score = cmi.getJSONObject("cmi.score.min").getDouble("value", 0);
            raw_score = cmi.getJSONObject("cmi.score.raw").getDouble("value",
                    "asset".equals(typeCmi) ? 100 : 0);
            scaled_score = new Double(Math.round((raw_score * 100) / (max_score - min_score)));
            scaled_score = cmi.getJSONObject("cmi.score.scaled").getDouble("value", -1) != -1
                    ? (cmi.getJSONObject("cmi.score.scaled").getDouble("value") * (max_score - min_score)
                            + min_score)
                    : scaled_score;
            scaled_score_long = Math.round(scaled_score);
        }
        completion_statuses.add(completion_status);
        success_statuses.add(success_status);
        scores.add(scaled_score_long);
    }

    if (manifestItems.size() <= 1) {
        if (completion_statuses.size() == 1) {
            total_completion_status = completion_statuses.get(0);
        }
        if (success_statuses.size() == 1) {
            total_lesson_status = success_statuses.get(0);
        }
    } else {
        if (success_statuses.size() < manifestItems.size()) {
            total_lesson_status = "unknown";
        } else if (success_statuses.size() == manifestItems.size()) {
            for (int i = 0; i < success_statuses.size(); i++) {
                if ("unknown".equals(success_statuses.get(i))) {
                    total_lesson_status = "unknown";
                    break;
                }
                if ("passed".equals(success_statuses.get(i))) {
                    if ("passed".equals(total_lesson_status)) {
                        total_lesson_status = "passed";
                    }
                    if ("failed".equals(total_lesson_status)) {
                        total_lesson_status = "unknown";
                        break;
                    }
                }
                if ("failed".equals(success_statuses.get(i))) {
                    if ("passed".equals(total_lesson_status)) {
                        total_lesson_status = "unknown";
                        break;
                    }
                    if ("failed".equals(total_lesson_status)) {
                        total_lesson_status = "failed";
                    }
                }
            }
        }
        if (completion_statuses.size() < manifestItems.size()) {
            if (completion_statuses.size() <= 1) {
                total_completion_status = completion_statuses.get(0).equals("completed") ? "incomplete"
                        : completion_statuses.get(0);
            } else {
                total_completion_status = "incomplete";
            }
        } else if (completion_statuses.size() == manifestItems.size()) {
            for (int i = 0; i < completion_statuses.size(); i++) {
                total_score += scores.get(i);
                if ("incomplete".equals(completion_statuses.get(i))) {
                    total_completion_status = "incomplete";
                    break;
                }
                if ("completed".equals(completion_statuses.get(i))) {
                    if ("not attempted".equals(total_completion_status)) {
                        total_completion_status = "completed";
                    }
                    if ("unknown".equals(total_completion_status)) {
                        total_completion_status = "incomplete";
                        break;
                    }
                }
                if ("not attempted".equals(completion_statuses.get(i))) {
                    if ("completed".equals(total_completion_status)) {
                        total_completion_status = "incomplete";
                        break;
                    }
                    if ("unknown".equals(total_completion_status)) {
                        total_completion_status = "unknown";
                    }
                }
                if ("unknown".equals(completion_statuses.get(i))) {
                    if ("completed".equals(total_completion_status)) {
                        total_completion_status = "incomplete";
                        break;
                    }
                    if ("unknown".equals(total_completion_status)
                            || "not attempted".equals(total_completion_status)) {
                        total_completion_status = "unknown";
                    }
                }
            }
        }
    }

    for (int i = 0; i < scores.size(); i++) {
        total_score += scores.get(i);
    }
    total_score = total_score / (manifestItems.size() > 0 ? manifestItems.size() : 1);

    if ("incomplete".equals(total_completion_status) || "completed".equals(total_completion_status)) {
        learningActivityTry.setTryResultData(tryResultData);
        learningActivityTry.setResult(Math.round(total_score));

        if (Math.round(total_score) >= master_score || "passed".equals(total_lesson_status)) {
            Date endDate = new Date(System.currentTimeMillis());
            learningActivityTry.setEndDate(endDate);
        }

        learningActivityTryLocalService.updateLearningActivityTry(learningActivityTry);

        // If SCO says that the activity has been passed, then the learning activity result has to be marked as passed
        if ("passed".equals(total_lesson_status)) {
            LearningActivityResult laresult = learningActivityResultLocalService
                    .getByActIdAndUserId(learningActivityTry.getActId(), userId);
            if (!laresult.getPassed()) {
                laresult.setPassed(true);
                laresult.setEndDate(new Date(System.currentTimeMillis()));
                learningActivityResultLocalService.updateLearningActivityResult(laresult);
                if (laresult.getPassed()) {
                    moduleResultLocalService.update(laresult);
                }
            }
        }
        // If SCO says that the activity has been failed, then the learning activity result has to be marked as failed

        if ("failed".equals(total_lesson_status)) {
            LearningActivityResult laresult = learningActivityResultLocalService
                    .getByActIdAndUserId(learningActivityTry.getActId(), userId);
            if (!laresult.getPassed()) {
                laresult.setPassed(false);
                laresult.setEndDate(new Date(System.currentTimeMillis()));
                learningActivityResultLocalService.updateLearningActivityResult(laresult);
                moduleResultLocalService.update(laresult);

            }
        }

    }

    return this.getByActIdAndUserId(learningActivityTry.getActId(), userId);
}

From source file:com.liferay.lms.service.impl.LearningActivityResultLocalServiceImpl.java

License:Open Source License

public LearningActivityResult update(long latId, String tryResultData, String imsmanifest, long userId)
        throws SystemException, PortalException {
    LearningActivityTry learningActivityTry = learningActivityTryLocalService.getLearningActivityTry(latId);
    if (userId != learningActivityTry.getUserId()) {
        throw new PortalException();
    }//from   w ww .ja va 2s. com

    LearningActivity learningActivity = learningActivityLocalService
            .getLearningActivity(learningActivityTry.getActId());
    boolean completedAsPassed = GetterUtil.getBoolean(LearningActivityLocalServiceUtil
            .getExtraContentValue(learningActivityTry.getActId(), "completedAsPassed"), false);
    long passPuntuation = learningActivity.getPasspuntuation();
    List<String> manifestItems = new ArrayList<String>();
    Map<String, String> recursos = new HashMap<String, String>();

    Map<String, String> manifestResources = new HashMap<String, String>();
    boolean isPureAsset = false;
    long scos = 0;
    long assets = 0;

    try {
        if (Validator.isNotNull(imsmanifest)) {
            Document imsdocument = SAXReaderUtil.read(imsmanifest);
            List<Element> resources = new ArrayList<Element>();
            resources = imsdocument.getRootElement().element("resources").elements("resource");
            isPureAsset = true;
            for (Element resource : resources) {
                String identifier = resource.attributeValue("identifier");
                String type = resource.attributeValue("scormType");
                String type2 = resource.attributeValue("scormtype");
                String type3 = type != null ? type : type2 != null ? type2 : "asset";
                if (!"asset".equalsIgnoreCase(type3)) {
                    isPureAsset = false;
                    scos++;
                } else {
                    assets++;
                }
                manifestResources.put(identifier, type3);
            }
            List<Element> items = new ArrayList<Element>();
            items.addAll(imsdocument.getRootElement().element("organizations").elements("organization").get(0)
                    .elements("item"));
            for (int i = 0; i < items.size(); i++) {
                Element item = items.get(i);
                String identifier = item.attributeValue("identifier");
                String identifierref = item.attributeValue("identifierref");
                if (identifier != null && !"".equals(identifier) && identifierref != null
                        && !"".equals(identifierref)) {
                    manifestItems.add(identifier);
                    recursos.put(identifier, identifierref);
                }
                items.addAll(item.elements("item"));
            }
        }
    } catch (DocumentException e) {
    } catch (Exception e) {
        e.printStackTrace();
    }

    Long master_score = new Integer(learningActivity.getPasspuntuation()).longValue();

    JSONObject scorm = JSONFactoryUtil.createJSONObject();
    scorm = JSONFactoryUtil.createJSONObject(tryResultData);

    JSONObject organizations = scorm.getJSONObject("organizations");
    JSONArray organizationNames = organizations.names();
    JSONObject organization = organizations.getJSONObject(organizationNames.getString(0));

    JSONObject cmis = organization.getJSONObject("cmi");
    JSONArray cmiNames = cmis.names();

    List<String> completion_statuses = new ArrayList<String>();
    List<String> success_statuses = new ArrayList<String>();
    List<Long> scores = new ArrayList<Long>();

    String total_completion_status = "not attempted";
    String total_lesson_status = "";
    Double total_score = 0.0;

    if (cmis.length() == 0) { // Asset
        if (isPureAsset) {
            for (int i = 0; i < manifestItems.size(); i++) {
                completion_statuses.add("completed");
                success_statuses.add("passed");
                scores.add(new Long(100));
            }
            total_completion_status = "completed";
            total_lesson_status = "passed";
        } else {
            throw new PortalException();
        }
    } else {
        for (int i = 0; i < assets; i++) {
            completion_statuses.add("completed");
            success_statuses.add("passed");
            //scores.add(new Long(100));
        }
        for (int i = 0; i < cmiNames.length(); i++) {
            JSONObject cmi = cmis.getJSONObject(cmiNames.getString(i));
            String typeCmi = manifestResources.get(recursos.get(cmiNames.getString(i)));

            String completion_status = null;
            String success_status = null;
            Double max_score = null;
            Double min_score = null;
            Double raw_score = null;
            Double scaled_score = null;
            Long scaled_score_long = null;
            String suspend_data = cmi.getJSONObject("cmi.suspend_data").getString("value");

            if (cmi.getJSONObject("cmi.core.lesson_status") != null) { // 1.2
                String lesson_status = cmi.getJSONObject("cmi.core.lesson_status").getString("value");
                //"passed", "completed", "failed", "incomplete", "browsed", "not attempted"
                if ("passed".equals(lesson_status)) {
                    success_status = "passed";
                    completion_status = "completed";
                } else if ("failed".equals(lesson_status)) {
                    success_status = "failed";
                    completion_status = "completed";
                } else if ("completed".equals(lesson_status)) {
                    if (completedAsPassed) {
                        success_status = "passed"; // or passed
                    } else {
                        success_status = "unknown";
                    }
                    completion_status = "completed";
                } else if ("browsed".equals(lesson_status)) {
                    success_status = "passed";
                    completion_status = "completed";
                } else if ("incomplete".equals(lesson_status)) {
                    success_status = "unknown";
                    completion_status = "incomplete";
                } else if ("not attempted".equals(lesson_status)) {
                    success_status = "unknown";
                    completion_status = "not attempted";
                    if (suspend_data.contains("1")) {
                        completion_status = "completed";
                        if (suspend_data.contains("0")) {
                            completion_status = "incomplete";
                        }
                        tryResultData.replaceAll("\"not attempted\"", "\"" + completion_status + "\"");
                    }
                }
                max_score = cmi.getJSONObject("cmi.core.score.max").getDouble("value", 100);
                min_score = cmi.getJSONObject("cmi.core.score.min").getDouble("value", 0);
                raw_score = cmi.getJSONObject("cmi.core.score.raw").getDouble("value",
                        "asset".equals(typeCmi) ? max_score : 0);
                if ("passed".equals(success_status) && raw_score == 0 && completedAsPassed) {
                    raw_score = (double) passPuntuation;
                }
                scaled_score = new Double(Math.round((raw_score * 100) / (max_score - min_score)));
                scaled_score_long = Math.round(scaled_score);
            } else { // 1.3
                //"completed", "incomplete", "not attempted", "unknown"
                completion_status = cmi.getJSONObject("cmi.completion_status").getString("value");
                if ("completed".equals(completion_status)) {
                    if (completedAsPassed) {
                        success_status = "passed"; // or passed
                    } else {
                        success_status = cmi.getJSONObject("cmi.success_status").getString("value");
                    }
                } else {
                    success_status = cmi.getJSONObject("cmi.success_status").getString("value");
                }
                //"passed", "failed", "unknown"

                max_score = cmi.getJSONObject("cmi.score.max").getDouble("value", 100);
                min_score = cmi.getJSONObject("cmi.score.min").getDouble("value", 0);
                raw_score = cmi.getJSONObject("cmi.score.raw").getDouble("value",
                        "asset".equals(typeCmi) ? 100 : 0);
                if ("passed".equals(success_status) && raw_score == 0 && completedAsPassed) {
                    raw_score = (double) passPuntuation;
                }
                scaled_score = new Double(Math.round((raw_score * 100) / (max_score - min_score)));
                scaled_score = cmi.getJSONObject("cmi.score.scaled").getDouble("value", -1) != -1
                        ? (cmi.getJSONObject("cmi.score.scaled").getDouble("value") * (max_score - min_score)
                                + min_score)
                        : scaled_score;
                scaled_score_long = Math.round(scaled_score);
            }
            completion_statuses.add(completion_status);
            success_statuses.add(success_status);
            scores.add(scaled_score_long);
        }
    }

    if (!isPureAsset) {
        if (manifestItems.size() <= 1) {
            if (completion_statuses.size() == 1) {
                total_completion_status = completion_statuses.get(0);
            }
            if (success_statuses.size() == 1) {
                total_lesson_status = success_statuses.get(0);
            }
        } else {
            if (success_statuses.size() < manifestItems.size()) {
                total_lesson_status = "unknown";
            } else if (success_statuses.size() == manifestItems.size()) {
                for (int i = 0; i < success_statuses.size(); i++) {
                    if ("unknown".equals(success_statuses.get(i))) {
                        total_lesson_status = "unknown";
                        break;
                    }
                    if ("passed".equals(success_statuses.get(i))) {
                        if ("passed".equals(total_lesson_status) || "".equals(total_lesson_status)) {
                            total_lesson_status = "passed";
                        }
                        if ("failed".equals(total_lesson_status)) {
                            total_lesson_status = "unknown";
                            break;
                        }
                    }
                    if ("failed".equals(success_statuses.get(i))) {
                        if ("passed".equals(total_lesson_status)) {
                            total_lesson_status = "unknown";
                            break;
                        }
                        if ("failed".equals(total_lesson_status)) {
                            total_lesson_status = "failed";
                        }
                    }
                }
            }
            if (completion_statuses.size() < manifestItems.size()) {
                if (completion_statuses.size() <= 1) {
                    total_completion_status = completion_statuses.get(0).equals("completed") ? "incomplete"
                            : completion_statuses.get(0);
                } else {
                    total_completion_status = "incomplete";
                }
            } else if (completion_statuses.size() == manifestItems.size()) {
                for (int i = 0; i < completion_statuses.size(); i++) {
                    //total_score += scores.get(i);
                    if ("incomplete".equals(completion_statuses.get(i))) {
                        total_completion_status = "incomplete";
                        break;
                    }
                    if ("completed".equals(completion_statuses.get(i))) {
                        if ("not attempted".equals(total_completion_status)) {
                            total_completion_status = "completed";
                        }
                        if ("unknown".equals(total_completion_status)) {
                            total_completion_status = "incomplete";
                            break;
                        }
                    }
                    if ("not attempted".equals(completion_statuses.get(i))) {
                        if ("completed".equals(total_completion_status)) {
                            total_completion_status = "incomplete";
                            break;
                        }
                        if ("unknown".equals(total_completion_status)) {
                            total_completion_status = "unknown";
                        }
                    }
                    if ("unknown".equals(completion_statuses.get(i))) {
                        if ("completed".equals(total_completion_status)) {
                            total_completion_status = "incomplete";
                            break;
                        }
                        if ("unknown".equals(total_completion_status)
                                || "not attempted".equals(total_completion_status)) {
                            total_completion_status = "unknown";
                        }
                    }
                }
            }
        }
    }

    for (int i = 0; i < scores.size(); i++) {
        total_score += scores.get(i);
    }
    if (scos > 0) {
        total_score = total_score / (scos);
    } else {
        total_score = total_score / ((scos + assets) > 0 ? (scos + assets) : 1);
    }
    if ("incomplete".equals(total_completion_status) || "completed".equals(total_completion_status)) {
        learningActivityTry.setTryResultData(tryResultData);
        learningActivityTry.setResult(Math.round(total_score));
        if (Math.round(total_score) >= master_score) {
            total_lesson_status = "passed";
        }
        learningActivityTryLocalService.updateLearningActivityTry(learningActivityTry);

        // If SCO says that the activity has been passed, then the learning activity result has to be marked as passed
        if ("passed".equals(total_lesson_status)) {
            LearningActivityResult laresult = learningActivityResultLocalService
                    .getByActIdAndUserId(learningActivityTry.getActId(), userId);
            if (!laresult.getPassed()) {
                laresult.setPassed(true);
                laresult.setEndDate(new Date(System.currentTimeMillis()));
                learningActivityResultLocalService.updateLearningActivityResult(laresult);
                if (laresult.getPassed()) {
                    moduleResultLocalService.update(laresult);
                }
            }
        }
        // If SCO says that the activity has been failed, then the learning activity result has to be marked as failed

        if ("failed".equals(total_lesson_status)) {
            LearningActivityResult laresult = learningActivityResultLocalService
                    .getByActIdAndUserId(learningActivityTry.getActId(), userId);
            if (laresult.getEndDate() == null) {
                laresult.setPassed(false);
                laresult.setEndDate(new Date(System.currentTimeMillis()));
                learningActivityResultLocalService.updateLearningActivityResult(laresult);
                moduleResultLocalService.update(laresult);

            }
        }

    }

    //auditing
    if (learningActivity != null) {
        AuditingLogFactory.audit(learningActivity.getCompanyId(), learningActivity.getGroupId(),
                LearningActivityResult.class.getName(), learningActivity.getPrimaryKey(),
                learningActivity.getUserId(), AuditConstants.UPDATE, null);
    }

    return this.getByActIdAndUserId(learningActivityTry.getActId(), userId);
}

From source file:com.liferay.lms.service.impl.LearningActivityTryLocalServiceImpl.java

License:Open Source License

public HashMap<Long, Long> getMapTryResultData(long actId, long userId)
        throws SystemException, PortalException {
    HashMap<Long, Long> answersMap = new HashMap<Long, Long>();
    LearningActivityTry actTry = getLastLearningActivityTryByActivityAndUser(actId, userId);
    String xml = actTry.getTryResultData();

    if (xml.equals(""))
        return answersMap;

    Document document;//w w w .ja v a2  s  .c om
    try {
        document = SAXReaderUtil.read(xml);
        Element rootElement = document.getRootElement();

        for (Element question : rootElement.elements("question")) {
            for (Element answer : question.elements("answer")) {
                answersMap.put(Long.valueOf(question.attributeValue("id")),
                        Long.valueOf(answer.attributeValue("id")));
            }
        }
    } catch (DocumentException e) {
    }

    return answersMap;
}

From source file:com.liferay.lms.service.impl.TestQuestionLocalServiceImpl.java

License:Open Source License

public void importXML(long actId, Document document)
        throws DocumentException, SystemException, PortalException {
    Element rootElement = document.getRootElement();
    for (Element question : rootElement.elements("question")) {
        importXMLQuestion(actId, question);
    }// www .ja  v a 2  s .  c  om

}

From source file:com.liferay.lms.servlet.SCORMFileServerServlet.java

License:Open Source License

/**
 * Procesa los metodos HTTP GET y POST.<br>
 * Busca en la ruta que se le ha pedido el comienzo del directorio
 * "contenidos" y sirve el fichero./*  ww w  .j av a  2s . com*/
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws ServletException, java.io.IOException {
    String mime_type;
    String charset;
    String patharchivo;
    String uri;

    try {
        User user = PortalUtil.getUser(request);

        if (user == null) {
            String userId = null;
            String companyId = null;
            Cookie[] cookies = ((HttpServletRequest) request).getCookies();
            if (Validator.isNotNull(cookies)) {
                for (Cookie c : cookies) {
                    if ("COMPANY_ID".equals(c.getName())) {
                        companyId = c.getValue();
                    } else if ("ID".equals(c.getName())) {
                        userId = hexStringToStringByAscii(c.getValue());
                    }
                }
            }

            if (userId != null && companyId != null) {
                try {
                    Company company = CompanyLocalServiceUtil.getCompany(Long.parseLong(companyId));
                    Key key = company.getKeyObj();

                    String userIdPlain = Encryptor.decrypt(key, userId);

                    user = UserLocalServiceUtil.getUser(Long.valueOf(userIdPlain));

                    // Now you can set the liferayUser into a thread local
                    // for later use or
                    // something like that.

                } catch (Exception pException) {
                    throw new RuntimeException(pException);
                }
            }
        }

        String rutaDatos = SCORMContentLocalServiceUtil.getBaseDir();

        // Se comprueba que el usuario tiene permisos para acceder.
        // Damos acceso a todo el mundo al directorio "personalizacion",
        // para permitir mostrar a todos la pantalla de identificacion.
        uri = URLDecoder.decode(request.getRequestURI(), "UTF-8");
        uri = uri.substring(uri.indexOf("scorm/") + "scorm/".length());
        patharchivo = rutaDatos + "/" + uri;

        String[] params = uri.split("/");
        long groupId = GetterUtil.getLong(params[1]);
        String uuid = params[2];
        SCORMContent scormContent = SCORMContentLocalServiceUtil.getSCORMContentByUuidAndGroupId(uuid, groupId);

        boolean allowed = false;
        if (user == null) {
            user = UserLocalServiceUtil.getDefaultUser(PortalUtil.getDefaultCompanyId());
        }
        PermissionChecker pc = PermissionCheckerFactoryUtil.create(user);
        allowed = pc.hasPermission(groupId, SCORMContent.class.getName(), scormContent.getScormId(),
                ActionKeys.VIEW);
        if (!allowed) {
            AssetEntry scormAsset = AssetEntryLocalServiceUtil.getEntry(SCORMContent.class.getName(),
                    scormContent.getPrimaryKey());
            long scormAssetId = scormAsset.getEntryId();
            int typeId = new Long((new SCORMLearningActivityType()).getTypeId()).intValue();
            long[] groupIds = user.getGroupIds();
            for (long gId : groupIds) {
                List<LearningActivity> acts = LearningActivityLocalServiceUtil
                        .getLearningActivitiesOfGroupAndType(gId, typeId);
                for (LearningActivity act : acts) {
                    String entryId = LearningActivityLocalServiceUtil.getExtraContentValue(act.getActId(),
                            "assetEntry");
                    if (Validator.isNotNull(entryId) && Long.valueOf(entryId) == scormAssetId) {
                        allowed = pc.hasPermission(gId, LearningActivity.class.getName(), act.getActId(),
                                ActionKeys.VIEW);
                        if (allowed) {
                            break;
                        }
                    }
                }
                if (allowed) {
                    break;
                }
            }

        }
        if (allowed) {

            File archivo = new File(patharchivo);

            // Si el archivo existe y no es un directorio se sirve. Si no,
            // no se hace nada.
            if (archivo.exists() && archivo.isFile()) {

                // El content type siempre antes del printwriter
                mime_type = MimeTypesUtil.getContentType(archivo);
                charset = "";
                if (archivo.getName().toLowerCase().endsWith(".html")
                        || archivo.getName().toLowerCase().endsWith(".htm")) {
                    mime_type = "text/html";
                    if (isISO(FileUtils.readFileToString(archivo))) {
                        charset = "ISO-8859-1";
                    }
                }
                if (archivo.getName().toLowerCase().endsWith(".swf")) {
                    mime_type = "application/x-shockwave-flash";
                }
                if (archivo.getName().toLowerCase().endsWith(".mp4")) {
                    mime_type = "video/mp4";
                }
                if (archivo.getName().toLowerCase().endsWith(".flv")) {
                    mime_type = "video/x-flv";
                }
                response.setContentType(mime_type);
                if (Validator.isNotNull(charset)) {
                    response.setCharacterEncoding(charset);

                }
                response.addHeader("Content-Type",
                        mime_type + (Validator.isNotNull(charset) ? "; " + charset : ""));
                /*if (archivo.getName().toLowerCase().endsWith(".swf")
                      || archivo.getName().toLowerCase().endsWith(".flv")) {
                   response.addHeader("Content-Length",
                String.valueOf(archivo.length()));
                }
                */
                if (archivo.getName().toLowerCase().endsWith("imsmanifest.xml")) {
                    FileInputStream fis = new FileInputStream(patharchivo);

                    String sco = ParamUtil.get(request, "scoshow", "");
                    Document manifest = SAXReaderUtil.read(fis);
                    if (sco.length() > 0) {

                        Element organizatEl = manifest.getRootElement().element("organizations")
                                .element("organization");
                        Element selectedItem = selectItem(organizatEl, sco);
                        if (selectedItem != null) {
                            selectedItem.detach();
                            java.util.List<Element> items = organizatEl.elements("item");
                            for (Element item : items) {

                                organizatEl.remove(item);
                            }
                            organizatEl.add(selectedItem);
                        }
                    }
                    //clean unused resources.
                    Element resources = manifest.getRootElement().element("resources");
                    java.util.List<Element> theResources = resources.elements("resource");
                    Element organizatEl = manifest.getRootElement().element("organizations")
                            .element("organization");
                    java.util.List<String> identifiers = getIdentifierRefs(organizatEl);
                    for (Element resource : theResources) {
                        String identifier = resource.attributeValue("identifier");
                        if (!identifiers.contains(identifier)) {
                            resources.remove(resource);
                        }
                    }
                    response.getWriter().print(manifest.asXML());
                    fis.close();
                    return;

                }

                if (mime_type.startsWith("text") || mime_type.endsWith("javascript")
                        || mime_type.equals("application/xml")) {

                    java.io.OutputStream out = response.getOutputStream();
                    FileInputStream fis = new FileInputStream(patharchivo);

                    byte[] buffer = new byte[512];
                    int i = 0;

                    while (fis.available() > 0) {
                        i = fis.read(buffer);
                        if (i == 512)
                            out.write(buffer);
                        else
                            out.write(buffer, 0, i);

                    }

                    fis.close();
                    out.flush();
                    out.close();
                    return;
                }
                //If not manifest
                String fileName = archivo.getName();
                long length = archivo.length();
                long lastModified = archivo.lastModified();
                String eTag = fileName + "_" + length + "_" + lastModified;
                long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }
                long ifModifiedSince = request.getDateHeader("If-Modified-Since");
                if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }

                // If-Match header should contain "*" or ETag. If not, then return 412.
                String ifMatch = request.getHeader("If-Match");
                if (ifMatch != null && !matches(ifMatch, eTag)) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return;
                }

                // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
                long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
                if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return;
                }

                // Validate and process range -------------------------------------------------------------

                // Prepare some variables. The full Range represents the complete file.
                Range full = new Range(0, length - 1, length);
                List<Range> ranges = new ArrayList<Range>();

                // Validate and process Range and If-Range headers.
                String range = request.getHeader("Range");
                if (range != null) {

                    // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
                    if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
                        response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                        return;
                    }

                    // If-Range header should either match ETag or be greater then LastModified. If not,
                    // then return full file.
                    String ifRange = request.getHeader("If-Range");
                    if (ifRange != null && !ifRange.equals(eTag)) {
                        try {
                            long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                            if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                                ranges.add(full);
                            }
                        } catch (IllegalArgumentException ignore) {
                            ranges.add(full);
                        }
                    }

                    // If any valid If-Range header, then process each part of byte range.
                    if (ranges.isEmpty()) {
                        for (String part : range.substring(6).split(",")) {
                            // Assuming a file with length of 100, the following examples returns bytes at:
                            // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                            long start = sublong(part, 0, part.indexOf("-"));
                            long end = sublong(part, part.indexOf("-") + 1, part.length());

                            if (start == -1) {
                                start = length - end;
                                end = length - 1;
                            } else if (end == -1 || end > length - 1) {
                                end = length - 1;
                            }

                            // Check if Range is syntactically valid. If not, then return 416.
                            if (start > end) {
                                response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                                return;
                            }

                            // Add range.
                            ranges.add(new Range(start, end, length));
                        }
                    }
                }
                boolean acceptsGzip = false;
                String disposition = "inline";

                if (mime_type.startsWith("text")) {
                    //String acceptEncoding = request.getHeader("Accept-Encoding");
                    // acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
                    // mime_type += ";charset=UTF-8";
                }

                // Else, expect for images, determine content disposition. If content type is supported by
                // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
                else if (!mime_type.startsWith("image")) {
                    String accept = request.getHeader("Accept");
                    disposition = accept != null && accepts(accept, mime_type) ? "inline" : "attachment";
                }

                // Initialize response.
                response.reset();
                response.setBufferSize(DEFAULT_BUFFER_SIZE);
                response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("ETag", eTag);
                response.setDateHeader("Last-Modified", lastModified);
                response.setDateHeader("Expires", expires);

                // Send requested file (part(s)) to client ------------------------------------------------

                // Prepare streams.
                RandomAccessFile input = null;
                OutputStream output = null;

                try {
                    // Open streams.
                    input = new RandomAccessFile(archivo, "r");
                    output = response.getOutputStream();

                    if (ranges.isEmpty() || ranges.get(0) == full) {

                        // Return full file.
                        Range r = full;
                        response.setContentType(mime_type);
                        response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

                        if (content) {

                            // Content length is not directly predictable in case of GZIP.
                            // So only add it if there is no means of GZIP, else browser will hang.
                            response.setHeader("Content-Length", String.valueOf(r.length));

                            // Copy full range.
                            copy(input, output, r.start, r.length);
                        }

                    } else if (ranges.size() == 1) {

                        // Return single part of file.
                        Range r = ranges.get(0);
                        response.setContentType(mime_type);
                        response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
                        response.setHeader("Content-Length", String.valueOf(r.length));
                        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                        if (content) {
                            // Copy single part range.
                            copy(input, output, r.start, r.length);
                        }

                    } else {

                        // Return multiple parts of file.
                        response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
                        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                        if (content) {
                            // Cast back to ServletOutputStream to get the easy println methods.
                            ServletOutputStream sos = (ServletOutputStream) output;

                            // Copy multi part range.
                            for (Range r : ranges) {
                                // Add multipart boundary and header fields for every range.
                                sos.println();
                                sos.println("--" + MULTIPART_BOUNDARY);
                                sos.println("Content-Type: " + mime_type);
                                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                                // Copy single part range of multi part range.
                                copy(input, output, r.start, r.length);
                            }

                            // End with multipart boundary.
                            sos.println();
                            sos.println("--" + MULTIPART_BOUNDARY + "--");
                        }
                    }
                } finally {
                    // Gently close streams.
                    close(output);
                    close(input);
                }
            } else {
                //java.io.OutputStream out = response.getOutputStream();
                response.sendError(404);
                //out.write(uri.getBytes());
            }
        } else {
            response.sendError(401);
        }
    } catch (Exception e) {
        System.out.println("Error en el processRequest() de ServidorArchivos: " + e.getMessage());
    }
}