Example usage for java.lang Thread interrupted

List of usage examples for java.lang Thread interrupted

Introduction

In this page you can find the example usage for java.lang Thread interrupted.

Prototype

public static boolean interrupted() 

Source Link

Document

Tests whether the current thread has been interrupted.

Usage

From source file:org.kchine.rpf.PoolUtils.java

public static void ping(final ManagedServant servant, long pingTimeOut) throws RemoteException {

    final Object[] resultHolder = new Object[1];
    Runnable pingRunnable = new Runnable() {
        public void run() {
            try {
                servant.ping();/* www  . j  a v a  2s . co  m*/
                resultHolder[0] = PING_DONE;
            } catch (Exception e) {
                final boolean wasInterrupted = Thread.interrupted();
                if (wasInterrupted) {
                    resultHolder[0] = new PingInterrupted();
                } else {
                    resultHolder[0] = e;
                }
            }
        }
    };

    Thread pingThread = InterruptibleRMIThreadFactory.getInstance().newThread(pingRunnable);
    pingThread.start();

    long t1 = System.currentTimeMillis();
    while (resultHolder[0] == null) {
        if ((System.currentTimeMillis() - t1) > pingTimeOut) {
            pingThread.interrupt();
            resultHolder[0] = new PingTimeout();
            break;
        }
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        }
    }

    if (resultHolder[0] instanceof Throwable) {
        throw (RemoteException) resultHolder[0];
    }

}

From source file:org.jumpmind.symmetric.AbstractSymmetricEngine.java

public synchronized void stop() {

    log.info("Stopping SymmetricDS externalId={} version={} database={}",
            new Object[] { parameterService == null ? "?" : parameterService.getExternalId(), Version.version(),
                    symmetricDialect == null ? "?" : symmetricDialect.getName() });
    if (jobManager != null) {
        jobManager.stopJobs();/*  w w w .j av  a 2  s  .  co m*/
    }
    if (routerService != null) {
        routerService.stop();
    }
    if (nodeCommunicationService != null) {
        nodeCommunicationService.stop();
    }

    if (pushService != null) {
        pushService.stop();
    }

    if (dataLoaderService != null) {
        dataLoaderService.stop();
    }

    if (statisticManager != null) {
        List<ProcessInfo> infos = statisticManager.getProcessInfos();
        for (ProcessInfo processInfo : infos) {
            Thread thread = processInfo.getThread();
            if (processInfo.getStatus() != Status.OK && thread.isAlive()) {
                log.info("Trying to interrupt thread '{}' ", thread.getName());
                try {
                    thread.interrupt();
                } catch (Exception e) {
                    log.info("Caught exception while attempting to interrupt thread", e);
                }
            }
        }

        Thread.interrupted();
    }

    started = false;
    starting = false;

}

From source file:canreg.client.dataentry.Import.java

