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.asqatasun.service.command.AuditCommandImpl.java

@Override
public void analyse() {
    audit = auditDataService.read(audit.getId());
    if (!audit.getStatus().equals(AuditStatus.ANALYSIS)) {
        LOGGER.warn(/*  ww  w  .  j a va2s.c om*/
                new StringBuilder(AUDIT_STATUS_IS_LOGGER_STR).append(audit.getStatus()).append(WHILE_LOGGER_STR)
                        .append(AuditStatus.ANALYSIS).append(WAS_REQUIRED_LOGGER_STR).toString());
        return;
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Analysing " + audit.getSubject().getURL());
    }
    // debug tools
    Date beginProcessDate = null;
    Date endProcessDate = null;
    Date endPersistDate;
    Long persistenceDuration = (long) 0;

    WebResource parentWebResource = audit.getSubject();
    if (parentWebResource instanceof Page) {
        analyserService.analyse(parentWebResource, audit);
        webResourceDataService.saveOrUpdate(parentWebResource);
    } else if (parentWebResource instanceof Site) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Analysing results of scope site");
            beginProcessDate = Calendar.getInstance().getTime();
        }
        analyserService.analyse(parentWebResource, audit);
        if (LOGGER.isDebugEnabled()) {
            endProcessDate = Calendar.getInstance().getTime();
            LOGGER.debug(new StringBuilder("Analysing results of scope site took ")
                    .append(endProcessDate.getTime() - beginProcessDate.getTime()).append(MS_LOGGER_STR)
                    .toString());
        }
        webResourceDataService.saveOrUpdate(parentWebResource);

        if (LOGGER.isDebugEnabled()) {
            endPersistDate = Calendar.getInstance().getTime();
            LOGGER.debug(new StringBuilder("Persisting Analysis results of scope site ")
                    .append(endPersistDate.getTime() - endProcessDate.getTime()).append(MS_LOGGER_STR)
                    .toString());
            persistenceDuration = persistenceDuration + (endPersistDate.getTime() - endProcessDate.getTime());
        }

        Long nbOfContent = webResourceDataService.getNumberOfChildWebResource(parentWebResource);
        Long i = (long) 0;
        List<WebResource> webResourceList;
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(new StringBuilder("Analysing ").append(nbOfContent).append(" elements ").toString());
        }
        while (i.compareTo(nbOfContent) < 0) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(new StringBuilder("Analysing results of scope page from ").append(i)
                        .append(TO_LOGGER_STR).append(i + analyseTreatmentWindow).toString());
                beginProcessDate = Calendar.getInstance().getTime();
            }
            webResourceList = webResourceDataService.getWebResourceFromItsParent(parentWebResource,
                    i.intValue(), analyseTreatmentWindow);
            for (WebResource webResource : webResourceList) {
                if (LOGGER.isDebugEnabled()) {
                    endProcessDate = Calendar.getInstance().getTime();
                    LOGGER.debug(new StringBuilder("Analysing results for page ").append(webResource.getURL())
                            .append(" took ").append(endProcessDate.getTime() - beginProcessDate.getTime())
                            .append(MS_LOGGER_STR).toString());
                }
                analyserService.analyse(webResource, audit);
                if (LOGGER.isDebugEnabled()) {
                    endPersistDate = Calendar.getInstance().getTime();
                    LOGGER.debug(new StringBuilder("Persisting Analysis results for page ")
                            .append(webResource.getURL()).append(" took ")
                            .append(endPersistDate.getTime() - endProcessDate.getTime()).append(MS_LOGGER_STR)
                            .toString());
                    persistenceDuration = persistenceDuration
                            + (endPersistDate.getTime() - endProcessDate.getTime());
                }
            }
            i = i + analyseTreatmentWindow;
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(new StringBuilder("Application spent ").append(persistenceDuration)
                .append(" ms to write in Disk while analysing").toString());
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(audit.getSubject().getURL() + " has been analysed");
    }
    setStatusToAudit(AuditStatus.COMPLETED);
    if (cleanUpRelatedContent) {
        cleanUpTestData(audit);
    }
}

