Example usage for java.util.logging SimpleFormatter SimpleFormatter

List of usage examples for java.util.logging SimpleFormatter SimpleFormatter

Introduction

In this page you can find the example usage for java.util.logging SimpleFormatter SimpleFormatter.

Prototype

SimpleFormatter

Source Link

Usage

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/acceptallaccount", method = RequestMethod.POST)
public String acceptAllAccount(Model model) {
    try {/*from   w  w  w. j  av a2s .  c  om*/
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBAdminStudentAccts.log");
        logger.addHandler(handler);
        handler.setFormatter(new SimpleFormatter());
        StudentDAO.acceptAllAccount();
        List<Students> accountrequests = StudentDAO.getAccountRequests();
        model.addAttribute("accountrequests", accountrequests);
        logger.info("Successfully accepted all accounts");
        logger.info("Accounts successfully updated to model");
        handler.close();
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "adminmanagerequests";
}

From source file:org.noroomattheinn.utils.Utils.java

public static void setupLogger(File where, String basename, Logger logger, Level level) {
    rotateLogs(where, basename, 3);/*from  w ww .  j a v  a  2  s.  com*/

    FileHandler fileHandler;
    try {
        logger.setLevel(level);
        fileHandler = new FileHandler((new File(where, basename + "-00.log")).getAbsolutePath());
        fileHandler.setFormatter(new SimpleFormatter());
        fileHandler.setLevel(level);
        logger.addHandler(fileHandler);

        for (Handler handler : Logger.getLogger("").getHandlers()) {
            if (handler instanceof ConsoleHandler) {
                handler.setLevel(level);
            }
        }
    } catch (IOException | SecurityException ex) {
        logger.severe("Unable to establish log file: " + ex);
    }
}

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/deleteaccount", method = RequestMethod.POST)
public String deleteAccount(Model model, @RequestParam(value = "email") String email) {
    try {/*w w  w .  j a  v  a 2s. co  m*/
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBAdminStudentAccts.log");
        logger.addHandler(handler);
        handler.setFormatter(new SimpleFormatter());
        StudentDAO.deleteAccount(email);
        List<Students> allStudents = StudentDAO.getAcceptedAccounts();
        model.addAttribute("allstudents", allStudents);
        logger.info("Successfully deleted: " + email);
        logger.info("Accounts successfully updated to model");
        handler.close();
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "adminmanageaccounts";
}

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/addschool", method = RequestMethod.POST)
public String addSchool(Model model, @RequestParam(value = "schoolname") String schoolName,
        @RequestParam(value = "academicyear") String academicYear,
        @RequestParam(value = "numsemesters") String numSemesters,
        @RequestParam(value = "numperiods") String numPeriods, @RequestParam(value = "numdays") String numDays,
        @RequestParam(value = "legalblocks") String legalBlocks,
        @RequestParam(value = "lunchrange") String lunchRange) {
    try {//from w  ww  . j av a2s .co  m
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBAddSchool.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        boolean valid = true;
        if (schoolName.isEmpty() || academicYear.isEmpty() || numSemesters.isEmpty() || numPeriods.isEmpty()
                || legalBlocks.isEmpty() || lunchRange.isEmpty()) {
            model.addAttribute("fillout", "Please fill out all Required Fields");
            valid = false;
        }
        Schools school = SchoolDAO.getSchoolByNameYear(schoolName, academicYear);
        String academicYearRegex = "[0-9]{4}-[0-9]{4}";
        String lunchRangeRegex = "[0-9]-[0-9]";
        int periods = Integer.parseInt(numPeriods);
        int days = Integer.parseInt(numDays);
        int semesters = Integer.parseInt(numSemesters);
        String legalBlockRegex = "(<[1-" + periods + "];([1-" + days + "](,[1-" + days + "]){0," + days + "})>)"
                + "(#<[1-" + periods + "];([1-" + days + "](,[1-" + days + "]){0," + days + "})>)*";
        if (!academicYear.matches(academicYearRegex)) {
            model.addAttribute("ayregex", "Academic Year is invalid");
            logger.info("Invalid Academic Year");
            valid = false;
        }
        if (!lunchRange.matches(lunchRangeRegex)) {
            model.addAttribute("lrregex", "Lunch Range is invalid");
            logger.info("Invalid Lunch Range");
            valid = false;
        }
        if (periods <= 9) {
            if (!legalBlocks.matches(legalBlockRegex)) {
                model.addAttribute("lbregex", "Legal Block set is invalid");
                logger.info("Invalid Legal Block");
                valid = false;
            }
        }
        if (school != null) {
            model.addAttribute("taken", "There is already a school with this name and academic year.");
            logger.info("Invalid name and academic year");
            valid = false;
        }
        if (valid == true) {
            SchoolDAO.addSchool(schoolName, academicYear, semesters, days, periods, lunchRange);
            Schools tempSchool = SchoolDAO.getSchoolByNameYear(schoolName, academicYear);
            int schoolIDForSB = tempSchool.getSchoolid();
            //Add all scheduleblocks
            String[] lbArray = legalBlocks.split("#");
            //Array of strings in the format ({1;1,2,3}
            for (String s : lbArray) {
                String temp = s.substring(1, s.length() - 1);
                String[] tempArray = temp.split(";");
                int pd = Integer.parseInt(tempArray[0]);
                ScheduleBlockDAO.addScheduleBlock(schoolIDForSB, pd, tempArray[1]);
            }

            model.addAttribute("added", "School has been successfully added.");
            logger.info("Successfully added school " + schoolName);
        }
        handler.close();
        logger.removeHandler(handler);
        // Scheduleblocks are in the form of <period;day1,day2..>#<period;day1,day2..>.
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "adminaddschool";
}

From source file:brut.apktool.Main.java

private static void setupLogging(Verbosity verbosity) {
    Logger logger = Logger.getLogger("");
    for (Handler handler : logger.getHandlers()) {
        logger.removeHandler(handler);//from   w  w w.j  a va 2s. c o  m
    }
    LogManager.getLogManager().reset();

    if (verbosity == Verbosity.QUIET) {
        return;
    }

    Handler handler = new Handler() {
        @Override
        public void publish(LogRecord record) {
            if (getFormatter() == null) {
                setFormatter(new SimpleFormatter());
            }

            try {
                String message = getFormatter().format(record);
                if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
                    System.err.write(message.getBytes());
                } else {
                    System.out.write(message.getBytes());
                }
            } catch (Exception exception) {
                reportError(null, exception, ErrorManager.FORMAT_FAILURE);
            }
        }

        @Override
        public void close() throws SecurityException {
        }

        @Override
        public void flush() {
        }
    };

    logger.addHandler(handler);

    if (verbosity == Verbosity.VERBOSE) {
        handler.setLevel(Level.ALL);
        logger.setLevel(Level.ALL);
    } else {
        handler.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                return record.getLevel().toString().charAt(0) + ": " + record.getMessage()
                        + System.getProperty("line.separator");
            }
        });
    }
}

