Example usage for java.lang Long compareTo

List of usage examples for java.lang Long compareTo

Introduction

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

Prototype

public int compareTo(Long anotherLong) 

Source Link

Document

Compares two Long objects numerically.

Usage

From source file:org.opendatakit.survey.android.tasks.InitializationTask.java

/**
 * Scan the given formDir and update the Forms database. If it is the
 * formsFolder, then any 'framework' forms should be forbidden. If it is not
 * the formsFolder, only 'framework' forms should be allowed
 *
 * @param mediaPath//  www.j  av a  2s . c  om
 *          -- full formDir
 * @param isFormsFolder
 * @param baseStaleMediaPath
 *          -- path prefix to the stale forms/framework directory.
 */
private final void updateFormDir(File formDir, boolean isFormsFolder, String baseStaleMediaPath) {
    Uri formsProviderContentUri = Uri.parse("content://" + FormsProviderAPI.AUTHORITY);
    String formDirectoryPath = formDir.getAbsolutePath();
    WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath);

    boolean needUpdate = true;
    FormInfo fi = null;
    Uri uri = null;
    Cursor c = null;
    try {
        File formDef = new File(formDir, ODKFileUtils.FORMDEF_JSON_FILENAME);

        String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?";
        String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, formDir) };
        c = appContext.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null,
                selection, selectionArgs, null);

        if (c == null) {
            WebLogger.getLogger(appName).w(t,
                    "updateFormDir: " + formDirectoryPath + " null cursor -- cannot update!");
            return;
        }

        if (c.getCount() > 1) {
            c.close();
            WebLogger.getLogger(appName).w(t, "updateFormDir: " + formDirectoryPath
                    + " multiple records from cursor -- delete all and restore!");
            // we have multiple records for this one directory.
            // Rename the directory. Delete the records, and move the
            // directory back.
            File tempMediaPath = moveToStaleDirectory(formDir, baseStaleMediaPath);
            appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                    selection, selectionArgs);
            FileUtils.moveDirectory(tempMediaPath, formDir);
            // we don't know which of the above records was correct, so
            // reparse this to get ground truth...
            fi = new FormInfo(appContext, appName, formDef);
        } else if (c.getCount() == 1) {
            c.moveToFirst();
            String id = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID));
            uri = Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), id);
            Long lastModificationDate = ODKDatabaseUtils.get().getIndexAsType(c, Long.class,
                    c.getColumnIndex(FormsColumns.DATE));
            Long formDefModified = ODKFileUtils.getMostRecentlyModifiedDate(formDir);
            if (lastModificationDate.compareTo(formDefModified) == 0) {
                WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath + " formDef unchanged");
                fi = new FormInfo(appName, c, false);
                needUpdate = false;
            } else {
                WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath + " formDef revised");
                fi = new FormInfo(appContext, appName, formDef);
                needUpdate = true;
            }
        } else if (c.getCount() == 0) {
            // it should be new, try to parse it...
            fi = new FormInfo(appContext, appName, formDef);
        }

        // Enforce that a formId == FormsColumns.COMMON_BASE_FORM_ID can only be
        // in the Framework directory
        // and that no other formIds can be in that directory. If this is not the
        // case, ensure that
        // this record is moved to the stale directory.

        if (fi.formId.equals(FormsColumns.COMMON_BASE_FORM_ID)) {
            if (isFormsFolder) {
                // we have a 'framework' form in the forms directory.
                // Move it to the stale directory.
                // Delete all records referring to this directory.
                moveToStaleDirectory(formDir, baseStaleMediaPath);
                appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                        selection, selectionArgs);
                return;
            }
        } else {
            if (!isFormsFolder) {
                // we have a non-'framework' form in the framework directory.
                // Move it to the stale directory.
                // Delete all records referring to this directory.
                moveToStaleDirectory(formDir, baseStaleMediaPath);
                appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                        selection, selectionArgs);
                return;
            }
        }
    } catch (SQLiteException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (IOException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (IllegalArgumentException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        try {
            FileUtils.deleteDirectory(formDir);
            WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath
                    + " Removing -- unable to parse formDef file: " + e.toString());
        } catch (IOException e1) {
            WebLogger.getLogger(appName).printStackTrace(e1);
            WebLogger.getLogger(appName)
                    .i(t, "updateFormDir: " + formDirectoryPath
                            + " Removing -- unable to delete form directory: " + formDir.getName() + " error: "
                            + e.toString());
        }
        return;
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    // Delete any entries matching this FORM_ID, but not the same directory and
    // which have a version that is equal to or older than this version.
    String selection;
    String[] selectionArgs;
    if (fi.formVersion == null) {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + FormsColumns.FORM_VERSION + " IS NULL";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId };
        selectionArgs = temp;
    } else {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + "( " + FormsColumns.FORM_VERSION + " IS NULL" + " OR " + FormsColumns.FORM_VERSION + " <=?"
                + " )";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId, fi.formVersion };
        selectionArgs = temp;
    }

    try {
        appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                selection, selectionArgs);
    } catch (SQLiteException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (Exception e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    }

    // See if we have any newer versions already present...
    if (fi.formVersion == null) {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + FormsColumns.FORM_VERSION + " IS NOT NULL";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId };
        selectionArgs = temp;
    } else {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + FormsColumns.FORM_VERSION + " >?";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId, fi.formVersion };
        selectionArgs = temp;
    }

    try {
        Uri uriApp = Uri.withAppendedPath(formsProviderContentUri, appName);
        c = appContext.getContentResolver().query(uriApp, null, selection, selectionArgs, null);

        if (c == null) {
            WebLogger.getLogger(appName).w(t,
                    "updateFormDir: " + uriApp.toString() + " null cursor -- cannot update!");
            return;
        }

        if (c.moveToFirst()) {
            // the directory we are processing is stale -- move it to stale
            // directory
            moveToStaleDirectory(formDir, baseStaleMediaPath);
            return;
        }
    } catch (SQLiteException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (IOException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    if (!needUpdate) {
        // no change...
        return;
    }

    try {
        // Now insert or update the record...
        ContentValues v = new ContentValues();
        String[] values = fi.asRowValues(FormsColumns.formsDataColumnNames);
        for (int i = 0; i < values.length; ++i) {
            v.put(FormsColumns.formsDataColumnNames[i], values[i]);
        }

        if (uri != null) {
            int count = appContext.getContentResolver().update(uri, v, null, null);
            WebLogger.getLogger(appName).i(t,
                    "updateFormDir: " + formDirectoryPath + " " + count + " records successfully updated");
        } else {
            appContext.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), v);
            WebLogger.getLogger(appName).i(t,
                    "updateFormDir: " + formDirectoryPath + " one record successfully inserted");
        }

    } catch (SQLiteException ex) {
        WebLogger.getLogger(appName).printStackTrace(ex);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + ex.toString());
        return;
    }
}