public static boolean importFiles(Task<Object, Void> task, Document doc,
        List<canreg.client.dataentry.Relation> map, File[] files, CanRegServerInterface server,
        ImportOptions io) throws SQLException, RemoteException, SecurityException, RecordLockedException {
    int numberOfLinesRead = 0;
    Writer reportWriter = new BufferedWriter(new OutputStreamWriter(System.out));
    if (io.getReportFileName() != null && io.getReportFileName().trim().length() > 0) {
        try {//from  w  ww .  j  a v  a  2s.  c  o  m
            reportWriter = new BufferedWriter(new FileWriter(io.getReportFileName()));
        } catch (IOException ex) {
            Logger.getLogger(Import.class.getName()).log(Level.WARNING, null, ex);
        }
    }
    boolean success = false;
    Set<String> noNeedToLookAtPatientVariables = new TreeSet<String>();
    noNeedToLookAtPatientVariables
            .add(canreg.common.Tools.toLowerCaseStandardized(io.getPatientIDVariableName()));
    noNeedToLookAtPatientVariables
            .add(canreg.common.Tools.toLowerCaseStandardized(io.getPatientRecordIDVariableName()));

    String[] lineElements;
    ResultCode worstResultCodeFound;
    //         CSVReader reader = null;
    CSVParser parser = null;
    CSVFormat format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(io.getSeparators()[0]);

    int linesToRead = io.getMaxLines();

    try {
        // first we get the patients
        if (task != null) {
            task.firePropertyChange(PROGRESS, 0, 0);
            task.firePropertyChange(PATIENTS, 0, 0);
        }
        if (files[0] != null) {
            reportWriter
                    .write("Starting to import patients from " + files[0].getAbsolutePath() + Globals.newline);
            FileInputStream patientFIS = new FileInputStream(files[0]);
            InputStreamReader patientISR = new InputStreamReader(patientFIS, io.getFileCharsets()[0]);

            Logger.getLogger(Import.class.getName()).log(Level.CONFIG, "Name of the character encoding {0}",
                    patientISR.getEncoding());

            int numberOfRecordsInFile = canreg.common.Tools.numberOfLinesInFile(files[0].getAbsolutePath());

            numberOfLinesRead = 0;

            if (linesToRead > 0) {
                linesToRead = Math.min(numberOfRecordsInFile, linesToRead);
            } else {
                linesToRead = numberOfRecordsInFile;
            }
            parser = CSVParser.parse(files[0], io.getFileCharsets()[0], format);

            for (CSVRecord csvRecord : parser) {
                // We allow for null tasks...
                boolean savePatient = true;
                boolean deletePatient = false;
                int oldPatientDatabaseRecordID = -1;

                if (task != null) {
                    task.firePropertyChange(PROGRESS, ((numberOfLinesRead - 1) * 100 / linesToRead) / 3,
                            ((numberOfLinesRead) * 100 / linesToRead) / 3);
                    task.firePropertyChange(PATIENTS, ((numberOfLinesRead - 1) * 100 / linesToRead),
                            ((numberOfLinesRead) * 100 / linesToRead));
                }

                // Build patient part
                Patient patient = new Patient();
                for (int i = 0; i < map.size(); i++) {
                    Relation rel = map.get(i);
                    if (rel.getDatabaseTableVariableID() >= 0
                            && rel.getDatabaseTableName().equalsIgnoreCase("patient")) {
                        if (rel.getVariableType().equalsIgnoreCase("Number")) {
                            if (csvRecord.get(rel.getFileColumnNumber()).length() > 0) {
                                try {
                                    patient.setVariable(rel.getDatabaseVariableName(),
                                            Integer.parseInt(csvRecord.get(rel.getFileColumnNumber())));
                                } catch (NumberFormatException ex) {
                                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                                            "Number format error in line: " + (numberOfLinesRead + 1 + 1)
                                                    + ". ",
                                            ex);
                                    success = false;
                                }
                            }
                        } else {
                            patient.setVariable(rel.getDatabaseVariableName(),
                                    csvRecord.get(rel.getFileColumnNumber()));
                        }
                    }
                    if (task != null) {
                        task.firePropertyChange(RECORD, i - 1 / map.size() * 50, i / map.size() * 50);
                    }
                }
                // debugOut(patient.toString());

                // debugOut(tumour.toString());
                // add patient to the database
                Object patientID = patient.getVariable(io.getPatientRecordIDVariableName());
                Patient oldPatientRecord = null;
                try {
                    oldPatientRecord = CanRegClientApp.getApplication().getPatientRecord((String) patientID,
                            false);
                } catch (DistributedTableDescriptionException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RecordLockedException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RemoteException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SecurityException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnknownTableException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (oldPatientRecord != null) {
                    // deal with discrepancies                        
                    switch (io.getDiscrepancies()) {
                    case ImportOptions.REJECT:
                        savePatient = false;
                        break;
                    case ImportOptions.UPDATE:
                        String updateReport = updateRecord(oldPatientRecord, patient);
                        if (updateReport.length() > 0) {
                            reportWriter.write(patient.getVariable(io.getTumourIDVariablename())
                                    + Globals.newline + updateReport);
                        }
                        oldPatientDatabaseRecordID = (Integer) oldPatientRecord
                                .getVariable(Globals.PATIENT_TABLE_RECORD_ID_VARIABLE_NAME);
                        patient = oldPatientRecord;
                        savePatient = true;
                        break;
                    case ImportOptions.OVERWRITE:
                        // deleteTumour;
                        oldPatientDatabaseRecordID = (Integer) oldPatientRecord
                                .getVariable(Globals.PATIENT_TABLE_RECORD_ID_VARIABLE_NAME);
                        String overWriteReport = overwriteRecord(oldPatientRecord, patient);
                        if (overWriteReport.length() > 0) {
                            reportWriter.write(patient.getVariable(io.getTumourIDVariablename())
                                    + Globals.newline + overWriteReport);
                        }
                        patient = oldPatientRecord;
                        savePatient = true;
                        break;
                    }
                    // reportWriter.write(tumour.getVariable(io.getTumourIDVariablename()) + "Tumour already exists.\n");
                }

                if (task != null) {
                    task.firePropertyChange(RECORD, 50, 75);
                }

                if ((!io.isTestOnly())) {
                    if (deletePatient) {
                        server.deleteRecord(oldPatientDatabaseRecordID, Globals.PATIENT_TABLE_NAME);
                    }
                    if (savePatient) {
                        if (patient.getVariable(Globals.PATIENT_TABLE_RECORD_ID_VARIABLE_NAME) != null) {
                            server.editPatient(patient);
                        } else {
                            server.savePatient(patient);
                        }
                    }
                }

                if (task != null) {
                    task.firePropertyChange(RECORD, 100, 75);
                }

                numberOfLinesRead++;

                if (Thread.interrupted()) {
                    //We've been interrupted: no more importing.
                    reportWriter.flush();
                    throw new InterruptedException();
                }
            }
            parser.close();
            reportWriter.write("Finished reading patients." + Globals.newline + Globals.newline);
            reportWriter.flush();
        }
        if (task != null) {
            task.firePropertyChange(PATIENTS, 100, 100);
            task.firePropertyChange("progress", 33, 34);
        }

        // then we get the tumours            
        if (task != null) {
            task.firePropertyChange(TUMOURS, 0, 0);
        }

        if (files[1] != null) {
            reportWriter
                    .write("Starting to import tumours from " + files[1].getAbsolutePath() + Globals.newline);

            FileInputStream tumourFIS = new FileInputStream(files[1]);
            InputStreamReader tumourISR = new InputStreamReader(tumourFIS, io.getFileCharsets()[1]);

            Logger.getLogger(Import.class.getName()).log(Level.CONFIG, "Name of the character encoding {0}",
                    tumourISR.getEncoding());

            numberOfLinesRead = 0;

            int numberOfRecordsInFile = canreg.common.Tools.numberOfLinesInFile(files[1].getAbsolutePath());

            if (linesToRead > 0) {
                linesToRead = Math.min(numberOfRecordsInFile, linesToRead);
            } else {
                linesToRead = numberOfRecordsInFile;
            }

            format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(io.getSeparators()[1]);

            parser = CSVParser.parse(files[1], io.getFileCharsets()[1], format);

            for (CSVRecord csvRecord : parser) {
                // We allow for null tasks...
                boolean saveTumour = true;
                boolean deleteTumour = false;

                if (task != null) {
                    task.firePropertyChange(PROGRESS, 33 + ((numberOfLinesRead - 1) * 100 / linesToRead) / 3,
                            33 + ((numberOfLinesRead) * 100 / linesToRead) / 3);
                    task.firePropertyChange(TUMOURS, ((numberOfLinesRead - 1) * 100 / linesToRead),
                            ((numberOfLinesRead) * 100 / linesToRead));
                }
                // Build tumour part
                Tumour tumour = new Tumour();
                for (int i = 0; i < map.size(); i++) {
                    Relation rel = map.get(i);
                    if (rel.getDatabaseTableVariableID() >= 0
                            && rel.getDatabaseTableName().equalsIgnoreCase("tumour")) {
                        if (rel.getVariableType().equalsIgnoreCase("Number")) {
                            if (csvRecord.get(rel.getFileColumnNumber()).length() > 0) {
                                try {
                                    tumour.setVariable(rel.getDatabaseVariableName(),
                                            Integer.parseInt(csvRecord.get(rel.getFileColumnNumber())));
                                } catch (NumberFormatException ex) {
                                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                                            "Number format error in line: " + (numberOfLinesRead + 1 + 1)
                                                    + ". ",
                                            ex);
                                    success = false;
                                }
                            }
                        } else {
                            tumour.setVariable(rel.getDatabaseVariableName(),
                                    csvRecord.get(rel.getFileColumnNumber()));
                        }
                    }
                    if (task != null) {
                        task.firePropertyChange(RECORD, i - 1 / map.size() * 50, i / map.size() * 50);
                    }
                }

                // see if this tumour exists in the database already
                // TODO: Implement this using arrays and getTumourRexords instead
                Tumour tumour2 = null;
                try {
                    tumour2 = CanRegClientApp.getApplication().getTumourRecordBasedOnTumourID(
                            (String) tumour.getVariable(io.getTumourIDVariablename()), false);
                } catch (DistributedTableDescriptionException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RecordLockedException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RemoteException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SecurityException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnknownTableException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (tumour2 != null) {
                    // deal with discrepancies
                    switch (io.getDiscrepancies()) {
                    case ImportOptions.REJECT:
                        saveTumour = false;
                        break;
                    case ImportOptions.UPDATE:
                        String updateReport = updateRecord(tumour2, tumour);
                        if (updateReport.length() > 0) {
                            reportWriter.write(tumour.getVariable(io.getTumourIDVariablename())
                                    + Globals.newline + updateReport);
                        }
                        tumour = tumour2;
                        saveTumour = true;
                        break;
                    case ImportOptions.OVERWRITE:
                        // deleteTumour;
                        deleteTumour = true;
                        saveTumour = true;
                        break;
                    }
                    // reportWriter.write(tumour.getVariable(io.getTumourIDVariablename()) + "Tumour already exists.\n");

                }

                Patient patient = null;
                try {
                    patient = CanRegClientApp.getApplication().getPatientRecord(
                            (String) tumour.getVariable(io.getPatientRecordIDTumourTableVariableName()), false);
                } catch (DistributedTableDescriptionException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RecordLockedException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RemoteException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SecurityException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnknownTableException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (patient != null) {
                    if (io.isDoChecks() && saveTumour) {
                        // run the edits...
                        String message = "";
                        LinkedList<CheckResult> checkResults = canreg.client.CanRegClientApp.getApplication()
                                .performChecks(patient, tumour);

                        Map<Globals.StandardVariableNames, CheckResult.ResultCode> mapOfVariablesAndWorstResultCodes = new EnumMap<Globals.StandardVariableNames, CheckResult.ResultCode>(
                                Globals.StandardVariableNames.class);
                        worstResultCodeFound = CheckResult.ResultCode.OK;
                        for (CheckResult result : checkResults) {
                            if (result.getResultCode() != CheckResult.ResultCode.OK
                                    && result.getResultCode() != CheckResult.ResultCode.NotDone) {
                                if (!result.getResultCode().equals(CheckResult.ResultCode.Missing)) {
                                    message += result + "\t";
                                    worstResultCodeFound = CheckResult.decideWorstResultCode(
                                            result.getResultCode(), worstResultCodeFound);
                                    for (Globals.StandardVariableNames standardVariableName : result
                                            .getVariablesInvolved()) {
                                        CheckResult.ResultCode worstResultCodeFoundForThisVariable = mapOfVariablesAndWorstResultCodes
                                                .get(standardVariableName);
                                        if (worstResultCodeFoundForThisVariable == null) {
                                            mapOfVariablesAndWorstResultCodes.put(standardVariableName,
                                                    result.getResultCode());
                                        } else if (CheckResult.compareResultSets(result.getResultCode(),
                                                worstResultCodeFoundForThisVariable) > 0) {
                                            mapOfVariablesAndWorstResultCodes.put(standardVariableName,
                                                    result.getResultCode());
                                        }
                                    }
                                }
                            }
                            // Logger.getLogger(Import.class.getName()).log(Level.INFO, result.toString());
                        }
                        // always generate ICD10...
                        // ConversionResult[] conversionResult = canreg.client.CanRegClientApp.getApplication().performConversions(Converter.ConversionName.ICDO3toICD10, patient, tumour);
                        // tumour.setVariable(io.getICD10VariableName(), conversionResult[0].getValue());

                        if (worstResultCodeFound != CheckResult.ResultCode.Invalid
                                && worstResultCodeFound != CheckResult.ResultCode.Missing) {
                            // generate ICD10 codes
                            ConversionResult[] conversionResult = canreg.client.CanRegClientApp.getApplication()
                                    .performConversions(Converter.ConversionName.ICDO3toICD10, patient, tumour);
                            tumour.setVariable(io.getICD10VariableName(), conversionResult[0].getValue());
                            // generate ICCC codes
                            ConversionResult[] conversionResultICCC = canreg.client.CanRegClientApp
                                    .getApplication()
                                    .performConversions(Converter.ConversionName.ICDO3toICCC3, patient, tumour);
                            tumour.setVariable(io.getICCCVariableName(), conversionResultICCC[0].getValue());
                        } else {
                            tumour.setVariable(io.getTumourRecordStatus(), "0");
                        }

                        if (worstResultCodeFound == CheckResult.ResultCode.OK) {
                            // message += "Cross-check conclusion: Valid";
                        } else {
                            reportWriter.write(tumour.getVariable(io.getTumourIDVariablename()) + "\t" + message
                                    + Globals.newline);
                            // System.out.println(tumour.getVariable(io.getTumourIDVariablename()) + " " + message);
                        }
                        tumour.setVariable(io.getTumourCheckStatus(),
                                CheckResult.toDatabaseVariable(worstResultCodeFound));

                    } else {
                        // try to generate ICD10, if missing, anyway
                        String icd10 = (String) tumour.getVariable(io.getICD10VariableName());
                        if (icd10 == null || icd10.trim().length() == 0) {
                            ConversionResult[] conversionResult = canreg.client.CanRegClientApp.getApplication()
                                    .performConversions(Converter.ConversionName.ICDO3toICD10, patient, tumour);
                            tumour.setVariable(io.getICD10VariableName(), conversionResult[0].getValue());
                        }
                        // try to generate ICCC3, if missing, anyway
                        String iccc = (String) tumour.getVariable(io.getICCCVariableName());
                        if (iccc == null || iccc.trim().length() == 0) {
                            ConversionResult[] conversionResult = canreg.client.CanRegClientApp.getApplication()
                                    .performConversions(Converter.ConversionName.ICDO3toICCC3, patient, tumour);
                            tumour.setVariable(io.getICCCVariableName(), conversionResult[0].getValue());
                        }
                    }
                } else {
                    reportWriter.write(tumour.getVariable(io.getTumourIDVariablename()) + "\t"
                            + "No patient matches this Tumour." + Globals.newline);
                    tumour.setVariable(io.getTumourRecordStatus(), "0");
                    tumour.setVariable(io.getTumourCheckStatus(),
                            CheckResult.toDatabaseVariable(ResultCode.Missing));
                }
                if (task != null) {
                    task.firePropertyChange(RECORD, 50, 75);
                }
                if (!io.isTestOnly()) {
                    if (deleteTumour) {
                        server.deleteRecord(
                                (Integer) tumour2.getVariable(Globals.TUMOUR_TABLE_RECORD_ID_VARIABLE_NAME),
                                Globals.TUMOUR_TABLE_NAME);
                    }
                    if (saveTumour) {
                        // if tumour has no record ID we save it
                        if (tumour.getVariable(Globals.TUMOUR_TABLE_RECORD_ID_VARIABLE_NAME) == null) {
                            server.saveTumour(tumour);
                        } // if not we edit it
                        else {
                            server.editTumour(tumour);
                        }
                    }
                }
                if (task != null) {
                    task.firePropertyChange(RECORD, 75, 100);
                }
                //Read next line of data

                numberOfLinesRead++;

                if (Thread.interrupted()) {
                    //We've been interrupted: no more importing.
                    reportWriter.flush();
                    throw new InterruptedException();
                }
            }
            parser.close();
            reportWriter.write("Finished reading tumours." + Globals.newline + Globals.newline);
            reportWriter.flush();
        }
        if (task != null) {
            task.firePropertyChange(TUMOURS, 100, 100);
        }
        // then at last we get the sources
        if (task != null) {
            task.firePropertyChange(SOURCES, 0, 0);
            task.firePropertyChange(PROGRESS, 66, 66);
        }
        if (files[2] != null) {
            reportWriter
                    .write("Starting to import sources from " + files[2].getAbsolutePath() + Globals.newline);

            FileInputStream sourceFIS = new FileInputStream(files[2]);
            InputStreamReader sourceISR = new InputStreamReader(sourceFIS, io.getFileCharsets()[2]);

            Logger.getLogger(Import.class.getName()).log(Level.CONFIG, "Name of the character encoding {0}",
                    sourceISR.getEncoding());

            numberOfLinesRead = 0;

            int numberOfRecordsInFile = canreg.common.Tools.numberOfLinesInFile(files[2].getAbsolutePath());

            if (linesToRead > 0) {
                linesToRead = Math.min(numberOfRecordsInFile, linesToRead);
            } else {
                linesToRead = numberOfRecordsInFile;
            }

            format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(io.getSeparators()[2]);

            parser = CSVParser.parse(files[2], io.getFileCharsets()[2], format);

            for (CSVRecord csvRecord : parser) {
                // We allow for null tasks...
                if (task != null) {
                    task.firePropertyChange(PROGRESS, 67 + ((numberOfLinesRead - 1) * 100 / linesToRead) / 3,
                            67 + ((numberOfLinesRead) * 100 / linesToRead) / 3);
                    task.firePropertyChange(SOURCES, ((numberOfLinesRead - 1) * 100 / linesToRead),
                            ((numberOfLinesRead) * 100 / linesToRead));
                }

                // Build source part
                Source source = new Source();
                for (int i = 0; i < map.size(); i++) {
                    Relation rel = map.get(i);
                    if (rel.getDatabaseTableVariableID() >= 0
                            && rel.getDatabaseTableName().equalsIgnoreCase(Globals.SOURCE_TABLE_NAME)) {
                        if (rel.getVariableType().equalsIgnoreCase("Number")) {
                            if (csvRecord.get(rel.getFileColumnNumber()).length() > 0) {
                                try {
                                    source.setVariable(rel.getDatabaseVariableName(),
                                            Integer.parseInt(csvRecord.get(rel.getFileColumnNumber())));
                                } catch (NumberFormatException ex) {
                                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                                            "Number format error in line: " + (numberOfLinesRead + 1 + 1)
                                                    + ". ",
                                            ex);
                                    success = false;
                                }
                            }
                        } else {
                            source.setVariable(rel.getDatabaseVariableName(),
                                    csvRecord.get(rel.getFileColumnNumber()));
                        }
                    }
                    if (task != null) {
                        task.firePropertyChange(RECORD, i - 1 / map.size() * 50, i / map.size() * 50);
                    }
                }

                Tumour tumour = null;
                try {
                    tumour = CanRegClientApp.getApplication().getTumourRecordBasedOnTumourID(
                            (String) source.getVariable(io.getTumourIDSourceTableVariableName()), false);
                } catch (DistributedTableDescriptionException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RecordLockedException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RemoteException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SecurityException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnknownTableException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                }
                if (task != null) {
                    task.firePropertyChange(RECORD, 50, 75);
                }
                boolean addSource = true;

                if (tumour != null) {
                    Set<Source> sources = tumour.getSources();
                    Object sourceRecordID = source.getVariable(io.getSourceIDVariablename());
                    // look for source in sources
                    for (Source oldSource : sources) {
                        if (oldSource.getVariable(io.getSourceIDVariablename()).equals(sourceRecordID)) {
                            // deal with discrepancies
                            switch (io.getDiscrepancies()) {
                            case ImportOptions.REJECT:
                                addSource = false;
                                break;
                            case ImportOptions.UPDATE:
                                String updateReport = updateRecord(oldSource, source);
                                if (updateReport.length() > 0) {
                                    reportWriter.write(tumour.getVariable(io.getTumourIDVariablename())
                                            + Globals.newline + updateReport);
                                }
                                source = oldSource;
                                addSource = false;
                                break;
                            case ImportOptions.OVERWRITE:
                                // deleteTumour;
                                sources.remove(oldSource);
                                addSource = true;
                                break;
                            }
                        }
                    }
                    if (addSource) {
                        sources.add(source);
                    }
                    tumour.setSources(sources);
                    if (!io.isTestOnly()) {
                        server.editTumour(tumour);
                    }
                } else {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null,
                            "No tumour for source record.");
                }
                if (task != null) {
                    task.firePropertyChange(RECORD, 75, 100);
                }
                //Read next line of data

                numberOfLinesRead++;

                if (Thread.interrupted()) {
                    //We've been interrupted: no more importing.
                    reportWriter.flush();
                    throw new InterruptedException();
                }
            }
            reportWriter.write("Finished reading sources." + Globals.newline + Globals.newline);
            reportWriter.flush();
            parser.close();
        }
        if (task != null) {
            task.firePropertyChange(SOURCES, 100, 100);
            task.firePropertyChange(PROGRESS, 100, 100);
            while (!task.isProgressPropertyValid()) {
                // wait untill progress has been updated...
            }
        }
        reportWriter.write("Finished" + Globals.newline);
        reportWriter.flush();
        success = true;
    } catch (IOException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                "Error in line: " + (numberOfLinesRead + 1 + 1) + ". ", ex);
        success = false;
    } catch (InterruptedException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.INFO,
                "Interupted on line: " + (numberOfLinesRead + 1) + ". ", ex);
        success = true;
    } catch (IndexOutOfBoundsException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                "String too short error in line: " + (numberOfLinesRead + 1 + 1) + ". ", ex);
        success = false;
    } finally {
        if (parser != null) {
            try {
                parser.close();
            } catch (IOException ex) {
                Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            reportWriter.flush();
            reportWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (task != null) {
        task.firePropertyChange(PROGRESS, 100, 100);
        task.firePropertyChange("finished", null, null);
    }
    return success;
}

From source file:org.kchine.rpf.PoolUtils.java

public static void reset(final ManagedServant servant, long resetTimeOut) throws RemoteException {
    final Object[] resultHolder = new Object[1];
    Runnable resetRunnable = new Runnable() {
        public void run() {
            try {
                servant.reset();/*from  w w  w.  j a v  a2  s  .co  m*/
                resultHolder[0] = RESET_DONE;
            } catch (Exception e) {
                final boolean wasInterrupted = Thread.interrupted();
                if (wasInterrupted) {
                    resultHolder[0] = new ResetInterrupted();
                } else {
                    resultHolder[0] = e;
                }
            }
        }
    };

    Thread resetThread = InterruptibleRMIThreadFactory.getInstance().newThread(resetRunnable);
    resetThread.start();

    long t1 = System.currentTimeMillis();
    while (resultHolder[0] == null) {
        if ((System.currentTimeMillis() - t1) > resetTimeOut) {
            resetThread.interrupt();
            resultHolder[0] = new ResetTimeout();
            break;
        }
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        }
    }

    if (resultHolder[0] instanceof Throwable) {
        throw (RemoteException) resultHolder[0];
    }
}

From source file:org.apache.cassandra.concurrent.ContinuationsExecutor.java

/**
 * Ensures that unless the pool is stopping, the current thread does not
 * have its interrupt set. This requires a double-check of state in case the
 * interrupt was cleared concurrently with a shutdownNow -- if so, the
 * interrupt is re-enabled./*from  w ww .  ja  v a 2 s .  c o  m*/
 */
private void clearInterruptsForTaskRun() {
    if (runStateLessThan(ctl.get(), STOP) && Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))
        Thread.currentThread().interrupt();
}

