Search in sources :

Example 61 with EnumSet

use of java.util.EnumSet in project karaf by apache.

the class FeaturesServiceImpl method uninstallFeatures.

@Override
public void uninstallFeatures(Set<String> features, String region, EnumSet<Option> options) throws Exception {
    State state = copyState();
    Map<String, Set<String>> required = copy(state.requirements);
    if (region == null || region.isEmpty()) {
        region = ROOT_REGION;
    }
    Set<String> fl = required.computeIfAbsent(region, k -> new HashSet<>());
    List<String> featuresToRemove = new ArrayList<>();
    for (String feature : new HashSet<>(features)) {
        List<String> toRemove = new ArrayList<>();
        feature = normalize(feature);
        if (feature.endsWith("/0.0.0")) {
            // Match only on name
            String nameSep = FEATURE_OSGI_REQUIREMENT_PREFIX + feature.substring(0, feature.indexOf(VERSION_SEPARATOR) + 1);
            for (String f : fl) {
                Pattern pattern = Pattern.compile(nameSep.substring(0, nameSep.length() - 1));
                Matcher matcher = pattern.matcher(f);
                if (matcher.matches() || normalize(f).startsWith(nameSep)) {
                    toRemove.add(f);
                }
            }
        } else {
            // Match on name and version
            String name = feature.substring(0, feature.indexOf(VERSION_SEPARATOR));
            String version = feature.substring(feature.indexOf(VERSION_SEPARATOR) + 1);
            Pattern pattern = getFeaturePattern(name, version);
            for (String f : fl) {
                Matcher matcher = pattern.matcher(f);
                if (matcher.matches()) {
                    toRemove.add(f);
                }
            }
        }
        toRemove.retainAll(fl);
        if (toRemove.isEmpty()) {
            throw new IllegalArgumentException("Feature named '" + feature + "' is not installed");
        }
        featuresToRemove.addAll(toRemove);
    }
    featuresToRemove = new ArrayList<>(new LinkedHashSet<>(featuresToRemove));
    print("Removing features: " + join(featuresToRemove), options.contains(Option.Verbose));
    fl.removeAll(featuresToRemove);
    if (fl.isEmpty()) {
        required.remove(region);
    }
    Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
    doProvisionInThread(required, stateChanges, state, options);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Pattern(java.util.regex.Pattern) EnumSet(java.util.EnumSet) Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) FeatureState(org.apache.karaf.features.FeatureState) StateStorage.toStringStringSetMap(org.apache.karaf.features.internal.service.StateStorage.toStringStringSetMap) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 62 with EnumSet

use of java.util.EnumSet in project karaf by apache.

the class FeaturesServiceImpl method checkResolve.

@SuppressWarnings({ "unchecked", "rawtypes" })
private void checkResolve() {
    File resolveFile = installSupport.getDataFile(RESOLVE_FILE);
    if (resolveFile == null || !resolveFile.exists()) {
        return;
    }
    Map<String, Object> request;
    try (FileInputStream fis = new FileInputStream(resolveFile)) {
        request = (Map<String, Object>) JsonReader.read(fis);
    } catch (IOException e) {
        LOGGER.warn("Error reading resolution request", e);
        return;
    }
    Map<String, Set<String>> requestedFeatures = toStringStringSetMap((Map) request.get("features"));
    Collection<String> opts = (Collection<String>) request.get("options");
    EnumSet<Option> options = EnumSet.noneOf(Option.class);
    for (String opt : opts) {
        options.add(Option.valueOf(opt));
    }
    // Resolve
    try {
        Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
        doProvisionInThread(requestedFeatures, stateChanges, copyState(), options);
    } catch (Exception e) {
        LOGGER.warn("Error updating state", e);
    }
}
Also used : EnumSet(java.util.EnumSet) Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Collection(java.util.Collection) File(java.io.File) StateStorage.toStringStringSetMap(org.apache.karaf.features.internal.service.StateStorage.toStringStringSetMap) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap)

Example 63 with EnumSet

use of java.util.EnumSet in project karaf by apache.

the class FeaturesServiceImpl method addRequirements.

@Override
public void addRequirements(Map<String, Set<String>> requirements, EnumSet<Option> options) throws Exception {
    State state = copyState();
    Map<String, Set<String>> required = copy(state.requirements);
    add(required, requirements);
    Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
    doProvisionInThread(required, stateChanges, state, options);
}
Also used : EnumSet(java.util.EnumSet) Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) FeatureState(org.apache.karaf.features.FeatureState) StateStorage.toStringStringSetMap(org.apache.karaf.features.internal.service.StateStorage.toStringStringSetMap) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap)

Example 64 with EnumSet

use of java.util.EnumSet in project Railcraft by Railcraft.

the class ChargeManager method forConnections.