From source file:biz.wolschon.fileformats.gnucash.baseclasses.SimpleAccount.java

/**
 * Compares our name to o.toString() .<br/>
 * If both starts with some digits the resulting
 * ${@link java.lang.Integer} are compared.<br/>
 * If one starts with a number and the other does not,
 * the one starting with a number is "bigger"<br/>
 * else and if both integers are equals a normals comparison of the
 * {@link java.lang.String} is done.     *
 * @param   o the Object to be compared.
 * @return  a negative integer, zero, or a positive integer as this object
 *      is less than, equal to, or greater than the specified object.
 *
 * @throws ClassCastException if the specified object's type prevents it
 *         from being compared to this Object.
 *///  w ww . j ava 2  s  . c  o m
public int compareNamesTo(final Object o) throws ClassCastException {

    // usually compare the qualified name
    String other = o.toString();
    String me = getQualifiedName();

    // if we have the same parent,
    // compare the unqualified name.
    // This enshures that the exception
    // for numbers is used within our parent-
    // account too and not just in the top-
    // level accounts
    if (o instanceof GnucashAccount && ((GnucashAccount) o).getParentAccountId() != null
            && getParentAccountId() != null
            && ((GnucashAccount) o).getParentAccountId().equalsIgnoreCase(getParentAccountId())) {
        other = ((GnucashAccount) o).getName();
        me = getName();
    }

    // compare

    Long i0 = startsWithNumber(other);
    Long i1 = startsWithNumber(me);
    if (i0 == null && i1 != null) {
        return 1;
    }
    if (i1 == null && i0 != null) {
        return -1;
    }
    if (i0 == null) {
        return me.compareTo(other);
    }
    if (i1 == null) {
        return me.compareTo(other);
    }

    if (i1.equals(i0)) {
        return me.compareTo(other);
    }

    return i1.compareTo(i0);
}

