Search in sources :

Example 6 with IImExporter

use of de.janrufmonitor.repository.imexport.IImExporter in project janrufmonitor by tbrandt77.

the class ConsoleImport method execute.

public void execute() throws Exception {
    this.isExecuting = true;
    if (this.getExecuteParams().length != 1) {
        System.out.println("ERROR: Paramters are invalid. Please specify a valid module for installation.");
        this.isExecuting = false;
        return;
    }
    String filename = this.getExecuteParams()[0];
    IImExporter imp = ImExportFactory.getInstance().getImporter("OldDatFileCallerImporter");
    if (imp != null && imp instanceof ICallerImporter) {
        ((ICallerImporter) imp).setFilename(filename);
        ICallerList cl = ((ICallerImporter) imp).doImport();
        ICallerManager mgr = this.getRuntime().getCallerManagerFactory().getCallerManager("CallerDirectory");
        if (mgr != null && mgr.isActive() && mgr.isSupported(IWriteCallerRepository.class)) {
            ((IWriteCallerRepository) mgr).setCaller(cl);
            System.out.println("INFO: Successfully imported " + cl.size() + " caller entries.");
        } else {
            System.out.println("ERROR: Caller manager is missing.");
        }
    } else {
        System.out.println("ERROR: import filter for DAT files is missing.");
    }
    this.isExecuting = false;
}
Also used : ICallerList(de.janrufmonitor.framework.ICallerList) IWriteCallerRepository(de.janrufmonitor.repository.types.IWriteCallerRepository) IImExporter(de.janrufmonitor.repository.imexport.IImExporter) ICallerImporter(de.janrufmonitor.repository.imexport.ICallerImporter) ICallerManager(de.janrufmonitor.repository.ICallerManager)

Example 7 with IImExporter

use of de.janrufmonitor.repository.imexport.IImExporter in project janrufmonitor by tbrandt77.

the class SynchronizerService method synchronize.

