Example usage for java.math BigInteger ZERO

List of usage examples for java.math BigInteger ZERO

Introduction

In this page you can find the example usage for java.math BigInteger ZERO.

Prototype

BigInteger ZERO

To view the source code for java.math BigInteger ZERO.

Click Source Link

Document

The BigInteger constant zero.

Usage

From source file:org.geowebcache.diskquota.ConfigLoader.java

private void validateQuota(Quota quota) throws ConfigurationException {
    if (quota == null) {
        throw new IllegalArgumentException("No quota defined");
    }/* w  w  w.  j a va 2  s .  co  m*/
    BigInteger limit = quota.getBytes();
    if (limit.compareTo(BigInteger.ZERO) < 0) {
        throw new ConfigurationException("Limit shall be >= 0: " + limit + ". " + quota);
    }

    log.debug("Quota validated: " + quota);
}

From source file:org.openestate.io.immoxml.ImmoXmlUtils.java

public static String printPositiveInteger(BigInteger value) {
    // ImmoXML specifies positive integer values excluding 0
    if (value == null || value.compareTo(BigInteger.ZERO) < 1)
        throw new IllegalArgumentException("Can't print positive integer value!");
    else/*www . j ava  2s. c o m*/
        return printInteger(value);
}

From source file:org.openestate.io.examples.ImmobiliareItWritingExample.java

/**
 * Create a {@link Property} with some example data.
 *
 * @return//from   w  ww .java2  s  . co  m
 * created example object
 */
