Example usage for java.util Set clear

List of usage examples for java.util Set clear

Introduction

In this page you can find the example usage for java.util Set clear.

Prototype

void clear();

Source Link

Document

Removes all of the elements from this set (optional operation).

Usage

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

@Override
public List<Trait> parseTraits(final InputStream inputStream) {
    checkNotNull(inputStream);//from ww  w. j  av  a2 s. co  m
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String reportId = null;
        String description = null;
        String trait = null;
        Set<String> possibleTraits = new HashSet<String>();
        List<Trait> traits = new ArrayList<Trait>();
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("traits".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    while (parser.nextToken() != JsonToken.END_OBJECT) {
                        String traitField = parser.getCurrentName();
                        parser.nextToken();

                        if ("report_id".equals(traitField)) {
                            reportId = parser.getText();
                        } else if ("description".equals(traitField)) {
                            description = parser.getText();
                        } else if ("trait".equals(traitField)) {
                            trait = parser.getText();
                        } else if ("possible_traits".equals(traitField)) {
                            while (parser.nextToken() != JsonToken.END_ARRAY) {
                                possibleTraits.add(parser.getText());
                            }
                        }
                    }
                    traits.add(new Trait(id, reportId, description, trait, possibleTraits));
                    reportId = null;
                    description = null;
                    trait = null;
                    possibleTraits.clear();
                }
            }
        }
        return traits;
    } catch (IOException e) {
        logger.warn("could not parse traits", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return null;
}

From source file:de.ingrid.importer.udk.strategy.v1.IDCStrategy1_0_4_fixInspireThemes.java

/** analyze all object searchterms and assign fitting INSPIRE themes */
private void updateInspireThemesOfObjects(HashMap<Integer, Long> themeIdToSearchtermId) throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Updating INSPIRE Themes of objects...");
    }//from   w w  w.  ja  va2s. co m

    // all INSPIRE themes of object ordered by LINE asc
    String psSql = "SELECT termObj.line, val.entry_id " + "FROM searchterm_obj termObj, searchterm_value val "
            + "WHERE termObj.searchterm_id = val.id " + "and val.type = 'I' " + "and termObj.obj_id = ? "
            + "order by termObj.line";
    PreparedStatement psReadObjInspireTerms = jdbc.prepareStatement(psSql);

    // insert INSPIRE theme into searchterm_value
    psSql = "INSERT INTO searchterm_value " + "(id, type, term, entry_id) " + "VALUES " + "(?, 'I', ?, ?)";
    PreparedStatement psInsertTerm = jdbc.prepareStatement(psSql);

    // connect INSPIRE theme with object (insert searchterm_obj)
    psSql = "INSERT INTO searchterm_obj " + "(id, obj_id, line, searchterm_id) " + "VALUES " + "(?, ?, ?, ?)";
    PreparedStatement psInsertTermObj = jdbc.prepareStatement(psSql);

    // remove INSPIRE theme from object
    psSql = "DELETE FROM searchterm_obj " + "WHERE obj_id=? " + "and searchterm_id=?";
    PreparedStatement psRemoveTermObj = jdbc.prepareStatement(psSql);

    // here we track ids of assigned INSPIRE themes of current object
    Set<Integer> currThemeIds = new HashSet<Integer>();
    int currLine = 0;
    long currObjId = -1;
    String currObjUuid = null;
    String currObjWorkState = null;

    // iterate over all searchterms applied to objects ordered by object
    String sqlAllObjTerms = "SELECT termObj.obj_id, val.term, obj.obj_uuid, obj.work_state "
            + "FROM t01_object obj, searchterm_obj termObj, searchterm_value val "
            + "WHERE obj.id = termObj.obj_id " + "and termObj.searchterm_id = val.id "
            + "order by termObj.obj_id";
    Statement st = jdbc.createStatement();
    ResultSet rs = jdbc.executeQuery(sqlAllObjTerms, st);
    while (rs.next()) {
        long readObjId = rs.getLong("obj_id");

        // check whether object changed
        if (readObjId != currObjId) {
            // object changed !

            // "finish" former object
            if (currObjId != -1) {
                // remove former "NO INSPIRE THEME" if new theme was added !
                if (currThemeIds.size() > 1 && currThemeIds.contains(UtilsInspireThemes.noInspireThemeId)) {
                    removeInspireThemeFromObject(UtilsInspireThemes.noInspireThemeId, currObjId,
                            themeIdToSearchtermId, psRemoveTermObj, currThemeIds, currObjUuid,
                            currObjWorkState);
                }
                // check whether former object has INSPIRE Theme, else add "NO INSPIRE THEME"
                if (currThemeIds.isEmpty()) {
                    addInspireThemeToObject(UtilsInspireThemes.noInspireThemeId, currObjId, 1,
                            themeIdToSearchtermId, psInsertTerm, psInsertTermObj, currThemeIds, null,
                            currObjUuid, currObjWorkState);
                }
            }

            // process "new" object
            currObjId = readObjId;
            // needed for logging
            currObjUuid = rs.getString("obj_uuid");
            currObjWorkState = rs.getString("work_state");
            currLine = 0;
            currThemeIds.clear();

            // fetch all assigned INSPIRE themes and max line
            psReadObjInspireTerms.setLong(1, currObjId);
            ResultSet rsObjInspireTerms = psReadObjInspireTerms.executeQuery();
            while (rsObjInspireTerms.next()) {
                currLine = rsObjInspireTerms.getInt("line");
                Integer entryId = rsObjInspireTerms.getInt("entry_id");
                currThemeIds.add(entryId);
            }
            rsObjInspireTerms.close();
        }

        // analyze read searchterm. Check whether contains inspire term !
        // add according INSPIRE themes if not added yet !

        // read searchterm, lower case for comparison
        String searchTerm = rs.getString("term");
        Set<Integer> newThemeIds = UtilsInspireThemes.getThemeIdsOfTerm(searchTerm, null);
        for (Integer newThemeId : newThemeIds) {
            if (!currThemeIds.contains(newThemeId)) {
                addInspireThemeToObject(newThemeId, currObjId, ++currLine, themeIdToSearchtermId, psInsertTerm,
                        psInsertTermObj, currThemeIds, searchTerm, currObjUuid, currObjWorkState);
            }
        }
    }
    rs.close();
    st.close();
    psReadObjInspireTerms.close();
    psInsertTerm.close();
    psInsertTermObj.close();
    psRemoveTermObj.close();

    if (log.isInfoEnabled()) {
        log.info("Updating INSPIRE Themes of objects... done");
    }
}