public static void forConnections(World world, BlockPos pos, BiConsumer<BlockPos, IChargeBlock.ChargeDef> action) {
    IBlockState state = WorldPlugin.getBlockState(world, pos);
    if (state.getBlock() instanceof IChargeBlock) {
        IChargeBlock block = (IChargeBlock) state.getBlock();
        IChargeBlock.ChargeDef chargeDef = block.getChargeDef(state, world, pos);
        if (chargeDef != null) {
            Map<BlockPos, EnumSet<IChargeBlock.ConnectType>> possibleConnections = chargeDef.getConnectType().getPossibleConnectionLocations(pos);
            for (Map.Entry<BlockPos, EnumSet<IChargeBlock.ConnectType>> connection : possibleConnections.entrySet()) {
                IBlockState otherState = WorldPlugin.getBlockState(world, connection.getKey());
                if (otherState.getBlock() instanceof IChargeBlock) {
                    IChargeBlock.ChargeDef other = ((IChargeBlock) otherState.getBlock()).getChargeDef(WorldPlugin.getBlockState(world, connection.getKey()), world, connection.getKey());
                    if (other != null && other.getConnectType().getPossibleConnectionLocations(connection.getKey()).get(pos).contains(chargeDef.getConnectType())) {
                        action.accept(connection.getKey(), other);
                    }
                }
            }
        }
    }
}
Also used : IBlockState(net.minecraft.block.state.IBlockState) EnumSet(java.util.EnumSet) BlockPos(net.minecraft.util.math.BlockPos) Map(java.util.Map)

Example 65 with EnumSet

use of java.util.EnumSet in project Payara by payara.

the class Utils method getScopeAwarePropagator.

/**
 * @return The in-scope instance of ContextMapPropagator so that
 * communication protocols can ask the ContextMapPropagator to handle
 * the context propagation bytes on the wire.
 */
