text:
package com.fasterxml.jackson.databind.deser;

import java.util.*;

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig;
import com.fasterxml.jackson.databind.deser.impl.*;
import com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer;
import com.fasterxml.jackson.databind.exc.InvalidDefinitionException;
import com.fasterxml.jackson.databind.introspect.*;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import com.fasterxml.jackson.databind.jsontype.impl.SubTypeValidator;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.fasterxml.jackson.databind.util.ClassUtil;
import com.fasterxml.jackson.databind.util.IgnorePropertiesUtil;
import com.fasterxml.jackson.databind.util.SimpleBeanPropertyDefinition;

/**
 * Concrete deserializer factory class that adds full Bean deserializer
 * construction logic using class introspection.
 * Note that factories specifically do not implement any form of caching:
 * aside from configuration they are stateless; caching is implemented
 * by other components.
 *

 * Instances of this class are fully immutable as all configuration is
 * done by using "fluent factories" (methods that construct new factory
 * instances with different configuration, instead of modifying instance).
 */
public class BeanDeserializerFactory
    extends BasicDeserializerFactory
    implements java.io.Serializable // since 2.1
{
    private static final long serialVersionUID = 1;

    /**
     * Signature of Throwable.initCause method.
     */
    private final static Class<?>[] INIT_CAUSE_PARAMS = new Class<?>[] { Throwable.class };

    /*
    /**********************************************************
    /* Life-cycle
    /**********************************************************
     */

    /**
     * Globally shareable thread-safe instance which has no additional custom deserializers
     * registered
     */
    public final static BeanDeserializerFactory instance = new BeanDeserializerFactory(
            new DeserializerFactoryConfig());

    public BeanDeserializerFactory(DeserializerFactoryConfig config) {
        super(config);
    }

    /**
     * Method used by module registration functionality, to construct a new bean
     * deserializer factory
     * with different configuration settings.
     */
    @Override
    public DeserializerFactory withConfig(DeserializerFactoryConfig config)
    {
        if (_factoryConfig == config) {
            return this;
        }
        /* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor;
         *    and we pretty much have to here either choose between losing subtype instance
         *    when registering additional deserializers, or losing deserializers.
         *    Instead, let's actually just throw an error if this method is called when subtype
         *    has not properly overridden this method; this to indicate problem as soon as possible.
         */
        ClassUtil.verifyMustOverride(BeanDeserializerFactory.class, this, "withConfig");
        return new BeanDeserializerFactory(config);
    }

    /*
    /**********************************************************
    /* DeserializerFactory API implementation
    /**********************************************************
     */

    /**
     * Method that {@link DeserializerCache}s call to create a new
     * deserializer for types other than Collections, Maps, arrays and
     * enums.
     */
    @SuppressWarnings("unchecked")
    @Override
    public JsonDeserializer<Object> createBeanDeserializer(DeserializationContext ctxt,
            JavaType type, BeanDescription beanDesc)
        throws JsonMappingException
    {
        final DeserializationConfig config = ctxt.getConfig();
        // First: we may also have custom overrides:
        JsonDeserializer<?> deser = _findCustomBeanDeserializer(type, config, beanDesc);
        if (deser != null) {
            // [databind#2392]
            if (_factoryConfig.hasDeserializerModifiers()) {
                for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
                    deser = mod.modifyDeserializer(ctxt.getConfig(), beanDesc, deser);
                }
            }
            return (JsonDeserializer<Object>) deser;
        }
        // One more thing to check: do we have an exception type (Throwable or its
        // sub-classes)? If so, need slightly different handling.
        if (type.isThrowable()) {
            return buildThrowableDeserializer(ctxt, type, beanDesc);
        }
        // Or, for abstract types, may have alternate means for resolution
        // (defaulting, materialization)

        // 29-Nov-2015, tatu: Also, filter out calls to primitive types, they are
        //    not something we could materialize anything for
        if (type.isAbstract() && !type.isPrimitive() && !type.isEnumType()) {
            // Let's make it possible to materialize abstract types.
            JavaType concreteType = materializeAbstractType(ctxt, type, beanDesc);
            if (concreteType != null) {
                // important: introspect actual implementation (abstract class or
                // interface doesn't have constructors, for one)
                beanDesc = config.introspect(concreteType);
                return buildBeanDeserializer(ctxt, concreteType, beanDesc);
            }
        }
        // Otherwise, may want to check handlers for standard types, from superclass:
        deser = findStdDeserializer(ctxt, type, beanDesc);
        if (deser != null) {
            return (JsonDeserializer<Object>)deser;
        }

        // Otherwise: could the class be a Bean class? If not, bail out
        if (!isPotentialBeanType(type.getRawClass())) {
            return null;
        }
        // For checks like [databind#1599]
        _validateSubType(ctxt, type, beanDesc);

        // 05-May-2020, tatu: [databind#2683] Let's actually pre-emptively catch
        //   certain types (for now, java.time.*) to give better error messages
        deser = _findUnsupportedTypeDeserializer(ctxt, type, beanDesc);
        if (deser != null) {
            return (JsonDeserializer<Object>)deser;
        }

        // Use generic bean introspection to build deserializer
        return buildBeanDeserializer(ctxt, type, beanDesc);
    }

    @Override
    public JsonDeserializer<Object> createBuilderBasedDeserializer(
            DeserializationContext ctxt, JavaType valueType, BeanDescription valueBeanDesc,
            Class<?> builderClass)
        throws JsonMappingException
    {
        // First: need a BeanDescription for builder class
        JavaType builderType;
        if (ctxt.isEnabled(MapperFeature.INFER_BUILDER_TYPE_BINDINGS)) {
            builderType = ctxt.getTypeFactory().constructParametricType(builderClass, valueType.getBindings());
        } else {
            builderType = ctxt.constructType(builderClass);
        }
        BeanDescription builderDesc = ctxt.getConfig().introspectForBuilder(builderType, valueBeanDesc);
        // 20-Aug-2020, tatu: May want to change at some point (after 2.12) to pass "valueBeanDesc"
        //    too; no urgent need at this point
        return buildBuilderBasedDeserializer(ctxt, valueType, builderDesc);
    }

    /**
     * Method called by {@link BeanDeserializerFactory} to see if there might be a standard
     * deserializer registered for given type.
     */
    protected JsonDeserializer<?> findStdDeserializer(DeserializationContext ctxt,
            JavaType type, BeanDescription beanDesc)
        throws JsonMappingException
    {
        // note: we do NOT check for custom deserializers here, caller has already
        // done that
        JsonDeserializer<?> deser = findDefaultDeserializer(ctxt, type, beanDesc);
        // Also: better ensure these are post-processable?
        if (deser != null) {
            if (_factoryConfig.hasDeserializerModifiers()) {
                for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
                    deser = mod.modifyDeserializer(ctxt.getConfig(), beanDesc, deser);
                }
            }
        }
        return deser;
    }

    /**
     * Helper method called to see if given type, otherwise to be taken as POJO type,
     * is "known but not supported" JDK type, and if so, return alternate handler
     * (deserializer).
     * Initially added to support more meaningful error messages when "Java 8 date/time"
     * support module not registered.
     *
     * @since 2.12
     */
    protected JsonDeserializer<Object> _findUnsupportedTypeDeserializer(DeserializationContext ctxt,
            JavaType type, BeanDescription beanDesc)
        throws JsonMappingException
    {
        // 05-May-2020, tatu: Should we check for possible Shape override to "POJO"?
        //   (to let users force 'serialize-as-POJO'? Or not?
        final String errorMsg = BeanUtil.checkUnsupportedType(type);
        if (errorMsg != null) {
            // 30-Sep-2020, tatu: [databind#2867] Avoid checks if there is a mix-in
            //    which likely providers a handler...
            if (ctxt.getConfig().findMixInClassFor(type.getRawClass()) == null) {
                return new UnsupportedTypeDeserializer(type, errorMsg);
            }
        }
        return null;
    }

    protected JavaType materializeAbstractType(DeserializationContext ctxt,
            JavaType type, BeanDescription beanDesc)
        throws JsonMappingException
    {
        // May have multiple resolvers, call in precedence order until one returns non-null
        for (AbstractTypeResolver r : _factoryConfig.abstractTypeResolvers()) {
            JavaType concrete = r.resolveAbstractType(ctxt.getConfig(), beanDesc);
            if (concrete != null) {
                return concrete;
            }
        }
        return null;
    }

    /*
    /**********************************************************
    /* Public construction method beyond DeserializerFactory API:
    /* can be called from outside as well as overridden by
    /* sub-classes
    /**********************************************************
     */

    /**
     * Method that is to actually build a bean deserializer instance.
     * All basic sanity checks have been done to know that what we have
     * may be a valid bean type, and that there are no default simple
     * deserializers.
     */
    @SuppressWarnings("unchecked")
    public JsonDeserializer<Object> buildBeanDeserializer(DeserializationContext ctxt,
            JavaType type, BeanDescription beanDesc)
        throws JsonMappingException
    {
        // First: check what creators we can use, if any
        ValueInstantiator valueInstantiator;
        /* 04-Jun-2015, tatu: To work around [databind#636], need to catch the
         *    issue, defer; this seems like a reasonable good place for now.
         *   Note, however, that for non-Bean types (Collections, Maps) this
         *   probably won't work and needs to be added elsewhere.
         */
        try {
            valueInstantiator = findValueInstantiator(ctxt, beanDesc);
        } catch (NoClassDefFoundError error) {
            return new ErrorThrowingDeserializer(error);
        } catch (IllegalArgumentException e0) {
            // 05-Apr-2017, tatu: Although it might appear cleaner to require collector
            //   to throw proper exception, it doesn't actually have reference to this
            //   instance so...
            throw InvalidDefinitionException.from(ctxt.getParser(),
                    ClassUtil.exceptionMessage(e0),
                   beanDesc, null)
                .withCause(e0);
        }
        BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc);
        builder.setValueInstantiator(valueInstantiator);
         // And then setters for deserializing from JSON Object
        addBeanProps(ctxt, beanDesc, builder);
        addObjectIdReader(ctxt, beanDesc, builder);

        // managed/back reference fields/setters need special handling... first part
        addBackReferenceProperties(ctxt, beanDesc, builder);
        addInjectables(ctxt, beanDesc, builder);

        final DeserializationConfig config = ctxt.getConfig();
        if (_factoryConfig.hasDeserializerModifiers()) {
            for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
                builder = mod.updateBuilder(config, beanDesc, builder);
            }
        }
        JsonDeserializer<?> deserializer;

        if (type.isAbstract() && !valueInstantiator.canInstantiate()) {
            deserializer = builder.buildAbstract();
        } else {
            deserializer = builder.build();
        }
        // may have modifier(s) that wants to modify or replace serializer we just built
        // (note that `resolve()` and `createContextual()` called later on)
        if (_factoryConfig.hasDeserializerModifiers()) {
            for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
                deserializer = mod.modifyDeserializer(config, beanDesc, deserializer);
            }
        }
        return (JsonDeserializer<Object>) deserializer;
    }

    /**
     * Method for constructing a bean deserializer that uses specified
     * intermediate Builder for binding data, and construction of the
     * value instance.
     * Note that implementation is mostly copied from the regular
     * BeanDeserializer build method.
     */
    @SuppressWarnings("unchecked")
    protected JsonDeserializer<Object> buildBuilderBasedDeserializer(
    		DeserializationContext ctxt, JavaType valueType, BeanDescription builderDesc)
        throws JsonMappingException
    {
        // Creators, anyone? (to create builder itself)
        ValueInstantiator valueInstantiator;
        try {
            valueInstantiator = findValueInstantiator(ctxt, builderDesc);
        } catch (NoClassDefFoundError error) {
            return new ErrorThrowingDeserializer(error);
        } catch (IllegalArgumentException e) {
            // 05-Apr-2017, tatu: Although it might appear cleaner to require collector
            //   to throw proper exception, it doesn't actually have reference to this
            //   instance so...
            throw InvalidDefinitionException.from(ctxt.getParser(),
                    ClassUtil.exceptionMessage(e),
                    builderDesc, null);
        }
        final DeserializationConfig config = ctxt.getConfig();
        BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, builderDesc);
        builder.setValueInstantiator(valueInstantiator);
         // And then "with methods" for deserializing from JSON Object
        addBeanProps(ctxt, builderDesc, builder);
        addObjectIdReader(ctxt, builderDesc, builder);

        // managed/back reference fields/setters need special handling... first part
        addBackReferenceProperties(ctxt, builderDesc, builder);
        addInjectables(ctxt, builderDesc, builder);

        JsonPOJOBuilder.Value builderConfig = builderDesc.findPOJOBuilderConfig();
        final String buildMethodName = (builderConfig == null) ?
                JsonPOJOBuilder.DEFAULT_BUILD_METHOD : builderConfig.buildMethodName;

        // and lastly, find build method to use:
        AnnotatedMethod buildMethod = builderDesc.findMethod(buildMethodName, null);
        if (buildMethod != null) { // note: can't yet throw error; may be given build method
            if (config.canOverrideAccessModifiers()) {
            	ClassUtil.checkAndFixAccess(buildMethod.getMember(), config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
            }
        }
        builder.setPOJOBuilder(buildMethod, builderConfig);
        // this may give us more information...
        if (_factoryConfig.hasDeserializerModifiers()) {
            for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
                builder = mod.updateBuilder(config, builderDesc, builder);
            }
        }
        JsonDeserializer<?> deserializer = builder.buildBuilderBased(
        		valueType, buildMethodName);

        // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:
        if (_factoryConfig.hasDeserializerModifiers()) {
            for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
                deserializer = mod.modifyDeserializer(config, builderDesc, deserializer);
            }
        }
        return (JsonDeserializer<Object>) deserializer;
    }

    protected void addObjectIdReader(DeserializationContext ctxt,
            BeanDescription beanDesc, BeanDeserializerBuilder builder)
        throws JsonMappingException
    {
        ObjectIdInfo objectIdInfo = beanDesc.getObjectIdInfo();
        if (objectIdInfo == null) {
            return;
        }
        Class<?> implClass = objectIdInfo.getGeneratorType();
        JavaType idType;
        SettableBeanProperty idProp;
        ObjectIdGenerator<?> gen;

        ObjectIdResolver resolver = ctxt.objectIdResolverInstance(beanDesc.getClassInfo(), objectIdInfo);

        // Just one special case: Property-based generator is trickier
        if (implClass == ObjectIdGenerators.PropertyGenerator.class) { // most special one, needs extra work
            PropertyName propName = objectIdInfo.getPropertyName();
            idProp = builder.findProperty(propName);
            if (idProp == null) {
                throw new IllegalArgumentException(String.format(
"Invalid Object Id definition for %s: cannot find property with name %s",
ClassUtil.getTypeDescription(beanDesc.getType()),
ClassUtil.name(propName)));
            }
            idType = idProp.getType();
            gen = new PropertyBasedObjectIdGenerator(objectIdInfo.getScope());
        } else {
            JavaType type = ctxt.constructType(implClass);
            idType = ctxt.getTypeFactory().findTypeParameters(type, ObjectIdGenerator.class)[0];
            idProp = null;
            gen = ctxt.objectIdGeneratorInstance(beanDesc.getClassInfo(), objectIdInfo);
        }
        // also: unlike with value deserializers, let's just resolve one we need here
        JsonDeserializer<?> deser = ctxt.findRootValueDeserializer(idType);
        builder.setObjectIdReader(ObjectIdReader.construct(idType,
                objectIdInfo.getPropertyName(), gen, deser, idProp, resolver));
    }

    @SuppressWarnings("unchecked")
    public JsonDeserializer<Object> buildThrowableDeserializer(DeserializationContext ctxt,
            JavaType type, BeanDescription beanDesc)
        throws JsonMappingException
    {
        final DeserializationConfig config = ctxt.getConfig();
        // first: construct like a regular bean deserializer...
        BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc);
        builder.setValueInstantiator(findValueInstantiator(ctxt, beanDesc));

        addBeanProps(ctxt, beanDesc, builder);
        // (and assume there won't be any back references)

        // But then let's decorate things a bit
        // Need to add "initCause" as setter for exceptions (sub-classes of Throwable).
        // 26-May-2022, tatu: [databind#3275] Looks like JDK 12 added "setCause()"
        //    which can wreak havoc, at least with NamingStrategy
        Iterator<SettableBeanProperty> it = builder.getProperties();
        while (it.hasNext()) {
            SettableBeanProperty prop = it.next();
            if ("setCause".equals(prop.getMember().getName())) {
                // For now this is allowed as we are returned "live" Iterator...
                it.remove();
                break;
            }
        }
        AnnotatedMethod am = beanDesc.findMethod("initCause", INIT_CAUSE_PARAMS);
        if (am != null) { // should never be null
            // [databind#3497]: must consider possible PropertyNamingStrategy
            String name = "cause";
            PropertyNamingStrategy pts = config.getPropertyNamingStrategy();
            if (pts != null) {
                name = pts.nameForSetterMethod(config, am, "cause");
            }
            SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(ctxt.getConfig(), am,
                    new PropertyName(name));
            SettableBeanProperty prop = constructSettableProperty(ctxt, beanDesc, propDef,
                    am.getParameterType(0));
            if (prop != null) {
                // 21-Aug-2011, tatus: We may actually have found 'cause' property
                //   to set... but let's replace it just in case, otherwise can end up with odd errors.
                builder.addOrReplaceProperty(prop, true);
            }
        }
        // update builder now that all information is in?
        if (_factoryConfig.hasDeserializerModifiers()) {
            for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
                builder = mod.updateBuilder(config, beanDesc, builder);
            }
        }
        JsonDeserializer<?> deserializer = builder.build();

        // At this point it ought to be a BeanDeserializer; if not, must assume
        // it's some other thing that can handle deserialization ok...
        if (deserializer instanceof BeanDeserializer) {
            deserializer = ThrowableDeserializer.construct(ctxt, (BeanDeserializer) deserializer);
        }

        // may have modifier(s) that wants to modify or replace serializer we just built:
        if (_factoryConfig.hasDeserializerModifiers()) {
            for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
                deserializer = mod.modifyDeserializer(config, beanDesc, deserializer);
            }
        }
        return (JsonDeserializer<Object>) deserializer;
    }

    /*
    /**********************************************************
    /* Helper methods for Bean deserializer construction
    /**********************************************************
     */

    /**
     * Overridable method that constructs a {@link BeanDeserializerBuilder}
     * which is used to accumulate information needed to create deserializer
     * instance.
     */
    protected BeanDeserializerBuilder constructBeanDeserializerBuilder(DeserializationContext ctxt,
            BeanDescription beanDesc) {
        return new BeanDeserializerBuilder(beanDesc, ctxt);
    }

    /**
     * Method called to figure out settable properties for the
     * bean deserializer to use.
     *

     * Note: designed to be overridable, and effort is made to keep interface
     * similar between versions.
     */
    protected void addBeanProps(DeserializationContext ctxt,
            BeanDescription beanDesc, BeanDeserializerBuilder builder)
        throws JsonMappingException
    {
        final boolean isConcrete = !beanDesc.getType().isAbstract();
        final SettableBeanProperty[] creatorProps = isConcrete
                ? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig())
                : null;
        final boolean hasCreatorProps = (creatorProps != null);

        // 01-May-2016, tatu: Which base type to use here gets tricky, since
        //   it may often make most sense to use general type for overrides,
        //   but what we have here may be more specific impl type. But for now
        //   just use it as is.
        JsonIgnoreProperties.Value ignorals = ctxt.getConfig()
                .getDefaultPropertyIgnorals(beanDesc.getBeanClass(),
                        beanDesc.getClassInfo());
        Set<String> ignored;
        if (ignorals != null) {
            boolean ignoreAny = ignorals.getIgnoreUnknown();
            builder.setIgnoreUnknownProperties(ignoreAny);
            // Or explicit/implicit definitions?
            ignored = ignorals.findIgnoredForDeserialization();
            for (String propName : ignored) {
                builder.addIgnorable(propName);
            }
        } else {
            ignored = Collections.emptySet();
        }
        JsonIncludeProperties.Value inclusions = ctxt.getConfig()
                .getDefaultPropertyInclusions(beanDesc.getBeanClass(),
                        beanDesc.getClassInfo());
        Set<String> included = null;
        if (inclusions != null) {
            included = inclusions.getIncluded();
            if (included != null) {
                for(String propName : included) {
                    builder.addIncludable(propName);
                }
            }
        }

        // Also, do we have a fallback "any" setter?
        AnnotatedMember anySetter = beanDesc.findAnySetterAccessor();
        if (anySetter != null) {
            builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetter));
        } else {
            // 23-Jan-2018, tatu: although [databind#1805] would suggest we should block
            //   properties regardless, for now only consider unless there's any setter...
            Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames();
            if (ignored2 != null) {
                for (String propName : ignored2) {
                    // allow ignoral of similarly named JSON property, but do not force;
                    // latter means NOT adding this to 'ignored':
                    builder.addIgnorable(propName);
                }
            }
        }
        final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)
                && ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS);

        // Ok: let's then filter out property definitions
        List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt,
                beanDesc, builder, beanDesc.findProperties(), ignored, included);
        // After which we can let custom code change the set
        if (_factoryConfig.hasDeserializerModifiers()) {
            for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
                propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);
            }
        }

        // At which point we still have all kinds of properties; not all with mutators:
        for (BeanPropertyDefinition propDef : propDefs) {
            SettableBeanProperty prop = null;

            // 18-Oct-2013, tatu: Although constructor parameters have highest precedence,
            //   we need to do linkage (as per [databind#318]), and so need to start with
            //   other types, and only then create constructor parameter, if any.
            if (propDef.hasSetter()) {
                AnnotatedMethod setter = propDef.getSetter();
                JavaType propertyType = setter.getParameterType(0);
                prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
            } else if (propDef.hasField()) {
                AnnotatedField field = propDef.getField();
                JavaType propertyType = field.getType();
                prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
            } else {
                // NOTE: specifically getter, since field was already checked above
                AnnotatedMethod getter = propDef.getGetter();
                if (getter != null) {
                    if (useGettersAsSetters && _isSetterlessType(getter.getRawType())) {
                        // 23-Jan-2018, tatu: As per [databind#1805], need to ensure we don't
                        //   accidentally sneak in getter-as-setter for `READ_ONLY` properties
                        if (builder.hasIgnorable(propDef.getName())) {
                            ;
                        } else {
                            prop = constructSetterlessProperty(ctxt, beanDesc, propDef);
                        }
                    } else if (!propDef.hasConstructorParameter()) {
                        PropertyMetadata md = propDef.getMetadata();
                        // 25-Oct-2016, tatu: If merging enabled, might not need setter.
                        //   We cannot quite support this with creator parameters; in theory
                        //   possibly, but right not not due to complexities of routing, so
                        //   just prevent
                        if (md.getMergeInfo() != null) {
                            prop = constructSetterlessProperty(ctxt, beanDesc, propDef);
                        }
                    }
                }
            }

            // 25-Sep-2014, tatu: No point in finding constructor parameters for abstract types
            //   (since they are never used anyway)
            if (hasCreatorProps && propDef.hasConstructorParameter()) {
                /* If property is passed via constructor parameter, we must
                 * handle things in special way. Not sure what is the most optimal way...
                 * for now, let's just call a (new) method in builder, which does nothing.
                 */
                // but let's call a method just to allow custom builders to be aware...
                final String name = propDef.getName();
                CreatorProperty cprop = null;

                for (SettableBeanProperty cp : creatorProps) {
                    if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {
                        cprop = (CreatorProperty) cp;
                        break;
                    }
                }
                if (cprop == null) {
                    List<String> n = new ArrayList<>();
                    for (SettableBeanProperty cp : creatorProps) {
                        n.add(cp.getName());
                    }
                    ctxt.reportBadPropertyDefinition(beanDesc, propDef,
"Could not find creator property with name %s (known Creator properties: %s)",
                            ClassUtil.name(name), n);
                    continue;
                }
                if (prop != null) {
                    cprop.setFallbackSetter(prop);
                }
                Class<?>[] views = propDef.findViews();
                if (views == null) {
                    views = beanDesc.findDefaultViews();
                }
                cprop.setViews(views);
                builder.addCreatorProperty(cprop);
                continue;
            }
            if (prop != null) {
                // one more thing before adding to builder: copy any metadata
                Class<?>[] views = propDef.findViews();
                if (views == null) {
                    views = beanDesc.findDefaultViews();
                }
                prop.setViews(views);
                builder.addProperty(prop);
            }
        }
    }

    private boolean _isSetterlessType(Class<?> rawType) {
        // May also need to consider getters
        // for Map/Collection properties; but with lowest precedence
        // should only consider Collections and Maps, for now?
        return Collection.class.isAssignableFrom(rawType)
                || Map.class.isAssignableFrom(rawType);
    }

    /**
     * Helper method called to filter out explicit ignored properties,
     * as well as properties that have "ignorable types".
     * Note that this will not remove properties that have no
     * setters.
     *
     * @deprecated in 2.12, remove from 3.0
     */
    @Deprecated
    protected List<BeanPropertyDefinition> filterBeanProps(DeserializationContext ctxt,
            BeanDescription beanDesc, BeanDeserializerBuilder builder,
            List<BeanPropertyDefinition> propDefsIn,
            Set<String> ignored)
        throws JsonMappingException
    {
        return filterBeanProps(ctxt, beanDesc, builder, propDefsIn, ignored, null);
    }

    /**
     * Helper method called to filter out explicit ignored properties,
     * as well as properties that have "ignorable types".
     * Note that this will not remove properties that have no
     * setters.
     *
     * @since 2.12
     */
    protected List<BeanPropertyDefinition> filterBeanProps(DeserializationContext ctxt,
                                                           BeanDescription beanDesc, BeanDeserializerBuilder builder,
                                                           List<BeanPropertyDefinition> propDefsIn,
                                                           Set<String> ignored,
                                                           Set<String> included)
    {
        ArrayList<BeanPropertyDefinition> result = new ArrayList<BeanPropertyDefinition>(
                Math.max(4, propDefsIn.size()));
        HashMap<Class<?>,Boolean> ignoredTypes = new HashMap<Class<?>,Boolean>();
        // These are all valid setters, but we do need to introspect bit more
        for (BeanPropertyDefinition property : propDefsIn) {
            String name = property.getName();
            // explicit ignoral using @JsonIgnoreProperties of @JsonIncludeProperties needs to block entries
            if (IgnorePropertiesUtil.shouldIgnore(name, ignored, included)) {
                continue;
            }
            if (!property.hasConstructorParameter()) { // never skip constructor params
                Class<?> rawPropertyType = property.getRawPrimaryType();
                // Some types are declared as ignorable as well
                if ((rawPropertyType != null)
                        && isIgnorableType(ctxt.getConfig(), property, rawPropertyType, ignoredTypes)) {
                    // important: make ignorable, to avoid errors if value is actually seen
                    builder.addIgnorable(name);
                    continue;
                }
            }
            result.add(property);
        }
        return result;
    }

    /**
     * Method that will find if bean has any managed- or back-reference properties,
     * and if so add them to bean, to be linked during resolution phase.
     *
     * @since 2.9
     */
    protected void addBackReferenceProperties(DeserializationContext ctxt,
            BeanDescription beanDesc, BeanDeserializerBuilder builder)
        throws JsonMappingException
    {
        // and then back references, not necessarily found as regular properties
        List<BeanPropertyDefinition> refProps = beanDesc.findBackReferences();
        if (refProps != null) {
            for (BeanPropertyDefinition refProp : refProps) {
                /*
                AnnotatedMember m = refProp.getMutator();
                JavaType type;
                if (m instanceof AnnotatedMethod) {
                    type = ((AnnotatedMethod) m).getParameterType(0);
                } else {
                    type = m.getType();
                    // 30-Mar-2017, tatu: Unfortunately it is not yet possible to make back-refs
                    //    work through constructors; but let's at least indicate the issue for now
                    if (m instanceof AnnotatedParameter) {
                        ctxt.reportBadTypeDefinition(beanDesc,
"Cannot bind back reference using Creator parameter (reference %s, parameter index #%d)",
ClassUtil.name(name), ((AnnotatedParameter) m).getIndex());
                    }
                }
                */
                String refName = refProp.findReferenceName();
                builder.addBackReferenceProperty(refName, constructSettableProperty(ctxt,
                        beanDesc, refProp, refProp.getPrimaryType()));
            }
        }
    }

    @Deprecated // since 2.9 (rename)
    protected void addReferenceProperties(DeserializationContext ctxt,
            BeanDescription beanDesc, BeanDeserializerBuilder builder)
        throws JsonMappingException
    {
        addBackReferenceProperties(ctxt, beanDesc, builder);
    }

    /**
     * Method called locate all members used for value injection (if any),
     * constructor {@link com.fasterxml.jackson.databind.deser.impl.ValueInjector} instances, and add them to builder.
     */
    protected void addInjectables(DeserializationContext ctxt,
            BeanDescription beanDesc, BeanDeserializerBuilder builder)
        throws JsonMappingException
    {
        Map<Object, AnnotatedMember> raw = beanDesc.findInjectables();
        if (raw != null) {
            for (Map.Entry<Object, AnnotatedMember> entry : raw.entrySet()) {
                AnnotatedMember m = entry.getValue();
                builder.addInjectable(PropertyName.construct(m.getName()),
                        m.getType(),
                        beanDesc.getClassAnnotations(), m, entry.getKey());
            }
        }
    }

    /**
     * Method called to construct fallback {@link SettableAnyProperty}
     * for handling unknown bean properties, given a method that
     * has been designated as such setter.
     *
     * @param mutator Either 2-argument method (setter, with key and value), or Field
     *     that contains Map; either way accessor used for passing "any values"
     */
    @SuppressWarnings("unchecked")
    protected SettableAnyProperty constructAnySetter(DeserializationContext ctxt,
            BeanDescription beanDesc, AnnotatedMember mutator)
        throws JsonMappingException
    {
        //find the java type based on the annotated setter method or setter field
        BeanProperty prop;
        JavaType keyType;
        JavaType valueType;
        final boolean isField = mutator instanceof AnnotatedField;

        if (mutator instanceof AnnotatedMethod) {
            // we know it's a 2-arg method, second arg is the value
            AnnotatedMethod am = (AnnotatedMethod) mutator;
            keyType = am.getParameterType(0);
            valueType = am.getParameterType(1);
            valueType = resolveMemberAndTypeAnnotations(ctxt, mutator, valueType);
            prop = new BeanProperty.Std(PropertyName.construct(mutator.getName()),
                    valueType, null, mutator,
                    PropertyMetadata.STD_OPTIONAL);

        } else if (isField) {
            AnnotatedField af = (AnnotatedField) mutator;
            // get the type from the content type of the map object
            JavaType fieldType = af.getType();
            // 31-Jul-2022, tatu: Not just Maps any more but also JsonNode, so:
            if (fieldType.isMapLikeType()) {
                fieldType = resolveMemberAndTypeAnnotations(ctxt, mutator, fieldType);
                keyType = fieldType.getKeyType();
                valueType = fieldType.getContentType();
                prop = new BeanProperty.Std(PropertyName.construct(mutator.getName()),
                        fieldType, null, mutator, PropertyMetadata.STD_OPTIONAL);
            } else if (fieldType.hasRawClass(JsonNode.class)
                    || fieldType.hasRawClass(ObjectNode.class)) {
                fieldType = resolveMemberAndTypeAnnotations(ctxt, mutator, fieldType);
                // Deserialize is individual values of ObjectNode, not full ObjectNode, so:
                valueType = ctxt.constructType(JsonNode.class);
                prop = new BeanProperty.Std(PropertyName.construct(mutator.getName()),
                        fieldType, null, mutator, PropertyMetadata.STD_OPTIONAL);

                // Unlike with more complicated types, here we do not allow any annotation
                // overrides etc but instead short-cut handling:
                return SettableAnyProperty.constructForJsonNodeField(ctxt,
                        prop, mutator, valueType,
                        ctxt.findRootValueDeserializer(valueType));
            } else {
                return ctxt.reportBadDefinition(beanDesc.getType(), String.format(
                        "Unsupported type for any-setter: %s -- only support `Map`s, `JsonNode` and `ObjectNode` ",
                        ClassUtil.getTypeDescription(fieldType)));
            }
        } else {
            return ctxt.reportBadDefinition(beanDesc.getType(), String.format(
                    "Unrecognized mutator type for any-setter: %s",
                    ClassUtil.nameOf(mutator.getClass())));
        }
        // First: see if there are explicitly specified
        // and then possible direct deserializer override on accessor
        KeyDeserializer keyDeser = findKeyDeserializerFromAnnotation(ctxt, mutator);
        if (keyDeser == null) {
            keyDeser = keyType.getValueHandler();
        }
        if (keyDeser == null) {
            keyDeser = ctxt.findKeyDeserializer(keyType, prop);
        } else {
            if (keyDeser instanceof ContextualKeyDeserializer) {
                keyDeser = ((ContextualKeyDeserializer) keyDeser)
                        .createContextual(ctxt, prop);
            }
        }
        JsonDeserializer<Object> deser = findContentDeserializerFromAnnotation(ctxt, mutator);
        if (deser == null) {
            deser = valueType.getValueHandler();
        }
        if (deser != null) {
            // As per [databind#462] need to ensure we contextualize deserializer before passing it on
            deser = (JsonDeserializer<Object>) ctxt.handlePrimaryContextualization(deser, prop, valueType);
        }
        TypeDeserializer typeDeser = valueType.getTypeHandler();
        if (isField) {
            return SettableAnyProperty.constructForMapField(ctxt,
                    prop, mutator, valueType, keyDeser, deser, typeDeser);
        }
        return SettableAnyProperty.constructForMethod(ctxt,
                prop, mutator, valueType, keyDeser, deser, typeDeser);
    }

    /**
     * Method that will construct a regular bean property setter using
     * the given setter method.
     *
     * @return Property constructed, if any; or null to indicate that
     *   there should be no property based on given definitions.
     */
    protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt,
            BeanDescription beanDesc, BeanPropertyDefinition propDef,
            JavaType propType0)
        throws JsonMappingException
    {
        // need to ensure method is callable (for non-public)
        AnnotatedMember mutator = propDef.getNonConstructorMutator();
        // 08-Sep-2016, tatu: issues like [databind#1342] suggest something fishy
        //   going on; add sanity checks to try to pin down actual problem...
        //   Possibly passing creator parameter?
        if (mutator == null) {
            ctxt.reportBadPropertyDefinition(beanDesc, propDef, "No non-constructor mutator available");
        }
        JavaType type = resolveMemberAndTypeAnnotations(ctxt, mutator, propType0);
        // Does the Method specify the deserializer to use? If so, let's use it.
        TypeDeserializer typeDeser = type.getTypeHandler();
        SettableBeanProperty prop;
        if (mutator instanceof AnnotatedMethod) {
            prop = new MethodProperty(propDef, type, typeDeser,
                    beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator);
        } else {
            // 08-Sep-2016, tatu: wonder if we should verify it is `AnnotatedField` to be safe?
            prop = new FieldProperty(propDef, type, typeDeser,
                    beanDesc.getClassAnnotations(), (AnnotatedField) mutator);
        }
        JsonDeserializer<?> deser = findDeserializerFromAnnotation(ctxt, mutator);
        if (deser == null) {
            deser = type.getValueHandler();
        }
        if (deser != null) {
            deser = ctxt.handlePrimaryContextualization(deser, prop, type);
            prop = prop.withValueDeserializer(deser);
        }
        // need to retain name of managed forward references:
        AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType();
        if (ref != null && ref.isManagedReference()) {
            prop.setManagedReferenceName(ref.getName());
        }
        ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo();
        if (objectIdInfo != null){
            prop.setObjectIdInfo(objectIdInfo);
        }
        return prop;
    }

    /**
     * Method that will construct a regular bean property setter using
     * the given setter method.
     */
    protected SettableBeanProperty constructSetterlessProperty(DeserializationContext ctxt,
            BeanDescription beanDesc, BeanPropertyDefinition propDef)
        throws JsonMappingException
    {
        final AnnotatedMethod getter = propDef.getGetter();
        JavaType type = resolveMemberAndTypeAnnotations(ctxt, getter, getter.getType());
        TypeDeserializer typeDeser = type.getTypeHandler();
        SettableBeanProperty prop = new SetterlessProperty(propDef, type, typeDeser,
                beanDesc.getClassAnnotations(), getter);
        JsonDeserializer<?> deser = findDeserializerFromAnnotation(ctxt, getter);
        if (deser == null) {
            deser = type.getValueHandler();
        }
        if (deser != null) {
            deser = ctxt.handlePrimaryContextualization(deser, prop, type);
            prop = prop.withValueDeserializer(deser);
        }
        return prop;
    }

    /*
    /**********************************************************
    /* Helper methods for Bean deserializer, other
    /**********************************************************
     */

    /**
     * Helper method used to skip processing for types that we know
     * cannot be (i.e. are never consider to be) beans:
     * things like primitives, Arrays, Enums, and proxy types.
     *

     * Note that usually we shouldn't really be getting these sort of
     * types anyway; but better safe than sorry.
     */
    protected boolean isPotentialBeanType(Class<?> type)
    {
        String typeStr = ClassUtil.canBeABeanType(type);
        if (typeStr != null) {
            throw new IllegalArgumentException("Cannot deserialize Class "+type.getName()+" (of type "+typeStr+") as a Bean");
        }
        if (ClassUtil.isProxyType(type)) {
            throw new IllegalArgumentException("Cannot deserialize Proxy class "+type.getName()+" as a Bean");
        }
        // also: can't deserialize some local classes: static are ok; in-method not;
        // other non-static inner classes are ok
        typeStr = ClassUtil.isLocalType(type, true);
        if (typeStr != null) {
            throw new IllegalArgumentException("Cannot deserialize Class "+type.getName()+" (of type "+typeStr+") as a Bean");
        }
        return true;
    }

    /**
     * Helper method that will check whether given raw type is marked as always ignorable
     * (for purpose of ignoring properties with type)
     */
    protected boolean isIgnorableType(DeserializationConfig config, BeanPropertyDefinition propDef,
            Class<?> type, Map<Class<?>,Boolean> ignoredTypes)
    {
        Boolean status = ignoredTypes.get(type);
        if (status != null) {
            return status.booleanValue();
        }
        // 22-Oct-2016, tatu: Slight check to skip primitives, String
        if ((type == String.class) || type.isPrimitive()) {
            status = Boolean.FALSE;
        } else {
            // 21-Apr-2016, tatu: For 2.8, can specify config overrides
            status = config.getConfigOverride(type).getIsIgnoredType();
            if (status == null) {
                BeanDescription desc = config.introspectClassAnnotations(type);
                status = config.getAnnotationIntrospector().isIgnorableType(desc.getClassInfo());
                // We default to 'false', i.e. not ignorable
                if (status == null) {
                    status = Boolean.FALSE;
                }
            }
        }
        ignoredTypes.put(type, status);
        return status.booleanValue();
    }

    /**
     * @since 2.8.11
     */
    protected void _validateSubType(DeserializationContext ctxt, JavaType type,
            BeanDescription beanDesc)
        throws JsonMappingException
    {
        SubTypeValidator.instance().validateSubType(ctxt, type, beanDesc);
    }
}