From source file:org.reunionemu.jreunion.server.Network.java

@Override
public void run() {
    logger.info("network thread starting");
    while (true) {
        try {/*from   ww w  .  java  2 s  . c o m*/
            // See if we've had any activity -- either an incoming connection,
            // or incoming data on an existing connection
            int num = selector.select();
            if (num == 0) {
                // we need synchronize here otherwise we might block again before we were able to change the selector
                synchronized (this) {
                    continue;
                }
            }

            // If we don't have any activity, loop around and wait again
            // Get the keys corresponding to the activity
            // that has been detected, and process them one by one

            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while (it.hasNext()) {
                // Get a key representing one of bits of I/O activity
                SelectionKey key = it.next();
                if (!key.isValid())
                    continue;

                SelectableChannel selectableChannel = key.channel();
                // What kind of activity is it?
                if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {

                    // It's an incoming connection.
                    // Register this socket with the Selector
                    // so we can listen for input on it                  

                    SocketChannel clientSocketChannel = ((ServerSocketChannel) selectableChannel).accept();

                    processAccept(clientSocketChannel);

                } else {
                    SocketChannel socketChannel = (SocketChannel) selectableChannel;

                    if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

                        // It's incoming data on a connection, so process it
                        boolean ok = processInput(socketChannel);

                        // If the connection is dead, then remove it
                        // from the selector and close it
                        if (!ok) {
                            LoggerFactory.getLogger(Network.class).info("Client Connection Lost");
                            key.cancel();
                            disconnect(socketChannel);
                        }

                    } else if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {

                        boolean ok = processOutput(socketChannel);
                        if (ok) {
                            socketChannel.register(selector, SelectionKey.OP_READ);
                        }
                    }
                }
            }
            // We remove the selected keys, because we've dealt with them.
            keys.clear();

        } catch (Exception e) {
            if (e instanceof ClosedSelectorException || e instanceof InterruptedException)
                return;
            LoggerFactory.getLogger(Network.class).error("Error in network", e);
        }
    }

}

From source file:com.linkedin.d2.balancer.simple.SimpleLoadBalancerTest.java