From source file:org.kchine.rpf.PoolUtils.java

public static void die(final ManagedServant servant, long dieTimeOut) throws RemoteException {
    final Object[] resultHolder = new Object[1];
    Runnable dieRunnable = new Runnable() {
        public void run() {
            try {
                servant.die();//from   ww  w  . j a v a  2s .c om
                resultHolder[0] = DIE_DONE;
            } catch (UnmarshalException ue) {
                resultHolder[0] = DIE_DONE;
            } catch (Exception e) {
                final boolean wasInterrupted = Thread.interrupted();
                if (wasInterrupted) {
                    resultHolder[0] = new DieInterrupted();
                } else {
                    resultHolder[0] = e;
                }
            }
        }
    };

    Thread dieThread = InterruptibleRMIThreadFactory.getInstance().newThread(dieRunnable);
    dieThread.start();

    long t1 = System.currentTimeMillis();
    while (resultHolder[0] == null) {
        if ((System.currentTimeMillis() - t1) > dieTimeOut) {
            dieThread.interrupt();
            resultHolder[0] = new DieTimeout();
            break;
        }
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        }
    }

    if (resultHolder[0] instanceof Throwable) {
        throw (RemoteException) resultHolder[0];
    }
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

/**
 * Poll Fedora until the PID is found or timeout. This method will blocking until at most the specified timeout plus
 * the timeout of the underlying HTTP connection.
 *
 * @param pid/*from  w  w  w.  j ava 2s.c o  m*/
 *           the PID to look for
 * @param delay
 *           the delay between Fedora requests in seconds
 * @param timeout
 *           the total polling time in seconds
 * @return true when the object is found within timeout, false on timeout
 */
