Example usage for java.lang InterruptedException InterruptedException

List of usage examples for java.lang InterruptedException InterruptedException

Introduction

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

Prototype

public InterruptedException() 

Source Link

Document

Constructs an InterruptedException with no detail message.

Usage

From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java

/**
 * Uploads any unpublished casts./*w ww  .ja v  a  2 s  . c  om*/
 *
 * This is the method that does all the hard work.
 *
 * @param toSync
 * @param provider
 * @param syncMap
 * @param syncResult
 * @return the number of casts uploaded.
 * @throws JSONException
 * @throws NetworkProtocolException
 * @throws IOException
 * @throws NoPublicPath
 * @throws RemoteException
 * @throws OperationApplicationException
 * @throws SyncException
 * @throws InterruptedException
 */
private int uploadUnpublished(Uri toSync, Account account, ContentProviderClient provider, SyncMap syncMap,
        HashMap<String, SyncEngine.SyncStatus> syncStatuses, SyncResult syncResult)
        throws JSONException, NetworkProtocolException, IOException, NoPublicPath, RemoteException,
        OperationApplicationException, SyncException, InterruptedException {
    int count = 0;

    final String type = provider.getType(toSync);
    final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR);

    final Cursor uploadMe = provider.query(toSync, null, SELECTION_UNPUBLISHED, null, null);

    if (uploadMe == null) {
        throw new SyncException("could not query " + toSync);
    }

    final int idCol = uploadMe.getColumnIndex(JsonSyncableItem._ID);

    try {
        for (uploadMe.moveToFirst(); !uploadMe.isAfterLast(); uploadMe.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = uploadMe.getLong(idCol);

            final Uri localUri = isDir ? ContentUris.withAppendedId(toSync, id) : toSync;
            final String postUri = MediaProvider.getPostPath(mContext, localUri);

            Intent intent = new Intent(SYNC_STATUS_CHANGED);
            intent.putExtra(EXTRA_SYNC_STATUS, "castBegin");
            intent.putExtra(EXTRA_SYNC_ID, id);
            mContext.sendStickyBroadcast(intent);

            try {
                final JSONObject jo = JsonSyncableItem.toJSON(mContext, localUri, uploadMe, syncMap);

                if (DEBUG) {
                    Log.d(TAG, "uploading " + localUri + " to " + postUri);
                }

                // Upload! Any non-successful responses are handled by
                // exceptions.
                final HttpResponse res = mNetworkClient.post(postUri, jo.toString());

                long serverTime;
                try {
                    serverTime = getServerTime(res);
                    // We should never get a corrupted date from the server,
                    // but if it does happen,
                    // using the local time is a sane fallback.
                } catch (final DateParseException e) {
                    serverTime = System.currentTimeMillis();
                }

                // newly-created items return the JSON serialization of the
                // object as the server
                // knows it, so the local database needs to be updated to
                // reflect that.
                final JSONObject newJo = NetworkClient.toJsonObject(res);
                try {
                    final SyncStatus ss = loadItemFromJsonObject(newJo, syncMap, serverTime);

                    // update immediately, so that any cancellation or
                    // interruption of the sync
                    // keeps the local state in sync with what's on the
                    // server
                    final int updates = provider.update(localUri, ss.remoteCVs, null, null);

                    final String locUriString = localUri.toString();

                    if (updates == 1) {
                        ss.state = SyncState.NOW_UP_TO_DATE;
                        ss.local = localUri;

                        // ensure that it's findable by local URI too
                        syncStatuses.put(locUriString, ss);

                        syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson, true);

                        count++;
                        syncResult.stats.numUpdates++;

                    } else {
                        Log.e(TAG, "error updating " + locUriString);

                        syncResult.stats.numSkippedEntries++;
                    }

                    syncResult.stats.numEntries++;

                } catch (final JSONException e) {
                    if (DEBUG) {
                        Log.e(TAG, "result was " + newJo.toString());
                    }
                    throw e;
                }
            } finally {
                intent = new Intent(SYNC_STATUS_CHANGED);
                intent.putExtra(EXTRA_SYNC_STATUS, "castEnd");
                intent.putExtra(EXTRA_SYNC_ID, id);
                mContext.sendStickyBroadcast(intent);
            }
        }
    } finally {
        uploadMe.close();
    }

    return count;
}