public static ContextMapPropagator getScopeAwarePropagator() {
    return new ContextMapPropagator() {

        private WireAdapter wireAdapter = ContextBootstrap.getWireAdapter();

        private SimpleMap getMapIfItExists() {
            AccessControlledMap map = mapFinder.getMapIfItExists();
            return map == null ? null : map.simpleMap;
        }

        private SimpleMap getMapAndCreateIfNeeded() {
            return mapFinder.getMapAndCreateIfNeeded().simpleMap;
        }

        @Override
        public void sendRequest(OutputStream out, PropagationMode propagationMode) throws IOException {
            sendItems(propagationModeFilter, out, propagationMode, true);
        }

        @Override
        public void sendResponse(OutputStream out, PropagationMode propagationMode) throws IOException {
            sendItems(onewayPropagationModeFilter, out, propagationMode, false);
        }

        private void sendItems(Filter filter, OutputStream out, PropagationMode propagationMode, boolean sendLocation) throws IOException {
            ContextBootstrap.debug(MessageID.PROPAGATION_STARTED, "Outgoing");
            SimpleMap map = getMapIfItExists();
            if (map != null) {
                ContextBootstrap.debug(MessageID.USING_WIRE_ADAPTER, "Writing to", wireAdapter);
                wireAdapter.prepareToWriteTo(out);
                Iterator<Map.Entry<String, Entry>> items = map.iterator(filter, propagationMode);
                while (items.hasNext()) {
                    Map.Entry<String, Entry> mapEntry = items.next();
                    Entry entry = mapEntry.getValue();
                    Object value = entry.getValue();
                    if (value instanceof ContextLifecycle) {
                        ((ContextLifecycle) value).contextToPropagate();
                    }
                }
                items = map.iterator(filter, propagationMode);
                while (items.hasNext()) {
                    Map.Entry<String, Entry> mapEntry = items.next();
                    wireAdapter.write(mapEntry.getKey(), mapEntry.getValue());
                }
                wireAdapter.flush();
            }
            ContextBootstrap.debug(MessageID.PROPAGATION_COMPLETED, "Outgoing");
        }

        @Override
        public void receiveRequest(InputStream in) throws IOException {
            receive(in, new OriginatorFinder() {

                public boolean isOriginator(String key) {
                    return IS_NOT_ORIGINATOR;
                }
            });
        }

        private void receive(InputStream in, OriginatorFinder origFinder) throws IOException {
            ContextBootstrap.debug(MessageID.PROPAGATION_STARTED, "Ingoing");
            ContextAccessController accessController = ContextBootstrap.getContextAccessController();
            wireAdapter.prepareToReadFrom(in);
            SimpleMap map = getMapAndCreateIfNeeded();
            map.prepareToPropagate();
            for (String key = wireAdapter.readKey(); key != null; key = wireAdapter.readKey()) {
                try {
                    Entry entry = wireAdapter.readEntry();
                    if (entry == null) {
                        break;
                    } else {
                        entry.init(origFinder.isOriginator(key), accessController.isEveryoneAllowedToRead(key));
                        map.put(key, entry);
                    }
                } catch (ClassNotFoundException e) {
                    ContextBootstrap.getLoggerAdapter().log(Level.ERROR, e, MessageID.ERROR_UNABLE_TO_INSTANTIATE_CONTEXT_FROM_THE_WIRE);
                }
            }
            for (ContextLifecycle context : map.getAddedContextLifecycles()) {
                context.contextAdded();
            }
            ContextBootstrap.debug(MessageID.PROPAGATION_COMPLETED, "Ingoing");
        }

        @Override
        public void receiveResponse(InputStream in, PropagationMode mode) throws IOException {
            SimpleMap map = getMapAndCreateIfNeeded();
            final Set<String> keySet = clearPropagatedEntries(mode, map);
            ContextBootstrap.debug(MessageID.CLEARED_ENTRIES, keySet);
            receive(in, new OriginatorFinder() {

                @Override
                public boolean isOriginator(String key) {
                    return keySet.contains(key);
                }
            });
        }

        private Set<String> clearPropagatedEntries(PropagationMode mode, SimpleMap map) {
            Set<String> keySet = new HashSet<String>();
            Iterator<Map.Entry<String, Entry>> iterator = map.iterator(new Filter() {

                @Override
                public boolean keep(Map.Entry<String, Entry> mapEntry, PropagationMode mode) {
                    EnumSet<PropagationMode> modes = mapEntry.getValue().propagationModes;
                    return modes.contains(mode);
                }
            }, mode);
            while (iterator.hasNext()) {
                keySet.add(iterator.next().getKey());
                iterator.remove();
            }
            return keySet;
        }

        /**
         * Replaces the in-scope ContextMap entries with those in the srcContexts
         * that have the THREAD propagation mode.
         */
        @Override
        public void restoreThreadContexts(final AccessControlledMap srcContexts) {
            if (ContextBootstrap.IS_DEBUG) {
                ContextBootstrap.debug(MessageID.RESTORING_CONTEXTS, asList(srcContexts.entryIterator()));
            }
            if (srcContexts == null) {
                throw new IllegalArgumentException("You must specify a ContextMap.");
            }
            SimpleMap srcSimpleMap = srcContexts.simpleMap;
            if (!srcSimpleMap.map.isEmpty()) {
                SimpleMap destSimpleMap = mapFinder.getMapAndCreateIfNeeded().simpleMap;
                destSimpleMap.prepareToPropagate();
                if (destSimpleMap == srcSimpleMap) {
                    throw new IllegalArgumentException("Cannot restore a ContextMap on itself. The source and destination maps must not be the same.");
                }
                Iterator<Map.Entry<String, Entry>> iterator = srcSimpleMap.iterator(propagationModeFilter, PropagationMode.THREAD);
                while (iterator.hasNext()) {
                    Map.Entry<String, Entry> mapEntry = iterator.next();
                    destSimpleMap.put(mapEntry.getKey(), mapEntry.getValue());
                }
                for (ContextLifecycle context : destSimpleMap.getAddedContextLifecycles()) {
                    context.contextAdded();
                }
                if (ContextBootstrap.IS_DEBUG) {
                    ContextBootstrap.debug(MessageID.RESTORING_CONTEXTS, asList(mapFinder.getMapIfItExists().entryIterator()));
                }
            }
        }

        private LinkedList<String> asList(final Iterator<Map.Entry<String, Entry>> mapEntries) {
            LinkedList<String> list = new LinkedList<String>();
            while (mapEntries.hasNext()) {
                Map.Entry<String, Entry> mapEntry = mapEntries.next();
                list.add(mapEntry.getKey() + ": " + mapEntry.getValue());
            }
            return list;
        }

        @Override
        public void useWireAdapter(WireAdapter aWireAdapter) {
            wireAdapter = aWireAdapter;
        }
    };
}
Also used : ContextAccessController(org.glassfish.contextpropagation.bootstrap.ContextAccessController) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) HashSet(java.util.HashSet) ContextLifecycle(org.glassfish.contextpropagation.ContextLifecycle) InputStream(java.io.InputStream) WireAdapter(org.glassfish.contextpropagation.wireadapters.WireAdapter) EnumSet(java.util.EnumSet) LinkedList(java.util.LinkedList) ContextMapPropagator(org.glassfish.contextpropagation.spi.ContextMapPropagator) Filter(org.glassfish.contextpropagation.internal.SimpleMap.Filter) PropagationMode(org.glassfish.contextpropagation.PropagationMode) HashMap(java.util.HashMap) Map(java.util.Map) ContextMap(org.glassfish.contextpropagation.ContextMap)

Aggregations

EnumSet (java.util.EnumSet)65 Map (java.util.Map)18 Set (java.util.Set)18 ArrayList (java.util.ArrayList)13 HashMap (java.util.HashMap)13 HashSet (java.util.HashSet)12 Test (org.junit.Test)10 TreeSet (java.util.TreeSet)7 Collection (java.util.Collection)6 List (java.util.List)6 ParseUtils.unexpectedElement (org.jboss.as.controller.parsing.ParseUtils.unexpectedElement)6 LinkedHashSet (java.util.LinkedHashSet)5 TreeMap (java.util.TreeMap)5 StateStorage.toStringStringSetMap (org.apache.karaf.features.internal.service.StateStorage.toStringStringSetMap)5 PathAddress (org.jboss.as.controller.PathAddress)5 PathElement (org.jboss.as.controller.PathElement)5 ModelNode (org.jboss.dmr.ModelNode)5 IOException (java.io.IOException)4 FeatureState (org.apache.karaf.features.FeatureState)4 Collections (java.util.Collections)3