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

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

Introduction

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

Prototype

public String attributeValue(String name);

Source Link

Usage

From source file:com.liferay.layout.set.prototype.exportimport.data.handler.test.LayoutSetPrototypeStagedModelDataHandlerTest.java

License:Open Source License

protected Layout importLayoutFromLAR(StagedModel stagedModel) throws DocumentException, IOException {

    LayoutSetPrototype layoutSetPrototype = (LayoutSetPrototype) stagedModel;

    String fileName = layoutSetPrototype.getLayoutSetPrototypeId() + ".lar";

    String modelPath = ExportImportPathUtil.getModelPath(stagedModel, fileName);

    try (InputStream inputStream = portletDataContext.getZipEntryAsInputStream(modelPath)) {

        ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(inputStream);

        Document document = UnsecureSAXReaderUtil.read(zipReader.getEntryAsString("manifest.xml"));

        Element rootElement = document.getRootElement();

        Element layoutElement = rootElement.element("Layout");

        List<Element> elements = layoutElement.elements();

        List<Layout> importedLayouts = new ArrayList<>(elements.size());

        for (Element element : elements) {
            String layoutPrototypeUuid = element.attributeValue("layout-prototype-uuid");

            if (Validator.isNotNull(layoutPrototypeUuid)) {
                String path = element.attributeValue("path");

                Layout layout = (Layout) portletDataContext.fromXML(zipReader.getEntryAsString(path));

                importedLayouts.add(layout);
            }//from  ww  w  . j  a v  a2 s  .  c o  m
        }

        Assert.assertEquals(importedLayouts.toString(), 1, importedLayouts.size());

        return importedLayouts.get(0);
    } finally {
        zipReader.close();
    }
}

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

License:Open Source License

public HashMap<String, String> convertXMLExtraContentToHashMap(long actId)
        throws SystemException, PortalException {
    HashMap<String, String> hashMap = new HashMap<String, String>();
    String xml = "";

    try {/*  ww w . j  a v  a2  s  . c  o m*/
        LearningActivity activity = learningActivityPersistence.fetchByPrimaryKey(actId);

        if (activity != null && !activity.getExtracontent().equals("")) {
            xml = activity.getExtracontent();
        } else {
            return hashMap;
        }
        Document document;

        document = SAXReaderUtil.read(xml);
        Element rootElement = document.getRootElement();

        for (Element key : rootElement.elements()) {

            if (key.getName().contains("document")) {
                hashMap.put(key.getName(), key.attributeValue("id"));
            } else {
                hashMap.put(key.getName(), key.getText());
            }

        }

    } catch (DocumentException e) {
    }

    return hashMap;
}

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();
    }//from ww  w .  ja  v  a  2s  .  c o  m

    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 www  .ja v a 2 s . c  o  m*/

    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;//from   w  w  w.j  a v  a 2  s . c o m
    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.SCORMContentLocalServiceImpl.java

License:Open Source License