@Test(groups = { "small", "back-end" })
public void testLoadBalancerWithPartitionsSmoke()
        throws URISyntaxException, ServiceUnavailableException, InterruptedException, ExecutionException {
    for (int tryAgain = 0; tryAgain < 12; ++tryAgain) {
        Map<String, LoadBalancerStrategyFactory<? extends LoadBalancerStrategy>> loadBalancerStrategyFactories = new HashMap<String, LoadBalancerStrategyFactory<? extends LoadBalancerStrategy>>();
        Map<String, TransportClientFactory> clientFactories = new HashMap<String, TransportClientFactory>();
        List<String> prioritizedSchemes = new ArrayList<String>();

        MockStore<ServiceProperties> serviceRegistry = new MockStore<ServiceProperties>();
        MockStore<ClusterProperties> clusterRegistry = new MockStore<ClusterProperties>();
        MockStore<UriProperties> uriRegistry = new MockStore<UriProperties>();

        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        loadBalancerStrategyFactories.put("degrader", new DegraderLoadBalancerStrategyFactoryV3());

        clientFactories.put("http", new DoNothingClientFactory());

        SimpleLoadBalancerState state = new SimpleLoadBalancerState(executorService, uriRegistry,
                clusterRegistry, serviceRegistry, clientFactories, loadBalancerStrategyFactories);

        SimpleLoadBalancer loadBalancer = new SimpleLoadBalancer(state, 5, TimeUnit.SECONDS);

        FutureCallback<None> balancerCallback = new FutureCallback<None>();
        loadBalancer.start(balancerCallback);
        balancerCallback.get();//from www .  jav  a 2s .  c om

        URI uri1 = URI.create("http://test.qa1.com:1234");
        URI uri2 = URI.create("http://test.qa2.com:2345");
        URI uri3 = URI.create("http://test.qa3.com:6789");

        Map<URI, Double> uris = new HashMap<URI, Double>();

        uris.put(uri1, 1d);
        uris.put(uri2, 1d);
        uris.put(uri3, 1d);

        Map<URI, Map<Integer, PartitionData>> partitionDesc = new HashMap<URI, Map<Integer, PartitionData>>();

        Map<Integer, PartitionData> server1 = new HashMap<Integer, PartitionData>();
        server1.put(0, new PartitionData(1d));
        server1.put(1, new PartitionData(1d));

        Map<Integer, PartitionData> server2 = new HashMap<Integer, PartitionData>();
        server2.put(0, new PartitionData(1d));

        Map<Integer, PartitionData> server3 = new HashMap<Integer, PartitionData>();
        server3.put(1, new PartitionData(1d));
        partitionDesc.put(uri1, server1);
        partitionDesc.put(uri2, server2);
        partitionDesc.put(uri3, server3);

        prioritizedSchemes.add("http");

        int partitionMethod = tryAgain % 4;
        switch (partitionMethod) {
        case 0:
            clusterRegistry.put("cluster-1",
                    new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(),
                            new RangeBasedPartitionProperties("id=(\\d+)", 0, 50, 2)));
            break;
        case 1:
            clusterRegistry.put("cluster-1",
                    new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(),
                            new HashBasedPartitionProperties("id=(\\d+)", 2,
                                    HashBasedPartitionProperties.HashAlgorithm.valueOf("MODULO"))));
            break;
        case 2:
            clusterRegistry.put("cluster-1",
                    new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(),
                            new HashBasedPartitionProperties("id=(\\d+)", 2,
                                    HashBasedPartitionProperties.HashAlgorithm.valueOf("MD5"))));
            break;
        case 3:
            // test getRings with gap. here, no server serves partition 2
            clusterRegistry.put("cluster-1",
                    new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(),
                            new RangeBasedPartitionProperties("id=(\\d+)", 0, 50, 4)));
            server3.put(3, new PartitionData(1d));
            partitionDesc.put(uri3, server3);
            break;
        default:
            break;
        }

        serviceRegistry.put("foo", new ServiceProperties("foo", "cluster-1", "/foo", Arrays.asList("degrader"),
                Collections.<String, Object>emptyMap(), null, null, prioritizedSchemes, null));

        uriRegistry.put("cluster-1", new UriProperties("cluster-1", partitionDesc));

        if (partitionMethod == 3) {
            Map<Integer, Ring<URI>> ringMap = loadBalancer.getRings(URI.create("d2://foo"));
            assertEquals(ringMap.size(), 4);
            // the ring for partition 2 should be empty
            assertEquals(ringMap.get(2).toString(),
                    new ConsistentHashRing<URI>(Collections.emptyList()).toString());
            continue;
        }

        URI expectedUri1 = URI.create("http://test.qa1.com:1234/foo");
        URI expectedUri2 = URI.create("http://test.qa2.com:2345/foo");
        URI expectedUri3 = URI.create("http://test.qa3.com:6789/foo");

        Set<URI> expectedUris = new HashSet<URI>();
        expectedUris.add(expectedUri1);
        expectedUris.add(expectedUri2);
        expectedUris.add(expectedUri3);

        for (int i = 0; i < 1000; ++i) {
            int ii = i % 100;
            RewriteClient client = (RewriteClient) loadBalancer.getClient(new URIRequest("d2://foo/id=" + ii),
                    new RequestContext());
            String clientUri = client.getUri().toString();
            HashFunction<String[]> hashFunction = null;
            String[] str = new String[1];

            // test KeyMapper target host hint: request is always to target host regardless of what's in d2 URI and whether it's hash-based or range-based partitions
            RequestContext requestContextWithHint = new RequestContext();
            KeyMapper.TargetHostHints.setRequestContextTargetHost(requestContextWithHint, uri1);
            RewriteClient hintedClient1 = (RewriteClient) loadBalancer
                    .getClient(new URIRequest("d2://foo/id=" + ii), requestContextWithHint);
            String hintedUri1 = hintedClient1.getUri().toString();
            Assert.assertEquals(hintedUri1, uri1.toString() + "/foo");
            RewriteClient hintedClient2 = (RewriteClient) loadBalancer
                    .getClient(new URIRequest("d2://foo/action=purge-all"), requestContextWithHint);
            String hintedUri2 = hintedClient2.getUri().toString();
            Assert.assertEquals(hintedUri2, uri1.toString() + "/foo");
            // end test KeyMapper target host hint

            if (partitionMethod == 2) {
                hashFunction = new MD5Hash();
            }
            for (URI uri : expectedUris) {
                if (clientUri.contains(uri.toString())) {
                    // check if only key belonging to partition 0 gets uri2
                    if (uri.equals(uri2)) {
                        if (partitionMethod == 0) {
                            assertTrue(ii < 50);
                        } else if (partitionMethod == 1) {
                            assertTrue(ii % 2 == 0);
                        } else {
                            str[0] = ii + "";
                            assertTrue(hashFunction.hash(str) % 2 == 0);
                        }
                    }
                    // check if only key belonging to partition 1 gets uri3
                    if (uri.equals(uri3)) {
                        if (partitionMethod == 0) {
                            assertTrue(ii >= 50);
                        } else if (partitionMethod == 1) {
                            assertTrue(ii % 2 == 1);
                        } else {
                            str[0] = ii + "";
                            assertTrue(hashFunction.hash(str) % 2 == 1);
                        }
                    }
                }
            }
        }

        // two rings for two partitions
        Map<Integer, Ring<URI>> ringMap = loadBalancer.getRings(URI.create("d2://foo"));
        assertEquals(ringMap.size(), 2);

        if (partitionMethod != 2) {
            Set<String> keys = new HashSet<String>();
            for (int j = 0; j < 50; j++) {
                if (partitionMethod == 0) {
                    keys.add(j + "");
                } else {
                    keys.add(j * 2 + "");
                }
            }

            // if it is range based partition, all keys from 0 ~ 49 belong to partition 0 according to the range definition
            // if it is modulo based partition, all even keys belong to partition 0 because the partition count is 2
            // only from partition 0
            MapKeyResult<Ring<URI>, String> mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys);
            Map<Ring<URI>, Collection<String>> keyToPartition = mapKeyResult.getMapResult();
            assertEquals(keyToPartition.size(), 1);
            for (Ring<URI> ring : keyToPartition.keySet()) {
                assertEquals(ring, ringMap.get(0));
            }

            // now also from partition 1
            keys.add("51");
            mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys);
            assertEquals(mapKeyResult.getMapResult().size(), 2);
            assertEquals(mapKeyResult.getUnmappedKeys().size(), 0);

            // now only from partition 1
            keys.clear();
            keys.add("99");
            mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys);
            keyToPartition = mapKeyResult.getMapResult();
            assertEquals(keyToPartition.size(), 1);
            assertEquals(mapKeyResult.getUnmappedKeys().size(), 0);
            for (Ring<URI> ring : keyToPartition.keySet()) {
                assertEquals(ring, ringMap.get(1));
            }

            keys.add("100");

            mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys);
            if (partitionMethod == 0) {
                // key out of range
                Collection<MapKeyResult.UnmappedKey<String>> unmappedKeys = mapKeyResult.getUnmappedKeys();
                assertEquals(unmappedKeys.size(), 1);
            }

            try {
                loadBalancer.getClient(new URIRequest("d2://foo/id=100"), new RequestContext());
                if (partitionMethod == 0) {
                    // key out of range
                    fail("Should throw ServiceUnavailableException caused by PartitionAccessException");
                }
            } catch (ServiceUnavailableException e) {
            }
        }

        final CountDownLatch latch = new CountDownLatch(1);
        PropertyEventShutdownCallback callback = new PropertyEventShutdownCallback() {
            @Override
            public void done() {
                latch.countDown();
            }
        };

        state.shutdown(callback);

        if (!latch.await(60, TimeUnit.SECONDS)) {
            fail("unable to shutdown state");
        }

        executorService.shutdownNow();

        assertTrue(executorService.isShutdown(), "ExecutorService should have shut down!");
    }
}