protected static Property createProperty() {
    // create an example real estate for rent
    Property obj = FACTORY.createFeedPropertiesProperty();
    obj.setBuildingStatus(Status.ABITABILE);
    obj.setCategory(Category.COMMERCIALE);
    obj.setDateExpiration(Calendar.getInstance());
    obj.setDateUpdated(Calendar.getInstance());
    obj.setOperation(Operation.WRITE);
    obj.setUniqueId(RandomStringUtils.randomAlphanumeric(5));

    obj.setAgent(FACTORY.createFeedPropertiesPropertyAgent());
    obj.getAgent().setEmail("agency@test.org");
    obj.getAgent().setOfficeName("agency name");

    obj.setBlueprints(FACTORY.createFeedPropertiesPropertyBlueprints());
    obj.getBlueprints().getBlueprint().add(createPictureExtended());
    obj.getBlueprints().getBlueprint().add(createPictureExtended());
    obj.getBlueprints().getBlueprint().add(createPictureExtended());

    obj.setBuilding(FACTORY.createBuilding());
    obj.getBuilding().setCategory(Category.COMMERCIALE);
    obj.getBuilding().setClazz(Clazz.SIGNORILE);
    obj.getBuilding().setDetail(PropertyTypeBusiness.ALBERGO);
    obj.getBuilding().setStatus(Status.DISCRETO);
    obj.getBuilding().setType(PropertyType.BUNGALOW);

    obj.setExtraFeatures(FACTORY.createFeedPropertiesPropertyExtraFeatures());
    obj.getExtraFeatures().setAirConditioning(RandomUtils.nextInt(0, 2) == 1);
    obj.getExtraFeatures().setBalcony(RandomUtils.nextInt(0, 2) == 1);
    obj.getExtraFeatures().setBathrooms(BigInteger.valueOf(RandomUtils.nextLong(1, 5)));
    obj.getExtraFeatures().setBeamHeight(BigInteger.valueOf(RandomUtils.nextLong(1, 10)));
    obj.getExtraFeatures().setBedrooms(BigInteger.valueOf(RandomUtils.nextLong(1, 5)));
    obj.getExtraFeatures().setBuildYear(RandomUtils.nextInt(1900, 2000));
    obj.getExtraFeatures().setDocDescription("some descriptions");
    obj.getExtraFeatures().setDocSpecification("some specifications");
    obj.getExtraFeatures().setElevator(RandomUtils.nextInt(0, 2) == 1);
    obj.getExtraFeatures().setFloorplannerUrl("http://floorplanner-url.it/");
    obj.getExtraFeatures().setFreeConditions("free conditions");
    obj.getExtraFeatures().setFurniture(Furniture.PARZIALMENTE_ARREDATO);
    obj.getExtraFeatures().setGarden(Garden.NESSUNO);
    obj.getExtraFeatures().setHeating(Heat.AUTONOMO);
    obj.getExtraFeatures().setKitchen(Kitchen.SEMI_ABITABILE);
    obj.getExtraFeatures().setNet(RandomUtils.nextInt(0, 2) == 1);
    obj.getExtraFeatures().setNumFloors(BigInteger.valueOf(RandomUtils.nextLong(1, 5)));
    obj.getExtraFeatures().setOverheadCrane(YesNoReady.READY);
    obj.getExtraFeatures().setReception(RandomUtils.nextInt(0, 2) == 1);
    obj.getExtraFeatures().setRentContract(Rental.LIBERO);
    obj.getExtraFeatures().setSecurityAlarm(RandomUtils.nextInt(0, 2) == 1);
    obj.getExtraFeatures().setTerrace(RandomUtils.nextInt(0, 2) == 1);
    obj.getExtraFeatures().setVirtualTour("virtual tour");

    obj.getExtraFeatures().setAdditionalCosts(FACTORY.createAdditionalCostsType());
    obj.getExtraFeatures().getAdditionalCosts().setCurrency(Currency.getInstance("EUR"));
    obj.getExtraFeatures().getAdditionalCosts().setValue(BigInteger.valueOf(RandomUtils.nextLong(0, 5000)));

    obj.getExtraFeatures().setExternalArea(FACTORY.createLandSizeType());
    obj.getExtraFeatures().getExternalArea().setUnit(LandSizeUnit.M2);
    obj.getExtraFeatures().getExternalArea().setValue(BigInteger.valueOf(RandomUtils.nextLong(50, 5000)));

    obj.getExtraFeatures().setFloor(FACTORY.createFloor());
    obj.getExtraFeatures().getFloor().setType(Floor.FloorType.INTERMEDIO);
    obj.getExtraFeatures().getFloor().setValue(BigInteger.valueOf(RandomUtils.nextLong(0, 10)));

    obj.getExtraFeatures().setGarage(FACTORY.createBox());
    obj.getExtraFeatures().getGarage().setType(Box.BoxType.POSTO_AUTO);
    obj.getExtraFeatures().getGarage().setValue(BigInteger.valueOf(RandomUtils.nextLong(0, 10)));

    obj.getExtraFeatures().setOfficeSize(FACTORY.createSizeType());
    obj.getExtraFeatures().getOfficeSize().setUnit(SizeUnit.M2);
    obj.getExtraFeatures().getOfficeSize().setValue(BigInteger.valueOf(RandomUtils.nextLong(5, 50)));

    obj.setFeatures(FACTORY.createFeedPropertiesPropertyFeatures());
    obj.getFeatures().setEnergyClass(ClassEnergy.D);
    obj.getFeatures().setRooms(RandomUtils.nextInt(1, 5));

    obj.getFeatures().setEnergyPerformance(FACTORY.createClassEnergyPerformance());
    obj.getFeatures().getEnergyPerformance().setCertified(RandomUtils.nextInt(0, 2) == 1);
    obj.getFeatures().getEnergyPerformance().setUnit(EnergyUnit.KWH_M2ANNO);
    obj.getFeatures().getEnergyPerformance().setValue("energy performance");

    obj.getFeatures().setPrice(FACTORY.createPriceType());
    obj.getFeatures().getPrice().setCurrency(Currency.getInstance("EUR"));
    obj.getFeatures().getPrice().setReserved(RandomUtils.nextInt(0, 2) == 1);
    obj.getFeatures().getPrice().setValue(BigInteger.valueOf(RandomUtils.nextLong(500, 5000000)));

    obj.getFeatures().setSize(FACTORY.createSizeType());
    obj.getFeatures().getSize().setUnit(SizeUnit.M2);
    obj.getFeatures().getSize().setValue(BigInteger.valueOf(RandomUtils.nextLong(50, 5000)));

    obj.setLocation(FACTORY.createLocationStructure());
    obj.getLocation().setAdministrativeArea("administrative area");
    obj.getLocation().setCountryCode("DE");

    obj.getLocation().setCity(FACTORY.createLocationStructureCity());
    obj.getLocation().getCity().setCode(BigInteger.ZERO);
    obj.getLocation().getCity().setValue("Berlin");

    obj.getLocation().setLocality(FACTORY.createLocationStructureLocality());
    obj.getLocation().getLocality().setLatitude(BigDecimal.valueOf(RandomUtils.nextDouble(0, 90)));
    obj.getLocation().getLocality().setLongitude(BigDecimal.valueOf(RandomUtils.nextDouble(0, 90)));
    obj.getLocation().getLocality().setPostalCode("13125");

    obj.getLocation().getLocality().setNeighbourhood(FACTORY.createLocationStructureLocalityNeighbourhood());
    obj.getLocation().getLocality().getNeighbourhood().setId(BigInteger.ZERO);
    obj.getLocation().getLocality().getNeighbourhood().setType(LocationNeighbourhoodType.DISTRICT);
    obj.getLocation().getLocality().getNeighbourhood().setValue("about the neighbourhood");

    obj.getLocation().getLocality().setThoroughfare(FACTORY.createLocationStructureLocalityThoroughfare());
    obj.getLocation().getLocality().getThoroughfare().setDisplay(RandomUtils.nextInt(0, 2) == 1);
    obj.getLocation().getLocality().getThoroughfare().setValue("about thoroughfare");

    obj.getLocation().setSubAdministrativeArea(FACTORY.createLocationStructureSubAdministrativeArea());
    obj.getLocation().getSubAdministrativeArea().setCode(RandomStringUtils.randomAlphanumeric(5));
    obj.getLocation().getSubAdministrativeArea().setValue("Berlin");

    obj.setPictures(FACTORY.createFeedPropertiesPropertyPictures());
    obj.getPictures().getPictureUrlAndPicture().add(createPicture());
    obj.getPictures().getPictureUrlAndPicture().add(createPicture());
    obj.getPictures().getPictureUrlAndPicture().add(createPicture());

    obj.setPropertyType(FACTORY.createProptype());
    obj.getPropertyType().setBusinessType(FACTORY.createBusinessElement());
    obj.getPropertyType().getBusinessType().setCategory(BusinessElement.BusinessElementCategory.IMMOBILE);
    obj.getPropertyType().getBusinessType().setValue(PropertyTypeBusiness.ALTRO);
    obj.getPropertyType().setTerrains(FACTORY.createTerrains());
    obj.getPropertyType().getTerrains().getTerrain().add(TerrainType.SEMINATIVO);
    obj.getPropertyType().setType(PropertyTypeSimple.CASA_INDIPENDENTE);

    obj.setTransactionType(FACTORY.createTransactionType());
    obj.getTransactionType().setAuction(RandomUtils.nextInt(0, 2) == 1);
    obj.getTransactionType().setOwnership(OwnershipType.PARZIALE);
    obj.getTransactionType().setValue("notes about transaction");

    obj.setVideos(FACTORY.createFeedPropertiesPropertyVideos());
    obj.getVideos().getVideo().add(createVideo());
    obj.getVideos().getVideo().add(createVideo());

    return obj;
}