public SCORMContent addSCORMContent(String title, String description, File scormfile, boolean ciphered,
        ServiceContext serviceContext) throws SystemException, PortalException, IOException {

    SCORMContent scocontent = scormContentPersistence
            .create(counterLocalService.increment(SCORMContent.class.getName()));
    long userId = serviceContext.getUserId();
    scocontent.setCompanyId(serviceContext.getCompanyId());
    String uuid = serviceContext.getUuid();
    if (Validator.isNotNull(uuid)) {
        scocontent.setUuid(uuid);//from   ww  w  .j  av a  2 s .  c  o  m
    }
    scocontent.setGroupId(serviceContext.getScopeGroupId());
    scocontent.setUserId(userId);
    scocontent.setDescription(description);
    scocontent.setTitle(title);
    scocontent.setCiphered(ciphered);
    scocontent.setStatus(WorkflowConstants.STATUS_APPROVED);
    scocontent.setExpandoBridgeAttributes(serviceContext);
    scormContentPersistence.update(scocontent, true);
    String dirScorm = getDirScormPath(scocontent);
    File dir = new File(dirScorm);
    String dirScormZip = getDirScormzipPath(scocontent);
    File dirZip = new File(dirScormZip);

    FileUtils.forceMkdir(dir);
    FileUtils.forceMkdir(dirZip);
    File scormFileZip = new File(dirZip.getAbsolutePath() + "/" + scocontent.getUuid() + ".zip");
    FileUtils.copyFile(scormfile, scormFileZip);
    try {
        ZipFile zipFile = new ZipFile(scormfile);
        zipFile.extractAll(dir.getCanonicalPath());
        File manifestfile = new File(dir.getCanonicalPath() + "/imsmanifest.xml");
        try {
            Document imsdocument = SAXReaderUtil.read(manifestfile);
            Element item = imsdocument.getRootElement().element("organizations").elements("organization").get(0)
                    .elements("item").get(0);
            String resourceid = item.attributeValue("identifierref");
            java.util.List<Element> resources = imsdocument.getRootElement().element("resources")
                    .elements("resource");
            for (Element resource : resources) {
                if (resource.attributeValue("identifier").equals(resourceid)) {
                    scocontent.setIndex(resource.attributeValue("href"));
                    scormContentPersistence.update(scocontent, true);
                }
            }
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (ZipException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {
        resourceLocalService.addResources(serviceContext.getCompanyId(), serviceContext.getScopeGroupId(),
                userId, SCORMContent.class.getName(), scocontent.getPrimaryKey(), false,
                serviceContext.isAddGroupPermissions(), serviceContext.isAddGuestPermissions());
    } else {

        resourceLocalService.addModelResources(serviceContext.getCompanyId(), serviceContext.getScopeGroupId(),
                userId, SCORMContent.class.getName(), scocontent.getPrimaryKey(),
                serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());

    }

    assetEntryLocalService.updateEntry(userId, scocontent.getGroupId(), SCORMContent.class.getName(),
            scocontent.getScormId(), scocontent.getUuid(), 0, serviceContext.getAssetCategoryIds(),
            serviceContext.getAssetTagNames(), true, null, null, new java.util.Date(System.currentTimeMillis()),
            null, ContentTypes.TEXT_HTML, scocontent.getTitle(), null,
            HtmlUtil.extractText(scocontent.getDescription()), getUrlManifest(scocontent), null, 0, 0, null,
            false);

    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(SCORMContent.class);

    indexer.reindex(scocontent);

    return scocontent;

}

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

License:Open Source License

private long getQuestionType(Element question) {
    long type = -1;
    if ("multichoice".equals(question.attributeValue("type"))
            && "true".equals(question.element("single").getText()))
        type = 0;/*from  w ww .j  av a2s . co  m*/
    else if ("multichoice".equals(question.attributeValue("type"))
            && "false".equals(question.element("single").getText()))
        type = 1;
    else if ("essay".equals(question.attributeValue("type"))
            || "numerical".equals(question.attributeValue("type"))
            || "shortanswer".equals(question.attributeValue("type")))
        type = 2;
    else if ("cloze".equals(question.attributeValue("type")))
        type = 3;
    else if ("draganddrop".equals(question.attributeValue("type")))
        type = 4;
    else if ("sort".equals(question.attributeValue("type")))
        type = 5;
    return type;
}

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.//from w ww.  j a  v  a2s .  c om
 */
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());
    }
}

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

License:Open Source License

private List<String> getIdentifierRefs(Element organizatEl) {
    java.util.List<String> ident = new java.util.ArrayList<String>();
    // TODO Auto-generated method stub
    java.util.List<Element> items = organizatEl.elements("item");
    for (Element item : items) {
        String identi = item.attributeValue("identifierref");
        ident.add(identi);/*from ww  w.j av  a 2  s  . c o  m*/
        java.util.List<String> subident = getIdentifierRefs(item);
        if (subident != null && subident.size() > 0) {
            ident.addAll(subident);
        }

    }
    return ident;
}

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

License:Open Source License

private Element selectItem(Element organizatEl, String sco) {
    java.util.List<Element> items = organizatEl.elements("item");
    for (Element item : items) {
        if (item.attributeValue("identifier").equals(sco)) {
            return item;
        }/*  w  w w . jav a 2  s  .c  o  m*/
        Element retorno = selectItem(item, sco);
        if (retorno != null) {
            return retorno;
        }
    }
    return null;
}