From source file:org.ossie.properties.AnyUtils.java

/**
 * Attempts to convert the string value to the appropriate Java type.
 * //  w ww.  j  ava2s .c  o  m
 * @param stringValue the string form of the value
 * @param type the string form of the TypeCode
 * @return A Java object of theString corresponding to the typecode
 */
public static Object convertString(final String stringValue, final String type) {
    if (stringValue == null) {
        return null;
    }
    if (type.equals("string")) {
        return stringValue;
    } else if (type.equals("wstring")) {
        return stringValue;
    } else if (type.equals("boolean")) {
        if ("true".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue)) {
            return Boolean.parseBoolean(stringValue);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid boolean value");
    } else if (type.equals("char")) {
        if (stringValue.length() == 1) {
            return stringValue.charAt(0);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid char value");
    } else if (type.equals("wchar")) {
        return stringValue.charAt(0);
    } else if (type.equals("double")) {
        return Double.parseDouble(stringValue);
    } else if (type.equals("float")) {
        return Float.parseFloat(stringValue);
    } else if (type.equals("short")) {
        return Short.decode(stringValue);
    } else if (type.equals("long")) {
        return Integer.decode(stringValue);
    } else if (type.equals("longlong")) {
        return Long.decode(stringValue);
    } else if (type.equals("ulong")) {
        final long MAX_UINT = 2L * Integer.MAX_VALUE + 1L;
        final Long retVal = Long.decode(stringValue);
        if (retVal < 0 || retVal > MAX_UINT) {
            throw new IllegalArgumentException(
                    "ulong value must be greater than '0' and less than " + MAX_UINT);
        }
        return retVal;
    } else if (type.equals("ushort")) {
        final int MAX_USHORT = 2 * Short.MAX_VALUE + 1;
        final Integer retVal = Integer.decode(stringValue);
        if (retVal < 0 || retVal > MAX_USHORT) {
            throw new IllegalArgumentException(
                    "ushort value must be greater than '0' and less than " + MAX_USHORT);
        }
        return retVal;
    } else if (type.equals("ulonglong")) {
        final BigInteger MAX_ULONG_LONG = BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2))
                .add(BigInteger.ONE);
        final BigInteger retVal = bigIntegerDecode(stringValue);
        if (retVal.compareTo(BigInteger.ZERO) < 0 || retVal.compareTo(MAX_ULONG_LONG) > 0) {
            throw new IllegalArgumentException(
                    "ulonglong value must be greater than '0' and less than " + MAX_ULONG_LONG.toString());
        }
        return retVal;
    } else if (type.equals("objref")) {
        List<String> objrefPrefix = Arrays.asList("IOR:", "corbaname:", "corbaloc:");
        for (String prefix : objrefPrefix) {
            if (stringValue.startsWith(prefix)) {
                return stringValue;
            }
        }
        throw new IllegalArgumentException(stringValue + " is not a valid objref value");
    } else if (type.equals("octet")) {
        final short MIN_OCTET = 0;
        final short MAX_OCTET = 0xFF;
        short val = Short.valueOf(stringValue);
        if (val <= MAX_OCTET && val >= MIN_OCTET) {
            return Short.valueOf(val).byteValue();
        }
        throw new IllegalArgumentException(stringValue + " is not a valid octet value");
    } else {
        throw new IllegalArgumentException("Unknown CORBA Type: " + type);
    }
}

From source file:org.sakaiproject.contentreview.vericite.ContentReviewServiceVeriCite.java