From source file:com.bstek.dorado.data.config.xml.DataProviderParserDispatcher.java

@Override
protected Object doParse(Node node, ParseContext context) throws Exception {
    Element element = (Element) node;
    DataParseContext dataContext = (DataParseContext) context;
    Set<Node> parsingNodes = dataContext.getParsingNodes();
    Map<String, DataProviderDefinition> parsedDataProviders = dataContext.getParsedDataProviders();

    String name = element.getAttribute(XmlConstants.ATTRIBUTE_NAME);
    NodeWrapper nodeWrapper = null;/* www. j  a  va 2 s. co m*/
    if (!StringUtils.isEmpty(name)) {
        nodeWrapper = dataContext.getConfiguredDataProviders().get(name);
    }
    boolean isGlobal = (nodeWrapper != null && nodeWrapper.getNode() == node);

    DataProviderDefinition dataProvider = null;
    if (!StringUtils.isEmpty(name) && isGlobal) {
        // Comment 11/04/26 ?View?DataObjectGlobal DataObject???
        // DefinitionManager<DataProviderDefinition>
        // dataProviderDefinitionManager = dataContext
        // .getDataProviderDefinitionManager();
        // DataProviderDefinition dataProvider =
        // dataProviderDefinitionManager
        // .getDefinition(name);
        // if (dataProvider == null) {
        // dataProvider = parsedDataProviders.get(name);
        // }
        dataProvider = parsedDataProviders.get(name);
        if (dataProvider != null) {
            return dataProvider;
        }
    }

    XmlParser parser = null;
    String type = element.getAttribute(DataXmlConstants.ATTRIBUTE_PROVIDER_TYPE);
    DataProviderTypeRegisterInfo registryInfo = dataProviderTypeRegistry.getTypeRegistryInfo(type);
    if (registryInfo != null) {
        Class<? extends DataProvider> classType = registryInfo.getClassType();
        parser = xmlParserHelper.getXmlParser(classType);
    } else {
        throw new XmlParseException("Unrecognized DataProvider type[" + type + "].", element, context);
    }

    if (parser == null) {
        throw new XmlParseException("Can not get Parser for DataProvider of [" + type + "] type.", element,
                context);
    }

    if (isGlobal) {
        parsingNodes.add(element);
        dataContext.setPrivateObjectName(Constants.PRIVATE_DATA_OBJECT_PREFIX
                + DataXmlConstants.PATH_DATE_PROVIDER_SHORT_NAME + Constants.PRIVATE_DATA_OBJECT_SUBFIX + name);

        dataProvider = (DataProviderDefinition) parser.parse(node, dataContext);

        dataContext.restorePrivateObjectName();
        parsingNodes.clear();
    } else {
        String privateNameSection = dataContext.getPrivateNameSection(node);
        if (privateNameSection != null) {
            dataContext.setPrivateObjectNameSection(privateNameSection);
        }
        name = dataContext.getPrivateObjectName();

        dataProvider = (DataProviderDefinition) parser.parse(node, context);

        if (privateNameSection != null) {
            dataContext.restorePrivateObjectName();
        }
    }

    if (dataProvider != null) {
        dataProvider.setName(name);
        parsedDataProviders.put(name, dataProvider);
    }
    return dataProvider;
}

