Search in sources :

Example 86 with FileHandler

use of java.util.logging.FileHandler in project dataverse by IQSS.

the class HarvesterServiceBean method doHarvest.

/**
 * Run a harvest for an individual harvesting Dataverse
 * @param dataverseRequest
 * @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();
    }
}
Also used : MutableBoolean(org.apache.commons.lang.mutable.MutableBoolean) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Logger(java.util.logging.Logger) Dataverse(edu.harvard.iq.dataverse.Dataverse) Date(java.util.Date) FileHandler(java.util.logging.FileHandler) MutableLong(org.apache.commons.lang.mutable.MutableLong) PrintWriter(java.io.PrintWriter)

Example 87 with FileHandler

use of java.util.logging.FileHandler in project dataverse by IQSS.

the class OAISetServiceBean method exportAllSets.

public void exportAllSets() {
    String logTimestamp = logFormatter.format(new Date());
    Logger exportLogger = Logger.getLogger("edu.harvard.iq.dataverse.harvest.client.OAISetServiceBean." + "UpdateAllSets." + logTimestamp);
    String logFileName = "../logs" + File.separator + "oaiSetsUpdate_" + logTimestamp + ".log";
    FileHandler fileHandler = null;
    boolean fileHandlerSuceeded = false;
    try {
        fileHandler = new FileHandler(logFileName);
        exportLogger.setUseParentHandlers(false);
        fileHandlerSuceeded = true;
    } catch (IOException | SecurityException ex) {
        Logger.getLogger(DatasetServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (fileHandlerSuceeded) {
        exportLogger.addHandler(fileHandler);
    } else {
        exportLogger = logger;
    }
    List<OAISet> allSets = findAll();
    if (allSets != null) {
        for (OAISet set : allSets) {
            exportOaiSet(set, exportLogger);
        }
    }
    if (fileHandlerSuceeded) {
        // no, we are not potentially de-referencing a NULL pointer -
        // it's not NULL if fileHandlerSucceeded is true.
        fileHandler.close();
    }
}
Also used : DatasetServiceBean(edu.harvard.iq.dataverse.DatasetServiceBean) IOException(java.io.IOException) Logger(java.util.logging.Logger) Date(java.util.Date) FileHandler(java.util.logging.FileHandler)

Example 88 with FileHandler

use of java.util.logging.FileHandler in project dataverse by IQSS.

the class AuthFilter method init.

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    logger.info(AuthFilter.class.getName() + "initialized. filterConfig.getServletContext().getServerInfo(): " + filterConfig.getServletContext().getServerInfo());
    try {
        String glassfishLogsDirectory = "logs";
        FileHandler logFile = new FileHandler(".." + File.separator + glassfishLogsDirectory + File.separator + "authfilter.log");
        SimpleFormatter formatterTxt = new SimpleFormatter();
        logFile.setFormatter(formatterTxt);
        logger.addHandler(logFile);
    } catch (IOException ex) {
        Logger.getLogger(AuthFilter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(AuthFilter.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : SimpleFormatter(java.util.logging.SimpleFormatter) IOException(java.io.IOException) FileHandler(java.util.logging.FileHandler)

Example 89 with FileHandler

use of java.util.logging.FileHandler in project dataverse by IQSS.

the class LoggingUtil method getJobLogger.

public static Logger getJobLogger(String jobId) {
    try {
        Logger jobLogger = Logger.getLogger("job-" + jobId);
        FileHandler fh;
        String logDir = System.getProperty("com.sun.aas.instanceRoot") + System.getProperty("file.separator") + "logs" + System.getProperty("file.separator") + "batch-jobs" + System.getProperty("file.separator");
        checkCreateLogDirectory(logDir);
        fh = new FileHandler(logDir + "job-" + jobId + ".log");
        logger.log(Level.INFO, "JOB LOG: " + logDir + "job-" + jobId + ".log");
        jobLogger.addHandler(fh);
        fh.setFormatter(new JobLogFormatter());
        return jobLogger;
    } catch (SecurityException e) {
        logger.log(Level.SEVERE, "Unable to create job logger: " + e.getMessage());
        return null;
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Unable to create job logger: " + e.getMessage());
        return null;
    }
}
Also used : IOException(java.io.IOException) Logger(java.util.logging.Logger) FileHandler(java.util.logging.FileHandler)

Example 90 with FileHandler

use of java.util.logging.FileHandler in project AndrOBD by fr3ts0n.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    // instantiate superclass
    super.onCreate(savedInstanceState);
    // requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    requestWindowFeature(Window.FEATURE_PROGRESS);
    // get additional permissions
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Storage Permissions
        final int REQUEST_EXTERNAL_STORAGE = 1;
        final String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE };
        requestPermissions(PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        // Workaround for FileUriExposedException in Android >= M
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
    }
    dlgBuilder = new AlertDialog.Builder(this);
    // get preferences
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    // register for later changes
    prefs.registerOnSharedPreferenceChangeListener(this);
    // Overlay feature has to be set before window content is set
    if (prefs.getBoolean(PREF_AUTOHIDE, false) && prefs.getBoolean(PREF_OVERLAY, false))
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
    // Set up all data adapters
    mPidAdapter = new ObdItemAdapter(this, R.layout.obd_item, ObdProt.PidPvs);
    mVidAdapter = new VidItemAdapter(this, R.layout.obd_item, ObdProt.VidPvs);
    mDfcAdapter = new DfcItemAdapter(this, R.layout.obd_item, ObdProt.tCodes);
    currDataAdapter = mPidAdapter;
    // get list view
    mListView = getWindow().getLayoutInflater().inflate(R.layout.obd_list, null);
    // update all settings from preferences
    onSharedPreferenceChanged(prefs, null);
    // set up logging ...
    String logFileName = FileHelper.getPath(this).concat(File.separator).concat("log");
    try {
        // ensure log directory is available
        new File(logFileName).mkdirs();
        // Create new log file handler (max. 250 MB, 5 files rotated, non appending)
        logFileHandler = new FileHandler(logFileName.concat("/AndrOBD.log.%g.txt"), 250 * 1024 * 1024, 5, false);
        // Set log message formatter
        logFileHandler.setFormatter(new SimpleFormatter() {

            String format = "%1$tF\t%1$tT.%1$tL\t%4$s\t%3$s\t%5$s%n";

            @Override
            public synchronized String format(LogRecord lr) {
                return String.format(format, new Date(lr.getMillis()), lr.getSourceClassName(), lr.getLoggerName(), lr.getLevel().getLocalizedName(), lr.getMessage());
            }
        });
        // add file logging ...
        Logger.getLogger("").addHandler(logFileHandler);
        // set
        setLogLevels();
    } catch (IOException e) {
        // try to log error (at least with system logging)
        log.log(Level.SEVERE, logFileName, e);
    }
    // Log program startup
    log.info(String.format("%s %s starting", getString(R.string.app_name), getString(R.string.app_version)));
    // create file helper instance
    fileHelper = new FileHelper(this, CommService.elm);
    // set listeners for data structure changes
    setDataListeners();
    // automate elm status display
    CommService.elm.addPropertyChangeListener(this);
    // set up action bar
    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setDisplayShowTitleEnabled(true);
    }
    // start automatic toolbar hider
    setAutoHider(prefs.getBoolean(PREF_AUTOHIDE, false));
    // set content view
    setContentView(R.layout.startup_layout);
    // override comm medium with USB connect intent
    if ("android.hardware.usb.action.USB_DEVICE_ATTACHED".equals(getIntent().getAction())) {
        CommService.medium = CommService.MEDIUM.USB;
    }
    switch(CommService.medium) {
        case BLUETOOTH:
            // Get local Bluetooth adapter
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            log.fine("Adapter: " + mBluetoothAdapter);
            // If BT is not on, request that it be enabled.
            if (getMode() != MODE.DEMO && mBluetoothAdapter != null) {
                // remember initial bluetooth state
                initialBtStateEnabled = mBluetoothAdapter.isEnabled();
                if (!initialBtStateEnabled) {
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                }
            }
            break;
        case USB:
        case NETWORK:
            setMode(MODE.ONLINE);
            break;
    }
}
Also used : AlertDialog(android.app.AlertDialog) SimpleFormatter(java.util.logging.SimpleFormatter) Intent(android.content.Intent) IOException(java.io.IOException) Date(java.util.Date) FileHandler(java.util.logging.FileHandler) StrictMode(android.os.StrictMode) LogRecord(java.util.logging.LogRecord) File(java.io.File) ActionBar(android.app.ActionBar)

Aggregations

FileHandler (java.util.logging.FileHandler)139 SimpleFormatter (java.util.logging.SimpleFormatter)59 IOException (java.io.IOException)49 File (java.io.File)48 Logger (java.util.logging.Logger)36 Handler (java.util.logging.Handler)34 ConsoleHandler (java.util.logging.ConsoleHandler)15 Properties (java.util.Properties)14 BalancerRunner (org.mobicents.tools.sip.balancer.BalancerRunner)13 Formatter (java.util.logging.Formatter)12 Config (edu.neu.ccs.pyramid.configuration.Config)11 Date (java.util.Date)11 LogRecord (java.util.logging.LogRecord)10 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 Level (java.util.logging.Level)4 Pair (edu.neu.ccs.pyramid.util.Pair)3 FileInputStream (java.io.FileInputStream)3 FileNotFoundException (java.io.FileNotFoundException)3 LogFormat (de.Keyle.MyPet.api.util.LogFormat)2 CTFT (edu.neu.ccs.pyramid.calibration.CTFT)2