public String getIconUrlforScore(Long score) {
    String urlBase = "/library/content-review/";
    String suffix = ".png";

    if (score.compareTo(Long.valueOf(0)) < 0) {
        return urlBase + "greyflag" + suffix;
    } else if (score.equals(Long.valueOf(0))) {
        return urlBase + "blueflag" + suffix;
    } else if (score.compareTo(Long.valueOf(25)) < 0) {
        return urlBase + "greenflag" + suffix;
    } else if (score.compareTo(Long.valueOf(50)) < 0) {
        return urlBase + "yellowflag" + suffix;
    } else if (score.compareTo(Long.valueOf(75)) < 0) {
        return urlBase + "orangeflag" + suffix;
    } else {/* w ww . j ava2s .  c o m*/
        return urlBase + "redflag" + suffix;
    }
}

From source file:energy.usef.dso.service.business.DsoPlanboardBusinessService.java

/**
 * Gets the latest sequence number in a list of {@link Exchange}.
 *
 * @param exchanges {@link List} of {@link Exchange}.
 * @param participantDomain {@link String} domain name of the correspondent participant.
 * @return a {@link Long} with the highest sequence number;
 *///  www .  ja  v a2 s. c  o m
private Long getDocumentLatestSequenceNumber(List<? extends Exchange> exchanges, String participantDomain) {
    Long result = -1L;
    for (Exchange exchange : exchanges) {
        if (participantDomain.equals(exchange.getParticipantDomain())) {
            continue;
        }
        if (result.compareTo(exchange.getSequence()) == -1) {
            result = exchange.getSequence();
        }
    }
    return result;
}

From source file:controllers.api.v1.Web.java

/**
 * This utility method is used to sort the jsonArray based on FinishTime
 * @param jsonArray The jsonArray to be sorted
 * @return The sorted jsonArray based on finishtime
 *///www  .j a v  a  2s  . com
private static JsonArray getSortedJsonArrayByFinishTime(JsonArray jsonArray) {
    JsonArray sortedJsonArray = new JsonArray();
    List<JsonObject> jsonValues = new ArrayList<JsonObject>();
    for (int i = 0; i < jsonArray.size(); i++) {
        jsonValues.add(jsonArray.get(i).getAsJsonObject());
    }
    Collections.sort(jsonValues, new Comparator<JsonObject>() {
        public int compare(JsonObject a, JsonObject b) {
            Long first = a.get(JsonKeys.FINISH_TIME).getAsLong();
            Long second = b.get(JsonKeys.FINISH_TIME).getAsLong();
            return second.compareTo(first);
        }
    });
    for (JsonObject object : jsonValues) {
        sortedJsonArray.add(object);
    }
    return sortedJsonArray;
}

From source file:gobblin.runtime.local.LocalJobManager.java

/**
 * Restore the lastJobIdMap.//from www .jav a  2  s  .c  o  m
 */
private void restoreLastJobIdMap() throws IOException {
    FileSystem fs = FileSystem.get(
            URI.create(this.properties.getProperty(ConfigurationKeys.STATE_STORE_FS_URI_KEY)),
            new Configuration());

    // Root directory of task states store
    Path taskStateStoreRootDir = new Path(
            this.properties.getProperty(ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY));
    if (!fs.exists(taskStateStoreRootDir)) {
        return;
    }

    // List subdirectories (one for each job) under the root directory
    FileStatus[] rootStatuses = fs.listStatus(taskStateStoreRootDir);
    if (rootStatuses == null || rootStatuses.length == 0) {
        return;
    }

    LOG.info("Restoring the mapping between jobs and IDs of their last runs");

    for (FileStatus status : rootStatuses) {
        // List the task states files under each subdirectory corresponding to a job
        FileStatus[] statuses = fs.listStatus(status.getPath(), new PathFilter() {
            @Override
            public boolean accept(Path path) {
                return !path.getName().startsWith("current")
                        && path.getName().endsWith(TASK_STATE_STORE_TABLE_SUFFIX);
            }
        });

        if (statuses == null || statuses.length == 0) {
            continue;
        }

        // Sort the task states files by timestamp in descending order
        Arrays.sort(statuses, new Comparator<FileStatus>() {
            @Override
            public int compare(FileStatus fileStatus1, FileStatus fileStatus2) {
                String fileName1 = fileStatus1.getPath().getName();
                String taskId1 = fileName1.substring(0, fileName1.indexOf('.'));
                String fileName2 = fileStatus2.getPath().getName();
                String taskId2 = fileName2.substring(0, fileName2.indexOf('.'));

                Long ts1 = Long.parseLong(taskId1.substring(taskId1.lastIndexOf('_') + 1));
                Long ts2 = Long.parseLong(taskId2.substring(taskId2.lastIndexOf('_') + 1));

                return -Integer.signum(ts1.compareTo(ts2));
            }
        });

        // Each subdirectory is for one job, and the directory name is the job name.
        String jobName = status.getPath().getName();
        // The first task states file after sorting has the latest timestamp
        String fileName = statuses[0].getPath().getName();
        String lastJobId = fileName.substring(0, fileName.indexOf('.'));
        LOG.info(String.format("Restored last job ID %s for job %s", lastJobId, jobName));
        this.lastJobIdMap.put(jobName, lastJobId);
    }
}