From source file:org.openestate.io.openimmo.OpenImmoUtils.java

public static String printPositiveInteger(BigInteger value) {
    // OpenImmo specifies positive integer values excluding 0
    if (value == null || value.compareTo(BigInteger.ZERO) < 1)
        throw new IllegalArgumentException("Can't print positive integer value!");
    else//from   w w w. j a  v a 2  s.  co  m
        return printInteger(value);
}

From source file:com.emergya.siradmin.invest.InvestmentUpdater.java

public void getWsDataAndUpdateDB(List<LlaveBean> wsProjectList) {
    // 1. Get an iterator of all Chileindica
    // 2. Traverse the list of LlaveBean
    // 3. For every LlaveBean mark database element as no removable
    // 4. If llaveBean is Updatable, create or update element in DataBase.
    // 5. If there is any problem cheking with the web service, mark the
    // element as update error.
    List<Long> projectDbIds = service.getAllProjectDbIds();
    Collections.sort(wsProjectList);

    for (Iterator<Long> iterator = projectDbIds.iterator(); iterator.hasNext();) {
        Long dbId = iterator.next();
        ChileindicaInversionDataDto dto = (ChileindicaInversionDataDto) service.getById(dbId);
        LlaveBean keyToSearch = new LlaveBean();
        keyToSearch.setAno(dto.getAno());
        keyToSearch.setRegion(dto.getRegion());
        keyToSearch.setcFicha(dto.getCFicha());
        keyToSearch.setcInstitucion(dto.getCInstitucion());
        keyToSearch.setcPreinversion(dto.getCPreinversion());

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Tratando proyecto existente BBDD " + keyToSearch);
        }//from  ww  w.jav  a2s .  c o m
        // Buscamos si el proyecto existe entre las claves actuales
        int foundKeyIndex = Collections.binarySearch(wsProjectList, keyToSearch);
        if (foundKeyIndex >= 0) {
            LlaveBean foundKey = wsProjectList.get(foundKeyIndex);
            iterator.remove();
            wsProjectList.remove(foundKeyIndex);
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("El proyecto sigue existiendo en el servicio web de consulta de llaves");
            }
            // Si el proyecto ha sido actualizado en Chileindica recuperamos
            // los detalles del servicio web, borramos el proyecto original
            // de
            // la base de datos y creamos una entrada nueva en BD
            if (foundKey.isUpdatable()) {
                try {
                    ConsultaInversionPorLlaveGeorefResponse response = this.wsConsultaInversion
                            .getWSConsultaInversionPorLlaveGeorefPort()
                            .WSConsultaInversionPorLlaveGeoref(BigInteger.valueOf(foundKey.getRegion()),
                                    BigInteger.valueOf(foundKey.getAno()),
                                    BigInteger.valueOf(foundKey.getcInstitucion()),
                                    BigInteger.valueOf(foundKey.getcPreinversion()),
                                    BigInteger.valueOf(foundKey.getcFicha()));
                    com.emergya.siradmin.invest.client.investmentdata.Respuesta respuesta = response
                            .getRespuesta();
                    BigInteger codRespuesta = respuesta.getCodigoRespuesta();
                    if (BigInteger.ZERO.equals(codRespuesta)) {
                        // delete from DB and create new instance
                        service.delete(dto);
                        ChileindicaInversionDataDto updatedProject = createDtoFromWsResponse(response,
                                foundKey);
                        service.create(updatedProject);
                        foundKey.setStatus(UpdateStatus.OK);
                        if (LOGGER.isInfoEnabled()) {
                            LOGGER.info("Proyecto en BBDD actualizado");
                        }
                    } else {
                        if (LOGGER.isInfoEnabled()) {
                            LOGGER.info("Error obteniendo informacin del proyecto " + foundKey
                                    + ". Cdigo de repuesta = " + codRespuesta + ". Mensaje = "
                                    + respuesta.getTextoRespuesta());

                        }
                        // Guardamos el proyecto en BBDD con estado error
                        dto.setUpdateStatus(UpdateStatus.WS_ERROR);
                        dto.setLastUpdateTry(Calendar.getInstance().getTime());
                        foundKey.setStatus(UpdateStatus.WS_ERROR);
                        service.update(dto);
                    }

                } catch (DataAccessException e) {
                    if (LOGGER.isErrorEnabled()) {
                        LOGGER.error("Error almacenando proyecto " + foundKey + " en base de datos", e);
                    }
                    foundKey.setStatus(UpdateStatus.DB_ERROR);

                } catch (RemoteException e) {
                    // Guardamos el proyecto en BBDD con estado error
                    dto.setUpdateStatus(UpdateStatus.WS_ERROR);
                    dto.setLastUpdateTry(Calendar.getInstance().getTime());
                    service.update(dto);
                    foundKey.setStatus(UpdateStatus.WS_ERROR);
                } catch (ServiceException e) {
                    // Guardamos el proyecto en BBDD con estado error
                    dto.setUpdateStatus(UpdateStatus.WS_ERROR);
                    dto.setLastUpdateTry(Calendar.getInstance().getTime());
                    service.update(dto);
                    foundKey.setStatus(UpdateStatus.WS_ERROR);
                } catch (Throwable e) {
                    dto.setUpdateStatus(UpdateStatus.WS_ERROR);
                    dto.setLastUpdateTry(Calendar.getInstance().getTime());
                    service.update(dto);
                    foundKey.setStatus(UpdateStatus.WS_ERROR);
                }
            } else {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("El proyecto no necesita ser actualizado en BBDD");
                }
            }
        } else {
            // si el proyecto no ha sido devuleto por el WS Consulta de
            // llaves, se borra de la base de datos
            service.delete(dto);
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Se elimina el proyecto por no existir en la consulta de llaves " + keyToSearch);
            }
        }
    }

    // En este punto los elementos que quedan en projectDbIds pueden ser
    // eliminados de la base de datos puesto que no han sido devueltos por
    // el servicio web de consulta de llaves
    // for (Long id : projectDbIds) {
    // service.deleteById(id);
    // }

    // Ahora se crean los proyectos que queden en la lista de llaves
    // devueltas
    // por el servicio web.
    for (LlaveBean llave : wsProjectList) {
        ConsultaInversionPorLlaveGeorefResponse response;
        try {
            response = this.wsConsultaInversion.getWSConsultaInversionPorLlaveGeorefPort()
                    .WSConsultaInversionPorLlaveGeoref(BigInteger.valueOf(llave.getRegion()),
                            BigInteger.valueOf(llave.getAno()), BigInteger.valueOf(llave.getcInstitucion()),
                            BigInteger.valueOf(llave.getcPreinversion()),
                            BigInteger.valueOf(llave.getcFicha()));
            com.emergya.siradmin.invest.client.investmentdata.Respuesta respuesta = response.getRespuesta();
            BigInteger codRespuesta = respuesta.getCodigoRespuesta();
            if (BigInteger.ZERO.equals(codRespuesta)) {
                ChileindicaInversionDataDto newProject = createDtoFromWsResponse(response, llave);
                service.create(newProject);
                llave.setStatus(UpdateStatus.OK);
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Creada nueva entrada en BBDD");
                }

            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error(
                            "Error obteniendo informacin del proyecto " + llave + ". Cdigo de repuesta = "
                                    + codRespuesta + ". Mensaje = " + respuesta.getTextoRespuesta());
                }
                llave.setStatus(UpdateStatus.WS_ERROR);
            }

        } catch (DataAccessException e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Error almacenando proyecto " + llave + " en base de datos", e);
            }
            llave.setStatus(UpdateStatus.DB_ERROR);
        } catch (RemoteException e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Error obteniendo informacin del proyecto " + llave, e);
            }
            llave.setStatus(UpdateStatus.WS_ERROR);
        } catch (ServiceException e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Error obteniendo informacin del proyecto " + llave, e);
            }
            llave.setStatus(UpdateStatus.WS_ERROR);
        } catch (Throwable e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Error obteniendo informacin del proyecto " + llave, e);
            }
            llave.setStatus(UpdateStatus.WS_ERROR);
        }

    }

}