From source file:org.micromanager.plugins.magellan.imagedisplay.DisplayOverlayer.java

private void addSurfaceInterpolation(Overlay overlay, SingleResolutionInterpolation interp,
        int displayPixPerInterpTile) throws InterruptedException {
    int width = display_.getImagePlus().getWidth();
    int height = display_.getImagePlus().getHeight();
    ZoomableVirtualStack zStack = (ZoomableVirtualStack) display_.virtualStack_;
    double sliceZ = zStack.getZCoordinateOfDisplayedSlice(display_.getVisibleSliceIndex());
    double zStep = acq_.getZStep();

    //Make numTestPoints a factor of image size for clean display of surface
    int numTestPointsX = width / displayPixPerInterpTile;
    int numTestPointsY = height / displayPixPerInterpTile;
    double roiWidth = width / (double) numTestPointsX;
    double roiHeight = height / (double) numTestPointsY;

    for (int x = 0; x < numTestPointsX; x++) {
        for (int y = 0; y < numTestPointsY; y++) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }//w w w. j ava  2 s .  c o  m
            Point2D.Double stageCoord = display_.stageCoordFromImageCoords((int) ((x + 0.5) * roiWidth),
                    (int) ((y + 0.5) * roiHeight));
            if (!interp.isInterpDefined(stageCoord.x, stageCoord.y)) {
                continue;
            }
            float interpZ = interp.getInterpolatedValue(stageCoord.x, stageCoord.y);

            if (Math.abs(sliceZ - interpZ) < zStep / 2) {
                double roiX = roiWidth * x;
                double roiY = roiHeight * y;
                //calculate distance from last ROI for uninterrupted coverage of image
                int displayWidth = (int) (roiWidth * (x + 1)) - (int) (roiX);
                int displayHeight = (int) (roiHeight * (y + 1)) - (int) (roiY);
                Roi rect = new Roi(roiX, roiY, displayWidth, displayHeight); //make ROI
                int[] lutRed = VIRIDIS_RED;
                int[] lutBlue = VIRIDIS_BLUE;
                int[] lutGreen = VIRIDIS_GREEN;
                double colorScale = ((sliceZ - interpZ) / (zStep / 2) + 1) / 2; //between 0 and 1
                rect.setFillColor(new Color(lutRed[(int) (colorScale * lutRed.length)],
                        lutGreen[(int) (colorScale * lutGreen.length)],
                        lutBlue[(int) (colorScale * lutBlue.length)], 175));
                overlay.add(rect);
            }
        }
    }
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java

private CloseableHttpResponse executeMethod(HttpRequestBase httpMethod)
        throws InterruptedException, IOException {

    if (authenticator != null) {
        authenticator.configureRequest(httpMethod);
    }/*from   w  ww . j a v  a  2  s . c o  m*/

    RequestConfig.Builder requestConfig = RequestConfig.custom();
    requestConfig.setConnectTimeout(10 * 1000);
    requestConfig.setConnectionRequestTimeout(60 * 1000);
    requestConfig.setSocketTimeout(60 * 1000);
    httpMethod.setConfig(requestConfig.build());

    CloseableHttpResponse response = client.execute(API_HOST, httpMethod, context);
    while (response.getStatusLine().getStatusCode() == API_RATE_LIMIT_CODE) {
        release(httpMethod);
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        /*
        TODO: When bitbucket starts supporting rate limit expiration time, remove 5 sec wait and put code
              to wait till expiration time is over. It should also fix the wait for ever loop.
         */
        LOGGER.fine("Bitbucket Cloud API rate limit reached, sleeping for 5 sec then retry...");
        Thread.sleep(5000);
        response = client.execute(API_HOST, httpMethod, context);
    }
    return response;
}

From source file:org.micromanager.plugins.magellan.surfacesandregions.SurfaceInterpolator.java