From source file:org.dmb.trueprice.handlers.RecoverHandler.java

/**
 * Recuperer les infos du formulaire envoye a partir du mail, 
 * verifier et si ok proposer new mdp./*from www.j ava2  s . com*/
 * @param request
 * @return 
 */
public Membre processMail(HttpServletRequest request) {

    /* Rcupration des champs du formulaire */
    String email = ServletUtils.getRequestAttrValue(request, MAIL_RECOVERED);
    //        String motDePasse = ServletUtils.getRequestAttrValue( request, CHAMP_PASS );
    String checkSum = ServletUtils.getRequestAttrValue(request, MAIL_CHECKSUM);
    String secureLink = ServletUtils.getRequestAttrValue(request, MAIL_SECURE_LINK);

    //        Utilisateur utilisateur = new Utilisateur();
    Membre userFinal = null;

    /* Validation du champ email. */
    try {
        ServletUtils.validEmailSyntax(email);
        userFinal = new Membre();
        userFinal.setMbMail(email);
    } catch (Exception e) {
        setErreur(MAIL_RECOVERED, e.getMessage());
    }

    //        utilisateur.setMAIL(email );

    try {
        //            Utilisateur uVerif  = userManager.findByMail(utilisateur.getMbMail());
        Membre uVerif = utilisateurDao.findByMail(email);
        if (uVerif == null) {
            throw new Exception(
                    "Cette adresse email ne semble pas tre enregistre <a href=\"../connexion\">S'enregistrer</a>");
            //            } else if (uVerif.getId() != userFinal.getId() ) {   
            //                throw new Exception("The user is wrong or is not a member");   
        } else {
            userFinal = uVerif;
        }
    } catch (Exception e) {
        setErreur(CHAMP_MAIL_RECOVER, e.getMessage());
    }

    /*
    Vrification de la PRESENCE du checksum
    */
    try {
        checkSum = ServletUtils.getRequestAttrValue(request, MAIL_CHECKSUM);

        //            Integer.parseInt(checkSum);

    } catch (Exception e) {
        setErreur(MAIL_CHECKSUM, "Bad parameter value.");
        log.warn("Error with " + MAIL_CHECKSUM.toString() + " because > " + e.getMessage());

    }
    /*
    Vrification de la PRESENCE du secureLink
    */
    try {
        secureLink = ServletUtils.getRequestAttrValue(request, MAIL_SECURE_LINK);
    } catch (Exception e) {
        setErreur(MAIL_SECURE_LINK, "Bad parameter value.");
        log.warn("Error with " + MAIL_SECURE_LINK.toString() + " because > " + e.getMessage());
    }

    log.info("Got all params. Get file & unmarshall.");

    RecoveredMember fileMember = null;

    String filename = email;
    filename += "-" + checkSum;
    filename += ".xml";

    try {

        String fileFullPath = att_init_XmlFolder + File.separator + filename;

        //                FileUtils.createFile(att_init_XmlFolder.toString(), filename);

        log.info("Search data on file : " + fileFullPath);

        fileMember = JaxbTraductor.unmarshall(fileFullPath);

    } catch (Exception ex) {
        setErreur(CHAMP_RECORD, "Impossible de lire le fichier de sauvegarde. > " + ex.getMessage());
        ex.printStackTrace();
    }

    if (erreurs.isEmpty()) {

        log.info(
                "Read file OK. Verif given secureLink + checksum + consistency check on passwords and time elapsed.");
        log.debug("Got values from file : " + "\n mail = " + fileMember.getRecoveredMail() + "\n old ID = "
                + fileMember.getOldId() + "\n new ID = " + fileMember.getNewId() + "\n checksum = "
                + fileMember.getCheckSum() + "\n secure Link = " + fileMember.getSecureLink());

        Password oldPass;
        Password newPass = null;

        /* Validation des champs de scurit. */
        try {

            oldPass = pwdDao.findById(Long.valueOf(fileMember.getOldId()));
            newPass = pwdDao.findById(Long.valueOf(fileMember.getNewId()));

            if (oldPass != null) {
                if (newPass != null) {
                    log.info("Passwords exists. Need to change Member's password ID  from ["
                            + oldPass.getMbPassid() + "] for member [" + userFinal.getMbPseudo() + " <=> "
                            + userFinal.getMbMail() + "]\n New password is [" + oldPass.getMbPassid() + "].");
                } else {
                    log.error("Could not find password with ID [" + fileMember.getNewId() + "]");
                    setErreur(MAIL_CHECKSUM, "Could not find password with ID [" + fileMember.getNewId() + "]");
                }
            } else {
                log.error("Could not find password with ID [" + fileMember.getOldId() + "]");
                setErreur(MAIL_CHECKSUM, "Could not find password with ID [" + fileMember.getOldId() + "]");
            }

            /*
                VERIFICATION SECURE LINK is the right passphrase
            */
            // on vrifie que le secure link venant du mail 
            // est bien la passphrase correspondant au newPass gnr AVANT l'envoi du mail.
            if (pwdDao.simulateEncryption(new Password(secureLink), // la passphrase (== le MDP en clair)
                    newPass // la valeur stockee (== le MDP crypt)
            )) {

                // C'est le bon mot de passe on update le membre avec l'ID du newPass
                log.info("Given secureLink is the right one, continue by showing view to set a new Password.");

            } else {
                throw new Exception(
                        "Given secureLink is NOT the right one, cancel recover + delete the generated password.");
            }

            /*
                VERIFICATION CHECKSUM == oldPassID + newPassID 
                oldPassID + newPassID  =
            oldId + newId from xml file
                OR  
            oldId from DB Member's PassId
            + 
            newId from DB Pass found with secureLink Request
            */

            Long oldID = Long.parseLong(fileMember.getOldId());
            Long newID = Long.parseLong(fileMember.getNewId());
            Long sum = Long.parseLong(fileMember.getCheckSum());

            // On recupere en LONG valeurs d'ID (vieux et new) + somme
            if ( // Verifie que le contenu du fichier est valable 
            (sum.compareTo(newID + oldID) == 0)
                    // Verifie que les passwords trouves dans la db donne bien le meme resultat
                    && (sum.compareTo(oldPass.getMbPassid() + newPass.getMbPassid()) == 0)) {

                // C'est le bon mot de passe on update le membre avec l'ID du newPass
                log.info("Given checkSum is the right one, continue by showing view to set a new Password ");
            } else {
                throw new Exception(
                        "Given checkSum is NOT the right one. Cancel recover + delete old password.");
            }

        } catch (Exception e) {
            e.printStackTrace();
            setErreur(CHAMP_RECORD, "Bad parameter value.");
            log.warn("Error with " + MAIL_CHECKSUM.toString() + " because > " + e.getMessage());
            setErreur(MAIL_CHECKSUM, "Bad parameter value.");
            log.warn("Error with " + MAIL_CHECKSUM.toString() + " because > " + e.getMessage());
            setErreur(MAIL_SECURE_LINK, "Bad parameter value.");
            log.warn("Error with " + MAIL_SECURE_LINK.toString() + " because > " + e.getMessage());
            //            if (newPass.getMbPassid() != 0) {
            //                try {
            //                    removePassword(newPass.getMbPassid());
            //                } catch (NonexistentEntityException | NullPointerException ex) {
            //                    log.error("Could not delete generated passwaord because > " + ex.getMessage());
            //                    ex.printStackTrace();
            //                }
            //            }

        }

    }

    /**
     * Now rename File withour checkSum for next step.
     */
    if (erreurs.isEmpty()) {

        log.info("The recover is done with no errors. Start create entity Recovered an then marshall it ... ");

        //            RecoveredMember fileMember = null;

        filename = userFinal.getMbMail();
        filename += "-" + checkSum;
        filename += ".xml";

        String newName = userFinal.getMbMail() + ".xml";

        try {

            String fileFullPath = att_init_XmlFolder + File.separator + filename;

            FileUtils.renameFile(fileFullPath, fileFullPath.replace(filename, newName));

            log.info("File successfully renamed to [" + newName + "]");

        } catch (IOException ex) {
            setErreur(CHAMP_RECORD, "Impossible de creer le fichier de sauvegarde. > " + ex.getMessage());
            ex.printStackTrace();
        } catch (Exception ex) {
            setErreur(CHAMP_RECORD, "Impossible d'ecrire le fichier de sauvegarde. > " + ex.getMessage());
            ex.printStackTrace();
        }

    }

    /* Initialisation du rsultat global de la validation. */
    if (erreurs.isEmpty()) {
        resultat = "Message envoy.";

    } else {
        resultat = "Une erreur est survenue, veuillez ressayer.";
        userFinal = null;

    }

    return userFinal;
}

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