text:
import * as ts from 'typescript';
import { FileSystem } from '../file-system';
declare module 'typescript' {
    interface FileSystemEntries {
        readonly files: readonly string[];
        readonly directories: readonly string[];
    }
    const matchFiles: undefined | ((path: string, extensions: readonly string[] | undefined, excludes: readonly string[] | undefined, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string, directoryExists: (path: string) => boolean) => string[]);
}
/**
 * Implementation of a TypeScript parse config host that relies fully on
 * a given virtual file system.
 */
export declare class FileSystemHost implements ts.ParseConfigHost {
    private _fileSystem;
    useCaseSensitiveFileNames: boolean;
    constructor(_fileSystem: FileSystem);
    fileExists(path: string): boolean;
    readFile(path: string): string | undefined;
    readDirectory(rootDir: string, extensions: string[], excludes: string[] | undefined, includes: string[], depth?: number): string[];
    private _getFileSystemEntries;
}
/**
 * Creates a TypeScript compiler host that fully relies fully on the given
 * virtual file system. i.e. no interactions with the working directory.
 */
export declare function createFileSystemCompilerHost(options: ts.CompilerOptions, fileSystem: FileSystem): ts.CompilerHost;
/** Creates a format diagnostic host that works with the given file system. */
export declare function createFormatDiagnosticHost(fileSystem: FileSystem): ts.FormatDiagnosticsHost;

