Example usage for org.apache.commons.lang.mutable MutableInt setValue

List of usage examples for org.apache.commons.lang.mutable MutableInt setValue

Introduction

In this page you can find the example usage for org.apache.commons.lang.mutable MutableInt setValue.

Prototype

public void setValue(Object value) 

Source Link

Document

Sets the value from any Number instance.

Usage

From source file:org.bimserver.charting.SupportFunctions.java

public static ArrayList<LinkedHashMap<String, Object>> getIfcMaterialsByNameWithTreeStructure(
        String structureKeyword, IfcModelInterface model, Chart chart, MutableInt subChartCount) {
    // Derive the column name.
    String leafColumnName = structureKeyword;
    // Update the chart configuration.
    chart.setDimensionLookupKey(structureKeyword, leafColumnName);
    chart.setDimensionLookupKey("date", "date");
    chart.setDimensionLookupKey("size", "size");
    // Prepare to iterate the relationships.
    LinkedHashMap<String, ArrayList<Double>> materialNameWithSizes = new LinkedHashMap<>();
    // Iterate only the relationships.
    for (IfcRelAssociatesMaterial ifcRelAssociatesMaterial : model
            .getAllWithSubTypes(IfcRelAssociatesMaterial.class)) {
        // IfcMaterialSelect: IfcMaterial, IfcMaterialList, IfcMaterialLayerSetUsage, IfcMaterialLayerSet, IfcMaterialLayer.
        IfcMaterialSelect materialLike = ifcRelAssociatesMaterial.getRelatingMaterial();
        // If there was a material-like object, sum the names of what it decomposes into across X individually.
        if (materialLike != null) {
            // First, get size data from IFC products.
            ArrayList<Double> sizes = new ArrayList<>();
            // Iterate objects.
            EList<IfcRoot> ifcRoots = ifcRelAssociatesMaterial.getRelatedObjects();
            for (IfcRoot ifcRoot : ifcRoots) {
                Double size = 0.0;
                if (ifcRoot instanceof IfcObjectDefinition) {
                    IfcObjectDefinition ifcObjectDefinition = (IfcObjectDefinition) ifcRoot;
                    if (ifcObjectDefinition instanceof IfcObject) {
                        IfcObject ifcObject = (IfcObject) ifcObjectDefinition;
                        if (ifcObject instanceof IfcProduct) {
                            IfcProduct ifcProduct = (IfcProduct) ifcObject;
                            Double volume = getRoughVolumeEstimateFromIfcProduct(ifcProduct);
                            size = volume;
                        }/*w w  w .  ja  v  a2 s  . co  m*/
                    }
                }
                if (size != null && size > 0)
                    sizes.add(size);
            }
            // Get material names with percentages, like: Material Name -> 0.5
            LinkedHashMap<String, Double> materials = getNameOfMaterialsFromMaterialLikeWithPercents(
                    materialLike, false);
            // Second, iterate materials, realizing the percentage of the sizes onto the collection of sizes for each material name.
            for (Entry<String, Double> materialEntry : materials.entrySet()) {
                String materialName = materialEntry.getKey();
                Double percent = materialEntry.getValue();
                // Use material name if available. Otherwise, use OID of top-level material-like object.
                String name = (materialName != null) ? materialName
                        : String.format("%d", materialLike.getOid());
                // Add entry if it doesn't exist.
                if (!materialNameWithSizes.containsKey(name))
                    materialNameWithSizes.put(name, new ArrayList<Double>());
                ArrayList<Double> theseSizes = materialNameWithSizes.get(name);
                // Get existing size data.
                if (percent != null && percent > 0) {
                    // If not alteration is required, clone into the stack.
                    if (percent == 1.0)
                        theseSizes.addAll(sizes);
                    // Otherwise, realize the percent of the size.
                    else
                        for (Double size : sizes)
                            theseSizes.add(size * percent);
                }
            }
        }
    }
    //
    subChartCount.setValue(materialNameWithSizes.size());
    //
    ArrayList<LinkedHashMap<String, Object>> rawData = new ArrayList<>();
    //
    for (Entry<String, ArrayList<Double>> entry : materialNameWithSizes.entrySet()) {
        String name = entry.getKey();
        // Get existing size data.
        ArrayList<Double> sizes = materialNameWithSizes.get(name);
        // Sort, value ascending.
        Collections.sort(sizes, sortSmallerValuesToFront);
        sizes.add(0, 0.0);
        if (sizes.size() == 1)
            sizes.add(0, 0.0);
        // Count including empty first entry.
        double count = Math.max(1, sizes.size() - 1);
        double step = 10000.0 / count;
        double runningSize = 0.0;
        // Add sum of zero at entry zero.
        int i = 0;
        // Iterate objects, summing them across 0 to 10000 (an arbitrary range, a way to relate to other sums along X).
        for (Double size : sizes) {
            double someMeasurement = (size != null) ? size : 0.0;
            runningSize += someMeasurement;
            // Prepare to store this raw data entry.
            LinkedHashMap<String, Object> dataEntry = new LinkedHashMap<>();
            // Name the group.
            dataEntry.put(leafColumnName, name);
            dataEntry.put("date", i * step);
            dataEntry.put("size", runningSize);
            // Push the entry into the data pool.
            rawData.add(dataEntry);
            //
            i += 1;
        }
    }
    // Send it all back.
    return rawData;
}