From source file:com.ephesoft.dcma.tablefinder.share.TableExtractionResultModifierUtility.java

/**
 * This method gets the rectangle coordinates for the new merged row value.
 * /*from   w  w w . ja va 2s. c  o m*/
 * @param coordinatesList {@link Row}
 * @param currentRow {@link Row}
 */
public static void setMergedRowCoordinates(final Row previousRow, final Row currentRow) {
    LOGGER.trace("Entering method to merge coordinates of multiline column row.");
    if (null == previousRow || null == currentRow) {
        LOGGER.error("PreviousRow or currentRow is null. Coordinates of row could not be set.");
    } else {
        BigInteger minX0 = BigInteger.ZERO;
        BigInteger minY0 = BigInteger.ZERO;
        BigInteger maxX1 = BigInteger.ZERO;
        BigInteger maxY1 = BigInteger.ZERO;

        final Coordinates previousRowCoordinates = previousRow.getRowCoordinates();
        final Coordinates currentRowCoordinates = currentRow.getRowCoordinates();
        if (null == previousRowCoordinates || null == currentRowCoordinates) {
            LOGGER.error(
                    "previousRowCoordinates or currentRowCoordinates are null. Coordinates of row could not be set.");
        } else {
            final BigInteger previousRowX0 = previousRowCoordinates.getX0();
            final BigInteger previousRowY0 = previousRowCoordinates.getY0();
            final BigInteger previousRowX1 = previousRowCoordinates.getX1();
            final BigInteger previousRowY1 = previousRowCoordinates.getY1();

            final BigInteger currentRowX0 = currentRowCoordinates.getX0();
            final BigInteger currentRowY0 = currentRowCoordinates.getY0();
            final BigInteger currentRowX1 = currentRowCoordinates.getX1();
            final BigInteger currentRowY1 = currentRowCoordinates.getY1();

            if (previousRowX0.compareTo(currentRowX0) < 0) {
                minX0 = previousRowX0;
            } else {
                minX0 = currentRowX0;
            }
            if (previousRowY0.compareTo(currentRowY0) < 0) {
                minY0 = previousRowY0;
            } else {
                minY0 = currentRowY0;
            }
            if (previousRowX1.compareTo(currentRowX1) > 0) {
                maxX1 = previousRowX1;
            } else {
                maxX1 = currentRowX1;
            }
            if (previousRowY1.compareTo(currentRowY1) > 0) {
                maxY1 = previousRowY1;
            } else {
                maxY1 = currentRowY1;
            }

            final Coordinates coordinates = new Coordinates();
            coordinates.setX0(minX0);
            coordinates.setX1(maxX1);
            coordinates.setY0(minY0);
            coordinates.setY1(maxY1);
            previousRow.setRowCoordinates(coordinates);
            LOGGER.debug("Coordinates of row could are set: (X0, Y0, X1, Y1) are (", minX0, minY0, maxX1, maxY1,
                    ").");
        }
    }
    LOGGER.trace("Exiting method to merge coordinates of multiline column row.");
}