redpajama_set_name: RedPajamaGithub


text:
package com.evolveum.midpoint.testing.model.client.sample;

import com.evolveum.midpoint.model.client.ModelClientUtil;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ExecuteScriptsOptionsType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaListType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaOperationListType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.OutputFormatType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.SingleScriptOutputType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ModelExecuteOptionsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectDeltaOperationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType;
import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultMessage;
import com.evolveum.midpoint.xml.ns._public.model.model_3.ExecuteChangesType;
import com.evolveum.midpoint.xml.ns._public.model.model_3.ExecuteScriptsResponseType;
import com.evolveum.midpoint.xml.ns._public.model.model_3.ExecuteScriptsType;
import com.evolveum.midpoint.xml.ns._public.model.model_3.ModelPortType;
import com.evolveum.midpoint.xml.ns._public.model.model_3.ModelService;
import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType;
import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.io.IOUtils;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.handler.WSHandlerConstants;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author mederly
 *
 */
public class Upload {

	// Configuration
	public static final String ADM_USERNAME = "administrator";
	public static final String ADM_PASSWORD = "5ecr3t";
    private static final String DEFAULT_ENDPOINT_URL = "http://localhost:8080/midpoint/model/model-3";

    private static final String OPT_HELP = "h";
    public static final String OPT_FILE_TO_UPLOAD = "f";
    public static final String OPT_DIR_TO_UPLOAD = "d";
    public static final String OPT_URL = "url";
    public static final String OPT_USER = "u";
    public static final String OPT_PASSWORD = "p";
    public static final String OPT_FILE_FOR_RESULT = "fr";
    public static final String OPT_HIDE_RESULT = "hr";
    public static final String OPT_SHOW_RESULT = "sr";

