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) throws IOException, SecurityException 

Source Link

Document

Initialize a FileHandler to write to the given filename.

Usage

From source file:fr.ens.transcriptome.teolenn.Main.java

/**
 * Parse the options of the command line
 * @param args command line arguments/*from   ww  w  .ja  va  2s  .  c  o m*/
 * @return the number of optional arguments
 */
private static int parseCommandLine(final String args[]) {

    final Options options = makeOptions();
    final CommandLineParser parser = new GnuParser();

    int argsOptions = 0;

    try {

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            help(options);

        if (line.hasOption("about"))
            about();

        if (line.hasOption("version"))
            version();

        if (line.hasOption("license"))
            license();

        // Load configuration if exists
        try {
            if (line.hasOption("conf")) {
                Settings.loadSettings(new File(line.getOptionValue("conf")));
                argsOptions += 2;
            } else
                Settings.loadSettings();
        } catch (IOException e) {
            logger.severe("Error while reading configuration file.");
            System.exit(1);
        }

        // Set the number of threads
        if (line.hasOption("threads"))
            try {
                argsOptions += 2;
                Settings.setMaxthreads(Integer.parseInt(line.getOptionValue("threads")));
            } catch (NumberFormatException e) {
                logger.warning("Invalid threads number");
            }

        // Set the verbose mode for extenal tools
        if (line.hasOption("verbose")) {
            Settings.setStandardOutputForExecutable(true);
            argsOptions++;
        }

        // Set Log file
        if (line.hasOption("log")) {

            argsOptions += 2;
            try {
                Handler fh = new FileHandler(line.getOptionValue("log"));
                fh.setFormatter(Globals.LOG_FORMATTER);
                logger.setUseParentHandlers(false);

                logger.addHandler(fh);
            } catch (IOException e) {
                logger.severe("Error while creating log file: " + e.getMessage());
                System.exit(1);
            }
        }

        // Set the silent option
        if (line.hasOption("silent"))
            logger.setUseParentHandlers(false);

        // Set log level
        if (line.hasOption("loglevel")) {

            argsOptions += 2;
            try {
                logger.setLevel(Level.parse(line.getOptionValue("loglevel").toUpperCase()));
            } catch (IllegalArgumentException e) {

                logger.warning("Unknown log level (" + line.getOptionValue("loglevel")
                        + "). Accepted values are [SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST].");

            }
        }

    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    } catch (SecurityException e) {
        logger.severe(e.getMessage());
        System.exit(1);
    }

    // If there is no arguments after the option, show help
    if (argsOptions == args.length) {
        System.err.println("No inputs files.");
        System.err.println("type: " + Globals.APP_NAME_LOWER_CASE + " -h for more informations.");
        System.exit(1);
    }

    return argsOptions;
}

From source file:com.piusvelte.taplock.server.TapLockServer.java