public void synchronize(IProgressMonitor progressMonitor) {
    if (m_activeSync)
        return;
    this.m_activeSync = true;
    long start = System.currentTimeMillis();
    if (m_logger.isLoggable(Level.INFO))
        m_logger.info("--> Start Synchronizing (" + (progressMonitor == null ? "w/o progress monitor" : "with progress monitor") + ")");
    if (this.m_tamMap == null)
        this.m_tamMap = new HashMap();
    this.m_tamMap.clear();
    if (progressMonitor != null) {
        progressMonitor.beginTask(getI18nManager().getString(getNamespace(), "refreshprogress", "label", getLanguage()), IProgressMonitor.UNKNOWN);
        progressMonitor.worked(1);
        progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "loginprogress", "label", getLanguage()));
    }
    try {
        Thread.sleep((progressMonitor != null ? 500 : 100));
    } catch (InterruptedException e1) {
        m_logger.log(Level.SEVERE, e1.getMessage(), e1);
    }
    FirmwareManager fwm = FirmwareManager.getInstance();
    // fwm.startup();
    try {
        if (!fwm.isLoggedIn())
            fwm.login();
        if (progressMonitor != null)
            progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "getprogress", "label", getLanguage()));
        try {
            Thread.sleep((progressMonitor != null ? 1500 : 100));
        } catch (InterruptedException e1) {
            m_logger.log(Level.SEVERE, e1.getMessage(), e1);
        }
        long synctime = Long.parseLong(SynchronizerService.this.m_configuration.getProperty(CFG_SYNCTIME, "-1"));
        long oldestCallTime = -1;
        // added: 2013/02/04: check sync all
        boolean syncall = SynchronizerService.this.m_configuration.getProperty(CFG_SYNCALL, "false").equalsIgnoreCase("true");
        if (syncall) {
            synctime = -1;
            if (m_logger.isLoggable(Level.INFO))
                m_logger.info("Sync all option enabled.");
        }
        // sub getSynctimeOffset from time
        if (synctime > 0) {
            if (m_logger.isLoggable(Level.INFO))
                m_logger.info("Sync timestamp before decrementing offset: " + synctime);
            synctime -= this.getSyncTimeOffset();
            if (m_logger.isLoggable(Level.INFO))
                m_logger.info("Sync timestamp after decrementing offset: " + synctime);
        }
        if (m_logger.isLoggable(Level.INFO))
            m_logger.info("Syncing call list from FRITZ!Box with timestamp: " + synctime);
        List result = fwm.getCallList(synctime);
        if (m_logger.isLoggable(Level.INFO))
            m_logger.info("Call list size from FRITZ!Box: " + result.size());
        if (result.size() > 0) {
            ICallList m_callList = PIMRuntime.getInstance().getCallFactory().createCallList(result.size());
            List m_prefilteredList = new ArrayList(result.size());
            FritzBoxCallCsv call = null;
            Properties conf = PIMRuntime.getInstance().getConfigManagerFactory().getConfigManager().getProperties(FritzBoxMonitor.NAMESPACE);
            ICall c = null;
            FritzBoxUUIDManager.getInstance().init();
            boolean skipOutgoing = !Boolean.parseBoolean(conf.getProperty(CFG_OUTGOING, "false"));
            for (int i = 0, j = result.size(); i < j; i++) {
                call = new FritzBoxCallCsv((String) result.get(i), conf);
                // added 2016/01/11: check if outgoing call applicable
                if (call != null) {
                    if (call.isOutgoingCall() && skipOutgoing) {
                        if (m_logger.isLoggable(Level.INFO))
                            m_logger.info("Call import skipped by call state (outgoing) from FRITZ!Box.");
                        continue;
                    }
                    Date calltime = call.getPrecalculatedDate();
                    if (calltime != null && calltime.getTime() < synctime && synctime > 0) {
                        if (m_logger.isLoggable(Level.INFO))
                            m_logger.info("Call import skipped by timestamp (last sync time: " + new Date(synctime).toString() + ", call time: " + calltime.toString() + ") from FRITZ!Box.");
                        continue;
                    }
                    if (calltime != null && synctime < 0) {
                        if (oldestCallTime == -1)
                            oldestCallTime = calltime.getTime();
                        if (oldestCallTime > calltime.getTime())
                            oldestCallTime = calltime.getTime();
                        if (m_logger.isLoggable(Level.INFO))
                            m_logger.info("Set oldest call time to: " + new Date(oldestCallTime).toString());
                    }
                    m_prefilteredList.add(call);
                }
            }
            if (m_prefilteredList.size() > 0) {
                if (progressMonitor != null)
                    progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "identifyprogress", "label", getLanguage()));
                try {
                    Thread.sleep((progressMonitor != null ? 1000 : 100));
                } catch (InterruptedException e1) {
                    m_logger.log(Level.SEVERE, e1.getMessage(), e1);
                }
                for (int i = 0, j = m_prefilteredList.size(); i < j; i++) {
                    c = ((FritzBoxCallCsv) m_prefilteredList.get(i)).toCall();
                    if (c != null) {
                        if (getRuntime().getMsnManager().isMsnMonitored(c.getMSN())) {
                            if (progressMonitor != null) {
                                progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "processing", "label", getLanguage()) + Formatter.getInstance(this.getRuntime()).parse(IJAMConst.GLOBAL_VARIABLE_CALLERNUMBER, c));
                                try {
                                    Thread.sleep(75);
                                } catch (InterruptedException e1) {
                                    m_logger.log(Level.SEVERE, e1.getMessage(), e1);
                                }
                            }
                            if (!m_callList.contains(c)) {
                                if (m_logger.isLoggable(Level.INFO))
                                    m_logger.info("Adding call imported from FRITZ!Box: " + c.toString());
                                m_callList.add(c);
                            } else {
                                if (m_logger.isLoggable(Level.WARNING))
                                    m_logger.warning("Adding duplicated call imported from FRITZ!Box: " + c.toString());
                                c.setUUID(c.getUUID() + "-1");
                                ICip cip = c.getCIP();
                                // just a dirty hack
                                cip.setCIP("4");
                                c.setCIP(cip);
                                if (!m_callList.contains(c))
                                    m_callList.add(c);
                                else {
                                    c.setUUID(c.getUUID() + "-1");
                                    if (!m_callList.contains(c))
                                        m_callList.add(c);
                                }
                            }
                        }
                    }
                }
            }
            if (m_callList != null && m_callList.size() > 0) {
                if (progressMonitor != null)
                    progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "geocodeprogress", "label", getLanguage()));
                try {
                    Thread.sleep((progressMonitor != null ? 1000 : 100));
                } catch (InterruptedException e1) {
                    m_logger.log(Level.SEVERE, e1.getMessage(), e1);
                }
                boolean synctam = SynchronizerService.this.m_configuration.getProperty(CFG_SYNCTAM, "false").equalsIgnoreCase("true");
                if (synctam) {
                    if (m_logger.isLoggable(Level.INFO))
                        m_logger.info("Sync TAM recordings: " + Boolean.toString(synctam));
                    if (progressMonitor != null)
                        progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "tamprogress", "label", getLanguage()));
                    this.m_tamMap.putAll(fwm.getTamMessages(synctime));
                    try {
                        Thread.sleep((progressMonitor != null ? 1000 : 100));
                    } catch (InterruptedException e1) {
                        m_logger.log(Level.SEVERE, e1.getMessage(), e1);
                    }
                }
                if (m_logger.isLoggable(Level.INFO))
                    m_logger.info("Processing modifier services on call list: " + getRuntime().getServiceFactory().getModifierServices());
                processModifierServices(m_callList, progressMonitor);
                if (progressMonitor != null)
                    progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "synchprogress", "label", getLanguage()));
                try {
                    Thread.sleep((progressMonitor != null ? 1000 : 100));
                } catch (InterruptedException e1) {
                    m_logger.log(Level.SEVERE, e1.getMessage(), e1);
                }
                String repository = getRuntime().getConfigManagerFactory().getConfigManager().getProperty(Journal.NAMESPACE, "repository");
                ICallManager cm = getRuntime().getCallManagerFactory().getCallManager(repository);
                if (cm != null && cm.isActive() && cm.isSupported(IWriteCallRepository.class)) {
                    ICall ca = null;
                    boolean syncclean = SynchronizerService.this.m_configuration.getProperty(CFG_SYNCCLEAN, "false").equalsIgnoreCase("true");
                    if (synctime < 0) {
                        if (m_logger.isLoggable(Level.INFO))
                            m_logger.info("Set syntime to oldest call time to eliminate duplicates.");
                        synctime = oldestCallTime;
                    }
                    if (syncclean && synctime > 0 && cm.isSupported(IReadCallRepository.class) && cm.isSupported(IWriteCallRepository.class)) {
                        if (m_logger.isLoggable(Level.INFO))
                            m_logger.info("Remove duplicated entries (sync clean) option enabled.");
                        if (progressMonitor != null)
                            progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "syncclean", "label", getLanguage()));
                        try {
                            Thread.sleep((progressMonitor != null ? 500 : 100));
                        } catch (InterruptedException e1) {
                            m_logger.log(Level.SEVERE, e1.getMessage(), e1);
                        }
                        IFilter syncFilter = new DateFilter(new Date(System.currentTimeMillis()), new Date(synctime));
                        ICallList cl = ((IReadCallRepository) cm).getCalls(syncFilter);
                        if (cl.size() > 0) {
                            // 2009/03/18: added backup of cleaned calls
                            IImExporter exp = ImExportFactory.getInstance().getExporter("DatFileCallExporter");
                            if (exp != null & exp instanceof ICallExporter) {
                                if (m_logger.isLoggable(Level.INFO))
                                    m_logger.info("Creating backup of cleaned call list...");
                                File backupdir = new File(PathResolver.getInstance(getRuntime()).getDataDirectory(), "fritzbox-sync-clean-backup");
                                if (!backupdir.exists()) {
                                    backupdir.mkdirs();
                                }
                                File backupfile = new File(backupdir, Long.toString(synctime) + ".dat");
                                ((ICallExporter) exp).setFilename(backupfile.getAbsolutePath());
                                ((ICallExporter) exp).setCallList(cl);
                                if (((ICallExporter) exp).doExport()) {
                                    if (m_logger.isLoggable(Level.INFO))
                                        m_logger.info("Backup of cleaned call list successfully finished: " + backupfile.getAbsolutePath());
                                } else {
                                    if (m_logger.isLoggable(Level.WARNING))
                                        m_logger.warning("Backup of cleaned call list failed: " + backupdir.getAbsolutePath());
                                }
                            }
                            ((IWriteCallRepository) cm).removeCalls(createRedundancyList(m_callList, synctime));
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                    for (int i = 0, j = m_callList.size(); i < j; i++) {
                        ca = m_callList.get(i);
                        try {
                            ((IWriteCallRepository) cm).setCall(ca);
                            if (progressMonitor != null) {
                                progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "processing2", "label", getLanguage()) + Formatter.getInstance(this.getRuntime()).parse(IJAMConst.GLOBAL_VARIABLE_CALLERNAME, ca));
                                try {
                                    Thread.sleep(50);
                                } catch (InterruptedException e1) {
                                    m_logger.log(Level.SEVERE, e1.getMessage(), e1);
                                }
                            }
                            if (m_logger.isLoggable(Level.INFO))
                                m_logger.info("Call imported to repository: " + ca.toString());
                        } catch (Exception e) {
                            if (m_logger.isLoggable(Level.WARNING))
                                m_logger.warning("Call already in repository (skipped): " + ca.toString());
                        }
                    }
                    // added 2009/01/08: force refresh of journal, if opened
                    IEventBroker evtBroker = getRuntime().getEventBroker();
                    evtBroker.register(this);
                    evtBroker.send(this, evtBroker.createEvent(IEventConst.EVENT_TYPE_CALL_MANAGER_UPDATED));
                    evtBroker.unregister(this);
                    if (m_logger.isLoggable(Level.INFO))
                        m_logger.info("EventBroker notification sent: EVENT_TYPE_CALL_MANAGER_UPDATED");
                }
                boolean syncDelete = (m_configuration.getProperty(FritzBoxConst.CFG_SYNCDELETE, "false").equalsIgnoreCase("true") ? true : false);
                if (syncDelete) {
                    if (m_logger.isLoggable(Level.INFO))
                        m_logger.info("Delete after sync (sync delete) option enabled.");
                    if (progressMonitor != null)
                        progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "deleteprogress", "label", getLanguage()));
                    fwm.deleteCallList();
                }
                // added 2009/01/07: send mail notification after sync with fritzbox
                boolean syncNotify = (SynchronizerService.this.m_configuration.getProperty(FritzBoxConst.CFG_SYNC_NOTIFICATION, "false").equalsIgnoreCase("true") ? true : false);
                if (syncNotify) {
                    if (m_logger.isLoggable(Level.INFO))
                        m_logger.info("Send notification after sync (sync notification) option enabled.");
                    ICall ca = null;
                    if (progressMonitor != null)
                        progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "sendnotificationprogress", "label", getLanguage()));
                    for (int i = 0, j = m_callList.size(); i < j; i++) {
                        ca = m_callList.get(i);
                        sendMailNotification(ca);
                    }
                }
            }
            String text = getI18nManager().getString(getNamespace(), "finished", "label", getLanguage());
            if (m_callList.size() == 0)
                text = getI18nManager().getString(getNamespace(), "finished0", "label", getLanguage());
            if (m_callList.size() == 1)
                text = getI18nManager().getString(getNamespace(), "finished1", "label", getLanguage());
            if (progressMonitor != null)
                progressMonitor.setTaskName(StringUtils.replaceString(text, "{%1}", Integer.toString(m_callList.size())));
            if (m_callList.size() > 0)
                PropagationFactory.getInstance().fire(new Message(Message.INFO, getI18nManager().getString("monitor.FritzBoxMonitor", "title", "label", getLanguage()), new Exception(StringUtils.replaceString(text, "{%1}", Integer.toString(m_callList.size())))), "Tray");
            SynchronizerService.this.m_configuration.setProperty(CFG_SYNCTIME, Long.toString(System.currentTimeMillis()));
            getRuntime().getConfigManagerFactory().getConfigManager().setProperties(NAMESPACE, SynchronizerService.this.m_configuration);
            getRuntime().getConfigManagerFactory().getConfigManager().saveConfiguration();
            if (progressMonitor != null)
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    m_logger.log(Level.SEVERE, e1.getMessage(), e1);
                }
        } else {
            // no results from FB list
            if (progressMonitor != null)
                progressMonitor.setTaskName(getI18nManager().getString(getNamespace(), "noresults", "label", getLanguage()));
            try {
                Thread.sleep((progressMonitor != null ? 1500 : 100));
            } catch (InterruptedException e1) {
                m_logger.log(Level.SEVERE, e1.getMessage(), e1);
            }
        }
    } catch (IOException e) {
        m_logger.warning(e.toString());
        PropagationFactory.getInstance().fire(new Message(Message.ERROR, getNamespace(), "failedrefresh", e));
    } catch (FritzBoxLoginException e) {
        m_logger.warning(e.toString());
    } catch (GetCallListException e) {
        m_logger.warning(e.toString());
        PropagationFactory.getInstance().fire(new Message(Message.ERROR, getNamespace(), "failedrefresh", e));
    } catch (DeleteCallListException e) {
        m_logger.warning(e.toString());
        PropagationFactory.getInstance().fire(new Message(Message.ERROR, getNamespace(), "failedrefresh", e));
    } catch (CloneNotSupportedException e) {
        m_logger.warning(e.toString());
    } finally {
        if (progressMonitor != null)
            progressMonitor.done();
        this.m_activeSync = false;
    }
    if (m_logger.isLoggable(Level.INFO))
        m_logger.info("--> Finished Synchronizing (" + (progressMonitor == null ? "w/o progress monitor" : "with progress monitor") + ") in " + ((System.currentTimeMillis() - start) / 1000) + " sec.");
}
Also used : Message(de.janrufmonitor.exception.Message) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Properties(java.util.Properties) ICallManager(de.janrufmonitor.repository.ICallManager) ICallList(de.janrufmonitor.framework.ICallList) IImExporter(de.janrufmonitor.repository.imexport.IImExporter) ICallList(de.janrufmonitor.framework.ICallList) List(java.util.List) ArrayList(java.util.ArrayList) DateFilter(de.janrufmonitor.repository.filter.DateFilter) IEventBroker(de.janrufmonitor.framework.event.IEventBroker) IReadCallRepository(de.janrufmonitor.repository.types.IReadCallRepository) ICallExporter(de.janrufmonitor.repository.imexport.ICallExporter) FritzBoxLoginException(de.janrufmonitor.fritzbox.firmware.exception.FritzBoxLoginException) ICall(de.janrufmonitor.framework.ICall) ICip(de.janrufmonitor.framework.ICip) GetCallListException(de.janrufmonitor.fritzbox.firmware.exception.GetCallListException) IOException(java.io.IOException) Date(java.util.Date) IWriteCallRepository(de.janrufmonitor.repository.types.IWriteCallRepository) InvocationTargetException(java.lang.reflect.InvocationTargetException) DeleteCallListException(de.janrufmonitor.fritzbox.firmware.exception.DeleteCallListException) GetCallListException(de.janrufmonitor.fritzbox.firmware.exception.GetCallListException) FritzBoxLoginException(de.janrufmonitor.fritzbox.firmware.exception.FritzBoxLoginException) IOException(java.io.IOException) FritzBoxCallCsv(de.janrufmonitor.fritzbox.FritzBoxCallCsv) FirmwareManager(de.janrufmonitor.fritzbox.firmware.FirmwareManager) IFilter(de.janrufmonitor.repository.filter.IFilter) File(java.io.File) DeleteCallListException(de.janrufmonitor.fritzbox.firmware.exception.DeleteCallListException)