    private static boolean error = false;               // TODO implement seriously

	public static void main(String[] args) {
		try {

            Options options = new Options();
            options.addOption(OPT_HELP, "help", false, "Print this help information");
            options.addOption(OPT_FILE_TO_UPLOAD, "file", true, "File to be uploaded (XML for the moment)");
            options.addOption(OPT_DIR_TO_UPLOAD, "dir", true, "Whole directory to be uploaded (XML files only for the moment)");
            options.addOption(OPT_URL, true, "Endpoint URL (default: " + DEFAULT_ENDPOINT_URL + ")");
            options.addOption(OPT_USER, "user", true, "User name (default: " + ADM_USERNAME + ")");
            options.addOption(OPT_PASSWORD, "password", true, "Password");
            options.addOption(OPT_FILE_FOR_RESULT, "file-for-result", true, "Name of the file to write operation result into");
            options.addOption(OPT_HIDE_RESULT, "hide-result", false, "Don't display detailed operation result (default: showing if not SUCCESS)");
            options.addOption(OPT_SHOW_RESULT, "show-result", false, "Always show detailed operation result (default: showing if not SUCCESS)");
            CommandLineParser parser = new GnuParser();
            CommandLine cmdline = parser.parse(options, args);

            if (cmdline.hasOption(OPT_HELP) || (!cmdline.hasOption(OPT_FILE_TO_UPLOAD) && !cmdline.hasOption(OPT_DIR_TO_UPLOAD))) {
                HelpFormatter helpFormatter = new HelpFormatter();
                helpFormatter.printHelp("upload", options);
                System.out.println("\nNote that currently it is possible to upload only one object per file (i.e. no <objects> tag), and the " +
                        "file must be written using fully specified XML namespaces (i.e. namespace-guessing algorithm allowing to write data " +
                        "without namespaces is not available).");
                System.exit(-1);
            }

            System.out.println("=================================================================");

            ModelPortType modelPort = createModelPort(cmdline);
            if (cmdline.hasOption(OPT_FILE_TO_UPLOAD)) {
                uploadFile(new File(cmdline.getOptionValue(OPT_FILE_TO_UPLOAD)), cmdline, modelPort);
            }
            if (cmdline.hasOption(OPT_DIR_TO_UPLOAD)) {
                uploadDir(cmdline.getOptionValue(OPT_DIR_TO_UPLOAD), cmdline, modelPort);
            }

        } catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}