@Override
public void analyse() {
    audit = auditDataService.read(audit.getId());
    if (!audit.getStatus().equals(AuditStatus.ANALYSIS)) {
        LOGGER.warn(//from w  w w. jav  a  2  s .  c  o m
                new StringBuilder(AUDIT_STATUS_IS_LOGGER_STR).append(audit.getStatus()).append(WHILE_LOGGER_STR)
                        .append(AuditStatus.ANALYSIS).append(WAS_REQUIRED_LOGGER_STR).toString());
        return;
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Analysing " + audit.getSubject().getURL());
    }
    // debug tools
    Date beginProcessDate = null;
    Date endProcessDate = null;
    Date endPersistDate;
    Long persistenceDuration = Long.valueOf(0);

    WebResource parentWebResource = audit.getSubject();
    if (parentWebResource instanceof Page) {
        analyserService.analyse(parentWebResource, audit);
        webResourceDataService.saveOrUpdate(parentWebResource);
    } else if (parentWebResource instanceof Site) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Analysing results of scope site");
            beginProcessDate = Calendar.getInstance().getTime();
        }
        analyserService.analyse(parentWebResource, audit);
        if (LOGGER.isDebugEnabled()) {
            endProcessDate = Calendar.getInstance().getTime();
            LOGGER.debug(new StringBuilder("Analysing results of scope site took ")
                    .append(endProcessDate.getTime() - beginProcessDate.getTime()).append(MS_LOGGER_STR)
                    .toString());
        }
        webResourceDataService.saveOrUpdate(parentWebResource);

        if (LOGGER.isDebugEnabled()) {
            endPersistDate = Calendar.getInstance().getTime();
            LOGGER.debug(new StringBuilder("Persisting Analysis results of scope site ")
                    .append(endPersistDate.getTime() - endProcessDate.getTime()).append(MS_LOGGER_STR)
                    .toString());
            persistenceDuration = persistenceDuration + (endPersistDate.getTime() - endProcessDate.getTime());
        }

        Long nbOfContent = webResourceDataService.getNumberOfChildWebResource(parentWebResource);
        Long i = Long.valueOf(0);
        List<WebResource> webResourceList;
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(new StringBuilder("Analysing ").append(nbOfContent).append(" elements ").toString());
        }
        while (i.compareTo(nbOfContent) < 0) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(new StringBuilder("Analysing results of scope page from ").append(i)
                        .append(TO_LOGGER_STR).append(i + analyseTreatmentWindow).toString());
                beginProcessDate = Calendar.getInstance().getTime();
            }
            webResourceList = webResourceDataService.getWebResourceFromItsParent(parentWebResource,
                    i.intValue(), analyseTreatmentWindow);
            for (WebResource webResource : webResourceList) {
                if (LOGGER.isDebugEnabled()) {
                    endProcessDate = Calendar.getInstance().getTime();
                    LOGGER.debug(new StringBuilder("Analysing results for page ").append(webResource.getURL())
                            .append(" took ").append(endProcessDate.getTime() - beginProcessDate.getTime())
                            .append(MS_LOGGER_STR).toString());
                }
                analyserService.analyse(webResource, audit);
                if (LOGGER.isDebugEnabled()) {
                    endPersistDate = Calendar.getInstance().getTime();
                    LOGGER.debug(new StringBuilder("Persisting Analysis results for page ")
                            .append(webResource.getURL()).append(" took ")
                            .append(endPersistDate.getTime() - endProcessDate.getTime()).append(MS_LOGGER_STR)
                            .toString());
                    persistenceDuration = persistenceDuration
                            + (endPersistDate.getTime() - endProcessDate.getTime());
                }
            }
            i = i + analyseTreatmentWindow;
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(new StringBuilder("Application spent ").append(persistenceDuration)
                .append(" ms to write in Disk while analysing").toString());
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(audit.getSubject().getURL() + " has been analysed");
    }
    setStatusToAudit(AuditStatus.COMPLETED);
    if (cleanUpRelatedContent) {
        cleanUpTestData(audit);
    }
}

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