Example 8 with IImExporter

use of de.janrufmonitor.repository.imexport.IImExporter in project janrufmonitor by tbrandt77.

the class ExportAction method run.

public void run() {
    try {
        FileDialog dialog = new FileDialog(new Shell(DisplayManager.getDefaultDisplay()), SWT.SAVE);
        dialog.setText(this.getI18nManager().getString(this.getNamespace(), "title", "label", this.getLanguage()));
        List ids = ImExportFactory.getInstance().getAllExporterIds(IImExporter.CALL_MODE);
        String[] filternames = new String[ids.size()];
        String[] extensions = new String[ids.size()];
        IImExporter ie = null;
        for (int i = 0; i < ids.size(); i++) {
            ie = ImExportFactory.getInstance().getExporter((String) ids.get(i));
            filternames[i] = ie.getFilterName();
            extensions[i] = ie.getExtension();
        }
        dialog.setFilterNames(filternames);
        dialog.setFilterExtensions(extensions);
        String filter = getRuntime().getConfigManagerFactory().getConfigManager().getProperty(getNamespace(), "lastopeneddir");
        if (filter == null || filter.length() == 0 || !new File(filter).exists())
            filter = PathResolver.getInstance(getRuntime()).getUserDataDirectory();
        dialog.setFilterPath(filter);
        final String filename = dialog.open();
        if (filename == null)
            return;
        filter = new File(filename).getParentFile().getAbsolutePath();
        getRuntime().getConfigManagerFactory().getConfigManager().setProperty(getNamespace(), "lastopeneddir", filter);
        String ext = "";
        for (int i = 0; i < ids.size(); i++) {
            final IImExporter exp = ImExportFactory.getInstance().getExporter((String) ids.get(i));
            ext = exp.getExtension().substring(1);
            if (filename.endsWith(ext) && exp.getMode() == IImExporter.CALL_MODE) {
                ProgressMonitorDialog pmd = new ProgressMonitorDialog(DisplayManager.getDefaultDisplay().getActiveShell());
                try {
                    IRunnableWithProgress r = new IRunnableWithProgress() {

                        public void run(IProgressMonitor progressMonitor) {
                            progressMonitor.beginTask(getI18nManager().getString(getNamespace(), "exportprogress", "label", getLanguage()), IProgressMonitor.UNKNOWN);
                            progressMonitor.worked(1);
                            ((ICallExporter) exp).setCallList(((JournalController) m_app.getController()).getCallList());
                            exp.setFilename(filename);
                            if (((ICallExporter) exp).doExport()) {
                                progressMonitor.done();
                                PropagationFactory.getInstance().fire(new Message(Message.INFO, getI18nManager().getString(Journal.NAMESPACE, "title", "label", getLanguage()), new Exception(getI18nManager().getString(getNamespace(), "success", "description", getLanguage()))), "Tray");
                            } else {
                                progressMonitor.done();
                                new SWTExecuter() {

                                    protected void execute() {
                                        MessageDialog.openError(DisplayManager.getDefaultDisplay().getActiveShell(), getI18nManager().getString(getNamespace(), "error", "label", getLanguage()), getI18nManager().getString(getNamespace(), "error", "description", getLanguage()));
                                        m_logger.warning("Export of journal failed.");
                                    }
                                }.start();
                            }
                            progressMonitor.done();
                        }
                    };
                    pmd.setBlockOnOpen(false);
                    pmd.run(true, false, r);
                // ModalContext.run(r, true, pmd.getProgressMonitor(), DisplayManager.getDefaultDisplay());
                } catch (InterruptedException e) {
                    throw e;
                } catch (InvocationTargetException e) {
                    throw e;
                }
                m_app.updateViews(false);
            }
        }
    } catch (Exception ex) {
        this.m_logger.log(Level.SEVERE, ex.getMessage(), ex);
        PropagationFactory.getInstance().fire(new Message(Message.ERROR, getNamespace(), "error", ex));
    }
}
Also used : ICallExporter(de.janrufmonitor.repository.imexport.ICallExporter) Message(de.janrufmonitor.exception.Message) ProgressMonitorDialog(org.eclipse.jface.dialogs.ProgressMonitorDialog) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) Shell(org.eclipse.swt.widgets.Shell) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IImExporter(de.janrufmonitor.repository.imexport.IImExporter) List(java.util.List) FileDialog(org.eclipse.swt.widgets.FileDialog) File(java.io.File) SWTExecuter(de.janrufmonitor.ui.swt.SWTExecuter)

