Example usage for java.util LinkedHashMap keySet

List of usage examples for java.util LinkedHashMap keySet

Introduction

In this page you can find the example usage for java.util LinkedHashMap keySet.

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:hydrograph.ui.propertywindow.propertydialog.PropertyDialog.java

private void savePropertiesInComponentModel(AbstractWidget eltWidget,
        LinkedHashMap<String, Object> properties) {
    LinkedHashMap<String, Object> tempPropert = properties;
    LinkedHashMap<String, Object> componentConfigurationProperties = componentProperties
            .getComponentConfigurationProperties();
    for (String propName : tempPropert.keySet()) {
        componentConfigurationProperties.put(propName, tempPropert.get(propName));
    }// ww w  .  ja  v  a2 s. com
}

From source file:biz.netcentric.cq.tools.actool.configReader.YamlConfigReader.java

private Map<String, Set<AuthorizableConfigBean>> getAuthorizablesMap(final List<LinkedHashMap> yamlMap,
        final AuthorizableValidator authorizableValidator) throws AcConfigBeanValidationException {
    final Set<String> alreadyProcessedGroups = new HashSet<String>();
    final Map<String, Set<AuthorizableConfigBean>> principalMap = new LinkedHashMap<String, Set<AuthorizableConfigBean>>();

    if (yamlMap == null) {
        return principalMap;
    }/*from ww w.jav a2  s . c o  m*/
    final Session session = null;

    for (final LinkedHashMap currentMap : yamlMap) {

        final String currentPrincipal = (String) currentMap.keySet().iterator().next();

        final Matcher matcher = forLoopPattern.matcher(currentPrincipal);
        if (matcher.find()) {
            LOG.info("Principal name {} matches FOR loop pattern. Unrolling {}", currentPrincipal,
                    currentMap.get(currentPrincipal));
            final List<AuthorizableConfigBean> groups = unrollGroupForLoop(currentPrincipal,
                    (List<Map<String, ?>>) currentMap.get(currentPrincipal), new HashMap<String, String>());
            for (final AuthorizableConfigBean group : groups) {
                final String principal = group.getPrincipalID();
                if (!alreadyProcessedGroups.add(principal)) {
                    throw new IllegalArgumentException(
                            "There is more than one group definition for group: " + principal);
                }
                if (authorizableValidator != null) {
                    authorizableValidator.validate(group);
                }
                final Set<AuthorizableConfigBean> tmpSet = new LinkedHashSet<AuthorizableConfigBean>();
                tmpSet.add(group);
                principalMap.put(principal, tmpSet);
            }
        } else {

            if (!alreadyProcessedGroups.add(currentPrincipal)) {
                throw new IllegalArgumentException(
                        "There is more than one group definition for group: " + currentPrincipal);
            }
            LOG.info("start reading group configuration");
            LOG.info("Found principal: {} in config", currentPrincipal);

            final LinkedHashSet<AuthorizableConfigBean> tmpSet = new LinkedHashSet<AuthorizableConfigBean>();
            principalMap.put(currentPrincipal, tmpSet);

            final List<Map<String, String>> currentPrincipalData = (List<Map<String, String>>) currentMap
                    .get(currentPrincipal);

            if (currentPrincipalData != null && !currentPrincipalData.isEmpty()) {

                for (final Map<String, String> currentPrincipalDataMap : currentPrincipalData) {
                    final AuthorizableConfigBean tmpPrincipalConfigBean = new AuthorizableConfigBean();
                    setupAuthorizableBean(tmpPrincipalConfigBean, currentPrincipalDataMap,
                            (String) currentPrincipal);
                    if (authorizableValidator != null) {
                        authorizableValidator.validate(tmpPrincipalConfigBean);
                    }
                    principalMap.get(currentPrincipal).add(tmpPrincipalConfigBean);
                }
            }
        }
    }
    return principalMap;

}

From source file:org.kuali.kra.meeting.CommitteeScheduleMinute.java

@Override
public String toString() {
    StringBuffer retVal = new StringBuffer(50);
    LinkedHashMap hm = toStringMapper();
    for (Object key : hm.keySet()) {
        retVal.append(key.toString()).append(" : ");
        try {/*from  w ww.jav  a  2s.  c  o m*/
            retVal.append(hm.get(key).toString());
        } catch (Exception e) {
            retVal.append("NPE problem");
        }
        retVal.append("\n");
    }
    return retVal.toString();
}