@Override
public void process() {
    audit = auditDataService.getAuditWithTest(audit.getId());
    if (!audit.getStatus().equals(AuditStatus.PROCESSING)) {
        LOGGER.warn(//from  ww  w.j  a v a 2 s. c o m
                new StringBuilder(AUDIT_STATUS_IS_LOGGER_STR).append(audit.getStatus()).append(WHILE_LOGGER_STR)
                        .append(AuditStatus.PROCESSING).append(WAS_REQUIRED_LOGGER_STR).toString());
        return;
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Processing " + audit.getSubject().getURL());
    }
    // debug tools
    Date beginProcessDate = null;
    Date endProcessDate = null;
    Date endPersistDate;
    Long persistenceDuration = Long.valueOf(0);

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

    Set<ProcessResult> processResultSet = new HashSet<ProcessResult>();

    while (i.compareTo(nbOfContent) < 0) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(new StringBuilder("Processing from ").append(i).append(TO_LOGGER_STR)
                    .append(i + processingTreatmentWindow).append("for ").append(audit.getSubject().getURL())
                    .toString());
            beginProcessDate = Calendar.getInstance().getTime();
        }
        List<Content> contentList = retrieveContentList(webResourceId, i, processingTreatmentWindow,
                beginProcessDate, true, false);
        processResultSet.clear();
        processResultSet.addAll(processorService.process(contentList, audit.getTestList()));
        for (ProcessResult processResult : processResultSet) {
            processResult.setGrossResultAudit(audit);
        }

        if (LOGGER.isDebugEnabled()) {
            endProcessDate = Calendar.getInstance().getTime();
            LOGGER.debug(new StringBuilder("Processing of ").append(processingTreatmentWindow)
                    .append(" elements took ").append(endProcessDate.getTime() - beginProcessDate.getTime())
                    .append(MS_LOGGER_STR).append("for ").append(audit.getSubject().getURL()).toString());
        }
        processResultDataService.saveOrUpdate(processResultSet);
        if (LOGGER.isDebugEnabled()) {
            endPersistDate = Calendar.getInstance().getTime();
            LOGGER.debug(new StringBuilder("Persist processing of ").append(processingTreatmentWindow)
                    .append(" elements took ").append(endPersistDate.getTime() - endProcessDate.getTime())
                    .append(MS_LOGGER_STR).append("for ").append(audit.getSubject().getURL()).toString());
            persistenceDuration = persistenceDuration + (endPersistDate.getTime() - endProcessDate.getTime());
        }
        i = i + processingTreatmentWindow;
        System.gc();
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(new StringBuilder("Application spent ").append(persistenceDuration)
                .append(" ms to write in Disk while processing").toString());
    }

    if (processResultDataService.getNumberOfGrossResultFromAudit(audit) > 0) {
        setStatusToAudit(AuditStatus.CONSOLIDATION);
    } else {
        LOGGER.error("Audit has no gross result");
        setStatusToAudit(AuditStatus.ERROR);
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(audit.getSubject().getURL() + " has been processed");
    }
}