        if (error) {
            System.exit(-1);
        }
	}

    private static void uploadDir(String dirname, CommandLine cmdline, ModelPortType modelPort) {
        File[] files = new File(dirname).listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.toUpperCase().endsWith(".XML");
            }
        });
        for (File file : files) {
            uploadFile(file, cmdline, modelPort);
        }
    }

    private static void uploadFile(File file, CommandLine cmdline, ModelPortType modelPort) {
        System.out.println("Uploading file " + file);
        Object content;
        try {
            content = unmarshalFile(file);
        } catch (JAXBException|FileNotFoundException e) {
            System.err.println("Cannot read " + file + ": " + e.getMessage());
            e.printStackTrace();
            error = true;
            return;
        }
        if (content == null) {
            System.err.println("Nothing to be uploaded.");
            error = true;
            return;
        }
        if (!(content instanceof ObjectType)) {
            System.err.println("Expected an ObjectType to be uploaded; found " + content.getClass());
            error = true;
            return;
        }

        ObjectType objectType = (ObjectType) content;
        ObjectDeltaType objectDeltaType = new ObjectDeltaType();
        objectDeltaType.setChangeType(ChangeTypeType.ADD);
        objectDeltaType.setObjectType(ModelClientUtil.getTypeQName(objectType.getClass()));
        objectDeltaType.setObjectToAdd(objectType);

        ObjectDeltaListType objectDeltaListType = new ObjectDeltaListType();
        objectDeltaListType.getDelta().add(objectDeltaType);

        ModelExecuteOptionsType optionsType = new ModelExecuteOptionsType();
        optionsType.setIsImport(true);
        optionsType.setReevaluateSearchFilters(true);
        optionsType.setRaw(true);
        optionsType.setOverwrite(true);

        ExecuteChangesType executeChangesType = new ExecuteChangesType();
        executeChangesType.setDeltaList(objectDeltaListType);
        executeChangesType.setOptions(optionsType);

        ObjectDeltaOperationListType response;
        try {
            response = modelPort.executeChanges(objectDeltaListType, optionsType);
        } catch (Exception e) {
            System.err.println("Got exception when trying to execute the changes " + e.getMessage());
            error = true;
            return;
        }

        System.out.println("-----------------------------------------------------------------");

        if (response == null) {
            System.err.println("Unexpected empty response");
            error = true;
            return;
        }
        OperationResultType overallResult = new OperationResultType();
        boolean allSuccess = true;
        for (ObjectDeltaOperationType objectDeltaOperation : response.getDeltaOperation()) {
            if (objectDeltaOperation.getObjectDelta() != null) {
                ObjectDeltaType delta = objectDeltaOperation.getObjectDelta();
                System.out.print(delta.getChangeType() + " delta with OID " + delta.getOid() + " ");
            }
            OperationResultType resultType = objectDeltaOperation.getExecutionResult();
            System.out.println("resulted in " + getResultStatus(resultType));
            if (resultType == null || resultType.getStatus() != OperationResultStatusType.SUCCESS) {
                allSuccess = false;
                error = true;
            }
            overallResult.getPartialResults().add(resultType);
        }

        if (!cmdline.hasOption(OPT_HIDE_RESULT) && (cmdline.hasOption(OPT_SHOW_RESULT) || !allSuccess)) {
            System.out.println("\n\n" + marshalResult(overallResult));
        }
        if (cmdline.hasOption(OPT_FILE_FOR_RESULT)) {
            String filename = cmdline.getOptionValue(OPT_FILE_FOR_RESULT);
            try {
                FileWriter fileWriter = new FileWriter(filename, true);
                IOUtils.write(marshalResult(overallResult), fileWriter);
            } catch (IOException e) {
                System.err.println("Couldn't write operation result to file " + filename + ": " + e.getMessage());
                e.printStackTrace();
                error = true;
            }
        }

    }

    private static String getResultStatus(OperationResultType result) {
        if (result == null) {
            return "(null)";
        } else {
            return result.getStatus() + (result.getMessage() != null ? (": " + result.getMessage()) : "");
        }
    }

    private static String marshalResult(OperationResultType result) {
        if (result == null) {
            return "";
        } else {
            try {
                return marshalObject(new JAXBElement<>(new QName("result"), OperationResultType.class, result));
            } catch (JAXBException|FileNotFoundException e) {
                error = true;
                return("Couldn't marshall result: " + e.getMessage());
            }
        }
    }

    private static JAXBContext jaxbContext = null;

    private static JAXBContext getJaxbContext() throws JAXBException {
        if (jaxbContext == null) {
            jaxbContext = ModelClientUtil.instantiateJaxbContext();
        }
        return jaxbContext;
    }

    private static String marshalObject(Object object) throws JAXBException, FileNotFoundException {
        JAXBContext jc = getJaxbContext();
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        StringWriter sw = new StringWriter();
        marshaller.marshal(object, sw);
        return sw.toString();
    }

    private static Object unmarshalFile(File file) throws JAXBException, FileNotFoundException {
        JAXBContext jc = ModelClientUtil.instantiateJaxbContext();
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        Object o = unmarshaller.unmarshal(new FileInputStream(file));
        if (o instanceof JAXBElement) {
            return ((JAXBElement) o).getValue();
        } else {
            return o;
        }
    }

    public static ModelPortType createModelPort(CommandLine cmdLine) {
		String endpointUrl = cmdLine.getOptionValue(OPT_URL, DEFAULT_ENDPOINT_URL);
        String user = cmdLine.getOptionValue(OPT_USER, ADM_USERNAME);
		ClientPasswordHandler.setPassword(cmdLine.getOptionValue(OPT_PASSWORD, ADM_PASSWORD));
		System.out.println("Endpoint URL: " + endpointUrl);

		ModelService modelService = new ModelService();
		ModelPortType modelPort = modelService.getModelPort();
		BindingProvider bp = (BindingProvider)modelPort;
		Map<String, Object> requestContext = bp.getRequestContext();
		requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointUrl);

		org.apache.cxf.endpoint.Client client = ClientProxy.getClient(modelPort);
		org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint();

		Map<String,Object> outProps = new HashMap<>();

		outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
		outProps.put(WSHandlerConstants.USER, user);
		outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST);
		outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName());

		WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);
		cxfEndpoint.getOutInterceptors().add(wssOut);

		return modelPort;
	}

}


text:
{
  ("use strict");

  Object.defineProperty(_exports, "__esModule", {
    value: true
  });
  _exports.default = void 0;
  var a = 1;
  _exports.default = a;
}


text:
<!doctype html>
<title>TextTrack.mode</title>


text:
var MAX_POST_DESC_LENGTH = 140;

marked.setOptions({
  highlight: function (code) {
    return require('highlight.js').highlightAuto(code).value;
  }
});