From source file:com.tacitknowledge.util.migration.DistributedMigrationProcess.java

/**
 * Applies necessary patches to the system.
 *
 * @param patchInfoStore of the system to run
 * @param context        information and resources that are available to the migration tasks
 * @return the number of <code>MigrationTask</code>s that have executed
 * @throws MigrationException if a migration fails
 * @Override//  w  w  w .  j  a v a 2 s .c o m
 */
public final int doMigrations(final PatchInfoStore patchInfoStore, final MigrationContext context)
        throws MigrationException {
    log.debug("Starting doMigrations");
    // Get all the migrations, with their launchers, then get the list of
    // just the migrations
    LinkedHashMap migrationsWithLaunchers = getMigrationTasksWithLaunchers();
    List migrations = new ArrayList();
    migrations.addAll(migrationsWithLaunchers.keySet());

    // make sure the migrations are okay, then sort them
    validateTasks(migrations);
    Collections.sort(migrations);

    validateControlledSystems(patchInfoStore);

    // determine how many tasks we're going to execute
    int taskCount = patchDryRun(patchInfoStore, migrationsWithLaunchers);

    if (taskCount > 0) {
        log.info("A total of " + taskCount + " patch tasks will execute.");
    } else {
        log.info("System up-to-date.  No patch tasks will execute.");
    }

    // See if we should execute
    if (isReadOnly()) {
        if (taskCount > 0) {
            throw new MigrationException("Unapplied patches exist, but read-only flag is set");
        }

        log.info("In read-only mode - skipping patch application");
        return 0;
    }

    // Roll through each migration, applying it if necessary
    taskCount = 0;
    for (Iterator i = migrations.iterator(); i.hasNext();) {
        MigrationTask task = (MigrationTask) i.next();
        int migrationLevel = task.getLevel().intValue();
        boolean shouldApplyPatch = getMigrationRunnerStrategy().shouldMigrationRun(migrationLevel,
                patchInfoStore);

        if (shouldApplyPatch && !forceSync) {
            // Execute the task in the context it was loaded from
            JdbcMigrationLauncher launcher = (JdbcMigrationLauncher) migrationsWithLaunchers.get(task);
            // Get all the contexts the task will execute in
            for (Iterator j = launcher.getContexts().keySet().iterator(); j.hasNext();) {
                MigrationContext launcherContext = (MigrationContext) j.next();
                applyPatch(launcherContext, task, true);
            }
            taskCount++;
        } else if (forceSync)// if a sync is forced, need to check all
        // the contexts to identify the ones out of
        // sync
        {
            boolean patchesApplied = false;
            ArrayList outOfSyncContexts = new ArrayList();

            // first need to iterate over all the contexts and determined
            // which one's are out of sync.
            // can't sync yet because if there are multiple contexts that
            // are out of sync, after the
            // first one is synced, the remaining one's have their patch
            // level updated via the
            // MigrationListener.migrationSuccessful event.
            JdbcMigrationLauncher launcher = (JdbcMigrationLauncher) migrationsWithLaunchers.get(task);
            for (Iterator j = launcher.getContexts().keySet().iterator(); j.hasNext();) {
                MigrationContext launcherContext = (MigrationContext) j.next();
                PatchInfoStore patchInfoStoreOfContext = (PatchInfoStore) launcher.getContexts()
                        .get(launcherContext);

                if (!getMigrationRunnerStrategy().isSynchronized(patchInfoStore, patchInfoStoreOfContext)) {
                    outOfSyncContexts.add(launcherContext);
                }
            }

            // next patch the contexts that have been determined to be out
            // of sync
            for (Iterator iter = outOfSyncContexts.iterator(); iter.hasNext();) {
                MigrationContext launcherContext = (MigrationContext) iter.next();
                applyPatch(launcherContext, task, true);
                patchesApplied = true;
            }

            if (patchesApplied) {
                taskCount++;
            }
        } // else if forceSync
    }

    if (taskCount > 0) {
        log.info("Patching complete (" + taskCount + " patch tasks executed)");
    } else {
        log.info("System up-to-date.  No patch tasks have been run.");
    }

    return taskCount;
}

From source file:org.kutkaitis.timetable2.timetable.OptimizationResultsBean.java