private static void initialize() {
    (new File(APP_PATH)).mkdir();
    if (OS == OS_WIN)
        Security.addProvider(new BouncyCastleProvider());
    System.out.println("APP_PATH: " + APP_PATH);
    try {//w ww  . ja  v  a  2 s. c o m
        sLogFileHandler = new FileHandler(sLog);
    } catch (SecurityException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    } catch (IOException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    }

    File propertiesFile = new File(sProperties);
    if (!propertiesFile.exists()) {
        try {
            propertiesFile.createNewFile();
        } catch (IOException e) {
            writeLog("propertiesFile.createNewFile: " + e.getMessage());
        }
    }

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream(sProperties));
        if (prop.isEmpty()) {
            prop.setProperty(sPassphraseKey, sPassphrase);
            prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
            prop.store(new FileOutputStream(sProperties), null);
        } else {
            if (prop.containsKey(sPassphraseKey))
                sPassphrase = prop.getProperty(sPassphraseKey);
            else
                prop.setProperty(sPassphraseKey, sPassphrase);
            if (prop.containsKey(sDisplaySystemTrayKey))
                sDisplaySystemTray = Boolean.parseBoolean(prop.getProperty(sDisplaySystemTrayKey));
            else
                prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            if (prop.containsKey(sDebuggingKey))
                sDebugging = Boolean.parseBoolean(prop.getProperty(sDebuggingKey));
            else
                prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
        }
    } catch (FileNotFoundException e) {
        writeLog("prop load: " + e.getMessage());
    } catch (IOException e) {
        writeLog("prop load: " + e.getMessage());
    }

    if (sLogFileHandler != null) {
        sLogger = Logger.getLogger("TapLock");
        sLogger.setUseParentHandlers(false);
        sLogger.addHandler(sLogFileHandler);
        SimpleFormatter sf = new SimpleFormatter();
        sLogFileHandler.setFormatter(sf);
        writeLog("service starting");
    }

    if (sDisplaySystemTray && SystemTray.isSupported()) {
        final SystemTray systemTray = SystemTray.getSystemTray();
        Image trayIconImg = Toolkit.getDefaultToolkit()
                .getImage(TapLockServer.class.getResource("/systemtrayicon.png"));
        final TrayIcon trayIcon = new TrayIcon(trayIconImg, "Tap Lock");
        trayIcon.setImageAutoSize(true);
        PopupMenu popupMenu = new PopupMenu();
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem toggleSystemTrayIcon = new CheckboxMenuItem("Display Icon in System Tray");
        toggleSystemTrayIcon.setState(sDisplaySystemTray);
        CheckboxMenuItem toggleDebugging = new CheckboxMenuItem("Debugging");
        toggleDebugging.setState(sDebugging);
        MenuItem shutdownItem = new MenuItem("Shutdown Tap Lock Server");
        popupMenu.add(aboutItem);
        popupMenu.add(toggleSystemTrayIcon);
        if (OS == OS_WIN) {
            MenuItem setPasswordItem = new MenuItem("Set password");
            popupMenu.add(setPasswordItem);
            setPasswordItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JPanel panel = new JPanel();
                    JLabel label = new JLabel("Enter your Windows account password:");
                    JPasswordField passField = new JPasswordField(32);
                    panel.add(label);
                    panel.add(passField);
                    String[] options = new String[] { "OK", "Cancel" };
                    int option = JOptionPane.showOptionDialog(null, panel, "Tap Lock", JOptionPane.NO_OPTION,
                            JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (option == 0) {
                        String password = encryptString(new String(passField.getPassword()));
                        if (password != null) {
                            Properties prop = new Properties();
                            try {
                                prop.load(new FileInputStream(sProperties));
                                prop.setProperty(sPasswordKey, password);
                                prop.store(new FileOutputStream(sProperties), null);
                            } catch (FileNotFoundException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            } catch (IOException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            }
                        }
                    }
                }
            });
        }
        popupMenu.add(toggleDebugging);
        popupMenu.add(shutdownItem);
        trayIcon.setPopupMenu(popupMenu);
        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            writeLog("systemTray.add: " + e.getMessage());
        }
        aboutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newline = System.getProperty("line.separator");
                newline += newline;
                JOptionPane.showMessageDialog(null, "Tap Lock" + newline + "Copyright (c) 2012 Bryan Emmanuel"
                        + newline
                        + "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version."
                        + newline
                        + "This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details."
                        + newline
                        + "You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>."
                        + newline + "Bryan Emmanuel piusvelte@gmail.com");
            }
        });
        toggleSystemTrayIcon.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setTrayIconDisplay(e.getStateChange() == ItemEvent.SELECTED);
                if (!sDisplaySystemTray)
                    systemTray.remove(trayIcon);
            }
        });
        toggleDebugging.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setDebugging(e.getStateChange() == ItemEvent.SELECTED);
            }
        });
        shutdownItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                shutdown();
            }
        });
    }
    synchronized (sConnectionThreadLock) {
        (sConnectionThread = new ConnectionThread()).start();
    }
}

From source file:org.manalang.monkeygrease.MonkeygreaseFilter.java

/**
 * Initializes Monkeygrease. Internal servlet filter method.
 * //ww w  .  j a va  2  s .co m
 * @param filterConfig
 * @throws ServletException
 */
