Search in sources :

Example 1 with PropagationMode

use of org.glassfish.contextpropagation.PropagationMode in project Payara by payara.

the class DefaultWireAdapter method writePropagationModes.

private void writePropagationModes(ObjectOutputStream oos, EnumSet<PropagationMode> propagationModes) throws IOException {
    int count = propagationModes.size();
    oos.writeByte(count);
    for (PropagationMode propMode : propagationModes) {
        oos.writeByte(propMode.ordinal());
    }
}
Also used : PropagationMode(org.glassfish.contextpropagation.PropagationMode)

Example 2 with PropagationMode

use of org.glassfish.contextpropagation.PropagationMode 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)

Example 3 with PropagationMode

use of org.glassfish.contextpropagation.PropagationMode in project Payara by payara.

the class DefaultWireAdapter method nextEntry.

@Override
public Entry nextEntry() throws IOException, ClassNotFoundException {
    String className = null;
    Entry.ContextType contextType = Entry.ContextType.fromOrdinal(ois.readByte());
    ContextBootstrap.debug(MessageID.READ_CONTEXT_TYPE, contextType);
    Object value = null;
    switch(contextType) {
        case BOOLEAN:
            value = ois.readBoolean();
            break;
        case BYTE:
            value = ois.readByte();
            break;
        case SHORT:
            value = ois.readShort();
            break;
        case INT:
            value = ois.readInt();
            break;
        case LONG:
            value = ois.readLong();
            break;
        case STRING:
            value = ois.readUTF();
            break;
        case ASCII_STRING:
            value = readAscii();
            break;
        case VIEW_CAPABLE:
            try {
                PrivilegedWireAdapterAccessor priviledgedCM = (PrivilegedWireAdapterAccessor) ContextMapHelper.getScopeAwareContextMap();
                priviledgedCM.createViewCapable(key, false);
                Entry entry = priviledgedCM.getAccessControlledMap(false).getEntry(key);
                ContextBootstrap.debug(MessageID.READ_VALUE, "<a ViewCapable>");
                EnumSet<PropagationMode> propModes = readPropModes();
                ContextBootstrap.debug(MessageID.READ_PROP_MODES, propModes);
                return entry;
            } catch (InsufficientCredentialException e) {
                throw new AssertionError("Wire adapter should have sufficient privileges to create a ViewCapable.");
            }
        case SERIALIZABLE:
            value = WLSContext.HELPER.readFromBytes(readBytes(ois));
            break;
        case BIGDECIMAL:
        case BIGINTEGER:
        case ATOMICINTEGER:
        case ATOMICLONG:
            value = ois.readObject();
            break;
        case CHAR:
            value = ois.readChar();
            break;
        case DOUBLE:
            value = ois.readDouble();
            break;
        case FLOAT:
            value = ois.readFloat();
            break;
        case OPAQUE:
            boolean hasClassName = ois.readBoolean();
            className = hasClassName ? readAscii() : null;
            byte[] bytes = readBytes(ois);
            SerializableContextFactory factory = WireAdapter.HELPER.findContextFactory(key, className);
            value = factory == null ? bytes : WLSContext.HELPER.readFromBytes(factory.createInstance(), bytes);
            break;
        default:
            // TODO log unexpected case
            break;
    }
    ContextBootstrap.debug(MessageID.READ_VALUE, value);
    EnumSet<PropagationMode> propModes = readPropModes();
    ContextBootstrap.debug(MessageID.READ_PROP_MODES, propModes);
    return className == null ? new Entry(value, propModes, contextType) : Entry.createOpaqueEntryInstance(value, propModes, className);
}
Also used : Entry(org.glassfish.contextpropagation.internal.Entry) SerializableContextFactory(org.glassfish.contextpropagation.SerializableContextFactory) InsufficientCredentialException(org.glassfish.contextpropagation.InsufficientCredentialException) ContextType(org.glassfish.contextpropagation.internal.Entry.ContextType) PrivilegedWireAdapterAccessor(org.glassfish.contextpropagation.internal.Utils.PrivilegedWireAdapterAccessor) PropagationMode(org.glassfish.contextpropagation.PropagationMode)

Example 4 with PropagationMode

use of org.glassfish.contextpropagation.PropagationMode in project Payara by payara.

the class WLSWireAdapter method nextEntry.