private synchronized void updateConvexHullAndInterpolate() {
    //duplicate points for use on caluclation thread
    final LinkedList<Point3d> points = new LinkedList<Point3d>(points_);
    if (currentInterpolationTask_ != null && !currentInterpolationTask_.isDone()) {
        //cancel current interpolation because interpolation points have changed, call does not block
        currentInterpolationTask_.cancel(true);
    }// w  ww.  ja va  2s.co m
    //don't want one of the get methods returning a null object thinking it has a value
    synchronized (convexHullLock_) {
        convexHullVertices_ = null;
        convexHullRegion_ = null;
    }
    synchronized (interpolationLock_) {
        currentInterpolation_ = null;
    }
    synchronized (xyPositionLock_) {
        xyPositions_ = null;
    }
    numRows_ = 0;
    numCols_ = 0;

    currentInterpolationTask_ = executor_.submit(new Runnable() {
        @Override
        public void run() {
            if (points.size() > 2) {
                try {
                    //convert xyPoints to a vector2d for convex hull calculation
                    LinkedList<Vector2D> xyPoints = new LinkedList<Vector2D>();
                    for (Point3d p : points) {
                        xyPoints.add(new Vector2D(p.x, p.y));
                    }
                    ConvexHull2D hull = null;
                    hull = mChain_.generate(xyPoints);
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    synchronized (convexHullLock_) {
                        convexHullVertices_ = hull.getVertices();
                        convexHullLock_.notifyAll();
                    }
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    convexHullRegion_ = hull.createRegion();
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    calculateConvexHullBounds();
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    //use the most recently set overlap value for display purposes. When it comes time to calc the real thing, 
                    //get it from the acquisition settings
                    fitXYPositionsToConvexHull(FixedAreaAcquisitionSettings.getStoredTileOverlapPercentage());
                    //Interpolate surface as specified by the subclass method
                    interpolateSurface(points);
                    //let manager handle event firing to acquisitions using surface
                    manager_.surfaceUpdated(SurfaceInterpolator.this);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    });
}

From source file:de.blizzy.backup.restore.RestoreDialog.java

private void restoreEntry(Entry entry, File parentFolder, String outputFolder, int backupId,
        IProgressMonitor monitor, Shell shell) throws IOException, InterruptedException {

    if (monitor.isCanceled()) {
        throw new InterruptedException();
    }//from w w w. j  a va 2  s.  com

    boolean isFolder = entry.type == EntryType.FOLDER;

    if (entry.type == EntryType.FAILED_FILE) {
        if (alwaysRestoreFromOlderBackups == null) {
            alwaysRestoreFromOlderBackups = Boolean.valueOf(promptRestoreFromOlderBackups(shell));
        }
        if (alwaysRestoreFromOlderBackups.booleanValue()) {
            entry = findInOlderBackups(entry);
        }
    }

    if ((entry != null) && (entry.type != EntryType.FAILED_FILE)) {
        Path outputPath;
        if (entry.type == EntryType.FOLDER) {
            File newFolder = new File(parentFolder, escapeFileName(entry.name));
            FileUtils.forceMkdir(newFolder);

            Cursor<Record> cursor = getEntriesCursor(backupId, entry.id, null, -1);
            try {
                for (Entry e : getEntries(cursor, false)) {
                    restoreEntry(e, newFolder, outputFolder, backupId, monitor, shell);
                }
            } finally {
                database.closeQuietly(cursor);
            }

            outputPath = newFolder.toPath();
        } else {
            File inputFile = Utils.toBackupFile(entry.backupPath, outputFolder);
            File outputFile = new File(parentFolder, escapeFileName(entry.name));
            outputPath = outputFile.toPath();
            InputStream in = null;
            try {
                InputStream fileIn = new BufferedInputStream(new FileInputStream(inputFile));
                InputStream interceptIn = fileIn;
                for (IStorageInterceptor interceptor : storageInterceptors) {
                    interceptIn = interceptor.interceptInputStream(interceptIn, entry.length);
                }
                InputStream compressIn = entry.compression.getInputStream(interceptIn);
                in = compressIn;
                Files.copy(in, outputPath);
            } finally {
                IOUtils.closeQuietly(in);
            }
        }

        FileAttributes fileAttributes = FileAttributes.get(outputPath);
        if (entry.hidden) {
            fileAttributes.setHidden(entry.hidden);
        }
        FileTime createTime = (entry.creationTime != null) ? FileTime.fromMillis(entry.creationTime.getTime())
                : null;
        FileTime modTime = (entry.modificationTime != null)
                ? FileTime.fromMillis(entry.modificationTime.getTime())
                : null;
        fileAttributes.setTimes(createTime, modTime);
    }

    if (!isFolder) {
        monitor.worked(1);
    }
}

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  w w.  j ava 2 s. c om*/
            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: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   ww w . j a  va 2  s. 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: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//from  ww w . j  a va2  s. c o m
            .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;
}

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * @param s// w ww.  j  av a  2s. c o  m
 *            session, which contain the current persistent object
 * @param po
 *            object to delete
 * @throws PMException
 *             in case of failed rollback
 * @throws PMAlreadyLockedException
 *             in case of locked object
 * @throws PMDirtyVersionException
 *             in case of version conflict
 * @throws ProjectDeletedException
 *             if the project was deleted in another instance
 * @throws InterruptedException
 *             if the oepration was canceled
 */
public void deletePO(EntityManager s, IPersistentObject po) throws PMException, PMAlreadyLockedException,
        PMDirtyVersionException, ProjectDeletedException, InterruptedException {

    Validate.notNull(s);
    try {
        s.remove(po);
    } catch (PersistenceException e) {
        if (e.getCause() instanceof InterruptedException) {
            // Operation was canceled.
            throw new InterruptedException();
        }

        PersistenceManager.handleDBExceptionForMasterSession(po, e);
    }
}

From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java

/**
 * //ww  w.  j  a v  a2s .co  m
 * @param proj
 *            ProjectPO to be attached and saved.
 * @param newProjectName
 *            name part of the ProjectNamePO. If there is no new name, this
 *            parameter must be null (same project, different version)
 * @param mapperList mapper to resolve Parameter Names
 * @param compNameBindingList mapper to resolve Component Names
 * @param monitor The progress monitor for this potentially long-running 
 *                operation.
 * @throws PMException
 *             in case of any db error
 * @throws ProjectDeletedException if project is already deleted
 * @throws InterruptedException if the operation was canceled.
 */
public static void attachProjectToROSession(IProjectPO proj, String newProjectName,
        List<INameMapper> mapperList, List<IWritableComponentNameMapper> compNameBindingList,
        IProgressMonitor monitor) throws PMException, ProjectDeletedException, InterruptedException {

    monitor.beginTask(NLS.bind(Messages.ProjectWizardCreatingProject, newProjectName),
            getTotalWorkForSave(proj));
    // Register Persistence progress listeners
    setHbmProgressMonitor(monitor);
    GeneralStorage.getInstance().reset();
    EntityManager s = GeneralStorage.getInstance().getMasterSession();
    EntityTransaction tx = null;
    try {
        tx = Persistor.instance().getTransaction(s);

        s.persist(proj);
        proj.setParentProjectId(proj.getId());
        if (newProjectName != null) {
            ProjectNameBP.getInstance().setName(s, proj.getGuid(), newProjectName);
        }
        ProjectNameBP.getInstance().storeTransientNames(s);
        for (INameMapper mapper : mapperList) {
            mapper.persist(s, proj.getId());
        }
        for (IWritableComponentNameMapper compNameBinding : compNameBindingList) {
            CompNamePM.flushCompNames(s, proj.getId(), compNameBinding);
        }
        if (!monitor.isCanceled()) {
            Persistor.instance().commitTransaction(s, tx);
            GeneralStorage.getInstance().setProject(proj);
            for (INameMapper mapper : mapperList) {
                mapper.updateStandardMapperAndCleanup(proj.getId());
            }
            for (IComponentNameMapper compNameBinding : compNameBindingList) {
                compNameBinding.getCompNameCache().updateStandardMapperAndCleanup(proj.getId());
            }
        } else {
            Persistor.instance().rollbackTransaction(s, tx);
            GeneralStorage.getInstance().reset();
            for (INameMapper mapper : mapperList) {
                mapper.clearAllNames();
            }
            for (IComponentNameMapper compNameBinding : compNameBindingList) {
                compNameBinding.getCompNameCache().clear();
            }
            throw new InterruptedException();
        }
    } catch (PMException pme) {
        handleAlreadyLockedException(mapperList, s, tx);
    } catch (OperationCanceledException oce) {
        handleOperationCanceled(mapperList, s, tx);
    } catch (PersistenceException e) {
        handlePersistenceException(mapperList, s, tx, e);
    } catch (IncompatibleTypeException ite) {
        handleIncompatibleTypeException(mapperList, s, tx, ite);
    } finally {
        // Remove Persistence progress listeners
        setHbmProgressMonitor(null);
    }
    initBPs(proj);
}