private int calculateNotAppropriateWorkingDaysForTeacherIIIAndIV() {
    int penaltyPoints = 0;

    List<LinkedHashMap> teachersAllDay = getAllDaysTeacherTimeTable();

    for (LinkedHashMap<String, LinkedHashMap> daysTimeTable : teachersAllDay) {
        // Very dirty hack because of rush
        int weekDayNumber = teachersAllDay.indexOf(daysTimeTable);
        Days weekDay = decideWeekDay(weekDayNumber);
        Collection<String> teacherNames = daysTimeTable.keySet();

        teacher: for (String teacherName : teacherNames) {
            LinkedHashMap<String, String> teachersTimeTableForTheDay = daysTimeTable.get(teacherName);
            Collection<String> lectureNumbers = teachersTimeTableForTheDay.keySet();

            for (String lectureNumber : lectureNumbers) {
                String groupNameToSplit = teachersTimeTableForTheDay.get(lectureNumber);
                String[] splittedGroupNames = groupNameToSplit.split(":");
                String groupName = splittedGroupNames[1].trim();

                if (!StringUtils.equals(groupName, EMPTY_GROUP)) {
                    if (studentsMockData.getTeachersFromIIIAndIV().containsKey(teacherName)) {
                        if (studentsMockData.getTeachers().get(teacherName).getFreeDays() != null
                                && studentsMockData.getTeachers().get(teacherName).getFreeDays()
                                        .contains(weekDay)) {

                            penaltyPoints += PenaltyPoints.BAD_WORKING_DAYS_FOR_TEACHER_III_IV.penaltyPoints();
                            continue teacher;
                        }//from www. j av a 2 s . co m
                    }
                }

            }
        }
    }

    return penaltyPoints;

}

From source file:org.kutkaitis.timetable2.timetable.OptimizationResultsBean.java

private int calculateBadWorkingHoursTeacherIIIAndIV() {
    int penaltyPoints = 0;

    List<LinkedHashMap> teachersAllDay = getAllDaysTeacherTimeTable();

    for (LinkedHashMap<String, LinkedHashMap> daysTimeTable : teachersAllDay) {
        // Very dirty hack because of rush
        int weekDayNumber = teachersAllDay.indexOf(daysTimeTable);
        Days weekDay = decideWeekDay(weekDayNumber);
        Collection<String> teacherNames = daysTimeTable.keySet();

        for (String teacherName : teacherNames) {
            LinkedHashMap<String, String> teachersTimeTableForTheDay = daysTimeTable.get(teacherName);
            Collection<String> lectureNumbers = teachersTimeTableForTheDay.keySet();
            //                System.out.println("teacherName: " + teacherName);

            for (String lectureNumber : lectureNumbers) {
                String groupNameToSplit = teachersTimeTableForTheDay.get(lectureNumber);
                String[] splittedGroupNames = groupNameToSplit.split(":");
                String groupName = splittedGroupNames[1].trim();

                if (!StringUtils.equals(groupName, EMPTY_GROUP)) {
                    if (studentsMockData.getTeachersFromIIIAndIV().containsKey(teacherName)) {
                        if (studentsMockData.getTeachers().get(teacherName).getFreeLectures() != null) {
                            if (StringUtils.equals(studentsMockData.getTeachers().get(teacherName)
                                    .getFreeLectures().get(weekDay), lectureNumber)) {
                                penaltyPoints += PenaltyPoints.BAD_WORKING_HOURS_FOR_TEACHER_III_IV
                                        .penaltyPoints();
                            }/*  ww w  .j  a v a  2 s .c om*/

                        }
                    }
                }

            }
        }
    }

    return penaltyPoints;

}

From source file:com.itemanalysis.jmetrik.file.JmetrikFileExporter.java

