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 = "/studentassignedcourses", method = RequestMethod.GET)
public String assignedCourses(Model model) {
    try {/*ww  w .  j  ava 2 s.  com*/
        //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> studentCourses = CourseDAO.getCoursesForStudent(currentStudent.getStudentid());
        Schools school = SchoolDAO.getSchool(currentStudent.getSchoolid());
        List<List<Courses[]>> semesters = new ArrayList<>();
        List<Students> friends = StudentDAO.getFriends(currentStudent.getStudentid());
        for (Courses course : studentCourses) {
            for (Students friend : friends) {
                List<Courses> friendCourses = CourseDAO.getCoursesForStudent(friend.getStudentid());
                for (Courses friendCourse : friendCourses) {
                    if (friendCourse.getCourseid() == (course.getCourseid())) {
                        if (course.getFriends() != null) {
                            course.setFriends(course.getFriends() + " " + friend.getFirstname() + " "
                                    + friend.getLastname());
                        } else {
                            course.setFriends(friend.getFirstname() + " " + friend.getLastname());
                        }
                    }
                }
            }
        }
        logger.info("Successfully retrieved all friends for each course.");
        for (int s = 0; s < school.getNumsemesters(); s++) {
            List<Courses[]> schedule = new ArrayList<>();
            for (int i = 0; i < school.getNumperiods(); i++) {
                Courses[] period = new Courses[7];
                for (Courses course : studentCourses) {
                    Scheduleblocks sb = ScheduleBlockDAO.getScheduleBlock(course.getScheduleblockid());
                    if (sb.getPeriod() == i + 1) {
                        String[] days = sb.getDays().split(",");
                        String[] semester = course.getSemester().split(",");
                        for (String sem : semester) {
                            if (Integer.parseInt(sem) == s + 1) {
                                for (String day : days) {
                                    period[Integer.parseInt(day) - 1] = course;
                                }
                            }
                        }
                    }
                }
                schedule.add(period);
            }
            semesters.add(schedule);
        }
        logger.info("Successfully retrieved schedule for each semester.");
        Schools currentSchool = SchoolDAO.getSchool(currentStudent.getSchoolid());
        List<Schools> schoolyears = SchoolDAO.getSchoolSameName(currentSchool.getSchoolname());
        model.addAttribute("schoolyears", schoolyears);
        model.addAttribute("semester", semesters);
        handler.close();
        logger.removeHandler(handler);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "studentassignedcourses";
}

From source file:com.comphenix.protocol.PacketLogging.java

private void startLogging() {
    manager.removePacketListener(this);

    if (sendingTypes.isEmpty() && receivingTypes.isEmpty()) {
        return;/*from w w  w.ja va 2  s  . c o m*/
    }

    this.sendingWhitelist = ListeningWhitelist.newBuilder().types(sendingTypes).build();
    this.receivingWhitelist = ListeningWhitelist.newBuilder().types(receivingTypes).build();

    // Setup the file logger if it hasn't been already
    if (location == LogLocation.FILE && fileLogger == null) {
        fileLogger = Logger.getLogger("ProtocolLib-FileLogging");

        for (Handler handler : fileLogger.getHandlers())
            fileLogger.removeHandler(handler);
        fileLogger.setUseParentHandlers(false);

        try {
            File logFile = new File(plugin.getDataFolder(), "log.log");
            FileHandler handler = new FileHandler(logFile.getAbsolutePath(), true);
            handler.setFormatter(new LogFormatter());
            fileLogger.addHandler(handler);
        } catch (IOException ex) {
            plugin.getLogger().log(Level.SEVERE, "Failed to obtain log file:", ex);
            return;
        }
    }

    manager.addPacketListener(this);
}

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/deletescheduleblock", method = RequestMethod.POST)
public String deleteScheduleBlocks(Model model, @RequestParam(value = "scheduleblockID") String scheduleblockID,
        @RequestParam(value = "schoolid") String schoolid) {
    try {//from  w  ww . j  av  a  2s.c  o m
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBAdminScheduleBlocks.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        logger.info("Admin Viewing List of School's Schedule Blocks.");
        int sbid = Integer.parseInt(scheduleblockID);
        ScheduleBlockDAO.deleteScheduleBlock(sbid);
        logger.info("Scheduleblock " + sbid + " was deleted.");
        handler.close();
        logger.removeHandler(handler);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return editScheduleBlocks(model, schoolid);
}

From source file:org.geotools.utils.imagemosaic.MosaicIndexBuilder.java

/**
 * Main thread for the mosaic index builder.
 *///from   w w  w  . j a v  a2 s.co m
public void run() {

    // /////////////////////////////////////////////////////////////////////
    //
    // CREATING INDEX FILE
    //
    // /////////////////////////////////////////////////////////////////////

    // /////////////////////////////////////////////////////////////////////
    //
    // Create a file handler that write log record to a file called
    // my.log
    //
    // /////////////////////////////////////////////////////////////////////
    FileHandler handler = null;
    try {
        boolean append = true;
        handler = new FileHandler(new StringBuffer(locationPath).append("/error.txt").toString(), append);
        handler.setLevel(Level.SEVERE);
        // Add to the desired logger
        LOGGER.addHandler(handler);

        // /////////////////////////////////////////////////////////////////////
        //
        // Create a set of file names that have to be skipped since these are
        // our metadata files
        //
        // /////////////////////////////////////////////////////////////////////
        final Set<String> skipFiles = new HashSet<String>(
                Arrays.asList(new String[] { indexName + ".shp", indexName + ".dbf", indexName + ".shx",
                        indexName + ".prj", "error.txt", "error.txt.lck", indexName + ".properties" }));

        // /////////////////////////////////////////////////////////////////////
        //
        // Creating temp vars
        //
        // /////////////////////////////////////////////////////////////////////
        ShapefileDataStore index = null;
        Transaction t = new DefaultTransaction();
        // declaring a preciosion model to adhere the java double type
        // precision
        PrecisionModel precMod = new PrecisionModel(PrecisionModel.FLOATING);
        GeometryFactory geomFactory = new GeometryFactory(precMod);
        try {
            index = new ShapefileDataStore(
                    new File(locationPath + File.separator + indexName + ".shp").toURI().toURL());
        } catch (MalformedURLException ex) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            fireException(ex);
            return;
        }

        final List<File> files = new ArrayList<File>();
        recurse(files, locationPath);

        // /////////////////////////////////////////////////////////////////////
        //
        // Cycling over the files that have filtered out
        //
        // /////////////////////////////////////////////////////////////////////
        numFiles = files.size();
        String validFileName = null;
        final Iterator<File> filesIt = files.iterator();
        FeatureWriter<SimpleFeatureType, SimpleFeature> fw = null;
        boolean doneSomething = false;
        for (int i = 0; i < numFiles; i++) {

            StringBuffer message;
            // //
            //
            // Check that this file is actually good to go
            //
            // //         
            final File fileBeingProcessed = ((File) filesIt.next());
            if (!fileBeingProcessed.exists() || !fileBeingProcessed.canRead() || !fileBeingProcessed.isFile()) {
                // send a message
                message = new StringBuffer("Skipped file ").append(files.get(i))
                        .append(" snce it seems invalid.");
                if (LOGGER.isLoggable(Level.INFO))
                    LOGGER.info(message.toString());
                fireEvent(message.toString(), ((i * 99.0) / numFiles));
                continue;
            }

            // //
            //
            // Anyone has asked us to stop?
            //
            // //
            if (getStopThread()) {
                message = new StringBuffer("Stopping requested at file  ").append(i).append(" of ")
                        .append(numFiles).append(" files");
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine(message.toString());
                }
                fireEvent(message.toString(), ((i * 100.0) / numFiles));
                return;
            } // replacing chars on input path
            try {
                validFileName = fileBeingProcessed.getCanonicalPath();
            } catch (IOException e1) {
                fireException(e1);
                return;
            }
            validFileName = validFileName.replace('\\', '/');
            validFileName = validFileName.substring(locationPath.length() + 1,
                    fileBeingProcessed.getAbsolutePath().length());
            if (skipFiles.contains(validFileName))
                continue;
            message = new StringBuffer("Now indexing file ").append(validFileName);

            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine(message.toString());
            }
            fireEvent(message.toString(), ((i * 100.0) / numFiles));
            try {
                // ////////////////////////////////////////////////////////
                //
                //
                // STEP 1
                // Getting an ImageIO reader for this coverage.
                //
                //
                // ////////////////////////////////////////////////////////
                ImageInputStream inStream = ImageIO.createImageInputStream(fileBeingProcessed);
                if (inStream == null) {
                    if (LOGGER.isLoggable(Level.SEVERE))
                        LOGGER.severe(fileBeingProcessed
                                + " has been skipped since we could not get a stream for it");
                    continue;
                }
                inStream.mark();
                final Iterator<ImageReader> it = ImageIO.getImageReaders(inStream);
                ImageReader r = null;
                if (it.hasNext()) {
                    r = (ImageReader) it.next();
                    r.setInput(inStream);
                } else {
                    // release resources
                    try {
                        inStream.close();
                    } catch (Exception e) {
                        // ignore exception
                    }
                    //               try {
                    //                  r.dispose();
                    //               } catch (Exception e) {
                    //                  // ignore exception
                    //               }

                    // send a message
                    message = new StringBuffer("Skipped file ").append(files.get(i))
                            .append(":No ImageIO readeres avalaible.");
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.info(message.toString());
                    fireEvent(message.toString(), ((i * 99.0) / numFiles));
                    continue;
                }

                // ////////////////////////////////////////////////////////
                //
                // STEP 2
                // Getting a coverage reader for this coverage.
                //
                // ////////////////////////////////////////////////////////
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine(new StringBuffer("Getting a reader").toString());
                final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder
                        .findFormat(files.get(i));
                if (format == null || !format.accepts(files.get(i))) {
                    // release resources
                    try {
                        inStream.close();
                    } catch (Exception e) {
                        // ignore exception
                    }
                    try {
                        r.dispose();
                    } catch (Exception e) {
                        // ignore exception
                    }

                    message = new StringBuffer("Skipped file ").append(files.get(i))
                            .append(": File format is not supported.");
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.info(message.toString());
                    fireEvent(message.toString(), ((i * 99.0) / numFiles));
                    continue;
                }
                final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format
                        .getReader(files.get(i));
                envelope = (GeneralEnvelope) reader.getOriginalEnvelope();
                actualCRS = reader.getCrs();

                // /////////////////////////////////////////////////////////////////////
                //
                // STEP 3
                // Get the type specifier for this image and the check that the
                // image has the correct sample model and color model.
                // If this is the first cycle of the loop we initialize
                // eveything.
                //
                // /////////////////////////////////////////////////////////////////////
                final ImageTypeSpecifier its = ((ImageTypeSpecifier) r.getImageTypes(0).next());
                boolean skipFeature = false;
                if (globEnvelope == null) {
                    // /////////////////////////////////////////////////////////////////////
                    //
                    // at the first step we initialize everything that we will
                    // reuse afterwards starting with color models, sample
                    // models, crs, etc....
                    //
                    // /////////////////////////////////////////////////////////////////////
                    defaultCM = its.getColorModel();
                    if (defaultCM instanceof IndexColorModel) {
                        IndexColorModel icm = (IndexColorModel) defaultCM;
                        int numBands = defaultCM.getNumColorComponents();
                        defaultPalette = new byte[3][icm.getMapSize()];
                        icm.getReds(defaultPalette[0]);
                        icm.getGreens(defaultPalette[0]);
                        icm.getBlues(defaultPalette[0]);
                        if (numBands == 4)
                            icm.getAlphas(defaultPalette[0]);

                    }
                    defaultSM = its.getSampleModel();
                    defaultCRS = actualCRS;
                    globEnvelope = new GeneralEnvelope(envelope);

                    // /////////////////////////////////////////////////////////////////////
                    //
                    // getting information about resolution
                    //
                    // /////////////////////////////////////////////////////////////////////

                    // //
                    //
                    // get the dimension of the hr image and build the model
                    // as well as
                    // computing the resolution
                    // //
                    // resetting reader and recreating stream, turnaround for a
                    // strange imageio bug
                    r.reset();
                    try {
                        inStream.reset();
                    } catch (IOException e) {
                        inStream = ImageIO.createImageInputStream(fileBeingProcessed);
                    }
                    //let's check if we got something now
                    if (inStream == null) {
                        //skip file
                        if (LOGGER.isLoggable(Level.WARNING))
                            LOGGER.warning("Skipping file " + fileBeingProcessed.toString());
                        continue;
                    }
                    r.setInput(inStream);
                    numberOfLevels = r.getNumImages(true);
                    resolutionLevels = new double[2][numberOfLevels];
                    double[] res = getResolution(envelope, new Rectangle(r.getWidth(0), r.getHeight(0)),
                            defaultCRS);
                    resolutionLevels[0][0] = res[0];
                    resolutionLevels[1][0] = res[1];

                    // resolutions levels
                    if (numberOfLevels > 1) {

                        for (int k = 0; k < numberOfLevels; k++) {
                            res = getResolution(envelope, new Rectangle(r.getWidth(k), r.getHeight(k)),
                                    defaultCRS);
                            resolutionLevels[0][k] = res[0];
                            resolutionLevels[1][k] = res[1];
                        }
                    }

                    // /////////////////////////////////////////////////////////////////////
                    //
                    // creating the schema
                    //
                    // /////////////////////////////////////////////////////////////////////
                    final SimpleFeatureTypeBuilder featureBuilder = new SimpleFeatureTypeBuilder();
                    featureBuilder.setName("Flag");
                    featureBuilder.setNamespaceURI("http://www.geo-solutions.it/");
                    featureBuilder.add("location", String.class);
                    featureBuilder.add("the_geom", Polygon.class, this.actualCRS);
                    featureBuilder.setDefaultGeometry("the_geom");
                    final SimpleFeatureType simpleFeatureType = featureBuilder.buildFeatureType();
                    // create the schema for the new shape file
                    index.createSchema(simpleFeatureType);

                    // get a feature writer
                    fw = index.getFeatureWriter(t);
                } else {
                    // ////////////////////////////////////////////////////////
                    // 
                    // comparing ColorModel
                    // comparing SampeModel
                    // comparing CRSs
                    // ////////////////////////////////////////////////////////
                    globEnvelope.add(envelope);
                    actualCM = its.getColorModel();
                    actualSM = its.getSampleModel();
                    skipFeature = (i > 0 ? !(CRS.equalsIgnoreMetadata(defaultCRS, actualCRS)) : false);
                    if (skipFeature)
                        LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i))
                                .append(" because CRSs do not match.").toString());
                    skipFeature = checkColorModels(defaultCM, defaultPalette, actualCM);
                    if (skipFeature)
                        LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i))
                                .append(" because color models do not match.").toString());
                    // defaultCM.getNumComponents()==actualCM.getNumComponents()&&
                    // defaultCM.getClass().equals(actualCM.getClass())
                    // && defaultSM.getNumBands() == actualSM
                    // .getNumBands()
                    // && defaultSM.getDataType() == actualSM
                    // .getDataType() &&
                    //
                    // if (skipFeature)
                    // LOGGER
                    // .warning(new StringBuffer("Skipping image ")
                    // .append(files.get(i))
                    // .append(
                    // " because cm or sm does not match.")
                    // .toString());
                    // res = getResolution(envelope, new
                    // Rectangle(r.getWidth(0),
                    // r.getHeight(0)), defaultCRS);
                    // if (Math.abs((resX - res[0]) / resX) > EPS
                    // || Math.abs(resY - res[1]) > EPS) {
                    // LOGGER.warning(new StringBuffer("Skipping image
                    // ").append(
                    // files.get(i)).append(
                    // " because resolutions does not match.")
                    // .toString());
                    // skipFeature = true;
                    // }
                }

                // ////////////////////////////////////////////////////////
                //
                // STEP 4
                //
                // create and store features
                //
                // ////////////////////////////////////////////////////////
                if (!skipFeature) {

                    final SimpleFeature feature = fw.next();
                    feature.setAttribute(1,
                            geomFactory.toGeometry(new ReferencedEnvelope((Envelope) envelope)));
                    feature.setAttribute(
                            0, absolute
                                    ? new StringBuilder(this.locationPath).append(File.separatorChar)
                                            .append(validFileName).toString()
                                    : validFileName);
                    fw.write();

                    message = new StringBuffer("Done with file ").append(files.get(i));
                    if (LOGGER.isLoggable(Level.FINE)) {
                        LOGGER.fine(message.toString());
                    }
                    message.append('\n');
                    fireEvent(message.toString(), (((i + 1) * 99.0) / numFiles));
                    doneSomething = true;
                } else
                    skipFeature = false;

                // ////////////////////////////////////////////////////////
                //
                // STEP 5
                //
                // release resources
                //
                // ////////////////////////////////////////////////////////
                try {
                    inStream.close();
                } catch (Exception e) {
                    // ignore exception
                }
                try {
                    r.dispose();
                } catch (Exception e) {
                    // ignore exception
                }
                // release resources
                reader.dispose();

            } catch (IOException e) {
                fireException(e);
                break;
            } catch (ArrayIndexOutOfBoundsException e) {
                fireException(e);
                break;
            }

        }
        try {
            if (fw != null)
                fw.close();
            t.commit();
            t.close();
            index.dispose();
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
        createPropertiesFiles(globEnvelope, doneSomething);
    } catch (SecurityException el) {
        fireException(el);
        return;
    } catch (IOException el) {
        fireException(el);
        return;
    } finally {
        try {
            if (handler != null)
                handler.close();
        } catch (Throwable e) {
            // ignore
        }

    }

}

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/editschool", method = RequestMethod.POST)
public String editSchool(Model model, @RequestParam(value = "schoolID") String schoolID,
        @RequestParam(value = "schoolname") String schoolName,
        @RequestParam(value = "academicyear") String academicYear,
        @RequestParam(value = "numsemesters") String numSemesters,
        @RequestParam(value = "numdays") String numDays, @RequestParam(value = "numperiods") String numPeriods,
        @RequestParam(value = "lunchrange") String lunchRange) {
    try {//from  www .  j  a  va  2 s.  co m
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBAdminSchools.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        logger.info("Admin Viewing List of School's Schedule Blocks.");
        boolean valid = true;
        if (schoolName.isEmpty() || academicYear.isEmpty() || numSemesters.isEmpty() || numPeriods.isEmpty()
                || lunchRange.isEmpty()) {
            model.addAttribute("fillout", "Please fill out all Required Fields");
            valid = false;
        }
        int schoolid2 = Integer.parseInt(schoolID);
        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("Error: invalid academic year.");
            valid = false;
        }
        if (!lunchRange.matches(lunchRangeRegex)) {
            model.addAttribute("lrregex", "Lunch Range is invalid.");
            logger.info("Error: invalid lunch range.");
            valid = false;
        }
        if (valid == true) {
            SchoolDAO.editSchool(schoolid2, schoolName, academicYear, semesters, days, periods, lunchRange);
            //Check if scheduleblock string changed. If it didn't, then do NOT delete
            //Delete all existing scheduleblocks

            model.addAttribute("added", "School has been successfully edited.");
            logger.info("School was successfully edited");
        }
        logger.removeHandler(handler);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return editRequest(model, schoolID);
}