From source file:io.wcm.handler.mediasource.dam.impl.RenditionMetadata.java

@Override
public int compareTo(RenditionMetadata obj) {
    // always prefer the virtual crop rendition
    if (this instanceof VirtualCropRenditionMetadata) {
        return -1;
    } else if (obj instanceof VirtualCropRenditionMetadata) {
        return 1;
    }//from w w  w .  j  av a2  s.c  om

    // order by width, height, rendition path
    Long thisWidth = getWidth();
    Long otherWidth = obj.getWidth();
    if (thisWidth.equals(otherWidth)) {
        Long thisHeight = getHeight();
        Long otherHeight = obj.getHeight();
        if (thisHeight.equals(otherHeight)) {
            String thisPath = getRendition().getPath();
            String otherPath = obj.getRendition().getPath();
            if (!StringUtils.equals(thisPath, otherPath)) {
                // same with/height - prefer original rendition
                if (isOriginalRendition(getRendition())) {
                    return -1;
                } else if (isOriginalRendition(obj.getRendition())) {
                    return 1;
                } else {
                    return thisPath.compareTo(otherPath);
                }
            } else {
                return 0;
            }
        } else {
            return thisHeight.compareTo(otherHeight);
        }
    } else {
        return thisWidth.compareTo(otherWidth);
    }
}

From source file:org.asqatasun.service.command.AuditCommandImpl.java

@Override
public void adaptContent() {
    audit = auditDataService.read(audit.getId());
    if (!audit.getStatus().equals(AuditStatus.CONTENT_ADAPTING)) {
        LOGGER.warn(/* www .jav a 2  s  . c  o m*/
                new StringBuilder(AUDIT_STATUS_IS_LOGGER_STR).append(audit.getStatus()).append(WHILE_LOGGER_STR)
                        .append(AuditStatus.CONTENT_ADAPTING).append(WAS_REQUIRED_LOGGER_STR).toString());
        return;
    }

    LOGGER.info("Adapting " + audit.getSubject().getURL());

    // debug tools
    Date endRetrieveDate;
    Date endProcessDate;
    Date endPersistDate;
    Long persistenceDuration = (long) 0;

    boolean hasCorrectDOM = false;
    Long i = (long) 0;
    Long webResourceId = audit.getSubject().getId();
    Long nbOfContent = contentDataService.getNumberOfSSPFromWebResource(audit.getSubject(), HttpStatus.SC_OK);

    // Some actions have to be realized when the adaptation starts
    if (adaptationListener != null) {
        adaptationListener.adaptationStarted(audit);
    }

    while (i.compareTo(nbOfContent) < 0) {

        LOGGER.debug(new StringBuilder("Adapting ssp from  ").append(i).append(TO_LOGGER_STR)
                .append(i + adaptationTreatmentWindow).append(" for ").append(audit.getSubject().getURL())
                .toString());

        Collection<Content> contentList = contentDataService.getSSPFromWebResource(webResourceId, i,
                adaptationTreatmentWindow, true);
        endRetrieveDate = Calendar.getInstance().getTime();

        Set<Content> contentSet = new HashSet<>();
        // Set the referential to the contentAdapterService due to different
        // behaviour in the implementation. Has to be removed when accessiweb 2.1
        // implementations will be based on jsoup.
        contentSet.addAll(contentAdapterService.adaptContent(contentList));

        endProcessDate = Calendar.getInstance().getTime();
        LOGGER.debug(new StringBuilder("Adapting  ").append(contentList.size()).append(SSP_TOOK_LOGGER_STR)
                .append(endProcessDate.getTime() - endRetrieveDate.getTime()).append(MS_LOGGER_STR)
                .append(contentSet.size()).toString());

        hasCorrectDOM = hasCorrectDOM || hasContentSetAtLeastOneCorrectDOM(contentSet);

        this.encodeSourceAndPersistContentList(contentSet);

        endPersistDate = Calendar.getInstance().getTime();
        LOGGER.debug(new StringBuilder("Persisting  ").append(contentSet.size()).append(SSP_TOOK_LOGGER_STR)
                .append(endPersistDate.getTime() - endProcessDate.getTime()).append(MS_LOGGER_STR)
                .append("for ").append(audit.getSubject().getURL()).toString());
        persistenceDuration = persistenceDuration + (endPersistDate.getTime() - endProcessDate.getTime());
        i = i + adaptationTreatmentWindow;
        // explicit call of the Gc
        System.gc();
    }

    LOGGER.debug(new StringBuilder("Application spent ").append(persistenceDuration)
            .append(" ms to write in Disk while adapting").toString());

    if (hasCorrectDOM) {
        setStatusToAudit(AuditStatus.PROCESSING);
    } else {
        Logger.getLogger(AuditServiceImpl.class).warn("Audit has no corrected DOM");
        setStatusToAudit(AuditStatus.ERROR);
    }

    // Some actions have to be realized when the adaptation is completed
    if (adaptationListener != null) {
        adaptationListener.adaptationCompleted(audit);
    }
    LOGGER.info(audit.getSubject().getURL() + " has been adapted");
}