var csideHelp = {
  "current" : "home.html",
  "history" : ["home.html"],
  "document" : document,
  "breadcrumbs" : [
    {
      "title": "Home",
      "url": "home.html"
    }
  ],
  "busy": false,
  "extern": /^(https?|mailto):.+$/
}

String.prototype.capitalizeFirstLetter = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}
/* don't allow CSIDE control links in standalone documentation */
function CSIDE(func) {
  if ((typeof parent != 'undefined') && (typeof parent.cside != 'undefined')) {
    func();
  }
}

function blinkElement(selector) {
  CSIDE(function() {
    if (parent.$(selector) && !parent.$(selector).hasClass("pulse")) {
      parent.$(selector).addClass("pulse");
      setTimeout(function() {
        parent.$(selector).removeClass("pulse");
      }, 3000);
    }
  });
}

<!-- JQUERY -->
csideHelp.handleLink = function(e) {
  e.preventDefault();
  if (csideHelp.busy)
    return;
  csideHelp.busy = true;
  if (($(this).attr('rel') == "anchor") || ($(this).attr('rel') == "cside")) {
    csideHelp.busy = false;
    return;
  }
  if (csideHelp.extern.test($(this).attr('href')) && $(this).attr("rel") != "source") {
    parent.window.usingNode ? parent.window.gui.Shell.openExternal($(this).attr("href")) : parent.window.open($(this).attr("href"));
    csideHelp.busy = false;
    return;
  }
  var linkEle = $(this);
  if (linkEle.hasClass("breadcrumb")) {
    var breadcrumbIndex = $(linkEle).data('index');
    var popCount = (csideHelp.breadcrumbs.length - (breadcrumbIndex + 1));
    for (; popCount > 0; popCount--) {
      csideHelp.history.pop();
      csideHelp.breadcrumbs.pop();
    }
  }
  else {
    var bc = {};
    var newPage = true;
    bc.title = $(this).attr("title") || '???';
    bc.url = $(this).attr("href");
    /* prevent duplicate entries */
    for (var i  = 0; i < csideHelp.breadcrumbs.length; i++) {
      if (bc.url === csideHelp.breadcrumbs[i].url) {
        var newLength = (csideHelp.breadcrumbs.length - (i + 1));
        newPage = false;
        for (; newLength > 0; newLength--) {
          csideHelp.history.pop();
          csideHelp.breadcrumbs.pop();
        }
        break;
      }
    }
    if (newPage) {
      csideHelp.breadcrumbs.push(bc);
      csideHelp.history.push($(this).attr('href'));
    }
  }
  csideHelp.drawPage(linkEle.attr("href"));
  return false;
}

csideHelp.drawPage = function(url) {
  scrollTo(0, 0);
  csideHelp.redrawBreadcrumbs();
  $('#content').animate({opacity: 0}, 250, function() {
    $.get(url)
      .done(function(data) {
        var extension = url.substring(url.lastIndexOf("."), url.length);
        if (extension === ".md") {
          $("#content").html(marked(data));
        }
        else if (extension === ".xml") {
          $("#content").html("");
          document.getElementById("content").appendChild(parseXmlContent(data));
        }
        else {
          $("#content").html(data);
        }
        $('body a').attr("draggable", false); // disallow link 'drag'
      })
      .fail(function() {
        $("#content").load( "404.html", function( response, status, xhr ) {
          $('#content').animate({opacity: 1}, 250);
        });
        return;
      })
      .always(function() {
        csideHelp.busy = false;
        csideHelp.current = url;
        $('#content').animate({opacity: 1}, 250);
      })
  });
}

csideHelp.redrawBreadcrumbs = function() {

  // if we're getting busy remove the oldest page (that isn't the 'home' page)
  if (csideHelp.breadcrumbs.length > 5)
    csideHelp.breadcrumbs.splice(1, 1);

  // don't show bottom breadcrumbs on home page
  if (csideHelp.breadcrumbs.length < 2)
    $('.breadcrumbs').last().parent().fadeOut();
  else
    $('.breadcrumbs').last().parent().fadeIn();

  $('.breadcrumbs').html("");
  for (var i = 0; i < csideHelp.breadcrumbs.length; i++) {
    if ((i + 1) == csideHelp.breadcrumbs.length) {
      var ele = $('<span>');
    }
    else {
      var ele = $('<a>');
      ele.attr('href', csideHelp.breadcrumbs[i].url);
      ele.attr('title', csideHelp.breadcrumbs[i].title);
    }
    ele.text(csideHelp.breadcrumbs[i].title.capitalizeFirstLetter());
    ele.addClass('breadcrumb');
    ele.data('index', i);
    ele.appendTo('.breadcrumbs');
  }
}

/* ------------ W E B S I T E - N E W S - F E E D ------------ */
function parseXmlContent(data) {
  var container = document.createElement("ul");
  container.className = "feed";
  var header = document.createElement("h2");
  header.innerHTML = "News & Updates";
  container.appendChild(header);
  $(data).find("entry").each(function () { // or "item" or whatever suits your feed

    // construct components
    var listItem = document.createElement("li");
      var title = document.createElement("h3");
        var dDate = new Date($(this).find("published").text());
          title.innerHTML = $(this).find("title").text() + " - " + dDate.getDay() + "/" + dDate.getMonth() + "/" + dDate.getFullYear();
      var desc = document.createElement("p");
        desc.innerHTML = $(this).find("content").text().substring(0, MAX_POST_DESC_LENGTH) + "...";
      var link = document.createElement("a");
        link.href = $(this).find("id").text();
        link.innerHTML = "Read more";

    // append together
    listItem.appendChild(title);
    desc.appendChild(link);
    listItem.appendChild(desc);
    container.appendChild(listItem);
  });

  return container;
}


text:
var radio_value=0;
  		/*get the radio button value*/
  		$('input[name="tooling_type"]').click(function(){
  			var radio_value = $('input[name=tooling_type]:checked').val();
  			console.log(radio_value);
  		});


text:
using namespace std;

#define SH_MRT "sh_mrt"
#define SH_DRAW "sh_draw"

class MrtRenderer : public BasicRenderer {
private:
	GLuint mMrtFbo;
	GLuint mRenderBuffer;

public:
	MrtRenderer() :
			BasicRenderer(),
			mMrtFbo(0),
			mRenderBuffer(0) {}

	virtual ~MrtRenderer() {}

	void InitFbo(GLuint *texIds) {
		glGenRenderbuffers(1, &mRenderBuffer);
		check_gl_error("glGenRenderbuffers");
		glBindRenderbuffer(GL_RENDERBUFFER, mRenderBuffer);
		check_gl_error("glBindRenderbuffer");
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, mWidth, mHeight);
		check_gl_error("glRenderbufferStorage");

		glGenFramebuffers(1, &mMrtFbo);
		check_gl_error("glGenFramebuffers");

		glBindFramebuffer(GL_FRAMEBUFFER, mMrtFbo);
		check_gl_error("glBindFramebuffer");

		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mRenderBuffer);

		for (unsigned int i = 0; i < 4; i++) {
			glBindTexture(GL_TEXTURE_2D, texIds[i]);
			glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
								   GL_COLOR_ATTACHMENT0 + i,
								   GL_TEXTURE_2D, texIds[i], 0);
			glBindTexture(GL_TEXTURE_2D, 0);
			check_gl_error("glFramebufferTexture2D");

		}
		LOGI("texid [%d, %d, %d, %d]", texIds[0], texIds[1], texIds[2], texIds[3]);

		GLenum DrawBuffers[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3};
		glDrawBuffers(4, DrawBuffers);

		// Check FBO is ready to draw
		if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
			LOGE("FrameBufferObject is not complete!");
		}

		glBindRenderbuffer(GL_RENDERBUFFER, 0);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);

	}

	virtual void RenderFrame() {
		ComputeTick();

		glBindFramebuffer(GL_FRAMEBUFFER, mMrtFbo);
		glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
		Shader_Mgr.DrawObjects(SH_MRT);

		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
		glDisable(GL_CULL_FACE);
		Shader_Mgr.DrawObjects(SH_DRAW);
		glEnable(GL_CULL_FACE);

	}

};

MrtView::MrtView(void *data) : SampleView(data, false) {
	mViewRenderer = new MrtRenderer();

}

void MrtView::OnInit() {
	string mrt_vs = File_Loader.ReadFileToString("shader/view_mrt/mrt.vs");
	string mrt_fs = File_Loader.ReadFileToString("shader/view_mrt/mrt.fs");
	string draw_vs = File_Loader.ReadFileToString("shader/view_mrt/draw.vs");
	string draw_fs = File_Loader.ReadFileToString("shader/view_mrt/draw.fs");

	BasicMap<MaterialObj_U_Elem> mo_uniforms;
	mo_uniforms.mList[MTL_U_MAT_WORLD] = "worldMat";
	mo_uniforms.mList[MTL_U_CAMERA_VIEW] = "viewMat";
	mo_uniforms.mList[MTL_U_CAMERA_PROJ] = "projMat";
	mo_uniforms.mList[MTL_U_CAMERA_POS] = "eyePos";
	mo_uniforms.mList[MTL_U_MAT_SHINESS] = "materialSh";

	BasicMap<PointLt_U_Elem> lt_uniforms;
	lt_uniforms.mList[U_PL_DIFFUSE] = "sourceDiff";
	lt_uniforms.mList[U_PL_AMBIENT] = "sourceAmbi";
	lt_uniforms.mList[U_PL_SPECULAR] = "sourceSpec";
	lt_uniforms.mList[U_PL_POS] = "lightPos";

	mViewRenderer->GetNewObject(MATERIAL_OBJ, "chess", mo_uniforms)
			->ImportObj("obj3d/chess_tri", 2.0f)
			->AttachShader(mrt_vs, mrt_fs, SH_MRT)
			->AttachLight(POINT_LT, "point_light_1", lt_uniforms);

	Light_Mgr.GetLight("point_light_1")->mPosition = glm::vec3(0, 5.0f, 0);

	mViewRenderer->OffAutoRotate();

	mViewRenderer->GetCamera()->SetEye(glm::vec3(-15, 15, 15));

	int w = mViewRenderer->GetWidth();
	int h = mViewRenderer->GetHeight();
	TexProp texDiff(TEX_2D_PTR);
	texDiff.SetData("tex_diff", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texDiff.SetPointer(nullptr);
	texDiff.SetFilter();

	TexProp texDraw(TEX_2D_PTR);
	texDraw.SetData("tex_draw", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texDraw.SetPointer(nullptr);
	texDraw.SetFilter();

	TexProp texAmbi(TEX_2D_PTR);
	texAmbi.SetData("tex_ambi", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texAmbi.SetPointer(nullptr);
	texAmbi.SetFilter();

	TexProp texAttn(TEX_2D_PTR);
	texAttn.SetData("tex_attn", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texAttn.SetPointer(nullptr);
	texAttn.SetFilter();

	BasicObject *obj;

	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "diff", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texDiff, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(0));

	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "spec", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texDraw, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(-1.0, 0));
	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "ambi", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texAmbi, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(0, -1.0));
	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "attn", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texAttn, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(-1.0, -1.0));

	GLuint texIds[4];
	texIds[0] = Texture_Mgr.GetTextureId("tex_diff");
	texIds[1] = Texture_Mgr.GetTextureId("tex_draw");
	texIds[2] = Texture_Mgr.GetTextureId("tex_ambi");
	texIds[3] = Texture_Mgr.GetTextureId("tex_attn");
	LOGI("texid [%d, %d, %d, %d]", texIds[0], texIds[1], texIds[2], texIds[3]);

	mViewRenderer->SetCurrShader(SH_DRAW);

	dynamic_cast<MrtRenderer *>(mViewRenderer)->InitFbo(texIds);

}


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.facebook.thrift.annotation.cpp_deprecated;