From source file:com.bstek.dorado.data.config.xml.DataResolverParserDispatcher.java

@Override
protected Object doParse(Node node, ParseContext context) throws Exception {
    Element element = (Element) node;
    DataParseContext dataContext = (DataParseContext) context;
    Set<Node> parsingNodes = dataContext.getParsingNodes();
    Map<String, DataResolverDefinition> parsedDataResolvers = dataContext.getParsedDataResolvers();

    String name = element.getAttribute(XmlConstants.ATTRIBUTE_NAME);
    NodeWrapper nodeWrapper = null;/*  ww w  .j  a  v  a  2 s.c  om*/
    if (!StringUtils.isEmpty(name)) {
        nodeWrapper = dataContext.getConfiguredDataResolvers().get(name);
    }
    boolean isGlobal = (nodeWrapper != null && nodeWrapper.getNode() == node);

    DataResolverDefinition dataResolver = null;
    if (!StringUtils.isEmpty(name) && isGlobal) {
        // Comment 11/04/26 ?View?DataObjectGlobal DataObject???
        // DefinitionManager<DataResolverDefinition>
        // dataResolverDefinitionManager = dataContext
        // .getDataResolverDefinitionManager();
        // DataResolverDefinition dataResolver =
        // dataResolverDefinitionManager
        // .getDefinition(name);
        // if (dataResolver == null) {
        // dataResolver = parsedDataResolvers.get(name);
        // }
        dataResolver = parsedDataResolvers.get(name);
        if (dataResolver != null) {
            return dataResolver;
        }
    }

    XmlParser parser = null;
    String type = element.getAttribute(DataXmlConstants.ATTRIBUTE_RESOLVER_TYPE);
    DataResolverTypeRegisterInfo registryInfo = dataResolverTypeRegistry.getTypeRegistryInfo(type);
    if (registryInfo != null) {
        Class<? extends DataResolver> classType = registryInfo.getClassType();
        parser = xmlParserHelper.getXmlParser(classType);
    } else {
        throw new XmlParseException("Unrecognized DataResolver type[" + type + "].", element, context);
    }

    if (parser == null) {
        throw new XmlParseException("Can not get Parser for DataResolver of [" + type + "] type.", element,
                context);
    }

    if (isGlobal) {
        parsingNodes.add(element);
        dataContext.setPrivateObjectName(Constants.PRIVATE_DATA_OBJECT_PREFIX
                + DataXmlConstants.PATH_DATE_RESOLVER_SHORT_NAME + Constants.PRIVATE_DATA_OBJECT_SUBFIX + name);

        dataResolver = (DataResolverDefinition) parser.parse(node, dataContext);

        dataContext.restorePrivateObjectName();
        parsingNodes.clear();
    } else {
        String privateNameSection = dataContext.getPrivateNameSection(node);
        if (privateNameSection != null) {
            dataContext.setPrivateObjectNameSection(privateNameSection);
        }
        name = dataContext.getPrivateObjectName();

        dataResolver = (DataResolverDefinition) parser.parse(node, context);

        if (privateNameSection != null) {
            dataContext.restorePrivateObjectName();
        }
    }

    if (dataResolver != null) {
        dataResolver.setName(name);
        parsedDataResolvers.put(name, dataResolver);
    }
    return dataResolver;
}