From source file:com.sustainalytics.crawlerfilter.PDFTitleGeneration.java

/**
 * Method to initiate logger/*  w  ww . ja va 2 s  . c  o m*/
 * @param file is a File object. The log file will be placed in this file's folder
 */
public static void initiateLogger(File file) {
    FileHandler fileHandler;
    try {
        // This block configure the logger with handler and formatter
        fileHandler = new FileHandler(file.getParentFile().getAbsolutePath() + "/" + "log.txt", true);
        logger.addHandler(fileHandler);
        SimpleFormatter formatter = new SimpleFormatter();
        fileHandler.setFormatter(formatter);

    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:BSxSB.Controllers.StudentController.java

@RequestMapping(value = "/studentcourseofferings", method = RequestMethod.GET)
public String courseOfferings(Model model, @RequestParam(value = "year") String year) {
    try {/*  w w w. j  a v a 2s  .  co m*/
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBStudentCourseOfferings.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        Students currentStudent = StudentDAO.getStudent(name);
        int schoolid = currentStudent.getSchoolid();
        Schools sc = SchoolDAO.getSchool(schoolid);
        String schoolName = sc.getSchoolname();
        Schools schoolYear = SchoolDAO.getSchoolByNameYear(schoolName, year);
        int schoolYearID = schoolYear.getSchoolid();
        List<Courses> courses = CourseDAO.getCourseOfferingForSchool(schoolYearID);
        Schools currentSchool = SchoolDAO.getSchool(currentStudent.getSchoolid());
        List<Schools> schoolyears = SchoolDAO.getSchoolSameName(currentSchool.getSchoolname());
        List<Scheduleblocks> scheduleblocks = new ArrayList<>();
        for (Courses course : courses) {
            scheduleblocks.add(ScheduleBlockDAO.getScheduleBlock(course.getScheduleblockid()));
            logger.info("Retrieved course: " + course.getCourseidentifier());
        }
        model.addAttribute("scheduleblocks", scheduleblocks);
        model.addAttribute("schoolyears", schoolyears);
        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 "studentcourseofferings";
}

From source file:de.lazyzero.kkMulticopterFlashTool.KKMulticopterFlashTool.java

private void initLogger() {
    try {/*w ww . j  av  a 2  s.  c  om*/
        logFile = new FileHandler(LOG_FILE.getAbsolutePath(), false);
        logFile.setFormatter(new SimpleFormatter());
        logFile.setLevel(Level.INFO);
        logger.addHandler(logFile);

    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    logger.setLevel(Level.INFO);
}

From source file:eu.asterics.mw.services.AstericsErrorHandling.java

/**
 * This method creates the logger. Actually there are 4 types of loggers: 
 * "severe": logs fatal errors i.e. errors that prevent the ARE from functioning
 * "warning": logs errors other than fatal e.g. component errors
 * "info": logs informative messages/*from w  w  w  . ja  v a 2 s .  com*/
 * "fine": logs debugging messages
 * 
 * Each logger by default also logs all messages with severity level higher than its own. 
 * E.g. the warning logger logs warning and severe messages, the info logger logs info, 
 * warning and severe messages etc. The same applies to the consoleHandler, i.e. by 
 * setting its level to info, the console will also print severe and warning messages 
 * along with info messages
 */
public Logger getLogger() {
    if (logger == null) {
        logger = Logger.getLogger("AstericsLogger");

        FileHandler warningFileHandler, severeFileHandler, infoFileHandler, fineFileHandler;
        ConsoleHandler consoleHandler;
        try {
            //cleanup before starting:
            logger.setUseParentHandlers(false);

            // remove and handlers that will be replaced
            Handler[] handlers = logger.getHandlers();
            for (Handler handler : handlers) {
                if (handler.getClass() == ConsoleHandler.class)
                    logger.removeHandler(handler);
            }

            File logFolder = new File(System.getProperty(LOG_PATH_PROPERTY, ResourceRegistry.TMP_FOLDER));
            if (!logFolder.exists()) {
                FileUtils.forceMkdir(logFolder);
            }
            //Create handlers
            severeFileHandler = new FileHandler(new File(logFolder, "asterics_logger_severe.log").getPath(),
                    true);
            warningFileHandler = new FileHandler(new File(logFolder, "asterics_logger_warning.log").getPath(),
                    true);
            infoFileHandler = new FileHandler(new File(logFolder, "asterics_logger.log").getPath(), true);
            fineFileHandler = new FileHandler(new File(logFolder, "asterics_logger_fine.log").getPath(), true);
            consoleHandler = new ConsoleHandler();

            //Set report level of handlers
            severeFileHandler.setLevel(Level.SEVERE);
            warningFileHandler.setLevel(Level.WARNING);
            infoFileHandler.setLevel(Level.INFO);
            fineFileHandler.setLevel(Level.FINE);

            //The consoleHandler prints log messaged to the console. Its 
            //severety level can be adjusted accordingly. 
            String level = getLoggerLevel();
            switch (level) {
            case "INFO":
                consoleHandler.setLevel(Level.INFO);
                break;
            case "WARNING":
                consoleHandler.setLevel(Level.WARNING);
                break;
            case "FINE":
                consoleHandler.setLevel(Level.FINE);
                break;
            case "SEVERE":
                consoleHandler.setLevel(Level.SEVERE);
                break;

            default:
                consoleHandler.setLevel(Level.INFO);
                break;
            }

            //Add handlers to the logger
            logger.addHandler(warningFileHandler);
            logger.addHandler(severeFileHandler);
            logger.addHandler(infoFileHandler);
            logger.addHandler(fineFileHandler);
            logger.addHandler(consoleHandler);

            //Create formatters for the handlers (optional)
            severeFileHandler.setFormatter(new SimpleFormatter());
            warningFileHandler.setFormatter(new SimpleFormatter());
            infoFileHandler.setFormatter(new SimpleFormatter());
            fineFileHandler.setFormatter(new SimpleFormatter());
            consoleHandler.setFormatter(new SimpleFormatter());

            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);

        } catch (SecurityException e) {
            System.out.println(AstericsErrorHandling.class.getName() + ": Error creating AstericsLogger: "
                    + e.getMessage());
        } catch (IOException e) {
            //logger.warning(this.getClass().getName()+
            //   ": Error creating AstericsLogger: "+e.getMessage());
            System.out.println(AstericsErrorHandling.class.getName() + ": Error creating AstericsLogger: "
                    + e.getMessage());
        }
    }

    return logger;
}