import com.facebook.thrift.IntRangeSet;
import java.util.Map;
import java.util.HashMap;

@SuppressWarnings({ "unused" })
public enum EnumUnderlyingType implements com.facebook.thrift.TEnum {
  /**
   * ::std::int8_t
   */
  I8(0),
  /**
   * ::std::uint8_t
   */
  U8(1),
  /**
   * ::std::int16_t
   */
  I16(2),
  /**
   * ::std::uint16_t
   */
  U16(3),
  /**
   * ::std::uint32_t
   */
  U32(4);

  private final int value;

  private EnumUnderlyingType(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static EnumUnderlyingType findByValue(int value) {
    switch (value) {
      case 0:
        return I8;
      case 1:
        return U8;
      case 2:
        return I16;
      case 3:
        return U16;
      case 4:
        return U32;
      default:
        return null;
    }
  }
}


text:
__LLBC_NS_BEGIN

LLBC_LogJsonMsg::LLBC_LogJsonMsg(LLBC_Logger *logger,
                                 const char *tag,
                                 int lv,
                                 const char *file,
                                 int line,
                                 const char *func)
: _logger(logger)
, _tag(tag)
, _lv(lv)
, _file(file)
, _line(line)
, _func(func)

, _doc(*LLBC_GetObjectFromUnsafetyPool<LLBC_Json::Document>())
{
    _doc.SetObject();
}

LLBC_LogJsonMsg::~LLBC_LogJsonMsg()
{
    LLBC_ReleaseObjectToUnsafetyPool(&_doc);
}

void LLBC_LogJsonMsg::Finish(const char *fmt, ...)
{
    // Log level judge.
    if (_logger && _lv < _logger->GetLogLevel())
        return;

    // Format.
    va_list va;
    va_start(va, fmt);
    __LLBC_LibTls *libTls = __LLBC_GetLibTls();
    int len = vsnprintf(libTls->coreTls.loggerFmtBuf,
                        sizeof(libTls->coreTls.loggerFmtBuf),
                        fmt,
                        va);
    va_end(va);
    if (UNLIKELY(len < 0))
        return;

    // Doc add string with not copy.
    _doc.AddMember("msg", LLBC_JsonValue(libTls->coreTls.loggerFmtBuf, len).Move(), _doc.GetAllocator());

    // _doc stringify
    LLBC_Json::StringBuffer buffer;
    LLBC_Json::Writer<LLBC_Json::StringBuffer> writer(buffer);
    _doc.Accept(writer);

    // Output json log.
    if (UNLIKELY(!_logger))
        LLBC_LoggerManagerSingleton->UnInitOutput(_lv, buffer.GetString());
    else
        _logger->NonFormatOutput(_lv, _tag, _file, _line, _func, buffer.GetString(), buffer.GetLength());

    // Recycle self.
    LLBC_Recycle(this);
}

__LLBC_NS_END


text:
FROM registry.service.opg.digital/opguk/base

RUN mkdir -p /tmp/elasticsearchshareddata/beats

ENV BEATS_DASHBOARD_VERSION=5.3.3

RUN cd /tmp && \
   wget https://artifacts.elastic.co/downloads/beats/beats-dashboards/beats-dashboards-${BEATS_DASHBOARD_VERSION}.zip && \
   unzip beats-dashboards-${BEATS_DASHBOARD_VERSION}.zip

RUN cd /tmp/beats-dashboards-${BEATS_DASHBOARD_VERSION} && \
   cp -rv metricbeat/* /tmp/elasticsearchshareddata/beats && \
   cp -rv filebeat/* /tmp/elasticsearchshareddata/beats

RUN rm -rf /tmp/beats-dashboards-* && \
   chmod -R 644 /tmp/elasticsearchshareddata

VOLUME /tmp/elasticsearchshareddata

USER root
ENV  HOME /root


text:
using System;
using System.Linq;
using System.Linq.Expressions;
using Mono;

namespace Mono.Cecil
{
    static internal class __AssemblyDefinition
    {
        static public CustomAttribute Attribute<T>(this AssemblyDefinition assembly)
            where T : Attribute
        {
            var _attribute = new CustomAttribute(assembly.MainModule.Import(typeof(T).GetConstructor(Type.EmptyTypes)));
            assembly.CustomAttributes.Add(_attribute);
            return _attribute;
        }

        static public CustomAttribute Attribute<T>(this AssemblyDefinition assembly, Expression<Func<T>> expression)
            where T : Attribute
        {
            var _constructor = (expression.Body as NewExpression).Constructor;
            var _attribute = new CustomAttribute(assembly.MainModule.Import(_constructor));
            foreach (var _argument in (expression.Body as NewExpression).Arguments) { _attribute.ConstructorArguments.Add(new CustomAttributeArgument(assembly.MainModule.Import(_argument.Type), Expression.Lambda<Func<object>>(Expression.Convert(_argument, Metadata<object>.Type)).Compile()())); }
            assembly.CustomAttributes.Add(_attribute);
            return _attribute;
        }
    }
}


text:
namespace zetasql_fuzzer {

// Extracts a pointer to zetasql_fuzzer::SQLStringArg from expression.
std::unique_ptr<Argument> GetProtoExpr(
    const zetasql_expression_grammar::Expression& expression);

// Extracts a pointer to zetasql_fuzzer::ParameterValueMapArg from expression.
template <ParameterValueAs Intent>
extern std::unique_ptr<Argument> GetParam(
    const zetasql_expression_grammar::Expression& expression);

// Extracts a pointer to zetasql_fuzzer::ParameterValueListArg from expression.
template <ParameterValueAs Intent>
extern std::unique_ptr<Argument> GetPositionalParam(
    const zetasql_expression_grammar::Expression& expression);
}  // namespace zetasql_fuzzer

#endif  //ZETASQL_FUZZING_ARGUMENT_EXTRACTORS_H


text:
package org.apache.logging.log4j.core.net;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.AppenderLoggingException;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import org.apache.logging.log4j.core.net.TcpSocketManager.HostResolver;
import org.apache.logging.log4j.status.StatusLogger;
import org.junit.jupiter.api.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;

/**
 * Tests reconnection support of {@link org.apache.logging.log4j.core.appender.SocketAppender}.
 */
public class SocketAppenderReconnectTest {

    private static final long DEFAULT_POLL_MILLIS = 1_000L;
    private static final int EPHEMERAL_PORT = 0;
    private static final Logger LOGGER = StatusLogger.getLogger();

    /**
     * Tests if failures are propagated when reconnection fails.
     *
     * @see LOG4J2-2829
     */
    @Test
    void repeating_reconnect_failures_should_be_propagated() throws Exception {
        try (final LineReadingTcpServer server = new LineReadingTcpServer()) {

            // Start the server.
            server.start("Main", EPHEMERAL_PORT);
            final int port = server.serverSocket.getLocalPort();

            // Initialize the logger context.
            final LoggerContext loggerContext = initContext(port);
            try {

                // Verify the initial working state.
                verifyLoggingSuccess(server);

                // Stop the server, and verify the logging failure.
                server.close();
                verifyLoggingFailure();

                // Start the server again, and verify the logging success.
                server.start("Main", port);
                verifyLoggingSuccess(server);

            }

            // Shutdown the logger context.
            finally {
                Configurator.shutdown(loggerContext);
            }

        }
    }

    /**
     * Tests if all the {@link InetSocketAddress}es returned by an {@link HostResolver} is used for fallback on reconnect attempts.
     */
    @Test
    void reconnect_should_fallback_when_there_are_multiple_resolved_hosts() throws Exception {
        try (final LineReadingTcpServer primaryServer = new LineReadingTcpServer();
             final LineReadingTcpServer secondaryServer = new LineReadingTcpServer()) {

            // Start servers.
            primaryServer.start("Primary", EPHEMERAL_PORT);
            secondaryServer.start("Secondary", EPHEMERAL_PORT);

            // Mock the host resolver.
            final FixedHostResolver hostResolver = FixedHostResolver.ofServers(primaryServer, secondaryServer);
            TcpSocketManager.setHostResolver(hostResolver);
            try {

                // Initialize the logger context.
                final LoggerContext loggerContext = initContext(
                        // Passing an invalid port, since the resolution is supposed to be performed by the mocked host resolver anyway.
                        // Here, 0 does NOT mean an ephemeral port.
                        0);
                try {

                    // Verify the initial working state on the primary server.
                    verifyLoggingSuccess(primaryServer);

                    // Stop the primary server, and verify the logging success due to fallback on to the secondary server.
                    primaryServer.close();
                    verifyLoggingSuccess(secondaryServer);

                }

                // Shutdown the logger context.
                finally {
                    Configurator.shutdown(loggerContext);
                }

            } finally {
                // Reset the host resolver.
                TcpSocketManager.setHostResolver(new HostResolver());
            }

        }
    }