From source file:fr.landel.utils.assertor.predicate.PredicateAssertorIterableTest.java

/**
 * Test method for {@link AssertorIterable#contains}.
 * /*from www . jav  a 2 s  . co m*/
 * @throws IOException
 *             On contain
 */
@Test
public void testDoesNotContain() throws IOException {
    final String el1 = "element1";
    final String el2 = "element2";

    final Set<String> set = new HashSet<>();
    set.add(el1);

    Assertor.<Set<String>, String>ofIterable().not().contains(el2).that(set)
            .orElseThrow("iterable contains the element %s*");
    Assertor.<Set<String>, String>ofIterable().not().contains((String) null).that(set).orElseThrow();
    Assertor.<Set<String>, String>ofIterable(EnumAnalysisMode.STREAM).not().contains(el2).that(set)
            .orElseThrow("iterable contains the element %s*");
    Assertor.<Set<String>, String>ofIterable(EnumAnalysisMode.STREAM).not().contains((String) null).that(set)
            .orElseThrow();
    Assertor.<Set<String>, String>ofIterable(EnumAnalysisMode.PARALLEL).not().contains(el2).that(set)
            .orElseThrow("iterable contains the element %s*");
    Assertor.<Set<String>, String>ofIterable(EnumAnalysisMode.PARALLEL).not().contains((String) null).that(set)
            .orElseThrow();

    assertException(() -> {
        Assertor.<Set<String>, String>ofIterable().not().contains(el1).that(set).orElseThrow();
        fail(ERROR);
    }, IllegalArgumentException.class, "the iterable '[element1]' should NOT contain the object 'element1'");

    assertException(() -> {
        Assertor.<Set<String>, String>ofIterable().not().contains(el1).that(set)
                .orElseThrow("iterable contains the element %2$s*");
        fail(ERROR);
    }, IllegalArgumentException.class, "iterable contains the element " + el1);

    assertException(() -> {
        Assertor.<Set<String>, String>ofIterable().not().contains(el1).that(set).orElseThrow(new IOException(),
                false);
        fail(ERROR);
    }, IOException.class);

    set.clear();

    assertException(() -> {
        Assertor.<Iterable<String>, String>ofIterable().not().contains(el1).that((Iterable<String>) null)
                .orElseThrow();
        fail(ERROR);
    }, IllegalArgumentException.class, "the iterable cannot be null or empty");
}