public boolean pollForObject(PID pid, int delay, int timeout) throws InterruptedException {
    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() - startTime < timeout * 1000) {
        if (Thread.interrupted())
            throw new InterruptedException();
        try {
            ObjectProfile doc = this.getAccessClient().getObjectProfile(pid, null);
            if (doc != null)
                return true;
        } catch (ServiceException e) {
            if (log.isDebugEnabled())
                log.debug("Expected service exception while polling fedora", e);
        } catch (FedoraException e) {
            // fedora responded, but object not found
            log.debug("got exception from fedora", e);
        }
        if (Thread.interrupted())
            throw new InterruptedException();
        log.info(pid + " not found, waiting " + delay + " seconds..");
        Thread.sleep(delay * 1000);
    }
    return false;
}

From source file:io.github.arven.flare.boot.TomcatContainer.java

@Override
public void close() {
    final CountDownLatch end = new CountDownLatch(1);
    final TomcatContainer container = TomcatContainer.this;
    new Thread() {
        {//from   ww w  .j  a  va  2  s . c  o m
            setName("tomee-embedded-await-" + hashCode());
        }

        @Override
        public void run() {
            try {
                container.await();
                end.countDown();
            } catch (final Exception e) {
                end.countDown();
                throw new IllegalStateException(e);
            }
        }
    }.start();

    try {
        stop();
    } catch (final Exception e) {
        throw new IllegalStateException("Failed to stop container", e);
    }

    try {
        end.await();
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }
}

From source file:org.kchine.r.server.http.frontend.CommandServlet.java