From source file:org.sakaiproject.contentreview.impl.compilatio.CompilatioReviewServiceImpl.java

@Override
public String getIconUrlforScore(Long score) {
    String urlBase = "/sakai-contentreview-tool-federated/images/score_";
    String suffix = ".gif";

    if (score.compareTo(Long.valueOf(5)) <= 0) {
        return urlBase + "green" + suffix;
    } else if (score.compareTo(Long.valueOf(20)) <= 0) {
        return urlBase + "orange" + suffix;
    } else {/*ww w.  j ava 2 s. c  o m*/
        return urlBase + "red" + suffix;
    }
}

From source file:org.opens.tanaguru.service.command.AuditCommandImpl.java

@Override
public void adaptContent() {
    audit = auditDataService.read(audit.getId());
    if (!audit.getStatus().equals(AuditStatus.CONTENT_ADAPTING)) {
        LOGGER.warn(/*from  ww w. j  ava 2 s .  c  om*/
                new StringBuilder(AUDIT_STATUS_IS_LOGGER_STR).append(audit.getStatus()).append(WHILE_LOGGER_STR)
                        .append(AuditStatus.CONTENT_ADAPTING).append(WAS_REQUIRED_LOGGER_STR).toString());
        return;
    }

    LOGGER.info("Adapting " + audit.getSubject().getURL());

    // debug tools
    Date beginProcessDate;
    Date endRetrieveDate;
    Date endProcessDate;
    Date endPersistDate;
    Long persistenceDuration = Long.valueOf(0);

    boolean hasCorrectDOM = false;
    Long i = Long.valueOf(0);
    Long webResourceId = audit.getSubject().getId();
    Long nbOfContent = contentDataService.getNumberOfSSPFromWebResource(audit.getSubject(), HttpStatus.SC_OK);

    // Some actions have to be realized when the adaptation starts
    if (adaptationListener != null) {
        adaptationListener.adaptationStarted(audit);
    }

    while (i.compareTo(nbOfContent) < 0) {

        beginProcessDate = Calendar.getInstance().getTime();
        LOGGER.debug(new StringBuilder("Adapting ssp from  ").append(i).append(TO_LOGGER_STR)
                .append(i + adaptationTreatmentWindow).append(" for ").append(audit.getSubject().getURL())
                .toString());

        List<Content> contentList = retrieveContentList(webResourceId, i, adaptationTreatmentWindow,
                beginProcessDate, false, true);
        endRetrieveDate = Calendar.getInstance().getTime();

        Set<Content> contentSet = new HashSet<Content>();
        // Set the referential to the contentAdapterService due to different
        // behaviour in the implementation. Has to be removed when accessiweb 2.1
        // implementations will be based on jsoup.
        contentSet.addAll(contentAdapterService.adaptContent(contentList));

        endProcessDate = Calendar.getInstance().getTime();
        LOGGER.debug(new StringBuilder("Adapting  ").append(contentList.size()).append(SSP_TOOK_LOGGER_STR)
                .append(endProcessDate.getTime() - endRetrieveDate.getTime()).append(MS_LOGGER_STR)
                .append(contentSet.size()).toString());

        hasCorrectDOM = hasCorrectDOM || hasContentSetAtLeastOneCorrectDOM(contentSet);

        this.encodeSourceAndPersistContentList(contentSet);

        endPersistDate = Calendar.getInstance().getTime();
        LOGGER.debug(new StringBuilder("Persisting  ").append(contentSet.size()).append(SSP_TOOK_LOGGER_STR)
                .append(endPersistDate.getTime() - endProcessDate.getTime()).append(MS_LOGGER_STR)
                .append("for ").append(audit.getSubject().getURL()).toString());
        persistenceDuration = persistenceDuration + (endPersistDate.getTime() - endProcessDate.getTime());
        i = i + adaptationTreatmentWindow;
        // explicit call of the Gc
        System.gc();
    }

    LOGGER.debug(new StringBuilder("Application spent ").append(persistenceDuration)
            .append(" ms to write in Disk while adapting").toString());

    if (hasCorrectDOM) {
        setStatusToAudit(AuditStatus.PROCESSING);
    } else {
        Logger.getLogger(AuditServiceImpl.class).warn("Audit has no corrected DOM");
        setStatusToAudit(AuditStatus.ERROR);
    }

    // Some actions have to be realized when the adaptation is completed
    if (adaptationListener != null) {
        adaptationListener.adaptationCompleted(audit);
    }
    LOGGER.info(audit.getSubject().getURL() + " has been adapted");
}

