Example usage for java.util.logging FileHandler FileHandler

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

Introduction

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

Prototype

public FileHandler(String pattern, boolean append) throws IOException, SecurityException 

Source Link

Document

Initialize a FileHandler to write to the given filename, with optional append.

Usage

From source file:BSxSB.Controllers.StudentController.java

@RequestMapping(value = "/studenteditassigned", method = RequestMethod.GET)
public String editAssigned(Model model) {
    try {/*  www. j  a v  a  2s.  co m*/
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBStudentAssignedCourses.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        Students currentStudent = StudentDAO.getStudent(name);
        List<Courses> courses = CourseDAO.getCoursesForStudent(currentStudent.getStudentid());
        List<Scheduleblocks> scheduleblocks = new ArrayList<Scheduleblocks>();
        for (Courses course : courses) {
            scheduleblocks.add(ScheduleBlockDAO.getScheduleBlock(course.getScheduleblockid()));
        }
        Schools currentSchool = SchoolDAO.getSchool(currentStudent.getSchoolid());
        List<Schools> schoolyears = SchoolDAO.getSchoolSameName(currentSchool.getSchoolname());
        model.addAttribute("schoolyears", schoolyears);
        model.addAttribute("scheduleblocks", scheduleblocks);
        model.addAttribute("courses", courses);
        logger.info("Courses for this student added to model.");
        handler.close();
        logger.removeHandler(handler);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "studenteditassigned";
}

From source file:BSxSB.Controllers.StudentController.java

@RequestMapping(value = "/removeassign", method = RequestMethod.POST)
public String removeAssigned(Model model, @RequestParam(value = "id") int id) {
    try {//  www. j  a v  a 2 s. co  m
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBStudentAssignedCourses.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        Students currentStudent = StudentDAO.getStudent(name);
        RegistrationDAO.removereg(id, currentStudent.getStudentid());
        CourseDAO.decrementCourseStudentsAndDelete(id);
        logger.info("Course successfully deleted");
        List<Courses> courses = CourseDAO.getCoursesForStudent(currentStudent.getStudentid());
        List<Scheduleblocks> scheduleblocks = new ArrayList<Scheduleblocks>();
        for (Courses course : courses) {
            scheduleblocks.add(ScheduleBlockDAO.getScheduleBlock(course.getScheduleblockid()));
        }
        Schools currentSchool = SchoolDAO.getSchool(currentStudent.getSchoolid());
        List<Schools> schoolyears = SchoolDAO.getSchoolSameName(currentSchool.getSchoolname());
        model.addAttribute("schoolyears", schoolyears);
        model.addAttribute("scheduleblocks", scheduleblocks);
        model.addAttribute("courses", courses);
        logger.info("Courses for this student added to model.");
        handler.close();
        logger.removeHandler(handler);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "studenteditassigned";
}

From source file:org.archive.crawler.framework.CrawlJob.java

/**
 * Start the context, catching and reporting any BeansExceptions.
 *//*from  w  w w .j a v  a  2 s.com*/
protected synchronized void startContext() {
    try {
        ac.start();

        // job log file covering just this launch
        getJobLogger().removeHandler(currentLaunchJobLogHandler);
        File f = new File(ac.getCurrentLaunchDir(), "job.log");
        currentLaunchJobLogHandler = new FileHandler(f.getAbsolutePath(), true);
        currentLaunchJobLogHandler.setFormatter(new JobLogFormatter());
        getJobLogger().addHandler(currentLaunchJobLogHandler);

    } catch (BeansException be) {
        doTeardown();
        beansException(be);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getClass().getSimpleName() + ": " + e.getMessage(), e);
        try {
            doTeardown();
        } catch (Exception e2) {
            e2.printStackTrace(System.err);
        }
    }
}

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 {//  w w  w .jav  a2 s .  com
        //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:com.redhat.rcm.version.Cli.java

private static void configureLogging(boolean useConsole, final boolean useLogFile, final File logFile) {
    System.out.println("Log file is: " + logFile.getAbsolutePath());

    final List<Handler> handlers = new ArrayList<Handler>();

    if (!useConsole && !useLogFile) {
        if (!useLogFile) {
            System.out.println(/*from  w  w w  .  j av  a2 s .  co m*/
                    "\n\nNOTE: --no-console option has been OVERRIDDEN since --no-log-file option was also provided.\nOutputting to console ONLY.\n");
            useConsole = true;
        }
    }

    if (useConsole) {
        final Handler chandler = new ConsoleHandler();
        chandler.setFormatter(new VManFormatter());
        chandler.setLevel(Level.ALL);
        handlers.add(chandler);
    }

    if (useLogFile) {
        try {
            final File dir = logFile.getParentFile();
            if (dir != null && !dir.isDirectory() && !dir.mkdirs()) {
                throw new RuntimeException(
                        "Failed to create parent directory for logfile: " + dir.getAbsolutePath());
            }
            final Handler fhandler = new FileHandler(logFile.getPath(), false);
            fhandler.setFormatter(new VManFormatter());
            fhandler.setLevel(Level.ALL);
            handlers.add(fhandler);
        } catch (final IOException e) {
            final StringWriter sw = new StringWriter();
            final PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            System.out.printf("ERROR: Failed to initialize log file: %s. Reason: %s\n\n%s\n\n", logFile,
                    e.getMessage(), sw.toString());

            throw new RuntimeException("Failed to initialize logfile.");
        }
    }

    root.setUseParentHandlers(false);
    final Handler[] currenthandlers = root.getHandlers();
    for (final Handler h : currenthandlers) {
        h.close();
        root.removeHandler(h);
    }
    for (final Handler h : handlers) {
        root.addHandler(h);
    }
}

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 {//from w w  w. j  ava 2s. co m
        //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:br.bireme.tb.URLS.java

public static void main(final String[] args) throws IOException {
    if (args.length != 1) {
        usage();//  w w  w. j  a  v a  2  s.com
    }

    final String out = args[0].trim();
    final String outDir = (out.endsWith("/")) ? out : out + "/";
    final String LOG_DIR = "log";
    final File logDir = new File(LOG_DIR);
    if (!logDir.exists()) {
        if (!logDir.mkdir()) {
            throw new IOException("log directory [" + LOG_DIR + "] creation error");
        }
    }

    final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    final FileHandler fh = new FileHandler(getLogFileName(LOG_DIR), false);
    logger.addHandler(fh);

    final String URL = URLS.ROOT_URL;
    final TimeString time = new TimeString();

    time.start();
    generateFileStructure(URL, outDir + "celulasIDB");

    System.out.println("Total time: " + time.getTime());
}

From source file:BSxSB.Controllers.StudentController.java

@RequestMapping(value = "/studentgeneratecourses", method = RequestMethod.GET)
public String generateCourses(Model model) {
    try {//from  w  ww .ja va  2s.  co  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 {/*from  w w w. j a  v a 2 s .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 {/*w ww . j a  v  a  2 s .com*/
        //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";
}