Example 9 with IImExporter

use of de.janrufmonitor.repository.imexport.IImExporter in project janrufmonitor by tbrandt77.

the class ImportAction method run.

public void run(String[] filenames) {
    try {
        String filename = filenames[0];
        TableViewer viewer = (TableViewer) this.m_app.getApplication().getViewer();
        Cursor c = new Cursor(viewer.getTable().getDisplay(), SWT.CURSOR_WAIT);
        if (!filename.endsWith(this.m_app.getApplication().getConfiguration().getProperty(CFG_OLD_JOURNAL, "ajournal.dat"))) {
            File f = new File(filename);
            String ext = f.getName();
            IImExporter ie = ImExportFactory.getInstance().getImporterByExtension(ext);
            if (ie == null && ext.lastIndexOf(".") >= 0) {
                ext = "*" + ext.substring(ext.lastIndexOf("."));
                ie = ImExportFactory.getInstance().getImporterByExtension(ext);
                if (ie == null) {
                    PropagationFactory.getInstance().fire(new Message(Message.ERROR, getI18nManager().getString(Journal.NAMESPACE, "title", "label", getLanguage()), new Exception(getI18nManager().getString(getNamespace(), "error", "description", getLanguage()))), "Tray");
                    new SWTExecuter() {

                        protected void execute() {
                            MessageDialog.openError(DisplayManager.getDefaultDisplay().getActiveShell(), getI18nManager().getString(getNamespace(), "error", "label", getLanguage()), getI18nManager().getString(getNamespace(), "error", "description", getLanguage()));
                            m_logger.warning("Import of data failed.");
                        }
                    }.start();
                }
            }
            if (ie != null && ie.getMode() != IImExporter.CALL_MODE)
                return;
            final IImExporter imp = ie;
            imp.setFilename(filename);
            viewer.getTable().getShell().setCursor(c);
            ProgressMonitorDialog pmd = new ProgressMonitorDialog(DisplayManager.getDefaultDisplay().getActiveShell());
            try {
                IRunnableWithProgress r = new IRunnableWithProgress() {

                    public void run(IProgressMonitor progressMonitor) {
                        progressMonitor.beginTask(getI18nManager().getString(getNamespace(), "importprogress", "label", getLanguage()), IProgressMonitor.UNKNOWN);
                        progressMonitor.worked(1);
                        final ICallList importedCalls = getRuntime().getCallFactory().createCallList();
                        if (imp.getMode() == IImExporter.CALL_MODE) {
                            importedCalls.add(((ICallImporter) imp).doImport());
                            m_app.getController().addElements(importedCalls);
                        }
                        if (importedCalls.size() > 0) {
                            final String msg = StringUtils.replaceString(getI18nManager().getString(getNamespace(), "success", "description", getLanguage()), "{%1}", Integer.toString(importedCalls.size()));
                            PropagationFactory.getInstance().fire(new Message(Message.INFO, getI18nManager().getString(Journal.NAMESPACE, "title", "label", getLanguage()), new Exception(msg)), "Tray");
                            new SWTExecuter() {

                                protected void execute() {
                                    m_app.updateViews(true);
                                }
                            }.start();
                        } else {
                            PropagationFactory.getInstance().fire(new Message(Message.ERROR, getI18nManager().getString(Journal.NAMESPACE, "title", "label", getLanguage()), new Exception(getI18nManager().getString(getNamespace(), "error", "description", getLanguage()))), "Tray");
                            new SWTExecuter() {

                                protected void execute() {
                                    MessageDialog.openError(DisplayManager.getDefaultDisplay().getActiveShell(), getI18nManager().getString(getNamespace(), "error", "label", getLanguage()), getI18nManager().getString(getNamespace(), "error", "description", getLanguage()));
                                    m_logger.warning("Import of data failed.");
                                    // m_app.getController().addElements(importedCalls);
                                    m_app.updateViews(true);
                                }
                            }.start();
                        }
                        progressMonitor.done();
                    }
                };
                pmd.setBlockOnOpen(false);
                pmd.run(true, false, r);
            // ModalContext.run(r, true,
            // pmd.getProgressMonitor(),
            // DisplayManager.getDefaultDisplay());
            } catch (InterruptedException e) {
                throw e;
            } catch (InvocationTargetException e) {
                throw e;
            }
            viewer.getTable().getShell().setCursor(null);
            c.dispose();
        } else {
            // do ajournal.dat migration
            int style = SWT.APPLICATION_MODAL | SWT.YES | SWT.NO;
            MessageBox messageBox = new MessageBox(new Shell(DisplayManager.getDefaultDisplay()), style);
            messageBox.setMessage(this.getI18nManager().getString(this.getNamespace(), "migrationconfirm", "label", this.getLanguage()));
            if (messageBox.open() == SWT.YES) {
                viewer.getTable().getShell().setCursor(c);
                IImExporter imp = ImExportFactory.getInstance().getImporter("OldDatFileCallImporter");
                if (imp != null && (imp instanceof OldDatFileCallImporter)) {
                    ((OldDatFileCallImporter) imp).setDatePattern(this.m_app.getApplication().getConfiguration().getProperty(CFG_OLD_DATE, "dd.MM.yyyy HH:mm:ss"));
                    ((OldDatFileCallImporter) imp).setFilename(filename);
                    ICallList importedCalls = ((OldDatFileCallImporter) imp).doImport();
                    if (importedCalls != null) {
                        this.m_app.getController().addElements(importedCalls);
                        String msg = getI18nManager().getString(getNamespace(), "success", "description", getLanguage());
                        msg = StringUtils.replaceString(msg, "{%1}", Integer.toString(importedCalls.size()));
                        if (!suppressDialogs)
                            MessageDialog.openInformation(new Shell(DisplayManager.getDefaultDisplay()), getI18nManager().getString(getNamespace(), "success", "label", getLanguage()), msg);
                        m_app.updateViews(true);
                    }
                }
                viewer.getTable().getShell().setCursor(null);
                c.dispose();
            } else {
                return;
            }
        }
    } catch (Exception ex) {
        this.m_logger.log(Level.SEVERE, ex.getMessage(), ex);
        PropagationFactory.getInstance().fire(new Message(Message.ERROR, getNamespace(), "error", ex));
    }
}
Also used : Message(de.janrufmonitor.exception.Message) ProgressMonitorDialog(org.eclipse.jface.dialogs.ProgressMonitorDialog) OldDatFileCallImporter(de.janrufmonitor.repository.imexporter.OldDatFileCallImporter) Cursor(org.eclipse.swt.graphics.Cursor) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) MessageBox(org.eclipse.swt.widgets.MessageBox) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Shell(org.eclipse.swt.widgets.Shell) ICallList(de.janrufmonitor.framework.ICallList) IImExporter(de.janrufmonitor.repository.imexport.IImExporter) TableViewer(org.eclipse.jface.viewers.TableViewer) File(java.io.File) SWTExecuter(de.janrufmonitor.ui.swt.SWTExecuter)

Aggregations

IImExporter (de.janrufmonitor.repository.imexport.IImExporter)9 Message (de.janrufmonitor.exception.Message)7 File (java.io.File)7 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 List (java.util.List)7 Shell (org.eclipse.swt.widgets.Shell)7 SWTExecuter (de.janrufmonitor.ui.swt.SWTExecuter)5 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)5 ProgressMonitorDialog (org.eclipse.jface.dialogs.ProgressMonitorDialog)5 IRunnableWithProgress (org.eclipse.jface.operation.IRunnableWithProgress)5 FileDialog (org.eclipse.swt.widgets.FileDialog)5 ICallerList (de.janrufmonitor.framework.ICallerList)4 ICallList (de.janrufmonitor.framework.ICallList)3 IFilter (de.janrufmonitor.repository.filter.IFilter)2 ICallExporter (de.janrufmonitor.repository.imexport.ICallExporter)2 ICallerExporter (de.janrufmonitor.repository.imexport.ICallerExporter)2 ArrayList (java.util.ArrayList)2 Iterator (java.util.Iterator)2 Cursor (org.eclipse.swt.graphics.Cursor)2 MessageBox (org.eclipse.swt.widgets.MessageBox)2