From source file:de.escidoc.core.aa.business.UserAccountHandler.java

/**
 * See Interface for functional description.
 *
 * @param userId         The userId./*from   w  ww .j av a2  s. c o  m*/
 * @param preferencesXML The xml.
 * @return updated XML
 * @throws UserAccountNotFoundException   If
 * @throws XmlCorruptedException          If
 * @throws SystemException                If
 * @throws OptimisticLockingException     If the give last modification timestamp does not match the current one.
 * @throws MissingAttributeValueException If there is no last modificate date attribute.
 * @see de.escidoc.core.aa.service.interfaces.UserAccountHandlerInterface #createPreference(java.lang.String,
 *      java.lang.String)
 */
@Override
public String updatePreferences(final String userId, final String preferencesXML)
        throws UserAccountNotFoundException, XmlCorruptedException, SystemException, OptimisticLockingException,
        MissingAttributeValueException {

    final UserAccount userAccount = retrieveUserAccountById(userId);

    final ByteArrayInputStream in = XmlUtility.convertToByteArrayInputStream(preferencesXML);
    final StaxParser sp = new StaxParser(Elements.ELEMENT_USER_PREFERENCES);

    final UserPreferenceReadHandler uprh = new UserPreferenceReadHandler();
    sp.addHandler(uprh);

    final OptimisticLockingStaxHandler optimisticLockingHandler = new OptimisticLockingStaxHandler(
            userAccount.getLastModificationDate());
    sp.addHandler(optimisticLockingHandler);

    try {
        sp.parse(in);
    } catch (LastModificationDateMissingException e) {
        throw new MissingAttributeValueException(e);
    } catch (final MissingAttributeValueException e) {
        throw e;
    } catch (final OptimisticLockingException e) {
        throw e;
    } catch (final Exception e) {
        final String msg = MSG_UNEXPECTED_EXCEPTION + getClass().getName() + ".updatePreference: "
                + e.getClass().getName();
        throw new SystemException(msg, e);
    }

    // delete all existing preferences
    // FIXME name/value may be defined as primary key
    final Set<UserPreference> currentPreferences = userAccount.getUserPreferencesByUserId();
    // Iterator<UserPreference> curPrefsIterator =
    // currentPreferences.iterator();
    // while (curPrefsIterator.hasNext()) {
    // UserPreference preference = curPrefsIterator.next();
    // dao.delete(preference);
    // }
    currentPreferences.clear();

    // add all given preferences
    final Map<String, String> preferences = uprh.getPreferences();
    for (final Entry<String, String> e : preferences.entrySet()) {
        final UserPreference preference = new UserPreference();
        final String preferenceName = e.getKey();
        final String preferenceValue = e.getValue();
        preference.setUserAccountByUserId(userAccount);
        preference.setName(preferenceName);
        preference.setValue(preferenceValue);

        // dao.save(preference);
        // FIXME ? set does not prevent dublicate keys but dublicate objects
        // (FRS)
        currentPreferences.add(preference);
    }

    // update user in policy cache; rights may depend on preferences
    sendUserAccountUpdateEvent(userId);

    userAccount.touch();

    // TODO create XML via renderPreference
    return renderer.renderPreferences(userAccount, currentPreferences);
}

From source file:com.netflix.nicobar.core.module.ScriptModuleLoaderTest.java