From source file:BSxSB.Controllers.StudentController.java

@RequestMapping(value = "/submitassigned", method = RequestMethod.POST)
public String submitAssigned(Model model, @RequestParam(value = "courseidentifier") String courseidentifier,
        @RequestParam(value = "coursename") String coursename,
        @RequestParam(value = "instructor") String instructor,
        @RequestParam(value = "semesters") String[] semesters, @RequestParam(value = "period") String period,
        @RequestParam(value = "days") String[] days) {
    try {// www  .j  av  a  2 s . c om
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBStudentAssignedCourses.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        if (coursename.isEmpty() || instructor.isEmpty() || semesters[0].matches("noinput") || period.isEmpty()
                || days[0].matches("noinput")) {
            model.addAttribute("fieldempty", "Please fill out all required fields.");
            logger.info("Error: Fields are empty");
            handler.close();
            logger.removeHandler(handler);
            return enterCourses(model);
        }
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        Students currentStudent = StudentDAO.getStudent(name);
        int schoolid = currentStudent.getSchoolid();
        //Build the semester string
        String semString = "";
        for (int i = 0; i < semesters.length - 1; i++) {
            semString += semesters[i];
            semString += ",";
        }
        //Get rid of last ','
        semString = semString.substring(0, semString.length() - 1);
        //Build the scheduleblock days
        String daysString = "";
        for (int i = 0; i < days.length - 1; i++) {
            daysString += days[i];
            daysString += ",";
        }
        daysString = daysString.substring(0, daysString.length() - 1);
        int periodInt = Integer.parseInt(period);
        Scheduleblocks sb = ScheduleBlockDAO.getScheduleBlock(schoolid, periodInt, daysString);
        if (sb == null) {
            model.addAttribute("sbinvalid", "Scheduleblock provided is invalid.");
            logger.info("Error: The chosen scheduleblock does not exist for this school");
            // return error msg
        } else {
            Courses c = CourseDAO.getCourse(courseidentifier, coursename, sb.getScheduleblockid(), schoolid,
                    instructor, semString);
            if (c != null) {
                if (RegistrationDAO.isRegistered(c, currentStudent)) {
                    model.addAttribute("alreadyreg", "You are already registered for this course");
                    logger.info("Error: already registered for this course");
                } else {
                    RegistrationDAO.addRegistration(c.getCourseid(), currentStudent.getStudentid());
                    CourseDAO.incrementCourseStudents(c.getCourseid());
                    model.addAttribute("halfsuccess",
                            "Course already exists, you have been successfully added to the course roster.");
                    logger.info("Course exists and student has been added to roster");
                }
            } else {
                int sbid = sb.getScheduleblockid();
                Courses newCourse = new Courses(schoolid, coursename, courseidentifier, instructor, sbid,
                        semString);
                newCourse.setNumstudents(1);
                int studentid = currentStudent.getStudentid();
                CourseDAO.addCourse(newCourse, studentid);
                model.addAttribute("success", "New course successfully added.");
                logger.info("Course " + courseidentifier + " " + coursename + " successfully added");
            }
        }

        Schools currentSchool = SchoolDAO.getSchool(currentStudent.getSchoolid());
        List<Schools> schoolyears = SchoolDAO.getSchoolSameName(currentSchool.getSchoolname());
        model.addAttribute("schoolyears", schoolyears);
        model.addAttribute("numSemesters", currentSchool.getNumsemesters());
        model.addAttribute("numPeriods", currentSchool.getNumperiods());
        model.addAttribute("numDays", currentSchool.getNumdays());
        handler.close();
        logger.removeHandler(handler);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "studententercourses";
}

From source file:MailHandlerDemo.java

/**
 * Example for various kinds of custom sorting, formatting, and filtering
 * for multiple attachment messages. The subject will contain the most
 * severe record and a count of remaining records. The log records are
 * ordered from most severe to least severe. The body uses a custom
 * formatter that includes a summary by date and time. The attachment use
 * XML and plain text formats. Each attachment has a different set of
 * filtering. The attachment names are generated from either a fixed name or
 * are built using the number and type of the records formatted. On close
 * any remaining messages are sent. Use the LogManager config option or
 * extend the MemoryHandler to emulate this behavior via the
 * logging.properties.//from w  w  w  .  j a  v  a  2  s .c o m
 */
private static void initCustomAttachments() {
    MailHandler h = new MailHandler();

    //Sort records by severity keeping the severe messages at the top.
    h.setComparator(Collections.reverseOrder(new SeverityComparator()));

    //Use subject to provide a hint as to what is in the email.
    h.setSubject(new CollectorFormatter());

    //Make the body give a simple summary of what happened.
    h.setFormatter(new SummaryFormatter());

    //Create 3 attachments.
    h.setAttachmentFormatters(new XMLFormatter(), new XMLFormatter(), new SimpleFormatter());

    //Filter each attachment differently.
    h.setAttachmentFilters(null, new DurationFilter(3L, 1000L), new DurationFilter(1L, 15L * 60L * 1000L));

    //Creating the attachment name formatters.
    h.setAttachmentNames(new CollectorFormatter("all.xml"),
            new CollectorFormatter("{3} records and {5} errors.xml"),
            new CollectorFormatter("{5,choice,0#no errors|1#1 error|1<" + "{5,number,integer} errors}.txt"));

    LOGGER.addHandler(h);
}

From source file:BSxSB.Controllers.StudentController.java

@RequestMapping(value = "/studentgeneratecourses", method = RequestMethod.GET)
public String generateCourses(Model model) {
    try {//from w w  w .j a v a2  s .c  o  m
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBStudentGenerateCourses.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        Students currentStudent = StudentDAO.getStudent(name);
        Schools currentSchool = SchoolDAO.getSchool(currentStudent.getSchoolid());
        List<Courses> courses = CourseDAO.getCourseOfferingForSchool(currentSchool.getSchoolid());
        List<Scheduleblocks> scheduleblocks = new ArrayList<>();
        for (Courses course : courses) {
            scheduleblocks.add(ScheduleBlockDAO.getScheduleBlock(course.getScheduleblockid()));
        }
        List<Schools> schoolyears = SchoolDAO.getSchoolSameName(currentSchool.getSchoolname());
        Generationcriteria gencriteria = GenerationcriteriaDAO
                .getGenerationCriteria(currentStudent.getStudentid());

        if (gencriteria != null) {
            String[] courseids = gencriteria.getCourseids().split(",");
            List<Courses> genCourses = new ArrayList<>();
            List<Scheduleblocks> genscheduleblocks = new ArrayList<>();
            if (!gencriteria.getCourseids().isEmpty()) {
                for (String courseid : courseids) {
                    Courses genCourse = CourseDAO.getCourse(Integer.parseInt(courseid));
                    genCourses.add(genCourse);
                    genscheduleblocks.add(ScheduleBlockDAO.getScheduleBlock(genCourse.getScheduleblockid()));
                }
            }
            if (gencriteria.getLunch() != null && !gencriteria.getLunch().isEmpty()) {
                String[] lunch = gencriteria.getLunch().split(",");
                model.addAttribute("lunch", lunch);
            }
            String lunchrange = currentSchool.getLunchrange();
            model.addAttribute("lunchrange", lunchrange);
            int numdays = currentSchool.getNumdays();
            String lunchdays = lunchToText(numdays);
            String[] lunchdays2 = lunchdays.split(",");
            model.addAttribute("lunchdays", lunchdays2);
            model.addAttribute("genscheduleblocks", genscheduleblocks);
            model.addAttribute("gencourses", genCourses);
            model.addAttribute("schoolyears", schoolyears);
            model.addAttribute("scheduleblocks", scheduleblocks);
            model.addAttribute("courses", courses);
            logger.info("Successfully loaded generation criteria.");
            handler.close();
            logger.removeHandler(handler);
        }
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

    return "studentgeneratecourses";
}

From source file:net.sf.dvstar.transmission.TransmissionView.java

private void initLogger() {

    try {//w w w. j  a va  2s.  co m
        FileHandler logFile = new FileHandler("%h/.JTransmission.log", true);
        logFile.setFormatter(new SimpleFormatter());

        globalLogger = Logger.getAnonymousLogger();
        Handler h[] = getGlobalLogger().getHandlers();
        for (int i = 0; i < h.length; i++) {
            globalLogger.removeHandler(h[i]);
        }

        globalLogger.addHandler(logFile);

        globalLogger.setLevel(logginLevel);
        globalLogger.setUseParentHandlers(false);

        globalLogger.log(Level.INFO, "Started");
        logFile.flush();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

From source file:BSxSB.Controllers.StudentController.java

@RequestMapping(value = "/adddesiredcourse", method = RequestMethod.POST)
public String adddesiredcourses(Model model, @RequestParam("id") String id) {
    try {//from  w w w .  j  a v  a2s .  c  o  m
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBStudentGenerateCourses.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        Students currentStudent = StudentDAO.getStudent(name);
        GenerationcriteriaDAO.addDesiredCourses(currentStudent.getStudentid(), id);
        logger.info("Course successfully added to generation criteria.");
        Schools currentSchool = SchoolDAO.getSchool(currentStudent.getSchoolid());
        List<Courses> courses = CourseDAO.getCourseOfferingForSchool(currentSchool.getSchoolid());
        List<Scheduleblocks> scheduleblocks = new ArrayList<>();
        for (Courses course : courses) {
            scheduleblocks.add(ScheduleBlockDAO.getScheduleBlock(course.getScheduleblockid()));
        }
        List<Schools> schoolyears = SchoolDAO.getSchoolSameName(currentSchool.getSchoolname());
        Generationcriteria gencriteria = GenerationcriteriaDAO
                .getGenerationCriteria(currentStudent.getStudentid());
        String[] courseids = gencriteria.getCourseids().split(",");
        List<Courses> genCourses = new ArrayList<>();
        List<Scheduleblocks> genscheduleblocks = new ArrayList<>();
        for (String courseid : courseids) {
            Courses genCourse = CourseDAO.getCourse(Integer.parseInt(courseid));
            genCourses.add(genCourse);
            genscheduleblocks.add(ScheduleBlockDAO.getScheduleBlock(genCourse.getScheduleblockid()));
        }
        if (gencriteria.getLunch() != null && !gencriteria.getLunch().isEmpty()) {
            String[] lunch = gencriteria.getLunch().split(",");
            model.addAttribute("lunch", lunch);
        }
        logger.info("Generation Criteria successfully updated.");
        String lunchrange = currentSchool.getLunchrange();
        model.addAttribute("lunchrange", lunchrange);
        int numdays = currentSchool.getNumdays();
        String lunchdays = lunchToText(numdays);
        String[] lunchdays2 = lunchdays.split(",");
        model.addAttribute("lunchdays", lunchdays2);
        model.addAttribute("genscheduleblocks", genscheduleblocks);
        model.addAttribute("gencourses", genCourses);
        model.addAttribute("schoolyears", schoolyears);
        model.addAttribute("scheduleblocks", scheduleblocks);
        model.addAttribute("courses", courses);
        handler.close();
        logger.removeHandler(handler);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "studentgeneratecourses";
}