private boolean exportFile() {
    JmetrikFileReader reader = null;//from  w ww .ja v a  2 s .c  o m
    BufferedWriter writer = null;
    CSVPrinter printer = null;

    if (outputFile.exists() && !overwrite)
        return false;

    try {
        reader = new JmetrikFileReader(dataFile);
        writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(outputFile.toPath())));

        reader.openConnection();

        if (hasHeader) {
            String[] colNames = reader.getColumnNames();
            printer = new CSVPrinter(writer,
                    CSVFormat.DEFAULT.withCommentMarker('#').withDelimiter(delimiter).withHeader(colNames));
        } else {
            printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#').withDelimiter(delimiter));
        }

        LinkedHashMap<VariableName, VariableAttributes> variableAttributes = reader.getVariableAttributes();
        JmetrikCSVRecord record = null;
        VariableAttributes tempAttributes = null;

        //print scored values
        if (scored) {
            String tempValue = "";
            while (reader.hasNext()) {
                record = reader.next();

                for (VariableName v : variableAttributes.keySet()) {
                    tempAttributes = variableAttributes.get(v);
                    tempValue = record.originalValue(v);

                    if (tempAttributes.getItemType() == ItemType.NOT_ITEM) {
                        //write original string if not an item
                        if (record.isMissing(v, tempValue) && empty) {
                            printer.print("");
                        } else {
                            printer.print(tempValue);
                        }

                    } else {
                        //write scored value if a test item
                        if (record.isMissing(v, tempValue) && empty) {
                            printer.print("");
                        } else {
                            printer.print(tempAttributes.getItemScoring().computeItemScore(tempValue));
                        }

                    }

                }
                printer.println();
            }

            //print original values
        } else {
            String tempValue = "";
            while (reader.hasNext()) {
                record = reader.next();

                for (VariableName v : variableAttributes.keySet()) {
                    tempValue = record.originalValue(v);
                    if (record.isMissing(v, tempValue) && empty) {
                        printer.print("");
                    } else {
                        printer.print(tempValue);
                    }
                }
                printer.println();
            }
        }

    } catch (IOException ex) {
        theException = ex;
    } finally {
        try {
            if (reader != null)
                reader.close();
            if (printer != null)
                printer.close();
            if (writer != null)
                writer.close();
        } catch (IOException ex) {
            theException = ex;
        }

    }
    return true;
}

From source file:org.kutkaitis.timetable2.timetable.OptimizationResultsBean.java

private int calculateLectureWindowsInStudentsGroup() {
    int penaltyPoints = 0;
    List<LinkedHashMap> teachersAllDay = getAllDaysTeacherTimeTable();
    LinkedHashMap<Student, LinkedHashMap<String, String>> studentsTimeTableForMonday = new LinkedHashMap();
    LinkedHashMap<Student, LinkedHashMap<String, String>> studentsTimeTableForTuesday = new LinkedHashMap();
    LinkedHashMap<Student, LinkedHashMap<String, String>> studentsTimeTableForWednesday = new LinkedHashMap();
    LinkedHashMap<Student, LinkedHashMap<String, String>> studentsTimeTableForThursday = new LinkedHashMap();
    LinkedHashMap<Student, LinkedHashMap<String, String>> studentsTimeTableForFriday = new LinkedHashMap();

    List<LinkedHashMap> allDaysStudentsTimeTables = addStudentsTimeTablesToTheList(studentsTimeTableForMonday,
            studentsTimeTableForTuesday, studentsTimeTableForWednesday, studentsTimeTableForThursday,
            studentsTimeTableForFriday);

    for (LinkedHashMap<String, LinkedHashMap> daysTimeTable : teachersAllDay) {
        // Very dirty hack because of rush
        int weekDayNumber = teachersAllDay.indexOf(daysTimeTable);
        Days weekDay = decideWeekDay(weekDayNumber);
        Collection<String> teacherNames = daysTimeTable.keySet();
        //            System.out.println("Day: " + weekDay);
        LinkedHashMap<Student, LinkedHashMap<String, String>> studentsTimeTableForDay = allDaysStudentsTimeTables
                .get(weekDayNumber);// w w  w .  ja  v a  2 s . c  o  m
        //            System.out.println("studentsTimeTableForDay: " + studentsTimeTableForDay);

        LinkedHashMap<String, String> teachersTimeTableForTheDay = daysTimeTable
                .get(teacherNames.iterator().next());
        Collection<String> lectureNumbers = teachersTimeTableForTheDay.keySet();

        for (String teacherName : teacherNames) {
            //                System.out.println("teacherName: " + teacherName);

            for (String lectureNumber : lectureNumbers) {
                //                    System.out.println("lectureNumber: " + lectureNumber);
                String groupNameToSplit = teachersTimeTableForTheDay.get(lectureNumber);
                String[] splittedGroupNames = groupNameToSplit.split(":");
                String groupName = splittedGroupNames[1].trim();
                if (!StringUtils.equals(groupName, EMPTY_GROUP)) {
                    List<Student> groupsStudentsList = studentsMockData.getGroups().get(groupName)
                            .getStudents();

                    for (Student stud : groupsStudentsList) {
                        studentsTimeTableForDay.get(stud).put(lectureNumber, groupNameToSplit);
                    }

                    //                        System.out.println("studentsTimeTable for the day 2: " + studentsTimeTableForDay);

                    //                        System.out.println("group name: " + groupName);
                    //                        System.out.println("group students: " + groupsStudentsList);
                    //                    
                    //                        System.out.println(": " + studentsTimeTableForDay.get(groupsStudentsList));
                    //                        
                    //                    if (studentsTimeTableForDay.containsKey(groupsStudentsList)) {
                    //                        System.out.println("groupsStudentsList: " + groupsStudentsList);
                    ////                        System.out.println("StudentsTimeTableForTheDay: " + studentsTimeTableForDay);
                    //                        
                    ////                        studentsTimeTableForDay.get(groupsStudentsList).put(lectureNumber, groupNameToSplit);
                    //                    } else {
                    //                        System.out.println("Doesn't contain");
                    //                    }
                }

            }
        }
    }
    System.out.println("AllDaysTM: " + allDaysStudentsTimeTables);

    return penaltyPoints;
}