From source file:org.dishevelled.matrix.AbstractMatrix1DTest.java

public void testForEachNonNull() {
    Matrix1D<String> m = createMatrix1D(100);
    final MutableInt count = new MutableInt();

    count.setValue(0);
    m.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();//  www. j a v a2  s  .c  o m
        }
    });
    assertEquals("count == 0", 0, count.intValue());

    count.setValue(0);
    m.setQuick(0L, "foo");
    m.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();
        }
    });
    assertEquals("count == 1", 1, count.intValue());

    count.setValue(0);
    m.assign("foo");
    m.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();
        }
    });
    assertEquals("count == 100", 100, count.intValue());

    try {
        m.forEachNonNull(null);
        fail("forEachNonNull(null) expected IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }
}

From source file:org.dishevelled.matrix.AbstractMatrix2DTest.java

public void testForEachNonNull() {
    Matrix2D<String> m = createMatrix2D(10, 10);
    final MutableInt count = new MutableInt();

    count.setValue(0);
    m.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();/* w w w  .j  a  v  a 2 s  .c  om*/
        }
    });
    assertEquals("count == 0", 0, count.intValue());

    count.setValue(0);
    m.setQuick(0L, 0L, "foo");
    m.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();
        }
    });
    assertEquals("count == 1", 1, count.intValue());

    count.setValue(0);
    m.assign("foo");
    m.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();
        }
    });
    assertEquals("count == 100", 100, count.intValue());

    Matrix1D<String> row = m.viewRow(0);
    count.setValue(0);
    row.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();
        }
    });
    assertEquals("count == 10", 10, count.intValue());

    try {
        m.forEachNonNull(null);
        fail("forEachNonNull(null) expected IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }
}

From source file:org.dishevelled.matrix.AbstractMatrix3DTest.java

public void testForEachNonNull() {
    Matrix3D<String> m = createMatrix3D(10, 10, 10);
    final MutableInt count = new MutableInt();

    count.setValue(0);
    m.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();/*from  w w  w.  ja  v  a  2  s . c o  m*/
        }
    });
    assertEquals("count == 0", 0, count.intValue());

    count.setValue(0);
    m.setQuick(0L, 0L, 0L, "foo");
    m.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();
        }
    });
    assertEquals("count == 1", 1, count.intValue());

    count.setValue(0);
    m.assign("foo");
    m.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();
        }
    });
    assertEquals("count == 1000", 1000, count.intValue());

    Matrix3D<String> rowFlip = m.viewRowFlip();
    count.setValue(0);
    rowFlip.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();
        }
    });
    assertEquals("count == 1000", 1000, count.intValue());

    Matrix2D<String> slice = m.viewSlice(0);
    count.setValue(0);
    slice.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();
        }
    });
    assertEquals("count == 100", 100, count.intValue());

    Matrix1D<String> firstRowOfSlice = slice.viewRow(0);
    count.setValue(0);
    firstRowOfSlice.forEachNonNull(new UnaryProcedure<String>() {
        public void run(final String s) {
            count.increment();
        }
    });
    assertEquals("count == 10", 10, count.intValue());

    try {
        m.forEachNonNull(null);
        fail("forEachNonNull(null) expected IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }
}

From source file:org.failearly.dataz.internal.datastore.state.DataStoreStatesTest.java

@Test
public void in_which_order_should_multiple_registered_callbacks_executed() throws Exception {
    // arrange / given
    final MutableInt result = new MutableInt(0);
    final DataStoreState initial = DataStoreStates.create(originDataStore);

    final DataStoreState reserved = initial.reserve();
    reserved.register((ds) -> result.setValue(result.intValue() / 5)); // result /=5
    reserved.register((ds) -> result.setValue(result.intValue() * 20)); // result *=20
    reserved.register((ds) -> result.setValue(result.intValue() + 7)); // result += 7

    // act / when
    reserved.release();// www . j ava2 s.  c o m

    // assert / then
    assertThat("Executed in LIFO-Order?", result.intValue(), is((7 * 20) / 5));
}

From source file:org.jahia.services.content.decorator.JCRFrozenNodeAsRegular.java

/**
 * {@inheritDoc}//from   w w  w .  j  av a  2  s  . co m
 */
public boolean copy(JCRNodeWrapper dest, String name, boolean allowsExternalSharedNodes,
        Map<String, List<String>> references, List<String> ignoreNodeTypes, int maxBatch, MutableInt batchCount)
        throws RepositoryException {
    JCRNodeWrapper copy = null;
    try {
        copy = (JCRNodeWrapper) getSession().getItem(dest.getPath() + "/" + name);
        if (!copy.isCheckedOut()) {
            getSession().checkout(copy);
        }
    } catch (PathNotFoundException ex) {
        // node does not exist
    }

    if (ignoreNodeTypes != null) {
        for (String nodeType : ignoreNodeTypes) {
            if (isNodeType(nodeType)) {
                return false;
            }
        }
    }

    batchCount.increment();
    if (maxBatch > 0 && batchCount.intValue() > maxBatch) {
        try {
            session.save();
            batchCount.setValue(0);
        } catch (ConstraintViolationException e) {
            // save on the next node when next node is needed (like content node for files)
            batchCount.setValue(maxBatch - 1);
        }
    }

    final Map<String, String> uuidMapping = getSession().getUuidMapping();

    if (copy == null || copy.getDefinition().allowsSameNameSiblings()) {
        if (!dest.isCheckedOut() && dest.isVersioned()) {
            getSession().checkout(dest);
        }
        String typeName = getPrimaryNodeTypeName();
        copy = dest.addNode(name, typeName, getIdentifier(), objectNode.getProperty("jcr:created").getDate(),
                objectNode.getProperty("jcr:createdBy").getString(),
                objectNode.getProperty("jcr:lastModified").getDate(),
                objectNode.getProperty("jcr:lastModifiedBy").getString());
    }

    try {
        NodeType[] mixin = getMixinNodeTypes();
        for (NodeType aMixin : mixin) {
            copy.addMixin(aMixin.getName());
        }
    } catch (RepositoryException e) {
        logger.error("Error adding mixin types to copy", e);
    }

    if (copy != null) {
        uuidMapping.put(getIdentifier(), copy.getIdentifier());
        if (hasProperty("jcr:language")) {
            copy.setProperty("jcr:language", objectNode.getProperty("jcr:language").getString());
        }
        copyProperties(copy, references);
    }

    NodeIterator ni = getNodes();
    while (ni.hasNext()) {
        JCRNodeWrapper source = (JCRNodeWrapper) ni.next();
        if (source.isNodeType("mix:shareable")) {
            if (uuidMapping.containsKey(source.getIdentifier())) {
                // ugly save because to make node really shareable
                getSession().save();
                copy.clone(getSession().getNodeByUUID(uuidMapping.get(source.getIdentifier())),
                        source.getName());
            } else if (allowsExternalSharedNodes) {
                copy.clone(source, source.getName());
            } else {
                source.copy(copy, source.getName(), allowsExternalSharedNodes, references, ignoreNodeTypes,
                        maxBatch, batchCount);
            }
        } else {
            source.copy(copy, source.getName(), allowsExternalSharedNodes, references, ignoreNodeTypes,
                    maxBatch, batchCount);
        }
    }

    return true;
}

From source file:org.jahia.services.content.JCRNodeWrapperImpl.java

public boolean internalCopy(JCRNodeWrapper dest, String name, boolean allowsExternalSharedNodes,
        Map<String, List<String>> references, List<String> ignoreNodeTypes, int maxBatch, MutableInt batchCount,
        boolean isTopObject) throws RepositoryException {
    if (isTopObject) {
        getSession().getUuidMapping().put("top-" + getIdentifier(), StringUtils.EMPTY);
    }/*  w w  w .  jav a2 s.  com*/
    JCRNodeWrapper copy = null;
    try {
        copy = (JCRNodeWrapper) session.getItem(dest.getPath() + "/" + name);
        getSession().checkout(copy);
    } catch (PathNotFoundException ex) {
        // node does not exist
    }

    if (ignoreNodeTypes != null) {
        for (String nodeType : ignoreNodeTypes) {
            if (isNodeType(nodeType)) {
                return false;
            }
        }
    }

    batchCount.increment();
    if (maxBatch > 0 && batchCount.intValue() > maxBatch) {
        try {
            session.save();
            batchCount.setValue(0);
        } catch (ConstraintViolationException e) {
            // save on the next node when next node is needed (like content node for files)
            batchCount.setValue(maxBatch - 1);
        }
    }

    final Map<String, String> uuidMapping = getSession().getUuidMapping();

    if (copy == null || copy.getDefinition().allowsSameNameSiblings()) {
        if (dest.isVersioned()) {
            session.checkout(dest);
        }
        String typeName = getPrimaryNodeTypeName();
        try {
            copy = dest.addNode(name, typeName);
        } catch (ItemExistsException e) {
            copy = dest.getNode(name);
        } catch (ConstraintViolationException e) {
            logger.error("Cannot copy node", e);
            return false;
        }
    }

    try {
        if (copy.getProvider().isUpdateMixinAvailable()) {
            NodeType[] mixin = objectNode.getMixinNodeTypes();
            for (NodeType aMixin : mixin) {
                if (!Constants.forbiddenMixinToCopy.contains(aMixin.getName())) {
                    copy.addMixin(aMixin.getName());
                }
            }
        }
    } catch (RepositoryException e) {
        logger.error("Error adding mixin types to copy", e);
    }

    if (copy != null) {
        uuidMapping.put(getIdentifier(), copy.getIdentifier());
        if (hasProperty("jcr:language")) {
            copy.setProperty("jcr:language", getProperty("jcr:language").getString());
        }
        copyProperties(copy, references);
    }

    NodeIterator ni = getNodes();
    while (ni.hasNext()) {
        JCRNodeWrapper source = (JCRNodeWrapper) ni.next();
        if (source.isNodeType("mix:shareable")) {
            if (uuidMapping.containsKey(source.getIdentifier())) {
                // ugly save because to make node really shareable
                session.save();
                copy.clone(session.getNodeByUUID(uuidMapping.get(source.getIdentifier())), source.getName());
            } else if (allowsExternalSharedNodes) {
                copy.clone(source, source.getName());
            } else {
                doCopy(source, copy, source.getName(), allowsExternalSharedNodes, references, ignoreNodeTypes,
                        maxBatch, batchCount, false);
            }
        } else if (!source.isNodeType(Constants.JAHIAMIX_MARKED_FOR_DELETION_ROOT)
                && !source.isNodeType(Constants.JAHIANT_REFERENCEINFIELD)) {
            doCopy(source, copy, source.getName(), allowsExternalSharedNodes, references, ignoreNodeTypes,
                    maxBatch, batchCount, false);
        }
    }

    return true;
}

From source file:org.ngrinder.agent.service.ClusteredAgentManagerService.java

/**
 * Get the available agent count map in all regions of the user, including
 * the free agents and user specified agents.
 *
 * @param user current user/*w w  w  .ja v a  2s.c  o m*/
 * @return user available agent count map
 */
@Override
public Map<String, MutableInt> getAvailableAgentCountMap(User user) {
    Set<String> regions = getRegions();
    Map<String, MutableInt> availShareAgents = newHashMap(regions);
    Map<String, MutableInt> availUserOwnAgent = newHashMap(regions);
    for (String region : regions) {
        availShareAgents.put(region, new MutableInt(0));
        availUserOwnAgent.put(region, new MutableInt(0));
    }
    String myAgentSuffix = "owned_" + user.getUserId();

    for (AgentInfo agentInfo : getAllActive()) {
        // Skip all agents which are disapproved, inactive or
        // have no region prefix.
        if (!agentInfo.isApproved()) {
            continue;
        }

        String fullRegion = agentInfo.getRegion();
        String region = extractRegionFromAgentRegion(fullRegion);
        if (StringUtils.isBlank(region) || !regions.contains(region)) {
            continue;
        }
        // It's my own agent
        if (fullRegion.endsWith(myAgentSuffix)) {
            incrementAgentCount(availUserOwnAgent, region, user.getUserId());
        } else if (!fullRegion.contains("owned_")) {
            incrementAgentCount(availShareAgents, region, user.getUserId());
        }
    }

    int maxAgentSizePerConsole = getMaxAgentSizePerConsole();

    for (String region : regions) {
        MutableInt mutableInt = availShareAgents.get(region);
        int shareAgentCount = mutableInt.intValue();
        mutableInt.setValue(Math.min(shareAgentCount, maxAgentSizePerConsole));
        mutableInt.add(availUserOwnAgent.get(region));
    }
    return availShareAgents;
}

From source file:org.openvpms.component.business.service.archetype.ArchetypeServiceListenerTestCase.java

/**
 * Verifies that the {@link IMObject#getVersion()} is correctly reported within an {@link IArchetypeServiceListener}
 * in the context of a transaction.//  w ww. jav  a  2s  . c  o m
 */
@Test
public void testVersion() {
    final MutableInt version = new MutableInt();
    final IArchetypeService service = getArchetypeService();

    final Party person = createPerson();
    service.addListener("party.customerperson", new AbstractArchetypeServiceListener() {
        @Override
        public void saved(IMObject object) {
            version.setValue(object.getVersion());
        }
    });

    template.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            save(person);
            return null;
        }
    });
    assertEquals(0, person.getVersion());
    assertEquals(0, version.intValue());

    person.getDetails().put("lastName", "Gum");
    template.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            save(person);
            return null;
        }
    });
    assertEquals(1, person.getVersion());
    assertEquals(1, version.intValue());
}