From source file:jp.aegif.nemaki.cmis.aspect.query.solr.SolrQueryProcessor.java

@Override
public ObjectList query(CallContext callContext, String repositoryId, String statement,
        Boolean searchAllVersions, Boolean includeAllowableActions, IncludeRelationships includeRelationships,
        String renditionFilter, BigInteger maxItems, BigInteger skipCount) {

    SolrServer solrServer = solrUtil.getSolrServer();

    // TODO walker is required?
    QueryUtilStrict util = new QueryUtilStrict(statement, new CmisTypeManager(repositoryId, typeManager), null);
    QueryObject queryObject = util.getQueryObject();

    // Get where caluse as Tree
    Tree whereTree = null;/* www .  j a v a  2s  .  c  om*/
    try {
        util.processStatement();
        Tree tree = util.parseStatement();
        whereTree = extractWhereTree(tree);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Build solr statement of WHERE
    String whereQueryString = "";
    if (whereTree == null || whereTree.isNil()) {
        whereQueryString = "*:*";
    } else {
        try {
            SolrPredicateWalker solrPredicateWalker = new SolrPredicateWalker(repositoryId, queryObject,
                    solrUtil, contentService);
            Query whereQuery = solrPredicateWalker.walkPredicate(whereTree);
            whereQueryString = whereQuery.toString();
        } catch (Exception e) {
            e.printStackTrace();
            // TODO Output more detailed exception
            exceptionService.invalidArgument("Invalid CMIS SQL statement!");
        }
    }

    // Build solr query of FROM
    String fromQueryString = "";

    String repositoryQuery = "repository_id:" + repositoryId;

    fromQueryString += repositoryQuery + " AND ";

    TypeDefinition td = queryObject.getMainFromName();
    // includedInSupertypeQuery
    List<TypeDefinitionContainer> typeDescendants = typeManager.getTypesDescendants(repositoryId, td.getId(),
            BigInteger.valueOf(-1), false);
    Iterator<TypeDefinitionContainer> iterator = typeDescendants.iterator();
    List<String> tables = new ArrayList<String>();
    while (iterator.hasNext()) {
        TypeDefinition descendant = iterator.next().getTypeDefinition();
        if (td.getId() != descendant.getId()) {
            boolean isq = (descendant.isIncludedInSupertypeQuery() == null) ? false
                    : descendant.isIncludedInSupertypeQuery();
            if (!isq)
                continue;
        }
        String table = descendant.getQueryName();
        tables.add(table.replaceAll(":", "\\\\:"));
    }

    Term t = new Term(solrUtil.getPropertyNameInSolr(PropertyIds.OBJECT_TYPE_ID),
            StringUtils.join(tables, " "));
    fromQueryString += new TermQuery(t).toString();

    // Execute query
    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQuery(whereQueryString);
    solrQuery.setFilterQueries(fromQueryString);

    //TEST
    solrQuery.set(CommonParams.START, 0);
    solrQuery.set(CommonParams.ROWS, maxItems.intValue());

    QueryResponse resp = null;
    try {
        resp = solrServer.query(solrQuery);
    } catch (SolrServerException e) {
        e.printStackTrace();
    }

    // Output search results to ObjectList
    if (resp != null && resp.getResults() != null && resp.getResults().getNumFound() != 0) {
        SolrDocumentList docs = resp.getResults();

        List<Content> contents = new ArrayList<Content>();
        for (SolrDocument doc : docs) {
            String docId = (String) doc.getFieldValue("object_id");
            Content c = contentService.getContent(repositoryId, docId);

            // When for some reason the content is missed, pass through
            if (c == null) {
                logger.warn("[objectId=" + docId + "]It is missed in DB but still rests in Solr.");
            } else {
                contents.add(c);
            }

        }

        List<Lock> locks = threadLockService.readLocks(repositoryId, contents);
        try {
            threadLockService.bulkLock(locks);

            // Filter out by permissions
            List<Content> permitted = permissionService.getFiltered(callContext, repositoryId, contents);

            // Filter return value with SELECT clause
            Map<String, String> requestedWithAliasKey = queryObject.getRequestedPropertiesByAlias();
            String filter = null;
            if (!requestedWithAliasKey.keySet().contains("*")) {
                // Create filter(queryNames) from query aliases
                filter = StringUtils.join(requestedWithAliasKey.values(), ",");
            }

            // Build ObjectList
            String orderBy = orderBy(queryObject);
            ObjectList result = compileService.compileObjectDataList(callContext, repositoryId, permitted,
                    filter, includeAllowableActions, includeRelationships, renditionFilter, false, maxItems,
                    skipCount, false, orderBy);

            return result;

        } finally {
            threadLockService.bulkUnlock(locks);
        }
    } else {
        ObjectListImpl nullList = new ObjectListImpl();
        nullList.setHasMoreItems(false);
        nullList.setNumItems(BigInteger.ZERO);
        return nullList;
    }
}

From source file:com.spotify.reaper.unit.service.SegmentRunnerTest.java

@Test
public void failureTest() throws InterruptedException, ReaperException, ExecutionException {
    final IStorage storage = new MemoryStorage();
    RepairUnit cf = storage/*  w  ww  . j  ava2s  .  c  o  m*/
            .addRepairUnit(new RepairUnit.Builder("reaper", "reaper", Sets.newHashSet("reaper")));
    RepairRun run = storage.addRepairRun(
            new RepairRun.Builder("reaper", cf.getId(), DateTime.now(), 0.5, 1, RepairParallelism.PARALLEL));
    storage.addRepairSegments(Collections.singleton(
            new RepairSegment.Builder(run.getId(), new RingRange(BigInteger.ONE, BigInteger.ZERO), cf.getId())),
            run.getId());
    final long segmentId = storage.getNextFreeSegment(run.getId()).get().getId();

    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final MutableObject<Future<?>> future = new MutableObject<>();

    AppContext context = new AppContext();
    context.storage = storage;
    context.jmxConnectionFactory = new JmxConnectionFactory() {
        @Override
        public JmxProxy connect(final Optional<RepairStatusHandler> handler, String host) {
            JmxProxy jmx = mock(JmxProxy.class);
            when(jmx.getClusterName()).thenReturn("reaper");
            when(jmx.isConnectionAlive()).thenReturn(true);
            when(jmx.tokenRangeToEndpoint(anyString(), any(RingRange.class)))
                    .thenReturn(Lists.newArrayList(""));
            when(jmx.triggerRepair(any(BigInteger.class), any(BigInteger.class), anyString(),
                    Matchers.<RepairParallelism>any(), Sets.newHashSet(anyString())))
                            .then(new Answer<Integer>() {
                                @Override
                                public Integer answer(InvocationOnMock invocation) {
                                    assertEquals(RepairSegment.State.NOT_STARTED,
                                            storage.getRepairSegment(segmentId).get().getState());
                                    future.setValue(executor.submit(new Runnable() {
                                        @Override
                                        public void run() {
                                            handler.get().handle(1, ActiveRepairService.Status.STARTED,
                                                    "Repair command 1 has started");
                                            assertEquals(RepairSegment.State.RUNNING,
                                                    storage.getRepairSegment(segmentId).get().getState());
                                            handler.get().handle(1, ActiveRepairService.Status.SESSION_FAILED,
                                                    "Repair command 1 has failed");
                                            assertEquals(RepairSegment.State.NOT_STARTED,
                                                    storage.getRepairSegment(segmentId).get().getState());
                                            handler.get().handle(1, ActiveRepairService.Status.FINISHED,
                                                    "Repair command 1 has finished");
                                            assertEquals(RepairSegment.State.NOT_STARTED,
                                                    storage.getRepairSegment(segmentId).get().getState());
                                        }
                                    }));

                                    return 1;
                                }
                            });

            return jmx;
        }
    };
    RepairRunner rr = mock(RepairRunner.class);
    RepairUnit ru = mock(RepairUnit.class);
    SegmentRunner sr = new SegmentRunner(context, segmentId, Collections.singleton(""), 1000, 0.5,
            RepairParallelism.PARALLEL, "reaper", ru, rr);
    sr.run();

    future.getValue().get();
    executor.shutdown();

    assertEquals(RepairSegment.State.NOT_STARTED, storage.getRepairSegment(segmentId).get().getState());
    assertEquals(1, storage.getRepairSegment(segmentId).get().getFailCount());
}

From source file:piuk.blockchain.android.util.WalletUtils.java

public static String formatValue(final BigInteger value, final String plusSign, final String minusSign) {
    final boolean negative = value.compareTo(BigInteger.ZERO) < 0;
    final BigInteger absValue = value.abs();

    final String sign = negative ? minusSign : plusSign;

    final int coins = absValue.divide(Utils.COIN).intValue();
    final int cents = absValue.remainder(Utils.COIN).intValue();

    if (cents % 1000000 == 0)
        return String.format("%s%d.%02d", sign, coins, cents / 1000000);
    else if (cents % 10000 == 0)
        return String.format("%s%d.%04d", sign, coins, cents / 10000);
    else/*from w w w .j  a v a  2 s .c o  m*/
        return String.format("%s%d.%08d", sign, coins, cents);
}

From source file:com.ethercamp.harmony.service.WalletService.java

private BigInteger calculatePendingChange(Map<String, TransactionInfo> transactions, String hexAddress,
        BigInteger txFee) {/*ww w. j  a  v  a  2s  . c o  m*/
    return transactions.values().stream().filter(info -> info.getAddress().equals(hexAddress))
            .map(info -> info.getAmount())
            .reduce(BigInteger.ZERO, (state, amount) -> state.add(amount).add(txFee));
}