From source file:com.primeleaf.krystal.web.view.cpanel.SummaryReportView.java

@SuppressWarnings("unchecked")
private void printSummaryReport() throws Exception {
    printBreadCrumbs();/*  ww w.  java  2s  . c  o  m*/
    if (request.getAttribute(HTTPConstants.REQUEST_ERROR) != null) {
        printErrorDismissable((String) request.getAttribute(HTTPConstants.REQUEST_ERROR));
    }
    if (request.getAttribute(HTTPConstants.REQUEST_MESSAGE) != null) {
        printSuccessDismissable((String) request.getAttribute(HTTPConstants.REQUEST_MESSAGE));
    }

    try {
        out.println("<div class=\"panel panel-default\">");
        out.println(
                "<div class=\"panel-heading\"><h4><i class=\"fa fa-lg fa-bar-chart-o\"></i> Repository Content Summary</h4></div>");
        out.println("<div class=\"panel-body\">");

        out.println("<div class=\"row\">");

        out.println("<div class=\"col-lg-4\">");
        out.println("<div class=\"panel panel-default\">");
        out.println("<div class=\"panel-heading\">");
        out.println("<div class=\"row\">");
        out.println("<div class=\"col-xs-4\">");
        out.println("<i class=\"fa fa-folder-open fa-3x\"></i>");
        out.println("</div>");
        out.println("<div class=\"col-xs-8 text-right\">");
        out.println("<h3>" + request.getAttribute("DOCUMENT_CLASSES") + "</h3>");
        out.println("<p >Document Classes</p>");
        out.println("</div>");
        out.println("</div>");//row
        out.println("</div>");//panel-heading
        out.println("</div>");//panel
        out.println("</div>");//col-lg-4

        out.println("<div class=\"col-lg-4\">");
        out.println("<div class=\"panel panel-default\">");
        out.println("<div class=\"panel-heading\">");
        out.println("<div class=\"row\">");
        out.println("<div class=\"col-xs-6\">");
        out.println("<i class=\"fa fa-file fa-3x\"></i>");
        out.println("</div>");
        out.println("<div class=\"col-xs-6 text-right\">");
        out.println("<h3>" + request.getAttribute("DOCUMENTS") + "</h3>");
        out.println("<p >Documents</p>");
        out.println("</div>");
        out.println("</div>");//row
        out.println("</div>");//panel-heading
        out.println("</div>");//panel
        out.println("</div>");//col-lg-4

        out.println("<div class=\"col-lg-4\">");
        out.println("<div class=\"panel panel-default\">");
        out.println("<div class=\"panel-heading\">");
        out.println("<div class=\"row\">");
        out.println("<div class=\"col-xs-6\">");
        out.println("<i class=\"fa fa-user fa-3x\"></i>");
        out.println("</div>");
        out.println("<div class=\"col-xs-6 text-right\">");
        out.println("<h3>" + request.getAttribute("USERS") + "</h3>");
        out.println("<p >Users</p>");
        out.println("</div>");
        out.println("</div>");//row
        out.println("</div>");//panel-heading
        out.println("</div>");//panel
        out.println("</div>");//col-lg-4

        out.println("</div>");//row

        ArrayList<DocumentClass> documentClasses = (ArrayList<DocumentClass>) request
                .getAttribute("DOCUMENTCLASSLIST");
        if (documentClasses.size() > 0) {
            //charts rendering starts here
            out.println("<div class=\"panel panel-default\">");
            out.println("<div class=\"panel-heading\">");
            out.println("<i class=\"fa fa-pie-chart fa-lg\"></i> Charts");
            out.println("</div>");
            out.println("<div class=\"panel-body\">");
            out.println("<div class=\"row\">");
            out.println("<div class=\"col-sm-6 text-center\">");
            out.println("<h3>Documents : " + request.getAttribute("DOCUMENTS") + "</h3>");
            out.println("<div id=\"classchart\" style=\"height:280px;\">");
            out.println("<script>");
            out.println("new Morris.Donut({");
            out.println("  element: 'classchart',");
            out.println("  data: [");

            for (DocumentClass documentClass : documentClasses) {
                int documentCount = documentClass.getActiveDocuments();
                out.println("    { label: \"" + StringEscapeUtils.escapeHtml4(documentClass.getClassName())
                        + "\", value: " + documentCount + " },");
            }
            out.println("  ],");
            out.println("});");
            out.println("</script>");
            out.println("</div>");
            out.println("</div>");//col-sm-6

            double totalSize = (Double) request.getAttribute("TOTALSIZE");
            out.println("<div class=\"col-sm-6 text-center\">");
            out.println("<h3>Total Size : " + StringHelper.formatSizeText(totalSize) + "</h3>");
            out.println("<div id=\"sizechart\" style=\"height:280px;\">");
            out.println("<script>");
            out.println("new Morris.Donut({");
            out.println("  element: 'sizechart',");
            out.println("  data: [");

            for (DocumentClass documentClass : documentClasses) {
                double documentSize = (Double) request.getAttribute(documentClass.getClassName() + "_SIZE");
                out.println("{ label: \"" + StringEscapeUtils.escapeHtml4(documentClass.getClassName())
                        + "\", value: " + documentSize + " },");
            }
            out.println("  ], " + " formatter : function (y, data) { " + " var result = '';"
                    + " if(y > 1024) { result = parseFloat(y/1024).toFixed(1)+ ' KB'} "
                    + " if(y > 1048576) { result = parseFloat(y/1048576).toFixed(1)+' MB'} "
                    + " if(y > 1073741824) { result = parseFloat(y/1073741824).toFixed(1)+' GB'} "
                    + "return result } ");
            out.println("});");
            out.println("</script>");
            out.println("</div>");
            out.println("</div>");//col-sm-6
            out.println("</div>");//row

            if (documentClasses.size() > 0) {
                out.println("<div class=\"text-center\">");
                out.println("<div id=\"linechart\" style=\"height:280px;\">");
                out.println("<script>");
                out.println("new Morris.Line({");
                out.println("  element: 'linechart',");
                out.println("  data: [");
                LinkedHashMap<String, Integer> chartValues = (LinkedHashMap<String, Integer>) request
                        .getAttribute(documentClasses.get(0).getClassName() + "_CHARTVALUES");

                for (String month : chartValues.keySet()) {
                    out.print("{y : '" + month + "'");
                    for (DocumentClass documentClass : documentClasses) {
                        chartValues = (LinkedHashMap<String, Integer>) request
                                .getAttribute(documentClass.getClassName() + "_CHARTVALUES");
                        out.print(", c" + documentClass.getClassId() + " : " + chartValues.get(month));
                    }
                    out.println("},");
                }
                out.println("  ],");
                out.println("   xkey: 'y',");
                out.print(" ykeys: [");
                for (DocumentClass documentClass : documentClasses) {
                    out.print("'c" + documentClass.getClassId() + "',");
                }
                out.println("],");
                out.println(" labels: [");
                for (DocumentClass documentClass : documentClasses) {
                    out.print("'" + StringEscapeUtils.escapeHtml4(documentClass.getClassName()) + "',");
                }
                out.println("]");
                out.println("});");
                out.println("</script>");
                out.println("</div>");//line-chart
                out.println("</div>");//
            }

            out.println("</div>");//panel-body
            out.println("</div>");//panel
        }
        //charts rendering ends here

        out.println("<div class=\"panel  panel-default\">");
        out.println("<div class=\"panel-heading\">");
        out.println("<i class=\"fa fa-folder-open fa-lg\"></i> Document Classes");
        out.println("</div>");
        ArrayList<DocumentClass> documentClassList = (ArrayList<DocumentClass>) request
                .getAttribute("DOCUMENTCLASSLIST");
        if (documentClassList.size() > 0) {
            out.println("<div class=\"table-responsive\">");
            out.println("<table class=\"table table-condensed table-stripped\">");
            out.println("<thead><tr>");
            out.println("<th>Document Class</th>");
            out.println("<th class=\"text-center\">Documents</th>");
            out.println("<th class=\"text-right\">Total Size</th></tr></thead>");
            out.println("<tbody>");
            for (DocumentClass documentClass : documentClassList) {
                int documentCount = documentClass.getActiveDocuments();
                double documentSize = (Double) request.getAttribute(documentClass.getClassName() + "_SIZE");
                String ownerName = (String) request.getAttribute(documentClass.getClassName() + "_OWNER");
                out.println("<tr>");
                out.println("<td style=\"width:80%;\">");
                out.println("<h4 class=\"text-danger\">"
                        + StringEscapeUtils.escapeHtml4(documentClass.getClassName()) + "</h4>");
                out.println(
                        "<h5>" + StringEscapeUtils.escapeHtml4(documentClass.getClassDescription()) + "</h5>");
                out.println("<p>");
                out.println("<i>Created By " + ownerName);
                out.println(" , " + StringHelper.getFriendlyDateTime(documentClass.getCreated()) + "</i>");
                out.println("</p>");
                out.println("</td>");

                out.println("<td style=\"width:10%;\" class=\"text-center\">");
                out.println("<h4>" + documentCount + "</h4>");
                out.println("</td>");

                out.println("<td class=\"text-right\">");
                out.println("<h4>" + StringHelper.formatSizeText(documentSize) + "</h4>");
                out.println("</td>");
                out.println("</tr>");//row

            } // for
            out.println("</tbody>");
            out.println("</table>");
            out.println("</div>");
        } else {
            out.println("<div class=\"panel-body\">"); //panel
            out.println("No document class found");
            out.println("</div>"); //panel-body
        }
        out.println("</div>"); //panel

        out.println("</div>");
        out.println("</div>");
        out.println("</div>");

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.nordapp.web.servlet.SessionCallServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {// w w  w . java  2  s.c om

        //@SuppressWarnings("unused")
        final String mandatorId = RequestPath.getMandator(req);
        final String uuid = RequestPath.getSession(req);

        //
        // Session handler
        //
        //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession());
        SessionControl ctrl = new SessionControlImpl(context);
        ctrl.setMandatorID(mandatorId);
        ctrl.setCertID(uuid);

        ctrl.loadTempSession();
        ctrl.getAll();
        ctrl.incRequestCounter();
        ctrl.setAll();
        ctrl.saveTempSession();

        //
        // Process upload
        //

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);

        //The mandator
        Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID());
        if (mandator == null) {
            throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + ".");
        }

        FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp");

        File repository = tmpLoc.add("http-upload").toFile();
        if (!repository.exists()) {
            repository.mkdirs();
        }
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // Gets the JSON data
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(LinkedHashMap.class, new GsonHashMapDeserializer());
        Gson gson = gsonBuilder.create();

        Map<String, Object> res = new HashMap<String, Object>();
        try {
            // parses the request's content to extract file data
            //@SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(req);

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (item.isFormField()) {
                        //data
                        res.put(item.getFieldName(), item.getString());
                        //ioc.setField(item.getFieldName(), item);
                    } else {
                        //Gets JSON as Stream
                        Reader json = new InputStreamReader(item.getInputStream());
                        //String json = item.getString();

                        try {
                            @SuppressWarnings("unchecked")
                            LinkedHashMap<String, Object> mapJ = gson.fromJson(json, LinkedHashMap.class);
                            for (String key : mapJ.keySet()) {
                                Object val = mapJ.get(key);
                                if (val == null)
                                    continue;

                                res.put(key, val);
                            } //for
                        } finally {
                            json.close();
                        }
                    } //fi
                } //for

            } //fi
        } catch (Exception ex) {
            req.setAttribute("message", "There was an error: " + ex.getMessage());
        }

        process(ctrl, req, resp, res);

    } catch (Exception e) {
        ResponseHandler rsHdl = new ResponseHandler(context, null);
        rsHdl.sendError(logger, e, resp, null);
    }
}