@Test
public void testCompileErrorAbortsRelink() throws Exception {
    // original graph: A->B->C->D
    long originalCreateTime = 1000;
    Set<ScriptArchive> updateArchives = new HashSet<ScriptArchive>();
    updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("A")
            .addCompilerPluginId("mockPlugin").addModuleDependency("B").build(), originalCreateTime));
    ScriptArchive archiveB = new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("B")
            .addCompilerPluginId("mockPlugin").addModuleDependency("C").build(), originalCreateTime);
    updateArchives.add(archiveB);//w w  w  .jav  a 2  s.co  m
    updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C")
            .addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), originalCreateTime));
    updateArchives.add(new TestDependecyScriptArchive(
            new ScriptModuleSpec.Builder("D").addCompilerPluginId("mockPlugin").build(), originalCreateTime));

    when(MOCK_COMPILER.shouldCompile(Mockito.any(ScriptArchive.class))).thenReturn(true);
    when(MOCK_COMPILER.compile(Mockito.any(ScriptArchive.class), Mockito.any(JBossModuleClassLoader.class),
            Mockito.any(Path.class))).thenReturn(Collections.<Class<?>>emptySet());

    ScriptModuleListener mockListener = createMockListener();
    ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder().addListener(mockListener)
            .addPluginSpec(new ScriptCompilerPluginSpec.Builder("mockPlugin")
                    .withPluginClassName(MockScriptCompilerPlugin.class.getName()).build())
            .build();

    moduleLoader.updateScriptArchives(updateArchives);
    reset(mockListener);
    reset(MOCK_COMPILER);
    when(MOCK_COMPILER.shouldCompile(Mockito.any(ScriptArchive.class))).thenReturn(true);
    when(MOCK_COMPILER.compile(Mockito.eq(archiveB), Mockito.any(JBossModuleClassLoader.class),
            Mockito.any(Path.class))).thenThrow(new ScriptCompilationException("TestCompileException", null));
    // update C. would normally cause C,B,A to be compiled in order, but B will fail, so A will be skipped
    updateArchives.clear();
    long updatedCreateTime = 2000;
    updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C")
            .addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), updatedCreateTime));

    moduleLoader.updateScriptArchives(updateArchives);

    // validate that only C was compiled.
    InOrder orderVerifier = inOrder(mockListener);
    orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("C", updatedCreateTime),
            moduleEquals("C", originalCreateTime));
    orderVerifier.verifyNoMoreInteractions();

    // validate the post-condition of the module database
    assertEquals(moduleLoader.getScriptModule("A").getCreateTime(), originalCreateTime);
    assertEquals(moduleLoader.getScriptModule("B").getCreateTime(), originalCreateTime);
    assertEquals(moduleLoader.getScriptModule("C").getCreateTime(), updatedCreateTime);
    assertEquals(moduleLoader.getScriptModule("D").getCreateTime(), originalCreateTime);
    assertEquals(moduleLoader.getAllScriptModules().size(), 4);
}

From source file:com.android.mms.transaction.MessagingNotification.java

/**
 * Checks to see if there are any "unseen" messages or delivery
 * reports and builds a sorted (by delivery date) list of unread notifications.
 *
 * @param context the context to use/*w ww  .  j  ava 2  s.co  m*/
 * @param newMsgThreadId The thread ID of a new message that we're to notify about; if there's
 *  no new message, use THREAD_NONE. If we should notify about multiple or unknown thread IDs,
 *  use THREAD_ALL.
 * @param isStatusMessage
 */
public static void blockingUpdateNewMessageIndicator(Context context, long newMsgThreadId,
        boolean isStatusMessage) {
    if (DEBUG) {
        Contact.logWithTrace(TAG, "blockingUpdateNewMessageIndicator: newMsgThreadId: " + newMsgThreadId);
    }
    final boolean isDefaultSmsApp = MmsConfig.isSmsEnabled(context);
    if (!isDefaultSmsApp) {
        cancelNotification(context, NOTIFICATION_ID);
        if (DEBUG || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
            Log.d(TAG,
                    "blockingUpdateNewMessageIndicator: not the default sms app - skipping " + "notification");
        }
        return;
    }

    // notificationSet is kept sorted by the incoming message delivery time, with the
    // most recent message first.
    SortedSet<NotificationInfo> notificationSet = new TreeSet<NotificationInfo>(INFO_COMPARATOR);

    Set<Long> threads = new HashSet<Long>(4);

    addMmsNotificationInfos(context, threads, notificationSet);
    addSmsNotificationInfos(context, threads, notificationSet);

    if (notificationSet.isEmpty()) {
        if (DEBUG) {
            Log.d(TAG, "blockingUpdateNewMessageIndicator: notificationSet is empty, "
                    + "canceling existing notifications");
        }
        cancelNotification(context, NOTIFICATION_ID);
    } else {
        if (DEBUG || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
            Log.d(TAG, "blockingUpdateNewMessageIndicator: count=" + notificationSet.size()
                    + ", newMsgThreadId=" + newMsgThreadId);
        }

        if (isInCurrentConversation(newMsgThreadId, threads)) {
            if (DEBUG) {
                Log.d(TAG,
                        "blockingUpdateNewMessageIndicator: newMsgThreadId == "
                                + "sCurrentlyDisplayedThreadId so NOT showing notification,"
                                + " but playing soft sound. threadId: " + newMsgThreadId);
            }
            playInConversationNotificationSound(context, newMsgThreadId);
            return;
        }
        updateNotification(context, newMsgThreadId, threads.size(), notificationSet);
    }

    // And deals with delivery reports (which use Toasts). It's safe to call in a worker
    // thread because the toast will eventually get posted to a handler.
    MmsSmsDeliveryInfo delivery = getSmsNewDeliveryInfo(context);
    if (delivery != null) {
        delivery.deliver(context, isStatusMessage);
    }

    notificationSet.clear();
    threads.clear();
}