public void init(FilterConfig filterConfig) throws ServletException {

    try {
        fh = new FileHandler("monkeygrease_%u.log");
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Send logger output to our FileHandler.
    log.addHandler(fh);
    log.getHandlers()[0].setFormatter(new LogFormatter());

    fc = filterConfig;
    confReloadCheckIntervalStr = fc.getInitParameter("confReloadCheckInterval");
    String commentsOnStr = fc.getInitParameter("commentsOn");
    COMMENTS_ON = commentsOnStr.toLowerCase().equals("true");
    String logLevel = fc.getInitParameter("logLevel");
    int logLevelInt;
    if (logLevel != null)
        logLevelInt = Integer.parseInt(logLevel);
    else
        logLevelInt = 0;
    remoteConfigURL = fc.getInitParameter("remoteConfigURL");
    if (remoteConfigURL != "" && remoteConfigURL != null)
        client = new HttpClient();

    switch (logLevelInt) {
    case SEVERE:
        log.setLevel(Level.SEVERE);
        break;
    case WARNING:
        log.setLevel(Level.WARNING);
        break;
    case INFO:
        log.setLevel(Level.INFO);
        break;
    case CONFIG:
        log.setLevel(Level.CONFIG);
        break;
    case FINE:
        log.setLevel(Level.FINE);
        break;
    case FINER:
        log.setLevel(Level.FINER);
        break;
    case FINEST:
        log.setLevel(Level.FINEST);
        break;
    default:
        log.setLevel(Level.SEVERE);
        break;
    }

    if (confReloadCheckIntervalStr != null && !"".equals(confReloadCheckIntervalStr)) {
        // convert to millis
        confReloadCheckInterval = 1000 * Integer.parseInt(confReloadCheckIntervalStr);
        confReloadCheckEnabled = true;
        if (confReloadCheckInterval == 0) {
            log.config("Reload check performed on each request");
        } else {
            log.config("Reload check set to " + confReloadCheckInterval / 1000 + "s");
        }
    } else {
        confReloadCheckEnabled = false;
    }

    sc = fc.getServletContext();
    cf = new Config(sc);
    rules = cf.getRules();

}

From source file:com.versusoft.packages.ooo.odt2daisy.addon.gui.UnoGUI.java

/**
 *
 * @param m_xContext Component context to be passed to a component via ::com::sun::star::lang::XSingleComponentFactory.
 * @param m_xFrame Frame object that serves as an "anchor" object where a component can be attached to.
 * @param isFullExport true if the content should be exported as Full DAISY, false if the content should be exported as DAISY XML (no audio).
 *///  w ww  .j a v  a  2s  . c  om
public UnoGUI(XComponentContext m_xContext, XFrame m_xFrame, boolean isFullExport) {

    this.m_xContext = m_xContext;
    this.m_xFrame = m_xFrame;
    this.isFullExport = isFullExport;

    try {

        // Configuring logger
        logFile = File.createTempFile(LOG_FILENAME, null);
        fh = new FileHandler(logFile.getAbsolutePath());
        fh.setFormatter(new SimpleFormatter());
        Logger.getLogger("").addHandler(fh);
        Logger.getLogger("").setLevel(Level.FINEST);
        logger.fine("entering");

        // Configuring Locale
        OOoLocale = new Locale(UnoUtils.getUILocale(m_xContext));
        L10N_MessageBox_Warning_Title = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("MessageBox_Warning_Title");
        L10N_No_Headings_Warning = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("No_Headings_Warning");
        L10N_Incompatible_Images_Error = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("Incompatible_Images_Error");
        L10N_Default_Export_Filename = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("Default_Export_Filename");
        L10N_MessageBox_Error_Title = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("MessageBox_Error_Title");
        L10N_DTD_Error_Message = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("DTD_Error_Message");
        L10N_Line = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("Line");
        L10N_Message = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("Message");
        L10N_MessageBox_InternalError_Title = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("MessageBox_InternalError_Title");
        L10N_Export_Aborted_Message = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("Export_Aborted_Message");
        L10N_MessageBox_Info_Title = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("MessageBox_Info_Title");
        L10N_Empty_Document_Message = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("Empty_Document_Message");
        L10N_Validated_DTD_Message = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("Validated_DTD_Message");
        L10N_PipelineLite_Update_Message = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("PipelineLite_Update_Message");
        L10N_PipelineLite_Size_Error_Message = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("PipelineLite_Size_Error_Message");
        L10N_PipelineLite_Extract_Message = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("PipelineLite_Extract_Message");
        L10N_PipelineLite_Extract_Error_Message = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("PipelineLite_Extract_Error_Message");
        L10N_PipelineLite_Exec_Error_Message = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("PipelineLite_Exec_Error_Message");
        L10N_StatusIndicator_Step_1 = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("StatusIndicator_Step_1");
        L10N_StatusIndicator_Step_2 = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("StatusIndicator_Step_2");
        L10N_StatusIndicator_Step_3 = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("StatusIndicator_Step_3");
        L10N_StatusIndicator_Step_4 = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("StatusIndicator_Step_4");
        L10N_StatusIndicator_Step_5 = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("StatusIndicator_Step_5");
        L10N_StatusIndicator_Step_6 = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("StatusIndicator_Step_6");
        L10N_StatusIndicator_Step_7 = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("StatusIndicator_Step_7");
        L10N_StatusIndicator_Step_8 = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("StatusIndicator_Step_8");
        L10N_StatusIndicator_Step_9 = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("StatusIndicator_Step_9");
        L10N_StatusIndicator_Step_10 = java.util.ResourceBundle
                .getBundle("com/versusoft/packages/ooo/odt2daisy/addon/l10n/Bundle", OOoLocale)
                .getString("StatusIndicator_Step_10");

        // Init Status Indicator
        xStatusIndicatorFactory = (XStatusIndicatorFactory) UnoRuntime
                .queryInterface(XStatusIndicatorFactory.class, m_xFrame);
        xStatusIndicator = xStatusIndicatorFactory.createStatusIndicator();

        // Query Uno Object
        xDoc = (XModel) UnoRuntime.queryInterface(XModel.class, m_xFrame.getController().getModel());

        parentWindow = xDoc.getCurrentController().getFrame().getContainerWindow();
        parentWindowPeer = (XWindowPeer) UnoRuntime.queryInterface(XWindowPeer.class, parentWindow);

        //DEBUG MODE
        //UnoAwtUtils.showInfoMessageBox(parentWindowPeer, L10N_MessageBox_Info_Title, "DEBUG MODE: "+logFile.getAbsolutePath());

    } catch (Exception ex) {
        logger.log(Level.SEVERE, null, ex);
    }

}

From source file:edu.harvard.iq.dataverse.harvest.client.HarvesterServiceBean.java

/**
 * Run a harvest for an individual harvesting Dataverse
 * @param dataverseRequest//from   w  w w  .j  a v  a  2 s . co m
 * @param harvestingClientId
 * @throws IOException
 */
public void doHarvest(DataverseRequest dataverseRequest, Long harvestingClientId) throws IOException {
    HarvestingClient harvestingClientConfig = harvestingClientService.find(harvestingClientId);

    if (harvestingClientConfig == null) {
        throw new IOException("No such harvesting client: id=" + harvestingClientId);
    }

    Dataverse harvestingDataverse = harvestingClientConfig.getDataverse();

    MutableBoolean harvestErrorOccurred = new MutableBoolean(false);
    String logTimestamp = logFormatter.format(new Date());
    Logger hdLogger = Logger.getLogger("edu.harvard.iq.dataverse.harvest.client.HarvesterServiceBean."
            + harvestingDataverse.getAlias() + logTimestamp);
    String logFileName = "../logs" + File.separator + "harvest_" + harvestingClientConfig.getName() + "_"
            + logTimestamp + ".log";
    FileHandler fileHandler = new FileHandler(logFileName);
    hdLogger.setUseParentHandlers(false);
    hdLogger.addHandler(fileHandler);

    PrintWriter importCleanupLog = new PrintWriter(new FileWriter(
            "../logs/harvest_cleanup_" + harvestingClientConfig.getName() + "_" + logTimestamp + ".txt"));

    List<Long> harvestedDatasetIds = null;

    List<Long> harvestedDatasetIdsThisBatch = new ArrayList<Long>();

    List<String> failedIdentifiers = new ArrayList<String>();
    List<String> deletedIdentifiers = new ArrayList<String>();

    Date harvestStartTime = new Date();

    try {
        boolean harvestingNow = harvestingClientConfig.isHarvestingNow();

        if (harvestingNow) {
            harvestErrorOccurred.setValue(true);
            hdLogger.log(Level.SEVERE, "Cannot begin harvesting, Dataverse " + harvestingDataverse.getName()
                    + " is currently being harvested.");

        } else {
            harvestingClientService.resetHarvestInProgress(harvestingClientId);
            harvestingClientService.setHarvestInProgress(harvestingClientId, harvestStartTime);

            if (harvestingClientConfig.isOai()) {
                harvestedDatasetIds = harvestOAI(dataverseRequest, harvestingClientConfig, hdLogger,
                        importCleanupLog, harvestErrorOccurred, failedIdentifiers, deletedIdentifiers,
                        harvestedDatasetIdsThisBatch);

            } else {
                throw new IOException("Unsupported harvest type");
            }
            harvestingClientService.setHarvestSuccess(harvestingClientId, new Date(),
                    harvestedDatasetIds.size(), failedIdentifiers.size(), deletedIdentifiers.size());
            hdLogger.log(Level.INFO, "COMPLETED HARVEST, server=" + harvestingClientConfig.getArchiveUrl()
                    + ", metadataPrefix=" + harvestingClientConfig.getMetadataPrefix());
            hdLogger.log(Level.INFO,
                    "Datasets created/updated: " + harvestedDatasetIds.size() + ", datasets deleted: "
                            + deletedIdentifiers.size() + ", datasets failed: " + failedIdentifiers.size());

            // now index all the datasets we have harvested - created, modified or deleted:
            /* (TODO: may not be needed at all. In Dataverse4, we may be able to get away with the normal 
            reindexing after every import. See the rest of the comments about batch indexing throughout 
            this service bean)
            if (this.processedSizeThisBatch > 0) {
                hdLogger.log(Level.INFO, "POST HARVEST, reindexing the remaining studies.");
                if (this.harvestedDatasetIdsThisBatch != null) {
                    hdLogger.log(Level.INFO, this.harvestedDatasetIdsThisBatch.size()+" studies in the batch");
                }
                hdLogger.log(Level.INFO, this.processedSizeThisBatch + " bytes of content");
                indexService.updateIndexList(this.harvestedDatasetIdsThisBatch);
                hdLogger.log(Level.INFO, "POST HARVEST, calls to index finished.");
            } else {
                hdLogger.log(Level.INFO, "(All harvested content already reindexed)");
            }
             */
        }
        //mailService.sendHarvestNotification(...getSystemEmail(), harvestingDataverse.getName(), logFileName, logTimestamp, harvestErrorOccurred.booleanValue(), harvestedDatasetIds.size(), failedIdentifiers);
    } catch (Throwable e) {
        harvestErrorOccurred.setValue(true);
        String message = "Exception processing harvest, server= " + harvestingClientConfig.getHarvestingUrl()
                + ",format=" + harvestingClientConfig.getMetadataPrefix() + " " + e.getClass().getName() + " "
                + e.getMessage();
        hdLogger.log(Level.SEVERE, message);
        logException(e, hdLogger);
        hdLogger.log(Level.INFO, "HARVEST NOT COMPLETED DUE TO UNEXPECTED ERROR.");
        // TODO: 
        // even though this harvesting run failed, we may have had successfully 
        // processed some number of datasets, by the time the exception was thrown. 
        // We should record that number too. And the number of the datasets that
        // had failed, that we may have counted.  -- L.A. 4.4
        harvestingClientService.setHarvestFailure(harvestingClientId, new Date());

    } finally {
        harvestingClientService.resetHarvestInProgress(harvestingClientId);
        fileHandler.close();
        hdLogger.removeHandler(fileHandler);
        importCleanupLog.close();
    }
}

From source file:com.symbian.driver.remoting.master.TDIWrapper.java

/**
 * initialization: checks all required folders exist. Load the manifest and
 * unzip the files required to run the tests.
 * /*from  w ww.j a  va 2 s .co  m*/
 * @param aTestPackage
 *            String : a test package path name.
 * @throws ParseException
 * @throws TimeLimitExceededException
 */
private Task initialize(File aTestPackage, File lResultsPath)
        throws IOException, ParseException, TimeLimitExceededException {
    TDConfig CONFIG = TDConfig.getInstance();

    File lRepository = CONFIG.getPreferenceFile(TDConfig.REPOSITORY_ROOT);
    File lEpocRoot = CONFIG.getPreferenceFile(TDConfig.EPOC_ROOT);

    // create results folder
    if (!lResultsPath.isDirectory() && !lResultsPath.mkdirs()) {
        throw new IOException("Could not create results directory." + lResultsPath.toString());
    }
    // set the results root to the output folder
    CONFIG.setPreferenceFile(TDConfig.RESULT_ROOT, lResultsPath);

    // set the logger to log to a file in the resultsPath
    iTraceHandler = new FileHandler(lResultsPath.getAbsolutePath() + File.separator + "trace.txt");
    Logger.getLogger("").addHandler(iTraceHandler);
    // create Input folder where to unzip the testpackage
    File lInputPath = new File(lResultsPath.getParent(), "Input");
    if (!lInputPath.isDirectory() && !lInputPath.mkdirs()) {
        throw new IOException("Could not create Input directory.");
    }
    Properties manifest = new Properties();
    // unzip it
    File lDepZip = new File(lInputPath.getAbsolutePath() + File.separator + "dependencies.zip");
    File lStatZip = new File(lInputPath.getAbsolutePath() + File.separator + "Stat.zip");
    File lRepositoryZip = new File(lInputPath.getAbsolutePath() + File.separator + "repository.zip");
    File lXmlZip = new File(lInputPath.getAbsolutePath() + File.separator + "xml.zip");

    LOGGER.fine("Unzipping package :" + aTestPackage.getName() + " To : " + lInputPath.getCanonicalPath());
    Zipper.Unzip(aTestPackage, lInputPath);

    LOGGER.fine("Reading manifest : " + lInputPath.getAbsolutePath() + File.separator + "Manifest.mf");

    manifest.load(new FileInputStream(lInputPath.getAbsolutePath() + File.separator + "Manifest.mf"));

    CONFIG.setPreference(TDConfig.PLATFORM, manifest.getProperty("platform"));
    CONFIG.setPreference(TDConfig.VARIANT, manifest.getProperty("build"));
    CONFIG.setPreferenceBoolean(TDConfig.PLATSEC, manifest.getProperty("platsec").equalsIgnoreCase("true")
            || manifest.getProperty("platsec").equalsIgnoreCase("on"));
    CONFIG.setPreferenceBoolean(TDConfig.TEST_EXECUTE, manifest.getProperty("testexec").equalsIgnoreCase("true")
            || manifest.getProperty("testexec").equalsIgnoreCase("on"));
    CONFIG.setPreferenceBoolean(TDConfig.SYS_BIN, manifest.getProperty("sysbin").equalsIgnoreCase("true")
            || manifest.getProperty("sysbin").equalsIgnoreCase("on"));
    CONFIG.setPreference(TDConfig.BUILD_NUMBER, manifest.getProperty("buildNumber"));
    CONFIG.setPreference(TDConfig.KERNEL, manifest.getProperty("kernel"));
    String lTransport = manifest.getProperty("transport");
    if (lTransport != null) {
        LOGGER.fine("Setting Transport to : " + lTransport);
        CONFIG.setPreference(TDConfig.TRANSPORT, lTransport);
    }
    String lRdebug = manifest.getProperty("rdebug");
    if (lRdebug != null) {
        CONFIG.setPreference(TDConfig.RDEBUG, lResultsPath.getCanonicalPath() + manifest.getProperty("rdebug"));
    }

    if (lRepositoryZip.isFile()) {
        LOGGER.fine("Unzipping " + lRepositoryZip.getAbsolutePath() + " To : " + lRepository);
        Zipper.Unzip(lRepositoryZip, lRepository);
        lRepositoryZip.delete();
    }

    File lRomImage = new File(lInputPath.getAbsolutePath(),
            manifest.getProperty("romFile") != null ? manifest.getProperty("romFile") : "NULL");
    LOGGER.fine("unzipping rom : " + lRomImage.toString() + "..." + manifest.getProperty("romFile"));
    if (lRomImage.isFile()) {
        if (Epoc.isTargetEmulator(CONFIG.getPreference(TDConfig.PLATFORM))) {
            LOGGER.info("Unzipping emulator image " + lRomImage.getAbsolutePath() + " To : " + lEpocRoot);

            Zipper.Unzip(lRomImage, lEpocRoot);
            lRomImage.delete();
        } else {
            LOGGER.info("Flashing " + lRomImage + " through port "
                    + CONFIG.getPreferenceInteger(TDConfig.TARGET_TEST));

            restoreRom(lRomImage, CONFIG.getPreferenceInteger(TDConfig.TARGET_TEST));

            try {
                // This is just a temporary solution as JStat connect hangs  
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                //do nothing
            }
        }
    }

    try {
        if (lDepZip.isFile()) {
            LOGGER.fine("Unzipping " + lDepZip.getAbsolutePath() + " To : " + lEpocRoot);
            Zipper.Unzip(lDepZip, lEpocRoot);
            lDepZip.delete();
        }

        if (lStatZip.isFile()) {
            LOGGER.fine("Unzipping " + lStatZip.getAbsolutePath() + " To : " + lEpocRoot);
            Zipper.Unzip(lStatZip, lEpocRoot);
            lStatZip.delete();
        }
    } catch (IOException lIO) {
        LOGGER.log(Level.SEVERE, "Failed to install dependencies " + lIO.getMessage());
    }

    File lTempFile = createTempDir(lResultsPath.getCanonicalPath(), "testDriverRemote", "driver");

    URI lXmlUri = URI
            .createFileURI(lTempFile.getCanonicalPath() + File.separator + manifest.getProperty("xmldriver"));
    lXmlUri = lXmlUri.appendFragment(manifest.getProperty("suite"));

    LOGGER.fine("Setting test suite to : " + lXmlUri.toString());
    CONFIG.setPreferenceURI(TDConfig.ENTRY_POINT_ADDRESS, lXmlUri);
    if (lXmlZip.isFile()) {
        LOGGER.fine("Unzipping " + lXmlZip.getAbsolutePath() + " To : " + lTempFile);
        String lPlatform = CONFIG.getPreference(TDConfig.PLATFORM);
        String lVariant = CONFIG.getPreference(TDConfig.VARIANT);
        File lSourceRoot = CONFIG.getPreferenceFile(TDConfig.SOURCE_ROOT);
        File lXmlRoot = CONFIG.getPreferenceFile(TDConfig.XML_ROOT);
        Zipper.Unzip(lXmlZip, lTempFile, lEpocRoot, lXmlRoot, lSourceRoot, lPlatform, lVariant);
        lXmlZip.delete();
    }
    return ResourceLoader.load(lXmlUri);
}

From source file:org.apache.oodt.cas.pge.PGETaskInstance.java

protected Logger createLogger() throws IOException, PGEException {
    File logDir = new File(pgeConfig.getExeDir(), "logs");
    if (!(logDir.exists() || logDir.mkdirs())) {
        throw new PGEException("mkdirs for logs directory return false");
    }//from w w  w. j av a2s .c  om

    Logger logger = Logger.getLogger(PGETaskInstance.class.getName() + "." + workflowInstId);
    FileHandler handler = new FileHandler(new File(logDir, createLogFileName()).getAbsolutePath());
    handler.setEncoding("UTF-8");
    handler.setFormatter(new SimpleFormatter());
    logger.addHandler(handler);
    return logger;
}

From source file:com.coprtools.core.CopyrightToolsEngine.java

/**
 * Enables the logging capabilities. Creates a log file in the roots path.
 *
 * @param rootPath/*from  w w  w  .  ja  v a  2 s . c o  m*/
 *            - the projects's root directory
 * @throws SecurityException
 * @throws IOException
 */
private void enableLogging(String rootPath) throws SecurityException, IOException {
    LOGGER.setLevel(Level.ALL);
    String logFilePath = rootPath + File.separator + InserterConstants.LOG_FILENAME;
    this.fileHandler = new FileHandler(logFilePath);
    fileHandler.setFormatter(new SimpleFormatter());
    fileHandler.setLevel(Level.ALL);
    LOGGER.addHandler(fileHandler);
}

From source file:uk.sipperfly.ui.Exactly.java

/**
 * Initialize the logger./* w w  w . ja v a  2 s . co m*/
 * Creates a log called "logfile.txt" in the current directory.
 */
public void initLogger() {
    logger = Logger.getLogger(GACOM);
    logger.setLevel(Level.INFO);
    try {
        filehandler = new FileHandler("logfile.txt");
        simpleformatter = new SimpleFormatter();
        filehandler.setFormatter(simpleformatter);

    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
    logger.addHandler(filehandler);
}

From source file:org.kalypso.model.hydrology.internal.test.OptimizeTest.java

private Logger createLogger(final File logFile) throws SecurityException, IOException {
    final Logger logger = Logger.getAnonymousLogger();
    final Handler[] handlers = logger.getHandlers();
    for (final Handler handler : handlers)
        logger.removeHandler(handler);/*ww w.j  av a  2  s . c o m*/

    final FileHandler fileHandler = new FileHandler(logFile.getAbsolutePath());
    logger.addHandler(fileHandler);

    return logger;
}