    private static LoggerContext initContext(final int port) {

        // Create the configuration builder.
        final ConfigurationBuilder<BuiltConfiguration> configBuilder = ConfigurationBuilderFactory
                .newConfigurationBuilder()
                .setStatusLevel(Level.ERROR)
                .setConfigurationName(SocketAppenderReconnectTest.class.getSimpleName());

        // Create the configuration.
        final String appenderName = "Socket";
        final Configuration config = configBuilder
                .add(configBuilder
                        .newAppender(appenderName, "SOCKET")
                        .addAttribute("host", "localhost")
                        .addAttribute("port", String.valueOf(port))
                        .addAttribute("protocol", Protocol.TCP)
                        .addAttribute("ignoreExceptions", false)
                        .addAttribute("reconnectionDelayMillis", 10)
                        .addAttribute("immediateFlush", true)
                        .add(configBuilder
                                .newLayout("PatternLayout")
                                .addAttribute("pattern", "%m%n")))
                .add(configBuilder.newLogger("org.apache.logging.log4j", Level.DEBUG))
                .add(configBuilder
                        .newRootLogger(Level.ERROR)
                        .add(configBuilder.newAppenderRef(appenderName)))
                .build(false);

        // Initialize the configuration.
        return Configurator.initialize(config);

    }

    private static void verifyLoggingSuccess(final LineReadingTcpServer server) throws Exception {
        final int messageCount = 100;
        // noinspection ConstantConditions
        assertTrue(messageCount > 1, "was expecting messageCount to be bigger than 1 due to LOG4J2-2829, found: " + messageCount);
        final List<String> expectedMessages = IntStream
                .range(0, messageCount)
                .mapToObj(messageIndex -> String.format("m%02d", messageIndex))
                .collect(Collectors.toList());
        final Logger logger = LogManager.getLogger();
        for (int messageIndex = 0; messageIndex < expectedMessages.size(); messageIndex++) {
            final String message = expectedMessages.get(messageIndex);
            // Due to socket initialization, the first write() might need some extra effort.
            if (messageIndex == 0) {
                awaitUntilSucceeds(() -> logger.info(message));
            } else {
                logger.info(message);
            }
        }
        expectedMessages.forEach(logger::info);
        final List<String> actualMessages = server.pollLines(messageCount);
        assertEquals(expectedMessages, actualMessages);
    }

    private static void awaitUntilSucceeds(final Runnable runnable) {
        // These figures are collected via trial-and-error; nothing scientific to look for here.
        final long pollIntervalMillis = DEFAULT_POLL_MILLIS;
        final long timeoutSeconds = 120L;
        await()
                .pollInterval(pollIntervalMillis, TimeUnit.MILLISECONDS)
                .atMost(timeoutSeconds, TimeUnit.SECONDS)
                .until(() -> {
                    runnable.run();
                    return true;
                });
    }

    private static void verifyLoggingFailure() {
        final Logger logger = LogManager.getLogger();
        int retryCount = 3;
        // noinspection ConstantConditions
        assertTrue(retryCount > 1, "was expecting retryCount to be bigger than 1 due to LOG4J2-2829, found: " + retryCount);
        for (int i = 0; i < retryCount; i++) {
            try {
                logger.info("should fail #" + i);
                fail("should have failed #" + i);
            } catch (final AppenderLoggingException ignored) {}
        }
    }

    /**
     * A simple TCP server implementation reading the accepted connection's input stream into a blocking queue of lines.
     *

     * The implementation is thread-safe, yet connections are handled sequentially, i.e., no parallelization.
     * The input stream of the connection is decoded in UTF-8.
     *

     */
    private static final class LineReadingTcpServer implements AutoCloseable {

        private static final int UNBOUND_PORT = -1;

        private volatile boolean running;

        private ServerSocket serverSocket;

        private Socket clientSocket;

        private Thread readerThread;

        private final BlockingQueue<String> lines = new LinkedBlockingQueue<>();

        private LineReadingTcpServer() {}

        private synchronized void start(final String name, final int port) throws IOException {
            if (!running) {
                running = true;
                serverSocket = createServerSocket(port);
                readerThread = createReaderThread(name);
                // Make sure the server socket is ready.
                if (serverSocket.getLocalPort() == UNBOUND_PORT || !serverSocket.isBound()) {
                    try {
                        Thread.sleep(DEFAULT_POLL_MILLIS);
                    } catch (InterruptedException e) {
                        throw new IllegalStateException(e);
                    }
                }
                assertNotEquals(UNBOUND_PORT, serverSocket.getLocalPort(),
                    () -> String.format("Server socket is not bound to port %s (0 = ephemeral). This can only happen if a machine runs out of ports.", port));
            }
        }

        private ServerSocket createServerSocket(final int port) throws IOException {
            final ServerSocket serverSocket = new ServerSocket(port);
            serverSocket.setReuseAddress(true);
            serverSocket.setSoTimeout(0);   // Zero indicates accept() will block indefinitely.
            return serverSocket;
        }

        private Thread createReaderThread(final String name) {
            final String threadName = "LineReadingTcpSocketServerReader-" + name;
            final Thread thread = new Thread(this::acceptClients, threadName);
            thread.setDaemon(true); // Avoid blocking JVM exit.
            thread.setUncaughtExceptionHandler((ignored, error) -> LOGGER.error("uncaught reader thread exception", error));
            thread.start();
            return thread;
        }

        private void acceptClients() {
            try {
                while (running) {
                    acceptClient();
                }
            } catch (final Exception error) {
                LOGGER.error("failed accepting client connections", error);
            }
        }

        private void acceptClient() throws Exception {

            // Accept the client connection.
            final Socket clientSocket;
            try {
                clientSocket = serverSocket.accept();
            } catch (SocketException ignored) {
                return;
            }
            clientSocket.setSoLinger(true, 0);    // Enable immediate forceful close.
            synchronized (this) {
                if (running) {
                    this.clientSocket = clientSocket;
                }
            }

            // Read from the client.
            try (final InputStream clientInputStream = clientSocket.getInputStream();
                 final InputStreamReader clientReader = new InputStreamReader(clientInputStream, StandardCharsets.UTF_8);
                 final BufferedReader clientBufferedReader = new BufferedReader(clientReader)) {
                while (running) {
                    final String line = clientBufferedReader.readLine();
                    if (line == null) {
                        break;
                    }
                    lines.put(line);
                }
            }

            // Ignore connection failures.
            catch (final SocketException ignored) {}

            // Clean up the client connection.
            finally {
                try {
                    synchronized (this) {
                        if (!clientSocket.isClosed()) {
                            clientSocket.shutdownOutput();
                            clientSocket.close();
                        }
                        this.clientSocket = null;
                    }
                } catch (final Exception error) {
                    LOGGER.error("failed closing client socket", error);
                }
            }

        }

        @Override
        public void close() throws Exception {

            // Stop the reader, if running.
            Thread stoppedReaderThread = null;
            synchronized (this) {
                if (running) {
                    running = false;
                    // acceptClient() might have closed the client socket due to a connection failure and haven't created a new one yet.
                    // Hence, here we double-check if the client connection is in place.
                    if (clientSocket != null && !clientSocket.isClosed()) {
                        // Interrupting a thread is not sufficient to unblock operations waiting on socket I/O: https://stackoverflow.com/a/4426050/1278899
                        // Hence, here we close the client socket to unblock the read from the client socket.
                        clientSocket.close();
                    }
                    serverSocket.close();
                    stoppedReaderThread = readerThread;
                    clientSocket = null;
                    serverSocket = null;
                    readerThread = null;
                }
            }

            // We wait for the termination of the reader thread outside the synchronized block.
            // Otherwise, there is a chance of deadlock with this join() and the synchronized block inside the acceptClient().
            if (stoppedReaderThread != null) {
                stoppedReaderThread.join();
            }

        }

        private List<String> pollLines(@SuppressWarnings("SameParameterValue") final int count) throws InterruptedException, TimeoutException {
            final List<String> polledLines = new ArrayList<>(count);
            for (int i = 0; i < count; i++) {
                final String polledLine = pollLine();
                polledLines.add(polledLine);
            }
            return polledLines;
        }

        private String pollLine() throws InterruptedException, TimeoutException {
            final String line = lines.poll(2, TimeUnit.SECONDS);
            if (line == null) {
                throw new TimeoutException();
            }
            return line;
        }

    }

    /**
     * {@link HostResolver} implementation always resolving to the given list of {@link #addresses}.
     */
    private static final class FixedHostResolver extends HostResolver {

        private final List<InetSocketAddress> addresses;

        private FixedHostResolver(List<InetSocketAddress> addresses) {
            this.addresses = addresses;
        }

        private static FixedHostResolver ofServers(LineReadingTcpServer... servers) {
            List<InetSocketAddress> addresses = Arrays
                    .stream(servers)
                    .map(server -> (InetSocketAddress) server.serverSocket.getLocalSocketAddress())
                    .collect(Collectors.toList());
            return new FixedHostResolver(addresses);
        }

        @Override
        public List<InetSocketAddress> resolveHost(String ignoredHost, int ignoredPort) {
            return addresses;
        }

    }

}


text:
{% if GOOGLE_ANALYTICS_CODE %}
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', "{{ GOOGLE_ANALYTICS_CODE }}"]);
  {% if GOOGLE_ANALYTICS_DOMAIN %}_gaq.push(['_setDomainName', "{{GOOGLE_ANALYTICS_DOMAIN}}"]);{% endif %}
  {% if GOOGLE_ANALYTICS_DOMAIN_UP %}_gaq.push(['_setAllowLinker', true]);{% endif %}
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
{% endif %}

{% if GOSQUARED_SITENAME %}
<script type="text/javascript">
  var GoSquared = {};
  GoSquared.acct = "{{ GOSQUARED_SITENAME }}";
  (function(w){
    function gs(){
      w._gstc_lt = +new Date;
      var d = document, g = d.createElement("script");
      g.type = "text/javascript";
      g.src = "//d1l6p2sc9645hc.cloudfront.net/tracker.js";
      var s = d.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(g, s);
    }
    w.addEventListener ?
      w.addEventListener("load", gs, false) :
      w.attachEvent("onload", gs);
  })(window);
</script>
{% endif %}


text:
var reboot = {};//default workspace

$(function () {
    reboot.search = {
        init: function () {
            $("#searchButton").click(function () {
                var searchText = $("#searchText").val();
                if (searchText.length > 0) {
                    window.location.href = "?keyword=" + searchText;
                }
            });

            $("#searchText").keypress(function (event) {
                if (event.which == 13) {
                    event.preventDefault();
                    $("#searchButton").click();
                }
            });
        },

    };

    reboot.search.init();
});