From source file:org.opendatakit.common.persistence.engine.gae.TaskLockImpl.java

/**
 *
 * @param entity// w  w w.ja  va 2  s.com
 * @return true if expired
 * @throws ODKTaskLockException
 */
private boolean isExpired(Entity entity) throws NullPointerException, ODKTaskLockException {
    if (entity == null) {
        throw new NullPointerException();
    }
    Long timestamp = getTimestamp(entity);
    Long current = System.currentTimeMillis();

    // log the lock
    String lockId = "UNKNOWN LOCK";
    Object obj = entity.getProperty(LOCK_ID_PROPERTY);
    if (obj instanceof String) {
        lockId = (String) obj;
    }
    log.info("LockId: " + lockId + " Time left: " + Long.toString(timestamp - current));
    if (current.compareTo(timestamp) > 0) {
        return true;
    }
    return false;
}

From source file:org.tdl.vireo.model.jpa.JpaSubmissionImpl.java

@Override
public Attachment findAttachmentById(Long id) {
    for (Attachment attachment : attachments) {
        if (id.compareTo(attachment.getId()) == 0)
            return attachment;
    }/*from w  w  w. j a  v  a  2  s .  com*/
    return null;
}

From source file:org.gbif.harvest.digir.DigirMetadataHandler.java

/**
 * Construct a new BioDatasource, or update a pre-existing one.
 *
 * @param name                of BioDatasource
 * @param url                 access point URL
 * @param resourceName        code//from w  w  w  .  j  ava2  s  . c o m
 * @param resourceCount       count
 * @param uddiKey             registry service UUID
 * @param params              map of BioDatasource params
 * @param contentNamespace    contentNamespace
 * @param mappingFile         name
 * @param protocol            name
 * @param parentDirectoryName parent directory name
 *
 * @throws HarvesterException thrown if method fails
 */