From source file:org.openvpms.web.component.im.edit.SelectorIMObjectCollectionEditorTestCase.java

/**
 * Tests the {@link SelectorIMObjectCollectionEditor#add(IMObject)}
 * and {@link SelectorIMObjectCollectionEditor#remove(IMObject)} methods.
 *//*from  w  w w  .  ja v  a  2s.  c om*/
@Test
public void testAddRemove() {
    Party customer = TestHelper.createCustomer(false);
    LayoutContext layoutContext = new DefaultLayoutContext(new LocalContext(), new HelpContext("foo", null));
    PropertySet set = new PropertySet(customer, layoutContext);
    CollectionProperty property = (CollectionProperty) set.get("type");
    SelectorIMObjectCollectionEditor editor = new SelectorIMObjectCollectionEditor(property, customer,
            layoutContext);
    final MutableInt modCount = new MutableInt(0);

    editor.addModifiableListener(new ModifiableListener() {
        @Override
        public void modified(Modifiable modifiable) {
            modCount.setValue(modCount.intValue() + 1);
        }
    });

    assertFalse(editor.isModified());
    Lookup accountType = TestHelper.getLookup("lookup.customerAccountType", "BAD_DEBT");
    editor.add(accountType);
    assertEquals(1, modCount.intValue());

    assertEquals(1, property.getValues().size());
    assertTrue(property.getValues().contains(accountType));
    assertTrue(editor.isModified());
    assertTrue(editor.isValid());
    assertFalse(editor.isSaved());

    assertTrue(editor.save());
    assertTrue(editor.isSaved());
    assertFalse(editor.isModified());

    editor.remove(accountType);
    assertTrue(property.getValues().isEmpty());
    assertEquals(2, modCount.intValue());
    assertTrue(editor.isModified());
    assertTrue(editor.isValid());
}