From source file:com.redhat.rhn.manager.rhnpackage.PackageManager.java

/**
 * Throw exception, if any of the packages aren't accessible by user or
 * aren't compatible with provided channel arch
 * @param user user/*from  w ww. j  a  v  a  2s.c  o  m*/
 * @param channel channel
 * @param packageIds package ids
 * @param checkArchCompat optionally arch compatibility doesn't have to be checked
 * (f.e. when removing packages, only orgt access is important)
 */
public static void verifyPackagesChannelArchCompatAndOrgAccess(User user, Channel channel,
        List<Long> packageIds, boolean checkArchCompat) {
    Long orgId = user.getOrg().getId();
    DataResult dr = PackageFactory.getPackagesChannelArchCompatAndOrgAccess(orgId, channel.getId(), packageIds);
    List<Long> found = new ArrayList<Long>();
    List<Long> archNonCompat = new ArrayList<Long>();
    List<Long> orgNoAccess = new ArrayList<Long>();
    for (Iterator i = dr.iterator(); i.hasNext();) {
        Map m = (Map) i.next();
        found.add((Long) m.get("id"));
        if (m.get("package_arch_id") == null) {
            archNonCompat.add((Long) m.get("id"));
        }
        if ((m.get("org_package") == null || orgId.compareTo((Long) m.get("org_package")) != 0)
                && m.get("org_access") == null && m.get("shared_access") == null) {
            orgNoAccess.add((Long) m.get("id"));
        }
    }
    List<Long> missing = new ArrayList<Long>(packageIds);
    missing.removeAll(found);
    orgNoAccess.addAll(missing);
    if (!orgNoAccess.isEmpty()) {
        StringBuilder msg = new StringBuilder("User: ");
        msg.append(user.getLogin());
        msg.append(" does not have access to packages: ");
        msg.append(orgNoAccess);
        LocalizationService ls = LocalizationService.getInstance();
        PermissionException pex = new PermissionException(msg.toString());
        pex.setLocalizedTitle(ls.getMessage("permission.jsp.title.package"));
        pex.setLocalizedSummary(ls.getMessage("permission.jsp.summary.package"));
        throw pex;
    }
    if (checkArchCompat && !archNonCompat.isEmpty()) {
        throw new IncompatibleArchException(channel.getChannelArch(), archNonCompat);
    }
}