private void createOrUpdateBioDatasource(String name, String url, String resourceName, String resourceCount,
        String uddiKey, Map<String, Object> params, String contentNamespace, String mappingFile,
        String protocol, String parentDirectoryName) throws HarvesterException {

    // Whether we're creating/updating, we always need to update params:
    params.put("url", url);
    params.put("resource_name", resourceName);
    params.put("contentNamespace", contentNamespace);
    params.put("mappingFile", mappingFile);
    params.put("protocol", protocol);
    params.put("harvesterFactory", Constants.DIGIR_HARVESTER_FACTORY);

    // construct the new, validated directory name
    String newValidDirectoryName = BioDatasourceUtils.constructBioDatasourceOperatorDirectoryName(resourceName,
            parentDirectoryName);
    params.put("directory", newValidDirectoryName);

    // get country name
    String country = null;
    if (params.containsKey("country")) {
        country = (String) params.get("country");
        // "country":null is converted to "country":"\"null\""
        if (StringUtils.equalsIgnoreCase(country, "\"null\"")) {
            country = null;
        }
    }

    // get provider name
    String dataProviderName = null;
    if (params.containsKey("providerName")) {
        dataProviderName = params.get("providerName").toString();
    }

    // add synchroniserFactories list to params
    synchroniserFactories = getSynchroniserFactories();
    List<String> factories = new LinkedList<String>();
    Iterator<AbstractSynchroniserFactory> iter = synchroniserFactories.iterator();
    while (iter.hasNext()) {
        Class cls = (iter.next().getClass());
        String clsName = cls.getName();
        factories.add(clsName);
    }
    params.put("synchroniserFactories", factories);

    // construct BioDatasource's name
    String newName = BioDatasourceUtils.constructBioDatasourceName(name, resourceName);

    Long id = bioDatasourceManager.checkIfBioDatasourceExists(newName, uddiKey);
    try {
        // if this is a new BioDatasource
        if (id.compareTo(-1L) == 0) {

            // default count to 0
            int count = 0;
            try {
                count = Integer.valueOf(resourceCount);
            } catch (NumberFormatException e) {
                count = 0;
                log.info("defaultCount", String.valueOf(count));
            }

            // update params
            Map<String, Object> newParams = new HashMap<String, Object>();
            newParams.putAll(params);
            newParams.put("name", newName);
            newParams.put("uddiKey", uddiKey);
            newParams.put("targetCount", String.valueOf(count));
            String parametersAsJson = JSONUtils.jsonFromMap(newParams);

            // create new BioDatasource
            BioDatasource datasource = new BioDatasource(newName, dataProviderName,
                    Constants.DIGIR_HARVESTER_FACTORY, parametersAsJson, count, uddiKey, country, url);

            bioDatasourceManager.save(datasource);
            log.info("createBioDatasource", newName);
            log.info("setCount", resourceCount);
        } else {
            BioDatasource bioDatasource = bioDatasourceManager.get(id);

            // update params
            Map<String, Object> oldParams = JSONUtils.mapFromJSON(bioDatasource.getParametersAsJSON());
            oldParams.putAll(params);

            // update its target count
            oldParams.put("targetCount", resourceCount);
            bioDatasource.setParametersAsJSON(JSONUtils.jsonFromMap(oldParams));
            bioDatasource.setTargetCount(Integer.parseInt(resourceCount));

            // in case the url has changed
            bioDatasource.setUrl(url);

            // in case the country has changed
            bioDatasource.setCountry(country);

            // in case the provider name has changed
            bioDatasource.setProviderName(BioDatasourceUtils.prepareStringForUI(dataProviderName));

            bioDatasourceManager.save(bioDatasource);
            log.info("createBioDatasource.exists", bioDatasource.getName());
            log.info("updateCount", resourceCount);
        }
    } catch (Exception e) {
        log.error("error.createBioDatasource", e.getMessage(), e);
        throw new HarvesterException(e.getMessage(), e);
    }
}

From source file:hsa.awp.admingui.controller.AdminGuiController.java

private boolean isNullOrZero(Long number) {
    return number == null || number.compareTo(0L) == 0;
}