@Override
public Entry nextEntry() throws IOException {
    EnumSet<PropagationMode> propModes = toPropagationMode(ois.readInt());
    ContextBootstrap.debug(MessageID.READ_PROP_MODES, propModes);
    String className = readAscii();
    Entry.ContextType contextType = toContextType(className);
    ContextBootstrap.debug(MessageID.READ_CONTEXT_TYPE, contextType);
    Object value;
    switch(contextType) {
        case LONG:
            value = ois.readLong();
            if (key.equals(Catalog.CATALOG_META_KEY)) {
                if (wlsCatalog == null)
                    throw new IllegalStateException("wlsCatalog should have been set by readHeader.");
                wlsCatalog.setMeta((Long) value);
            }
            break;
        case STRING:
            value = ois.readUTF();
            break;
        case ASCII_STRING:
            value = readAscii();
            break;
        case SERIALIZABLE:
            byte[] bytes = new byte[ois.readInt()];
            ois.readFully(bytes);
            try {
                Carrier carrier = Carrier.fromBytes(bytes);
                value = carrier.serializable;
                if (value instanceof ViewMeta) {
                    try {
                        value = ((PrivilegedWireAdapterAccessor) ContextMapHelper.getScopeAwareContextMap()).createViewCapable(key, false);
                    } catch (InsufficientCredentialException e) {
                        throw new AssertionError("Wire adapter should have sufficient privileges to create a ViewCapable.");
                    }
                } else {
                    if (key.equals(Catalog.CATALOG_KEY)) {
                        wlsCatalog.setPosisionsFrom((Catalog) value);
                    }
                }
            } catch (ClassNotFoundException e) {
                /*
         * OPTIMIZE If the object can be extracted we should extract it but it may be better to defer that until it is accessed
         * it the object cannot be created, we need to log a message and store the raw data as of type opaque byte[]
         */
                ContextBootstrap.debug(MessageID.READING_OPAQUE_TYPE, key, bytes.length);
                value = bytes;
                contextType = ContextType.OPAQUE;
            }
            break;
        case OPAQUE:
            /*
       * In general for OPAQUE that originated on WLS, we must have that class
       * on the glassfish server or things will break down. That is also
       * a requirement on WLS so we are not worse off.
       * We also need an implementation of ContextOutput
       */
            SerializableContextFactory factory = HELPER.findContextFactory(key, className);
            if (factory == null) {
                /* In this case if will not be possible to continue reading from the 
         * stream. LATER We can try to look for the next entry, but that is problematic.
         * A brute force approach would be to read a byte, mark the stream, 
         * and attempt reading the next entry and repeat if we fail to read the entry
         * However this can be tricky because we do no know where the end of data is
         * so we can easily read past the end of context data and thus affect the
         * overall reading of the message if the protocol does not record the size
         * of the context data. We can get around this by modifying legacy
         * wls to either include a catalog or write a long context that contains
         * the length of context data.
         */
                error(MessageID.ERROR_NO_WORK_CONTEXT_FACTORY, key, className);
                return null;
            } else {
                WLSContext ctx = factory.createInstance();
                if (ctx != null) {
                    ctx.readContext(ois);
                }
                value = ctx;
            }
            break;
        default:
            throw new AssertionError("Unsupported context type, " + contextType);
    }
    ContextBootstrap.debug(MessageID.READ_VALUE, value);
    return contextType == ContextType.OPAQUE ? Entry.createOpaqueEntryInstance(value, propModes, className) : new Entry(value, propModes, contextType);
}
Also used : ContextType(org.glassfish.contextpropagation.internal.Entry.ContextType) WLSContext(org.glassfish.contextpropagation.SerializableContextFactory.WLSContext) Entry(org.glassfish.contextpropagation.internal.Entry) SerializableContextFactory(org.glassfish.contextpropagation.SerializableContextFactory) InsufficientCredentialException(org.glassfish.contextpropagation.InsufficientCredentialException) PropagationMode(org.glassfish.contextpropagation.PropagationMode)

Example 5 with PropagationMode

use of org.glassfish.contextpropagation.PropagationMode in project Payara by payara.

the class BootstrapUtils method populateMap.

public static void populateMap() throws InsufficientCredentialException {
    ContextMap wcMap = ContextMapHelper.getScopeAwareContextMap();
    wcMap.put("true", true, PropagationMode.defaultSet());
    wcMap.put("string", "string", PropagationMode.defaultSet());
    wcMap.put("one", 1L, PropagationMode.defaultSet());
    ((ContextMapAdditionalAccessors) wcMap).putAscii("ascii", "ascii", PropagationMode.defaultSet());
    ((ContextMapAdditionalAccessors) wcMap).putSerializable("serializable", new HashSet<String>(Arrays.asList("foo")), PropagationMode.defaultSet());
    wcMap.put("byte", (byte) 'b', PropagationMode.defaultSet());
    // View Capable Stuff
    // 1 - Create the factory (assumes that you have already created a ViewCapable class
    ContextViewFactory viewCapableFactory = new ContextViewFactory() {

        @Override
        public ViewCapable createInstance(View view) {
            return new MyViewCapable(view);
        }

        @Override
        public EnumSet<PropagationMode> getPropagationModes() {
            return PropagationMode.defaultSet();
        }
    };
    // 2 - Register the factory
    ContextMapHelper.registerContextFactoryForPrefixNamed("view capable", viewCapableFactory);
    // 3 - Create the ViewCapable instance
    wcMap.createViewCapable("view capable");
    assertEquals("a value", ((MyViewCapable) wcMap.get("view capable")).getValue());
    wcMap.get("ascii");
}
Also used : ContextViewFactory(org.glassfish.contextpropagation.ContextViewFactory) ContextMapAdditionalAccessors(org.glassfish.contextpropagation.internal.Utils.ContextMapAdditionalAccessors) View(org.glassfish.contextpropagation.View) PropagationMode(org.glassfish.contextpropagation.PropagationMode) ContextMap(org.glassfish.contextpropagation.ContextMap)

Aggregations

PropagationMode (org.glassfish.contextpropagation.PropagationMode)5 ContextMap (org.glassfish.contextpropagation.ContextMap)2 InsufficientCredentialException (org.glassfish.contextpropagation.InsufficientCredentialException)2 SerializableContextFactory (org.glassfish.contextpropagation.SerializableContextFactory)2 Entry (org.glassfish.contextpropagation.internal.Entry)2 ContextType (org.glassfish.contextpropagation.internal.Entry.ContextType)2 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 EnumSet (java.util.EnumSet)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 ContextLifecycle (org.glassfish.contextpropagation.ContextLifecycle)1 ContextViewFactory (org.glassfish.contextpropagation.ContextViewFactory)1 WLSContext (org.glassfish.contextpropagation.SerializableContextFactory.WLSContext)1 View (org.glassfish.contextpropagation.View)1 ContextAccessController (org.glassfish.contextpropagation.bootstrap.ContextAccessController)1 Filter (org.glassfish.contextpropagation.internal.SimpleMap.Filter)1