protected void doAny(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = null;/* w ww.  j  a v a 2 s  .  co m*/
    Object result = null;

    try {
        final String command = request.getParameter("method");
        do {

            if (command.equals("ping")) {
                result = "pong";
                break;
            } else if (command.equals("logon")) {

                session = request.getSession(false);
                if (session != null) {
                    result = session.getId();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                boolean namedAccessMode = login.contains("@@");
                String sname = null;
                if (namedAccessMode) {
                    sname = login.substring(login.indexOf("@@") + "@@".length());
                    login = login.substring(0, login.indexOf("@@"));
                }

                System.out.println("login :" + login);
                System.out.println("pwd :" + pwd);

                if (_rkit == null && (!login.equals(System.getProperty("login"))
                        || !pwd.equals(System.getProperty("pwd")))) {
                    result = new BadLoginPasswordException();
                    break;
                }

                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                RPFSessionInfo.get().put("LOGIN", login);
                RPFSessionInfo.get().put("REMOTE_ADDR", request.getRemoteAddr());
                RPFSessionInfo.get().put("REMOTE_HOST", request.getRemoteHost());

                boolean nopool = !options.keySet().contains("nopool")
                        || ((String) options.get("nopool")).equals("")
                        || !((String) options.get("nopool")).equalsIgnoreCase("false");
                boolean save = options.keySet().contains("save")
                        && ((String) options.get("save")).equalsIgnoreCase("true");
                boolean selfish = options.keySet().contains("selfish")
                        && ((String) options.get("selfish")).equalsIgnoreCase("true");

                String privateName = (String) options.get("privatename");

                int memoryMin = DEFAULT_MEMORY_MIN;
                int memoryMax = DEFAULT_MEMORY_MAX;
                try {
                    if (options.get("memorymin") != null)
                        memoryMin = Integer.decode((String) options.get("memorymin"));
                    if (options.get("memorymax") != null)
                        memoryMax = Integer.decode((String) options.get("memorymax"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                boolean privateEngineMode = false;
                RServices r = null;
                URL[] codeUrls = null;

                if (_rkit == null) {

                    if (namedAccessMode) {

                        try {
                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    r = (RServices) ((DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                            System.getProperty("submit.ssh.host"),
                                            Integer.decode(System.getProperty("submit.ssh.port")),
                                            System.getProperty("submit.ssh.user"),
                                            System.getProperty("submit.ssh.password"),
                                            System.getProperty("submit.ssh.biocep.home"),
                                            "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                            "db", new Class<?>[] { DBLayerInterface.class })).lookup(sname);
                                }

                            } else {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    if (spFactory == null) {
                                        result = new NoRegistryAvailableException();
                                        break;
                                    }
                                    r = (RServices) spFactory.getServantProvider().getRegistry().lookup(sname);
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        if (nopool) {

                            /*                         
                            ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    
                            if (spFactory == null) {
                               result = new NoRegistryAvailableException();
                               break;
                            }
                                    
                            String nodeName = options.keySet().contains("node") ? (String) options.get("node") : System
                                  .getProperty("private.servant.node.name");
                            Registry registry = spFactory.getServantProvider().getRegistry();
                            NodeManager nm = null;
                            try {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name") + "_" + nodeName);
                            } catch (NotBoundException nbe) {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name"));
                            } catch (Exception e) {
                               result = new NoNodeManagerFound();
                               break;
                            }
                            r = (RServices) nm.createPrivateServant(nodeName);
                             */

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                DBLayerInterface dbLayer = (DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                        System.getProperty("submit.ssh.host"),
                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                        System.getProperty("submit.ssh.user"),
                                        System.getProperty("submit.ssh.password"),
                                        System.getProperty("submit.ssh.biocep.home"),
                                        "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                        "db", new Class<?>[] { DBLayerInterface.class });
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) dbLayer.lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {

                                    final String uid = (privateName != null && !privateName.equals(""))
                                            ? privateName
                                            : UUID.randomUUID().toString();
                                    final String[] jobIdHolder = new String[1];
                                    new Thread(new Runnable() {
                                        public void run() {
                                            try {

                                                String command = "java -Dlog.file="
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/log/%{uid}.log" + " -Drmi.port.start="
                                                        + System.getProperty("submit.ssh.rmi.port.start")
                                                        + " -Dname=%{uid}" + " -Dnaming.mode=db" + " -Ddb.host="
                                                        + System.getProperty("submit.ssh.host") + " -Dwait=true"
                                                        + " -jar "
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/biocep-core.jar";

                                                jobIdHolder[0] = SSHUtils.execSshBatch(command, uid,
                                                        System.getProperty("submit.ssh.prefix"),
                                                        System.getProperty("submit.ssh.host"),
                                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                                        System.getProperty("submit.ssh.user"),
                                                        System.getProperty("submit.ssh.password"),
                                                        System.getProperty("submit.ssh.biocep.home"));
                                                System.out.println("jobId:" + jobIdHolder[0]);

                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).start();

                                    long TIMEOUT = Long.decode(System.getProperty("submit.ssh.timeout"));
                                    long tStart = System.currentTimeMillis();
                                    while ((System.currentTimeMillis() - tStart) < TIMEOUT) {
                                        try {
                                            r = (RServices) dbLayer.lookup(uid);
                                        } catch (Exception e) {

                                        }
                                        if (r != null)
                                            break;
                                        try {
                                            Thread.sleep(10);
                                        } catch (Exception e) {
                                        }
                                    }

                                    if (r != null) {
                                        try {
                                            r.setJobId(jobIdHolder[0]);
                                        } catch (Exception e) {
                                            r = null;
                                        }
                                    }

                                }

                            } else {
                                System.out.println("LocalHttpServer.getLocalHttpServerPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                System.out.println("LocalRmiRegistry.getLocalRmiRegistryPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) LocalRmiRegistry.getInstance().lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {
                                    codeUrls = (URL[]) options.get("urls");
                                    System.out.println("CODE URL->" + Arrays.toString(codeUrls));
                                    //String 
                                    r = ServerManager.createR(System.getProperty("r.binary"), false, false,
                                            PoolUtils.getHostIp(), LocalHttpServer.getLocalHttpServerPort(),
                                            ServerManager.getRegistryNamingInfo(PoolUtils.getHostIp(),
                                                    LocalRmiRegistry.getLocalRmiRegistryPort()),
                                            memoryMin, memoryMax, privateName, false, codeUrls, null,
                                            (_webAppMode ? "javaws" : "standard"), null, "127.0.0.1");
                                }

                                privateEngineMode = true;
                            }

                        } else {

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                ServantProvider servantProvider = (ServantProvider) SSHTunnelingProxy
                                        .getDynamicProxy(System.getProperty("submit.ssh.host"),
                                                Integer.decode(System.getProperty("submit.ssh.port")),
                                                System.getProperty("submit.ssh.user"),
                                                System.getProperty("submit.ssh.password"),
                                                System.getProperty("submit.ssh.biocep.home"),
                                                "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                                "servant.provider", new Class<?>[] { ServantProvider.class });
                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxy()
                                            : servantProvider.borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxyNoWait()
                                            : servantProvider.borrowServantProxyNoWait(poolname));
                                }

                                System.out.println("---> borrowed : " + r);

                            } else {
                                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();

                                if (spFactory == null) {
                                    result = new NoRegistryAvailableException();
                                    break;
                                }

                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxy()
                                            : spFactory.getServantProvider().borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxyNoWait()
                                            : spFactory.getServantProvider()
                                                    .borrowServantProxyNoWait(poolname));
                                }
                            }
                        }
                    }
                } else {
                    r = _rkit.getR();
                }

                if (r == null) {
                    result = new NoServantAvailableException();
                    break;
                }

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "RS");
                session.setAttribute("R", r);
                session.setAttribute("NOPOOL", nopool);
                session.setAttribute("SAVE", save);
                session.setAttribute("LOGIN", login);
                session.setAttribute("NAMED_ACCESS_MODE", namedAccessMode);
                session.setAttribute("PROCESS_ID", r.getProcessId());
                session.setAttribute("JOB_ID", r.getJobId());
                session.setAttribute("SELFISH", selfish);
                session.setAttribute("IS_RELAY", _rkit != null);

                if (privateName != null)
                    session.setAttribute("PRIVATE_NAME", privateName);

                if (codeUrls != null && codeUrls.length > 0) {
                    session.setAttribute("CODEURLS", codeUrls);
                }

                session.setAttribute("THREADS", new ThreadsHolder());

                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                Vector<HttpSession> sessionVector = ((HashMap<RServices, Vector<HttpSession>>) getServletContext()
                        .getAttribute("R_SESSIONS")).get(r);
                if (sessionVector == null) {
                    sessionVector = new Vector<HttpSession>();
                    ((HashMap<RServices, Vector<HttpSession>>) getServletContext().getAttribute("R_SESSIONS"))
                            .put(r, sessionVector);
                }

                sessionVector.add(session);

                if (_rkit == null && save) {
                    UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), r);
                }

                System.out.println("---> Has Collaboration Listeners:" + r.hasRCollaborationListeners());
                if (selfish || !r.hasRCollaborationListeners()) {
                    try {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                        GDDevice[] devices = r.listDevices();
                        for (int i = 0; i < devices.length; ++i) {
                            String deviceName = devices[i].getId();
                            System.out.println("??? ---- deviceName=" + deviceName);
                            session.setAttribute(deviceName, devices[i]);
                        }

                    } finally {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                    }
                }

                if (privateEngineMode) {

                    if (options.get("newdevice") != null) {
                        GDDevice deviceProxy = null;
                        GDDevice[] dlist = r.listDevices();
                        if (dlist == null || dlist.length == 0) {
                            deviceProxy = r.newDevice(480, 480);
                        } else {
                            deviceProxy = dlist[0];
                        }
                        String deviceName = deviceProxy.getId();
                        session.setAttribute(deviceName, deviceProxy);
                        session.setAttribute("maindevice", deviceProxy);
                        saveSessionAttributes(session);
                    }

                    if (options.get("newgenericcallbackdevice") != null) {
                        GenericCallbackDevice genericCallBackDevice = null;
                        GenericCallbackDevice[] clist = r.listGenericCallbackDevices();
                        if (clist == null || clist.length == 0) {
                            genericCallBackDevice = r.newGenericCallbackDevice();
                        } else {
                            genericCallBackDevice = clist[0];
                        }
                        String genericCallBackDeviceName = genericCallBackDevice.getId();
                        session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                        session.setAttribute("maingenericcallbackdevice", genericCallBackDevice);
                        saveSessionAttributes(session);
                    }

                }

                result = session.getId();

                break;

            } else if (command.equals("logondb")) {

                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "DBS");
                session.setAttribute("REGISTRY", (DBLayer) spFactory.getServantProvider().getRegistry());
                session.setAttribute("SUPERVISOR",
                        new SupervisorUtils((DBLayer) spFactory.getServantProvider().getRegistry()));
                session.setAttribute("THREADS", new ThreadsHolder());
                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                result = session.getId();

                break;

            }

            session = request.getSession(false);
            if (session == null) {
                result = new NotLoggedInException();
                break;
            }

            if (command.equals("logoff")) {

                if (session.getAttribute("TYPE").equals("RS")) {
                    if (_rkit != null) {
                        /*
                        Enumeration<String> attributeNames = session.getAttributeNames();
                        while (attributeNames.hasMoreElements()) {
                           String aname = attributeNames.nextElement();
                           if (session.getAttribute(aname) instanceof GDDevice) {
                              try {
                                 _rkit.getRLock().lock();
                                 ((GDDevice) session.getAttribute(aname)).dispose();
                              } catch (Exception e) {
                                 e.printStackTrace();
                              } finally {
                                 _rkit.getRLock().unlock();
                              }
                           }
                        }
                        */
                    }
                }

                try {

                    session.invalidate();

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                result = null;
                break;
            }

            final boolean[] stop = { false };
            final HttpSession currentSession = session;

            if (command.equals("invoke")) {

                String servantName = (String) PoolUtils.hexToObject(request.getParameter("servantname"));
                final Object servant = session.getAttribute(servantName);
                if (servant == null) {
                    throw new Exception("Bad Servant Name :" + servantName);
                }
                String methodName = (String) PoolUtils.hexToObject(request.getParameter("methodname"));

                ClassLoader urlClassLoader = this.getClass().getClassLoader();
                if (session.getAttribute("CODEURLS") != null) {
                    urlClassLoader = new URLClassLoader((URL[]) session.getAttribute("CODEURLS"),
                            this.getClass().getClassLoader());
                }

                Class<?>[] methodSignature = (Class[]) PoolUtils
                        .hexToObject(request.getParameter("methodsignature"));

                final Method m = servant.getClass().getMethod(methodName, methodSignature);
                if (m == null) {
                    throw new Exception("Bad Method Name :" + methodName);
                }
                final Object[] methodParams = (Object[]) PoolUtils
                        .hexToObject(request.getParameter("methodparameters"), urlClassLoader);
                final Object[] resultHolder = new Object[1];
                Runnable rmiRunnable = new Runnable() {
                    public void run() {
                        try {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                            resultHolder[0] = m.invoke(servant, methodParams);
                            if (resultHolder[0] == null)
                                resultHolder[0] = RMICALL_DONE;
                        } catch (InvocationTargetException ite) {
                            if (ite.getCause() instanceof ConnectException) {
                                currentSession.invalidate();
                                resultHolder[0] = new NotLoggedInException();
                            } else {
                                resultHolder[0] = ite.getCause();
                            }
                        } catch (Exception e) {
                            final boolean wasInterrupted = Thread.interrupted();
                            if (wasInterrupted) {
                                resultHolder[0] = new RmiCallInterrupted();
                            } else {
                                resultHolder[0] = e;
                            }
                        } finally {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                        }
                    }
                };

                Thread rmiThread = InterruptibleRMIThreadFactory.getInstance().newThread(rmiRunnable);
                ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().add(rmiThread);
                rmiThread.start();

                long t1 = System.currentTimeMillis();

                while (resultHolder[0] == null) {

                    if ((System.currentTimeMillis() - t1) > RMICALL_TIMEOUT_MILLISEC || stop[0]) {
                        rmiThread.interrupt();
                        resultHolder[0] = new RmiCallTimeout();
                        break;
                    }

                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {
                    }
                }
                try {
                    ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().remove(rmiThread);
                } catch (IllegalStateException e) {
                }

                if (resultHolder[0] instanceof Throwable) {
                    throw (Throwable) resultHolder[0];
                }

                if (resultHolder[0] == RMICALL_DONE) {
                    result = null;
                } else {
                    result = resultHolder[0];
                }

                break;

            }

            if (command.equals("interrupt")) {
                final Vector<Thread> tvec = (Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS"))
                        .getThreads().clone();
                for (int i = 0; i < tvec.size(); ++i) {
                    try {
                        tvec.elementAt(i).interrupt();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                stop[0] = true;
                ((Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")).getThreads())
                        .removeAllElements();
                result = null;
                break;
            } else if (command.equals("saveimage")) {
                UserUtils.saveWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("loadimage")) {
                UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("newdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    boolean broadcasted = new Boolean(request.getParameter("broadcasted"));
                    GDDevice deviceProxy = null;
                    if (broadcasted) {
                        deviceProxy = ((RServices) session.getAttribute("R")).newBroadcastedDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    } else {
                        deviceProxy = ((RServices) session.getAttribute("R")).newDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    }

                    String deviceName = deviceProxy.getId();
                    System.out.println("deviceName=" + deviceName);
                    session.setAttribute(deviceName, deviceProxy);
                    saveSessionAttributes(session);
                    result = deviceName;
                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("listdevices")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                    result = new Vector<String>();
                    for (Enumeration<String> e = session.getAttributeNames(); e.hasMoreElements();) {
                        String attributeName = e.nextElement();
                        if (attributeName.startsWith("device_")) {
                            ((Vector<String>) result).add(attributeName);
                        }
                    }

                    break;

                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newgenericcallbackdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    GenericCallbackDevice genericCallBackDevice = ((RServices) session.getAttribute("R"))
                            .newGenericCallbackDevice();

                    String genericCallBackDeviceName = genericCallBackDevice.getId();
                    session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                    saveSessionAttributes(session);

                    result = genericCallBackDeviceName;

                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newspreadsheetmodeldevice")) {

                String spreadsheetModelDeviceId = request.getParameter("id");
                SpreadsheetModelRemote model = null;

                if (spreadsheetModelDeviceId == null || spreadsheetModelDeviceId.equals("")) {
                    model = ((RServices) session.getAttribute("R")).newSpreadsheetTableModelRemote(
                            Integer.decode(request.getParameter("rowcount")),
                            Integer.decode(request.getParameter("colcount")));
                } else {
                    model = ((RServices) session.getAttribute("R"))
                            .getSpreadsheetTableModelRemote(spreadsheetModelDeviceId);
                }

                SpreadsheetModelDevice spreadsheetDevice = model.newSpreadsheetModelDevice();
                String spreadsheetDeviceId = spreadsheetDevice.getId();
                session.setAttribute(spreadsheetDeviceId, spreadsheetDevice);
                saveSessionAttributes(session);
                result = spreadsheetDeviceId;
                break;

            } else if (command.equals("list")) {
                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }
                result = spFactory.getServantProvider().getRegistry().list();
                break;
            }

        } while (true);

    } catch (TunnelingException te) {
        result = te;
        te.printStackTrace();
    } catch (Throwable e) {
        result = new TunnelingException("Server Side", e);
        e.printStackTrace();
    }
    response.setContentType("application/x-java-serialized-object");
    new ObjectOutputStream(response.getOutputStream()).writeObject(result);
    response.flushBuffer();

}

From source file:canreg.client.dataentry.Convert.java

public static boolean importFile(canreg.client.gui.management.CanReg4MigrationInternalFrame.MigrationTask task,
        Document doc, List<canreg.client.dataentry.Relation> map, File file, CanRegServerInterface server,
        ImportOptions io) throws SQLException, RemoteException, SecurityException, RecordLockedException {
    boolean success = false;

    Set<String> noNeedToLookAtPatientVariables = new TreeSet<String>();

    noNeedToLookAtPatientVariables// w  w  w  .  j  a v a  2  s  .c  om
            .add(canreg.common.Tools.toLowerCaseStandardized(io.getPatientIDVariableName()));
    noNeedToLookAtPatientVariables
            .add(canreg.common.Tools.toLowerCaseStandardized(io.getPatientRecordIDVariableName()));

    String firstNameVariableName = io.getFirstNameVariableName();
    String sexVariableName = io.getSexVariableName();

    CSVParser parser = null;

    HashMap mpCodes = new HashMap();

    int numberOfLinesRead = 0;

    Map<String, Integer> nameSexTable = server.getNameSexTables();

    try {
        // Logger.getLogger(Import.class.getName()).log(Level.CONFIG, "Name of the character encoding {0}");

        int numberOfRecordsInFile = canreg.common.Tools.numberOfLinesInFile(file.getAbsolutePath());

        debugOut("Importing data from " + file);

        CSVFormat format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(io.getSeparator());

        parser = CSVParser.parse(file, io.getFileCharset(), format);

        int linesToRead = io.getMaxLines();
        if (linesToRead == -1 || linesToRead > numberOfRecordsInFile) {
            linesToRead = numberOfRecordsInFile;
        }

        for (CSVRecord csvRecord : parser) {
            numberOfLinesRead++;
            // We allow for null tasks...
            boolean needToSavePatientAgain = true;
            int patientDatabaseRecordID = -1;

            if (task != null) {
                if (canreg.client.gui.management.CanReg4MigrationInternalFrame.isPaused) {
                    task.firePropertyChange("paused", false, true);
                }
                if (!canreg.client.gui.management.CanReg4MigrationInternalFrame.isPaused) {
                    task.firePropertyChange("paused", true, false);
                    task.firePropertyChange("progress", (numberOfLinesRead - 1) * 100 / linesToRead,
                            (numberOfLinesRead) * 100 / linesToRead);
                }
            }

            // Build patient part
            Patient patient = new Patient();
            for (int i = 0; i < map.size(); i++) {
                Relation rel = map.get(i);
                if (rel.getDatabaseTableVariableID() >= 0
                        && rel.getDatabaseTableName().equalsIgnoreCase("patient")) {
                    if (rel.getFileColumnNumber() < csvRecord.size()) {
                        if (rel.getVariableType().equalsIgnoreCase("Number")) {
                            if (csvRecord.get(rel.getFileColumnNumber()).length() > 0) {
                                try {
                                    patient.setVariable(rel.getDatabaseVariableName(),
                                            Integer.parseInt(csvRecord.get(rel.getFileColumnNumber())));
                                } catch (NumberFormatException ex) {
                                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                                            "Number format error in line: " + (numberOfLinesRead + 1 + 1)
                                                    + ". ",
                                            ex);
                                    success = false;
                                }
                            }
                        } else {
                            patient.setVariable(rel.getDatabaseVariableName(),
                                    StringEscapeUtils.unescapeCsv(csvRecord.get(rel.getFileColumnNumber())));
                        }
                    } else {
                        Logger.getLogger(Import.class.getName()).log(Level.INFO,
                                "Something wrong with patient part of line " + numberOfLinesRead + ".",
                                new Exception("Error in line: " + numberOfLinesRead + ". Can't find field: "
                                        + rel.getDatabaseVariableName()));
                    }
                }
            }
            // debugOut(patient.toString());

            // Build tumour part
            Tumour tumour = new Tumour();
            for (int i = 0; i < map.size(); i++) {
                Relation rel = map.get(i);
                if (rel.getDatabaseTableVariableID() >= 0
                        && rel.getDatabaseTableName().equalsIgnoreCase("tumour")
                        && rel.getFileColumnNumber() < csvRecord.size()) {
                    if (rel.getFileColumnNumber() < csvRecord.size()) {
                        if (rel.getVariableType().equalsIgnoreCase("Number")) {
                            if (csvRecord.get(rel.getFileColumnNumber()).length() > 0) {
                                try {
                                    tumour.setVariable(rel.getDatabaseVariableName(),
                                            Integer.parseInt(csvRecord.get(rel.getFileColumnNumber())));
                                } catch (NumberFormatException ex) {
                                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                                            "Number format error in line: " + (numberOfLinesRead + 1 + 1)
                                                    + ". ",
                                            ex);
                                    success = false;
                                }
                            }
                        } else {
                            tumour.setVariable(rel.getDatabaseVariableName(),
                                    StringEscapeUtils.unescapeCsv(csvRecord.get(rel.getFileColumnNumber())));
                        }
                    } else {
                        Logger.getLogger(Import.class.getName()).log(Level.INFO,
                                "Something wrong with tumour part of line " + numberOfLinesRead + ".",
                                new Exception("Error in line: " + numberOfLinesRead + ". Can't find field: "
                                        + rel.getDatabaseVariableName()));
                    }
                }
            }

            // Build source part
            Set<Source> sources = Collections.synchronizedSet(new LinkedHashSet<Source>());
            Source source = new Source();
            for (int i = 0; i < map.size(); i++) {
                Relation rel = map.get(i);
                if (rel.getDatabaseTableVariableID() >= 0
                        && rel.getDatabaseTableName().equalsIgnoreCase(Globals.SOURCE_TABLE_NAME)
                        && rel.getFileColumnNumber() < csvRecord.size()) {
                    if (rel.getFileColumnNumber() < csvRecord.size()) {
                        if (rel.getVariableType().equalsIgnoreCase("Number")) {
                            if (csvRecord.get(rel.getFileColumnNumber()).length() > 0) {
                                try {
                                    source.setVariable(rel.getDatabaseVariableName(),
                                            Integer.parseInt(csvRecord.get(rel.getFileColumnNumber())));
                                } catch (NumberFormatException ex) {
                                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                                            "Number format error in line: " + (numberOfLinesRead + 1 + 1)
                                                    + ". ",
                                            ex);
                                    success = false;
                                }
                            }
                        } else {
                            source.setVariable(rel.getDatabaseVariableName(),
                                    StringEscapeUtils.unescapeCsv(csvRecord.get(rel.getFileColumnNumber())));
                        }
                    } else {
                        Logger.getLogger(Import.class.getName()).log(Level.INFO,
                                "Something wrong with source part of line " + numberOfLinesRead + ".",
                                new Exception("Error in line: " + numberOfLinesRead + ". Can't find field: "
                                        + rel.getDatabaseVariableName()));
                    }

                }

            }
            sources.add(source);
            tumour.setSources(sources);

            // debugOut(tumour.toString());
            // add patient to the database
            Object patientID = patient.getVariable(io.getPatientIDVariableName());
            Object patientRecordID = patient.getVariable(io.getPatientRecordIDVariableName());

            if (patientID == null) {
                // save the record to get the new patientID;
                patientDatabaseRecordID = server.savePatient(patient);
                patient = (Patient) server.getRecord(patientDatabaseRecordID, Globals.PATIENT_TABLE_NAME,
                        false);
                patientID = patient.getVariable(io.getPatientIDVariableName());
                patientRecordID = patient.getVariable(io.getPatientRecordIDVariableName());
            }

            if (io.isDataFromPreviousCanReg()) {
                // set update date for the patient the same as for the tumour
                Object updateDate = tumour.getVariable(io.getTumourUpdateDateVariableName());
                patient.setVariable(io.getPatientUpdateDateVariableName(), updateDate);

                // Set the patientID the same as the tumourID initially

                // Object tumourSequence = tumour.getVariable(io.getTumourSequenceVariableName());
                Object tumourSequence = "1";

                String tumourSequenceString = tumourSequence + "";
                while (tumourSequenceString.length() < Globals.ADDITIONAL_DIGITS_FOR_PATIENT_RECORD) {
                    tumourSequenceString = "0" + tumourSequenceString;
                }
                patientRecordID = patientID + "" + tumourSequenceString;

                // If this is a multiple primary tumour...
                String mpCodeString = (String) tumour.getVariable(io.getMultiplePrimaryVariableName());
                if (mpCodeString != null && mpCodeString.length() > 0) {
                    patientID = lookUpPatientID(mpCodeString, patientID, mpCodes);

                    // rebuild sequenceNumber
                    Tumour[] tumours = new Tumour[0];
                    try {
                        tumours = CanRegClientApp.getApplication()
                                .getTumourRecordsBasedOnPatientID(patientID + "", false);
                    } catch (DistributedTableDescriptionException ex) {
                        Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (UnknownTableException ex) {
                        Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    tumourSequenceString = (tumours.length + 1) + "";
                    while (tumourSequenceString.length() < Globals.ADDITIONAL_DIGITS_FOR_PATIENT_RECORD) {
                        tumourSequenceString = "0" + tumourSequenceString;
                    }

                    patientRecordID = patientID + "" + tumourSequenceString;
                    Patient[] oldPatients = null;
                    try {
                        oldPatients = CanRegClientApp.getApplication().getPatientRecordsByID((String) patientID,
                                false);
                    } catch (RemoteException ex) {
                        Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (SecurityException ex) {
                        Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (DistributedTableDescriptionException ex) {
                        Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (RecordLockedException ex) {
                        Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (SQLException ex) {
                        Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (UnknownTableException ex) {
                        Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    for (Patient oldPatient : oldPatients) {
                        if (!Tools.newRecordContainsNewInfo(patient, oldPatient,
                                noNeedToLookAtPatientVariables)) {
                            needToSavePatientAgain = false;
                            patient = oldPatient;
                            patientRecordID = oldPatient.getVariable(io.getPatientRecordIDVariableName());
                        }
                    }
                }

                Object tumourID = patientRecordID + "" + tumourSequenceString;
                //
                patient.setVariable(io.getPatientIDVariableName(), patientID);
                tumour.setVariable(io.getTumourIDVariablename(), tumourID);
                // And store the record ID

                patient.setVariable(io.getPatientRecordIDVariableName(), patientRecordID);

                // Set the patient ID number on the tumour
                tumour.setVariable(io.getPatientIDTumourTableVariableName(), patientID);
                tumour.setVariable(io.getPatientRecordIDTumourTableVariableName(), patientRecordID);

                // Set the deprecated flag to 0 - no obsolete records from CR4
                tumour.setVariable(io.getObsoleteTumourFlagVariableName(), "0");
                patient.setVariable(io.getObsoletePatientFlagVariableName(), "0");

            }

            // Set the name in the firstName database
            String sex = (String) patient.getVariable(sexVariableName);
            if (sex != null && sex.length() > 0) {
                Integer sexCode = Integer.parseInt(sex);
                String firstNames = (String) patient.getVariable(firstNameVariableName);
                if (firstNames != null) {
                    String[] firstNamesArray = firstNames.split(" ");
                    for (String firstName : firstNamesArray) {
                        if (firstName != null && firstName.trim().length() > 0) {
                            // here we use the locale specific toUpperCase
                            Integer registeredSexCode = nameSexTable.get(firstName);
                            if (registeredSexCode == null) {
                                NameSexRecord nsr = new NameSexRecord();
                                nsr.setName(firstName);
                                nsr.setSex(sexCode);

                                server.saveNameSexRecord(nsr, false);

                                nameSexTable.put(firstName, sexCode);
                            } else if (registeredSexCode != sexCode) {
                                if (registeredSexCode != 9) {
                                    sexCode = 9;
                                    NameSexRecord nsr = new NameSexRecord();
                                    nsr.setName(firstName);
                                    nsr.setSex(sexCode);
                                    server.saveNameSexRecord(nsr, true);
                                    nameSexTable.remove(firstName);
                                    nameSexTable.put(firstName, sexCode);
                                }
                            }
                        }
                    }
                }
            }

            if (needToSavePatientAgain) {
                if (patientDatabaseRecordID > 0) {
                    server.editPatient(patient);
                } else {
                    patientDatabaseRecordID = server.savePatient(patient);
                }
            }
            if (patient != null && tumour != null) {
                String icd10 = (String) tumour.getVariable(io.getICD10VariableName());
                if (icd10 == null || icd10.trim().length() == 0) {
                    ConversionResult[] conversionResult = canreg.client.CanRegClientApp.getApplication()
                            .performConversions(Converter.ConversionName.ICDO3toICD10, patient, tumour);
                    tumour.setVariable(io.getICD10VariableName(), conversionResult[0].getValue());
                }
            }
            if (tumour.getVariable(io.getPatientIDTumourTableVariableName()) == null) {
                tumour.setVariable(io.getPatientIDTumourTableVariableName(), patientID);
            }

            if (tumour.getVariable(io.getPatientRecordIDTumourTableVariableName()) == null) {
                tumour.setVariable(io.getPatientRecordIDTumourTableVariableName(), patientRecordID);
            }

            int tumourDatabaseIDNumber = server.saveTumour(tumour);

            if (Thread.interrupted()) {
                //We've been interrupted: no more importing.
                throw new InterruptedException();
            }
        }
        task.firePropertyChange("finished", null, null);
        success = true;
    } catch (IOException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                "Error in line: " + (numberOfLinesRead + 1 + 1) + ". ", ex);
        success = false;
    } catch (NumberFormatException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                "Error in line: " + (numberOfLinesRead + 1 + 1) + ". ", ex);
        success = false;
    } catch (InterruptedException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.INFO,
                "Interupted on line: " + (numberOfLinesRead + 1) + ". ", ex);
        success = true;
    } catch (IndexOutOfBoundsException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                "Error in line: " + (numberOfLinesRead + 1 + 1) + ". ", ex);
        success = false;
    } catch (SQLException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                "Error in line: " + (numberOfLinesRead + 1 + 1) + ". ", ex);
        success = false;
    } finally {
        if (parser != null) {
            try {
                parser.close();
            } catch (IOException ex) {
                Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return success;
}