text:
package org.apache.synapse.core.axis2;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMNode;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.*;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.engine.AxisEvent;
import org.apache.axis2.util.JavaUtils;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.synapse.SynapseArtifact;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.SynapseException;
import org.apache.synapse.aspects.AspectConfigurable;
import org.apache.synapse.aspects.AspectConfiguration;
import org.apache.synapse.config.SynapseConfigUtils;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.core.SynapseEnvironment;
import org.apache.synapse.endpoints.AddressEndpoint;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.endpoints.WSDLEndpoint;
import org.apache.synapse.mediators.base.SequenceMediator;
import org.apache.synapse.util.PolicyInfo;
import org.apache.synapse.util.resolver.CustomWSDLLocator;
import org.apache.synapse.util.resolver.CustomXmlSchemaURIResolver;
import org.apache.synapse.util.resolver.ResourceMap;
import org.apache.synapse.util.resolver.UserDefinedWSDLLocator;
import org.apache.synapse.util.resolver.UserDefinedXmlSchemaURIResolver;
import org.xml.sax.InputSource;

import javax.xml.stream.XMLStreamException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.*;

/**
 * <proxy-service name="string" [transports="(http |https |jms )+|all"] [trace="enable|disable"]>
 *    <description>..</description>?
 *    <target [inSequence="name"] [outSequence="name"] [faultSequence="name"] [endpoint="name"]>
 *       <endpoint>...</endpoint>
 *       <inSequence>...</inSequence>
 *       <outSequence>...</outSequence>
 *       <faultSequence>...</faultSequence>
 *    </target>?
 *    <publishWSDL uri=".." key="string" endpoint="string">
 *       <wsdl:definition>...</wsdl:definition>?
 *       <wsdl20:description>...</wsdl20:description>?
 *       <resource location="..." key="..."/>*
 *    </publishWSDL>?
 *    <enableSec/>?
 *    <enableRM/>?
 *    <policy key="string" [type=("in" |"out")] [operationName="string"]
 *      [operationNamespace="string"]>?
 *       // optional service parameters
 *    <parameter name="string">
 *       text | xml
 *    </parameter>?
 * </proxy-service>
 */
@SuppressWarnings({"UnusedDeclaration"})
public class ProxyService implements AspectConfigurable, SynapseArtifact {

    private static final Log log = LogFactory.getLog(ProxyService.class);
    private static final Log trace = LogFactory.getLog(SynapseConstants.TRACE_LOGGER);
    private final Log serviceLog;

    public static final String ABSOLUTE_SCHEMA_URL_PARAM = "showAbsoluteSchemaURL";
    public static final String ABSOLUTE_PROXY_SCHEMA_URL_PARAM = "showProxySchemaURL";
    /**
     * The name of the proxy service
     */
    private String name;
    /**
     * The proxy service description. This could be optional informative text about the service
     */
    private String description;
    /**
     * The transport/s over which this service should be exposed, or defaults to all available
     */
    private ArrayList transports;
    /**
     * Server names for which this service should be exposed
     */
    private List pinnedServers = new ArrayList();
    /**
     * The target endpoint key
     */
    private String targetEndpoint = null;
    /**
     * The target inSequence key
     */
    private String targetInSequence = null;
    /**
     * The target outSequence key
     */
    private String targetOutSequence = null;
    /**
     * The target faultSequence key
     */
    private String targetFaultSequence = null;
    /**
     * The inlined definition of the target endpoint, if defined
     */
    private Endpoint targetInLineEndpoint = null;
    /**
     * The inlined definition of the target in-sequence, if defined
     */
    private SequenceMediator targetInLineInSequence = null;
    /**
     * The in-lined definition of the target out-sequence, if defined
     */
    private SequenceMediator targetInLineOutSequence = null;
    /**
     * The in-lined definition of the target fault-sequence, if defined
     */
    private SequenceMediator targetInLineFaultSequence = null;
    /**
     * A list of any service parameters (e.g. JMS parameters etc)
     */
    private final Map<String, Object> parameters = new HashMap<String, Object>();
    /**
     * The key for the base WSDL
     */
    private String wsdlKey;
    /**
     * The URI for the base WSDL, if defined as a URL
     */
    private URI wsdlURI;
    /**
     * The in-lined representation of the service WSDL, if defined inline
     */
    private Object inLineWSDL;
    /**
     * A ResourceMap object allowing to locate artifacts (WSDL and XSD) imported
     * by the service WSDL to be located in the registry.
     */

    /**
     * Endpoint which used to resolve WSDL url
     * If address endpoint pointed, url+"?wsdl" will be use as WSDL url
     * If wsdl endpoint,  wsdl url of endpoint will be use to fetch wsdl
     */
    private String publishWSDLEndpoint;

    private ResourceMap resourceMap;
    /**
     * Policies to be set to the service, this can include service level, operation level,
     * message level or hybrid level policies as well.
     */
    private List<PolicyInfo> policies = new ArrayList<PolicyInfo>();
    /**
     * The keys for any supplied policies that would apply at the service level
     */
    private final List<String> serviceLevelPolicies = new ArrayList<String>();
    /**
     * The keys for any supplied policies that would apply at the in message level
     */
    private List<String> inMessagePolicies = new ArrayList<String>();
    /**
     * The keys for any supplied policies that would apply at the out message level
     */
    private List<String> outMessagePolicies = new ArrayList<String>();
    /**
     * Should WS Addressing be engaged on this service
     */
    private boolean wsAddrEnabled = false;
    /**
     * Should WS RM be engaged on this service
     */
    private boolean wsRMEnabled = false;
    /**
     * Should WS Sec be engaged on this service
     */
    private boolean wsSecEnabled = false;
    /**
     * Should this service be started by default on initialization?
     */
    private boolean startOnLoad = true;
    /**
     * Is this service running now?
     */
    private boolean running = false;

    public static final String ALL_TRANSPORTS = "all";

    /**
     * The variable that indicate tracing on or off for the current mediator
     */
    private int traceState = SynapseConstants.TRACING_UNSET;

    private AspectConfiguration aspectConfiguration;

    private String fileName;

    private URL filePath;

    private String serviceGroup;

    private boolean moduleEngaged;

    private boolean wsdlPublished;

    /**
     * Constructor
     *
     * @param name the name of the Proxy service
     */
    public ProxyService(String name) {
        this.name = name;
        serviceLog = LogFactory.getLog(SynapseConstants.SERVICE_LOGGER_PREFIX + name);
    }

    /**
     * Build the underlying Axis2 service from the Proxy service definition
     *
     * @param synCfg  the Synapse configuration
     * @param axisCfg the Axis2 configuration
     * @return the Axis2 service for the Proxy
     */
    public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) {

        auditInfo("Building Axis service for Proxy service : " + name);
        AxisService proxyService = null;

        // get the wsdlElement as an OMElement
        if (trace()) {
            trace.info("Loading the WSDL : " +
                (publishWSDLEndpoint != null ? " endpoint = " + publishWSDLEndpoint :
                (wsdlKey != null ? " key = " + wsdlKey :
                (wsdlURI != null ? " URI = " + wsdlURI : " <Inlined>"))));
        }

        InputStream wsdlInputStream = null;
        OMElement wsdlElement = null;
        boolean wsdlFound = false;
        String publishWSDL = null;

        SynapseEnvironment synEnv = SynapseConfigUtils.getSynapseEnvironment(axisCfg);
        String synapseHome = synEnv != null ? synEnv.getServerContextInformation()
                .getServerConfigurationInformation().getSynapseHome() : "";

        if (wsdlKey != null) {
            synCfg.getEntryDefinition(wsdlKey);
            Object keyObject = synCfg.getEntry(wsdlKey);
            if (keyObject instanceof OMElement) {
                wsdlElement = (OMElement) keyObject;
            }
            wsdlFound = true;
        } else if (inLineWSDL != null) {
            wsdlElement = (OMElement) inLineWSDL;
            wsdlFound = true;
        } else if (wsdlURI != null) {
            try {
            	URL url = wsdlURI.toURL();
                publishWSDL = url.toString();

                OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL, synapseHome);
                if (node instanceof OMElement) {
                    wsdlElement = (OMElement) node;
                }
                wsdlFound = true;
            } catch (MalformedURLException e) {
                handleException("Malformed URI for wsdl", e);
            } catch (IOException e) {
                //handleException("Error reading from wsdl URI", e);

                boolean enablePublishWSDLSafeMode = false;
                Map proxyParameters= this.getParameterMap();
                if (!proxyParameters.isEmpty()) {
                    if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
                        enablePublishWSDLSafeMode =
                                Boolean.parseBoolean(
                                        proxyParameters.get("enablePublishWSDLSafeMode").
                                                toString().toLowerCase());
                    } else {
                        if (trace()) {
                            trace.info("WSDL was unable to load for: " + publishWSDL);
                            trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" +
                                    "</syn:parameter> to proxy service.");
                        }
                        handleException("Error reading from wsdl URI", e);
                    }
                }

                if (enablePublishWSDLSafeMode) {
                    // this is if the wsdl cannot be loaded... create a dummy service and an operation for which
                    // our SynapseDispatcher will properly dispatch to

                    //!!!Need to add a reload function... And display that the wsdl/service is offline!!!
                    if (trace()) {
                        trace.info("WSDL was unable to load for: " + publishWSDL);
                        trace.info("enableURISafeMode: true");
                    }

                    log.warn("Unable to load the WSDL for : " + name, e);
                    return null;
                } else {
                    if (trace()) {
                        trace.info("WSDL was unable to load for: " + publishWSDL);
                        trace.info("enableURISafeMode: false");
                    }

                    handleException("Error reading from wsdl URI", e);
                }
            }
        } else if (publishWSDLEndpoint != null) {
            try {
                URL url = null;
                Endpoint ep = synCfg.getEndpoint(publishWSDLEndpoint);
                if (ep == null) {
                    handleException("Unable to resolve WSDL url. " + publishWSDLEndpoint + " is null");
                }

                if (ep instanceof AddressEndpoint) {
                    url = new URL(((AddressEndpoint) (ep)).getDefinition().getAddress() + "?wsdl");
                } else if (ep instanceof WSDLEndpoint) {
                    url = new URL(((WSDLEndpoint) (ep)).getWsdlURI());
                } else {
                    handleException("Unable to resolve WSDL url. " + publishWSDLEndpoint +
                            " is not a AddressEndpoint or WSDLEndpoint");
                }
                publishWSDL = url.toString();

                OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL, synapseHome);
                if (node instanceof OMElement) {
                    wsdlElement = (OMElement) node;
                }
                wsdlFound = true;
            } catch (MalformedURLException e) {
                handleException("Malformed URI for wsdl", e);
            } catch (IOException e) {
                //handleException("Error reading from wsdl URI", e);

                boolean enablePublishWSDLSafeMode = false;
                Map proxyParameters= this.getParameterMap();
                if (!proxyParameters.isEmpty()) {
                    if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
                        enablePublishWSDLSafeMode =
                                Boolean.parseBoolean(
                                        proxyParameters.get("enablePublishWSDLSafeMode").
                                                toString().toLowerCase());
                    } else {
                        if (trace()) {
                            trace.info("WSDL was unable to load for: " + publishWSDL);
                            trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" +
                                    "</syn:parameter> to proxy service.");
                        }
                        handleException("Error reading from wsdl URI " + publishWSDL, e);
                    }
                }

                if (enablePublishWSDLSafeMode) {
                    // this is if the wsdl cannot be loaded... create a dummy service and an operation for which
                    // our SynapseDispatcher will properly dispatch to

                    //!!!Need to add a reload function... And display that the wsdl/service is offline!!!
                    if (trace()) {
                        trace.info("WSDL was unable to load for: " + publishWSDL);
                        trace.info("enableURISafeMode: true");
                    }

                    log.warn("Unable to load the WSDL for : " + name, e);
                    return null;
                } else {
                    if (trace()) {
                        trace.info("WSDL was unable to load for: " + publishWSDL);
                        trace.info("enableURISafeMode: false");
                    }

                    handleException("Error reading from wsdl URI " + publishWSDL, e);
                }
            }
        } else {
            // this is for POX... create a dummy service and an operation for which
            // our SynapseDispatcher will properly dispatch to
            if (trace()) trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
            proxyService = new AxisService();
            AxisOperation mediateOperation = new InOutAxisOperation(
                    SynapseConstants.SYNAPSE_OPERATION_NAME);
            // Set the names of the two messages so that Axis2 is able to produce a WSDL (see SYNAPSE-366):
            mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE).setName("in");
            mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE).setName("out");
            proxyService.addOperation(mediateOperation);
        }

        // if a WSDL was found
        if (wsdlElement != null) {
            OMNamespace wsdlNamespace = wsdlElement.getNamespace();

            // serialize and create an input stream to read WSDL
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                if (trace()) trace.info("Serializing wsdlElement found to build an Axis2 service");
                wsdlElement.serialize(baos);
                wsdlInputStream = new ByteArrayInputStream(baos.toByteArray());
            } catch (XMLStreamException e) {
                handleException("Error converting to a StreamSource", e);
            }

            if (wsdlInputStream != null) {

                try {
                    // detect version of the WSDL 1.1 or 2.0
                    if (trace()) trace.info("WSDL Namespace is : "
                        + wsdlNamespace.getNamespaceURI());

                    if (wsdlNamespace != null) {
                        WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null;

                        if (WSDL2Constants.WSDL_NAMESPACE.
                                equals(wsdlNamespace.getNamespaceURI())) {
                            wsdlToAxisServiceBuilder =
                                    new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null);

                        } else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.
                                equals(wsdlNamespace.getNamespaceURI())) {
                            wsdlToAxisServiceBuilder =
                                    new WSDL11ToAxisServiceBuilder(wsdlInputStream);
                        } else {
                            handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
                        }

                        if (wsdlToAxisServiceBuilder == null) {
                            throw new SynapseException(
                                    "Could not get the WSDL to Axis Service Builder");
                        }

                        wsdlToAxisServiceBuilder.setBaseUri(wsdlURI != null ?
                                wsdlURI.toString() : synapseHome);

                        if (trace()) {
                            trace.info("Setting up custom resolvers");
                        }

                        // load the UserDefined WSDLResolver and SchemaURIResolver implementations
                        if (synCfg.getProperty(SynapseConstants.SYNAPSE_WSDL_RESOLVER) != null &&
                                synCfg.getProperty(SynapseConstants.SYNAPSE_SCHEMA_RESOLVER) != null) {
                            setUserDefinedResourceResolvers(synCfg, wsdlInputStream,
                                    wsdlToAxisServiceBuilder);
                        } else {
                            //Use the Custom Resolvers
                            // Set up the URIResolver

                            if (resourceMap != null) {
                                // if the resource map is available use it
                                wsdlToAxisServiceBuilder.setCustomResolver(
                                        new CustomXmlSchemaURIResolver(resourceMap, synCfg));
                                // Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
                                if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
                                    ((WSDL11ToAxisServiceBuilder)
                                            wsdlToAxisServiceBuilder).setCustomWSDLResolver(
                                            new CustomWSDLLocator(new InputSource(wsdlInputStream),
                                                    wsdlURI != null ? wsdlURI.toString() : "",
                                                    resourceMap, synCfg));
                                }
                            } else {
                                //if the resource map isn't available ,
                                //then each import URIs will be resolved using base URI
                                wsdlToAxisServiceBuilder.setCustomResolver(
                                        new CustomXmlSchemaURIResolver());
                                // Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
                                if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
                                    ((WSDL11ToAxisServiceBuilder)
                                            wsdlToAxisServiceBuilder).setCustomWSDLResolver(
                                            new CustomWSDLLocator(new InputSource(wsdlInputStream),
                                                    wsdlURI != null ? wsdlURI.toString() : ""));
                                }
                            }
                        }
                        if (trace()) {
                            trace.info("Populating Axis2 service using WSDL");
                            if (trace.isTraceEnabled()) {
                                trace.trace("WSDL : " + wsdlElement.toString());
                            }
                        }
                        proxyService = wsdlToAxisServiceBuilder.populateService();

                        // this is to clear the bindings and ports already in the WSDL so that the
                        // service will generate the bindings on calling the printWSDL otherwise
                        // the WSDL which will be shown is same as the original WSDL except for the
                        // service name
                        proxyService.getEndpoints().clear();

                    } else {
                        handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
                    }

                } catch (AxisFault af) {
                    handleException("Error building service from WSDL", af);
                } catch (IOException ioe) {
                    handleException("Error reading WSDL", ioe);
                }
            }
        } else if (wsdlFound) {
            handleException("Couldn't build the proxy service : " + name
                    + ". Unable to locate the specified WSDL to build the service");
        }

        // Set the name and description. Currently Axis2 uses the name as the
        // default Service destination
        if (proxyService == null) {
            throw new SynapseException("Could not create a proxy service");
        }
        proxyService.setName(name);
        if (description != null) {
            proxyService.setDocumentation(description);
        }
        // Setting file path for axis2 service
        if (filePath != null) {
            proxyService.setFileName(filePath);
        }
        // process transports and expose over requested transports. If none
        // is specified, default to all transports using service name as
        // destination
        if (transports == null || transports.size() == 0) {
            // default to all transports using service name as destination
        } else {
            if (trace()) trace.info("Exposing transports : " + transports);
            proxyService.setExposedTransports(transports);
        }

        // process parameters
        if (trace() && parameters.size() > 0) {
            trace.info("Setting service parameters : " + parameters);
        }
        for (Object o : parameters.keySet()) {
            String name = (String) o;
            Object value = parameters.get(name);

            Parameter p = new Parameter();
            p.setName(name);
            p.setValue(value);

            try {
                proxyService.addParameter(p);
            } catch (AxisFault af) {
                handleException("Error setting parameter : " + name + "" +
                    "to proxy service as a Parameter", af);
            }
        }

        if (JavaUtils.isTrueExplicitly(proxyService.getParameterValue(ABSOLUTE_SCHEMA_URL_PARAM))) {
            proxyService.setCustomSchemaNamePrefix("");
        }
        if (JavaUtils.isTrueExplicitly(proxyService.getParameterValue(ABSOLUTE_PROXY_SCHEMA_URL_PARAM))) {
            proxyService.setCustomSchemaNamePrefix("fullschemaurl");
        }

        if (JavaUtils.isTrueExplicitly(proxyService.getParameterValue("disableOperationValidation"))){
            try {
                AxisOperation defaultOp = processOperationValidation(proxyService);
                //proxyServiceGroup.setParent(axisCfg);
            } catch (AxisFault axisFault) {
                // ignore
            }
        }

        if (!policies.isEmpty()) {

            for (PolicyInfo pi : policies) {
                if (getPolicyFromKey(pi.getPolicyKey(), synCfg) == null) {
                    handleException("Cannot find Policy from the key");
                }

                if (pi.isServicePolicy()) {

                    proxyService.getPolicySubject().attachPolicy(
                            getPolicyFromKey(pi.getPolicyKey(), synCfg));

                } else if (pi.isOperationPolicy()) {

                    AxisOperation op = proxyService.getOperation(pi.getOperation());
                    if (op != null) {
                        op.getPolicySubject().attachPolicy(
                                getPolicyFromKey(pi.getPolicyKey(), synCfg));

                    } else {
                        handleException("Couldn't find the operation specified " +
                                "by the QName : " + pi.getOperation());
                    }

                } else if (pi.isMessagePolicy()) {

                    if (pi.getOperation() != null) {

                        AxisOperation op = proxyService.getOperation(pi.getOperation());
                        if (op != null) {
                            op.getMessage(pi.getMessageLable()).getPolicySubject().attachPolicy(
                                    getPolicyFromKey(pi.getPolicyKey(), synCfg));
                        } else {
                            handleException("Couldn't find the operation " +
                                    "specified by the QName : " + pi.getOperation());
                        }

                    } else {
                        // operation is not specified and hence apply to all the applicable messages
                        for (Iterator itr = proxyService.getOperations(); itr.hasNext();) {
                            Object obj = itr.next();
                            if (obj instanceof AxisOperation) {
                                // check whether the policy is applicable
                                if (!((obj instanceof OutOnlyAxisOperation && pi.getType()
                                        == PolicyInfo.MESSAGE_TYPE_IN) ||
                                        (obj instanceof InOnlyAxisOperation
                                        && pi.getType() == PolicyInfo.MESSAGE_TYPE_OUT))) {

                                    AxisMessage message = ((AxisOperation)
                                            obj).getMessage(pi.getMessageLable());
                                    message.getPolicySubject().attachPolicy(
                                            getPolicyFromKey(pi.getPolicyKey(), synCfg));
                                }
                            }
                        }
                    }
                } else {
                    handleException("Undefined Policy type");
                }
            }
        }

        // create a custom message receiver for this proxy service
        ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
        msgRcvr.setName(name);
        msgRcvr.setProxy(this);

        Iterator iter = proxyService.getOperations();
        while (iter.hasNext()) {
            AxisOperation op = (AxisOperation) iter.next();
            op.setMessageReceiver(msgRcvr);
        }

        try {
            proxyService.addParameter(
                    SynapseConstants.SERVICE_TYPE_PARAM_NAME, SynapseConstants.PROXY_SERVICE_TYPE);
            if (serviceGroup == null) {
                auditInfo("Adding service " + name + " to the Axis2 configuration");
                axisCfg.addService(proxyService);
            } else {
                auditInfo("Adding service " + name + " to the service group " + serviceGroup);
                if (axisCfg.getServiceGroup(serviceGroup) == null) {
                    // If the specified group does not exist we should create it
                    AxisServiceGroup proxyServiceGroup = new AxisServiceGroup();
                    proxyServiceGroup.setServiceGroupName(serviceGroup);
                    proxyServiceGroup.setParent(axisCfg);
                    // Add  the service to the new group and add the group the AxisConfiguration
                    proxyServiceGroup.addService(proxyService);
                    axisCfg.addServiceGroup(proxyServiceGroup);
                } else {
                    // Simply add the service to the existing group
                    proxyService.setParent(axisCfg.getServiceGroup(serviceGroup));
                    axisCfg.addServiceToExistingServiceGroup(proxyService, serviceGroup);
                }
            }
            this.setRunning(true);
        } catch (AxisFault axisFault) {
            try {
                if (axisCfg.getService(proxyService.getName()) != null) {
                    if (trace()) trace.info("Removing service " + name + " due to error : "
                        + axisFault.getMessage());
                    axisCfg.removeService(proxyService.getName());
                }
            } catch (AxisFault ignore) {}
            handleException("Error adding Proxy service to the Axis2 engine", axisFault);
        }

        // should Addressing be engaged on this service?
        if (wsAddrEnabled) {
            auditInfo("WS-Addressing is enabled for service : " + name);
            try {
                proxyService.engageModule(axisCfg.getModule(
                    SynapseConstants.ADDRESSING_MODULE_NAME), axisCfg);
            } catch (AxisFault axisFault) {
                handleException("Error loading WS Addressing module on proxy service : " + name, axisFault);
            }
        }

        // should RM be engaged on this service?
        if (wsRMEnabled) {
            auditInfo("WS-Reliable messaging is enabled for service : " + name);
            try {
                proxyService.engageModule(axisCfg.getModule(
                    SynapseConstants.RM_MODULE_NAME), axisCfg);
            } catch (AxisFault axisFault) {
                handleException("Error loading WS RM module on proxy service : " + name, axisFault);
            }
        }

        // should Security be engaged on this service?
        if (wsSecEnabled) {
            auditInfo("WS-Security is enabled for service : " + name);
            try {
                proxyService.engageModule(axisCfg.getModule(
                    SynapseConstants.SECURITY_MODULE_NAME), axisCfg);
            } catch (AxisFault axisFault) {
                handleException("Error loading WS Sec module on proxy service : "
                        + name, axisFault);
            }
        }

        moduleEngaged = wsSecEnabled || wsRMEnabled || wsAddrEnabled;
        wsdlPublished = wsdlFound;

        auditInfo("Successfully created the Axis2 service for Proxy service : " + name);
        return proxyService;
    }

    private void setUserDefinedResourceResolvers(SynapseConfiguration synCfg,
                                                 InputStream wsdlInputStream,
                                                 WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder) {
        String wsdlResolverName = synCfg.getProperty(SynapseConstants.SYNAPSE_WSDL_RESOLVER);
        String schemaResolverName = synCfg.getProperty(SynapseConstants.SYNAPSE_SCHEMA_RESOLVER);
        Class wsdlClazz, schemaClazz;
        Object wsdlClzzObject, schemaClazzObject;
        try {
            wsdlClazz = Class.forName(wsdlResolverName);
            schemaClazz = Class.forName(schemaResolverName);
        } catch (ClassNotFoundException e) {
            String msg =
                    "System could not find the class defined for the specific properties" +
                            " \n WSDLResolverImplementation:" + wsdlResolverName +
                            "\n SchemaResolverImplementation:" + schemaResolverName;
            handleException(msg, e);
            return;
        }

        try {
            wsdlClzzObject = wsdlClazz.newInstance();
            schemaClazzObject = schemaClazz.newInstance();
        } catch (Exception e) {
            String msg = "Could not create an instance from the class";
            handleException(msg, e);
            return;
        }

        UserDefinedXmlSchemaURIResolver userDefSchemaResolver =
                (UserDefinedXmlSchemaURIResolver) schemaClazzObject;
        userDefSchemaResolver.init(resourceMap, synCfg, wsdlKey);

        wsdlToAxisServiceBuilder.setCustomResolver(userDefSchemaResolver);
        if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
            UserDefinedWSDLLocator userDefWSDLLocator = (UserDefinedWSDLLocator) wsdlClzzObject;
            userDefWSDLLocator.init(new InputSource(wsdlInputStream),
                    wsdlURI != null ? wsdlURI.toString() : "", resourceMap, synCfg,
                    wsdlKey);
            ((WSDL11ToAxisServiceBuilder) wsdlToAxisServiceBuilder).
                    setCustomWSDLResolver(userDefWSDLLocator);
        }
    }

    private Policy getPolicyFromKey(String key, SynapseConfiguration synCfg) {

        synCfg.getEntryDefinition(key);
        return PolicyEngine.getPolicy(
                SynapseConfigUtils.getStreamSource(synCfg.getEntry(key)).getInputStream());
    }

    /**
     * Start the proxy service
     * @param synCfg the synapse configuration
     */
    public void start(SynapseConfiguration synCfg) {
        AxisConfiguration axisConfig = synCfg.getAxisConfiguration();
        if (axisConfig != null) {

            Parameter param = axisConfig.getParameter(SynapseConstants.SYNAPSE_ENV);
            if (param != null && param.getValue() instanceof SynapseEnvironment)  {
                SynapseEnvironment env = (SynapseEnvironment) param.getValue();
                if (targetInLineInSequence != null) {
                    targetInLineInSequence.init(env);
                }
                if (targetInLineOutSequence != null) {
                    targetInLineOutSequence.init(env);
                }
                if (targetInLineFaultSequence != null) {
                    targetInLineFaultSequence.init(env);
                }
            } else {
                auditWarn("Unable to find the SynapseEnvironment. " +
                        "Components of the proxy service may not be initialized");
            }

            AxisService as = axisConfig.getServiceForActivation(this.getName());
            as.setActive(true);
            axisConfig.notifyObservers(new AxisEvent(AxisEvent.SERVICE_START, as), as);
            this.setRunning(true);
            auditInfo("Started the proxy service : " + name);
        } else {
            auditWarn("Unable to start proxy service : " + name +
                ". Couldn't access Axis configuration");
        }
    }

    /**
     * Stop the proxy service
     * @param synCfg the synapse configuration
     */
    public void stop(SynapseConfiguration synCfg) {
        AxisConfiguration axisConfig = synCfg.getAxisConfiguration();
        if (axisConfig != null) {

            if (targetInLineInSequence != null) {
                targetInLineInSequence.destroy();
            }
            if (targetInLineOutSequence != null) {
                targetInLineOutSequence.destroy();
            }
            if (targetInLineFaultSequence != null) {
                targetInLineFaultSequence.destroy();
            }

            AxisService as = axisConfig.getServiceForActivation(this.getName());
            //If an active AxisService is found
            if (as != null && as.isActive()) {
                as.setActive(false);
                axisConfig.notifyObservers(new AxisEvent(AxisEvent.SERVICE_STOP, as), as);
            }
            this.setRunning(false);
            auditInfo("Stopped the proxy service : " + name);
        } else {
            auditWarn("Unable to stop proxy service : " + name +
                ". Couldn't access Axis configuration");
        }
    }

    private void handleException(String msg) {
        serviceLog.error(msg);
        log.error(msg);
        if (trace()) trace.error(msg);
        throw new SynapseException(msg);
    }

    private void handleException(String msg, Exception e) {
        serviceLog.error(msg);
        log.error(msg, e);
        if (trace()) trace.error(msg + " :: " + e.getMessage());
        throw new SynapseException(msg, e);
    }

    /**
     * Write to the general log, as well as any service specific logs the audit message at INFO
     * @param message the INFO level audit message
     */
    private void auditInfo(String message) {
        log.info(message);
        serviceLog.info(message);
        if (trace()) {
            trace.info(message);
        }
    }

    /**
     * Write to the general log, as well as any service specific logs the audit message at WARN
     * @param message the WARN level audit message
     */
    private void auditWarn(String message) {
        log.warn(message);
        serviceLog.warn(message);
        if (trace()) {
            trace.warn(message);
        }
    }

    /**
     * Return true if tracing should be enabled
     * @return true if tracing is enabled for this service
     */
    private boolean trace() {
        return traceState == SynapseConstants.TRACING_ON;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public ArrayList getTransports() {
        return transports;
    }

    public void addParameter(String name, Object value) {
        parameters.put(name, value);
    }

    public Map<String, Object> getParameterMap() {
        return this.parameters;
    }

    public void setTransports(ArrayList transports) {
        this.transports = transports;
    }

    public String getTargetEndpoint() {
        return targetEndpoint;
    }

    public void setTargetEndpoint(String targetEndpoint) {
        this.targetEndpoint = targetEndpoint;
    }

    public String getTargetInSequence() {
        return targetInSequence;
    }

    public void setTargetInSequence(String targetInSequence) {
        this.targetInSequence = targetInSequence;
    }

    public String getTargetOutSequence() {
        return targetOutSequence;
    }

    public void setTargetOutSequence(String targetOutSequence) {
        this.targetOutSequence = targetOutSequence;
    }

    public String getWSDLKey() {
        return wsdlKey;
    }

    public void setWSDLKey(String wsdlKey) {
        this.wsdlKey = wsdlKey;
    }

    public List<String> getServiceLevelPolicies() {
        return serviceLevelPolicies;
    }

    public void addServiceLevelPolicy(String serviceLevelPolicy) {
        this.serviceLevelPolicies.add(serviceLevelPolicy);
    }

    public boolean isWsAddrEnabled() {
        return wsAddrEnabled;
    }

    public void setWsAddrEnabled(boolean wsAddrEnabled) {
        this.wsAddrEnabled = wsAddrEnabled;
    }

    public boolean isWsRMEnabled() {
        return wsRMEnabled;
    }

    public void setWsRMEnabled(boolean wsRMEnabled) {
        this.wsRMEnabled = wsRMEnabled;
    }

    public boolean isWsSecEnabled() {
        return wsSecEnabled;
    }

    public void setWsSecEnabled(boolean wsSecEnabled) {
        this.wsSecEnabled = wsSecEnabled;
    }

    public boolean isStartOnLoad() {
        return startOnLoad;
    }

    public void setStartOnLoad(boolean startOnLoad) {
        this.startOnLoad = startOnLoad;
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

    /**
     * Returns the int value that indicate the tracing state
     *
     * @return Returns the int value that indicate the tracing state
     */
    public int getTraceState() {
        return traceState;
    }

    /**
     * Set the tracing State variable
     *
     * @param traceState tracing state
     */
    public void setTraceState(int traceState) {
        this.traceState = traceState;
    }

    public String getTargetFaultSequence() {
        return targetFaultSequence;
    }

    public void setTargetFaultSequence(String targetFaultSequence) {
        this.targetFaultSequence = targetFaultSequence;
    }

    public Object getInLineWSDL() {
        return inLineWSDL;
    }

    public void setInLineWSDL(Object inLineWSDL) {
        this.inLineWSDL = inLineWSDL;
    }

    public URI getWsdlURI() {
        return wsdlURI;
    }

    public void setWsdlURI(URI wsdlURI) {
        this.wsdlURI = wsdlURI;
    }

    public Endpoint getTargetInLineEndpoint() {
        return targetInLineEndpoint;
    }

    public void setTargetInLineEndpoint(Endpoint targetInLineEndpoint) {
        this.targetInLineEndpoint = targetInLineEndpoint;
    }

    public SequenceMediator getTargetInLineInSequence() {
        return targetInLineInSequence;
    }

    public void setTargetInLineInSequence(SequenceMediator targetInLineInSequence) {
        this.targetInLineInSequence = targetInLineInSequence;
    }

    public SequenceMediator getTargetInLineOutSequence() {
        return targetInLineOutSequence;
    }

    public void setTargetInLineOutSequence(SequenceMediator targetInLineOutSequence) {
        this.targetInLineOutSequence = targetInLineOutSequence;
    }

    public SequenceMediator getTargetInLineFaultSequence() {
        return targetInLineFaultSequence;
    }

    public void setTargetInLineFaultSequence(SequenceMediator targetInLineFaultSequence) {
        this.targetInLineFaultSequence = targetInLineFaultSequence;
    }

    public List getPinnedServers() {
        return pinnedServers;
    }

    public void setPinnedServers(List pinnedServers) {
        this.pinnedServers = pinnedServers;
    }

    public ResourceMap getResourceMap() {
        return resourceMap;
    }

    public void setResourceMap(ResourceMap resourceMap) {
        this.resourceMap = resourceMap;
    }

    public List<String> getInMessagePolicies() {
        return inMessagePolicies;
    }

    public void setInMessagePolicies(List<String> inMessagePolicies) {
        this.inMessagePolicies = inMessagePolicies;
    }

    public void addInMessagePolicy(String messagePolicy) {
        this.inMessagePolicies.add(messagePolicy);
    }

    public List<String> getOutMessagePolicies() {
        return outMessagePolicies;
    }

    public void setOutMessagePolicies(List<String> outMessagePolicies) {
        this.outMessagePolicies = outMessagePolicies;
    }

    public void addOutMessagePolicy(String messagePolicy) {
        this.outMessagePolicies.add(messagePolicy);
    }

    public List<PolicyInfo> getPolicies() {
        return policies;
    }

    public void setPolicies(List<PolicyInfo> policies) {
        this.policies = policies;
    }

    public void addPolicyInfo(PolicyInfo pi) {
        this.policies.add(pi);
    }

    public void configure(AspectConfiguration aspectConfiguration) {
        this.aspectConfiguration = aspectConfiguration;
    }

    public AspectConfiguration getAspectConfiguration() {
        return aspectConfiguration;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public void setFilePath(URL filePath) {
        this.filePath = filePath;
    }

    public String getServiceGroup() {
        return serviceGroup;
    }

    public void setServiceGroup(String serviceGroup) {
        this.serviceGroup = serviceGroup;
    }

    public boolean isModuleEngaged() {
        return moduleEngaged;
    }

    public void setModuleEngaged(boolean moduleEngaged) {
    	this.moduleEngaged = moduleEngaged;
    }

	public boolean isWsdlPublished() {
        return wsdlPublished;
    }

    private AxisOperation processOperationValidation(AxisService proxyService) throws AxisFault {
    	  AxisOperation mediateOperation = new InOutAxisOperation(
                  SynapseConstants.SYNAPSE_OPERATION_NAME);
          // Set the names of the two messages so that Axis2 is able to produce a WSDL (see SYNAPSE-366):
          mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE).setName("in");
          mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE).setName("out");
       // create a custom message receiver for this proxy service
          ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
          msgRcvr.setName(name);
          msgRcvr.setProxy(this);
          mediateOperation.setMessageReceiver(msgRcvr);
          mediateOperation.setParent(proxyService);
          proxyService.addParameter("_default_mediate_operation_", mediateOperation);
          return mediateOperation;

    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[ Proxy Service [ Name : ").append(name).append(" ] ]");
        return sb.toString();
    }

    public String getPublishWSDLEndpoint() {
        return publishWSDLEndpoint;
    }

    public void setPublishWSDLEndpoint(String publishWSDLEndpoint) {
        this.publishWSDLEndpoint = publishWSDLEndpoint;
    }
}


text:
package www.hwh.struts;

import com.opensymphony.xwork2.ActionSupport;

public class Action02 extends ActionSupport{

	public String add(){
		return SUCCESS;
	}

	public String delete(){
		//System.out.println("Delete");
		return SUCCESS;
	}
}

redpajama_set_name: RedPajamaGithub


text:
using Umbraco.Cms.Core.Sync;

namespace Umbraco.Cms.Core.Notifications
{
    public class DataTypeCacheRefresherNotification : CacheRefresherNotification
    {
        public DataTypeCacheRefresherNotification(object messageObject, MessageType messageType) : base(messageObject, messageType)
        {
        }
    }
}


text:
'''Volume driver for Dell Storage Center.'''

from oslo_log import log as logging
from oslo_utils import excutils

from cinder import exception
from cinder.i18n import _, _LE
from cinder.volume import driver
from cinder.volume.drivers.dell import dell_storagecenter_common
from cinder.zonemanager import utils as fczm_utils

LOG = logging.getLogger(__name__)

class DellStorageCenterFCDriver(dell_storagecenter_common.DellCommonDriver,
                                driver.FibreChannelDriver):

    '''Implements commands for Dell EqualLogic SAN ISCSI management.

    To enable the driver add the following line to the cinder configuration:
        volume_driver=cinder.volume.drivers.dell.DellStorageCenterFCDriver
    '''

    VERSION = '1.0.1'

    def __init__(self, *args, **kwargs):
        super(DellStorageCenterFCDriver, self).__init__(*args, **kwargs)
        self.backend_name =\
            self.configuration.safe_get('volume_backend_name') or 'Dell-FC'

    @fczm_utils.AddFCZone
    def initialize_connection(self, volume, connector):
        '''Initializes the connection and returns connection info.

        Assign any created volume to a compute node/host so that it can be
        used from that host.

        The  driver returns a driver_volume_type of 'fibre_channel'.
        The target_wwn can be a single entry or a list of wwns that
        correspond to the list of remote wwn(s) that will export the volume.
        '''

        # We use id to name the volume name as it is a
        # known unique name.
        volume_name = volume.get('id')
        LOG.debug('Initialize connection: %s', volume_name)
        with self._client.open_connection() as api:
            try:
                # Find our server.
                wwpns = connector.get('wwpns')
                for wwn in wwpns:
                    scserver = api.find_server(wwn)
                    if scserver is not None:
                        break

                # No? Create it.
                if scserver is None:
                    scserver = api.create_server_multiple_hbas(wwpns)
                # Find the volume on the storage center.
                scvolume = api.find_volume(volume_name)
                if scserver is not None and scvolume is not None:
                    mapping = api.map_volume(scvolume,
                                             scserver)
                    if mapping is not None:
                        # Since we just mapped our volume we had best update
                        # our sc volume object.
                        scvolume = api.find_volume(volume_name)
                        lun, targets, init_targ_map = api.find_wwns(scvolume,
                                                                    scserver)
                        if lun is not None and len(targets) > 0:
                            data = {'driver_volume_type': 'fibre_channel',
                                    'data': {'target_lun': lun,
                                             'target_discovered': True,
                                             'target_wwn': targets,
                                             'initiator_target_map':
                                             init_targ_map}}
                            LOG.debug('Return FC data:')
                            LOG.debug(data)
                            return data
                        LOG.error(_LE('Lun mapping returned null!'))

            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.error(_LE('Failed to initialize connection '))

        # We get here because our mapping is none so blow up.
        raise exception.VolumeBackendAPIException(
            _('unable to map volume'))

    @fczm_utils.RemoveFCZone
    def terminate_connection(self, volume, connector, force=False, **kwargs):
        # Get our volume name
        volume_name = volume.get('id')
        LOG.debug('Terminate connection: %s', volume_name)
        with self._client.open_connection() as api:
            try:
                wwpns = connector.get('wwpns')
                for wwn in wwpns:
                    scserver = api.find_server(wwn)
                    if scserver is not None:
                        break

                # Find the volume on the storage center.
                scvolume = api.find_volume(volume_name)
                # Get our target map so we can return it to free up a zone.
                lun, targets, init_targ_map = api.find_wwns(scvolume,
                                                            scserver)
                # If we have a server and a volume lets unmap them.
                if (scserver is not None and
                        scvolume is not None and
                        api.unmap_volume(scvolume, scserver) is True):
                    LOG.debug('Connection terminated')
                else:
                    raise exception.VolumeBackendAPIException(
                        _('Terminate connection failed'))

                # basic return info...
                info = {'driver_volume_type': 'fibre_channel',
                        'data': {}}

                # if not then we return the target map so that
                # the zone can be freed up.
                if api.get_volume_count(scserver) == 0:
                    info['data'] = {'target_wwn': targets,
                                    'initiator_target_map': init_targ_map}
                return info

            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.error(_LE('Failed to terminate connection'))
        raise exception.VolumeBackendAPIException(
            _('Terminate connection unable to connect to backend.'))

    def get_volume_stats(self, refresh=False):
        '''Get volume status.

        If 'refresh' is True, run update the stats first.
        '''
        if refresh:
            self._update_volume_stats()
            # Update our protocol to the correct one.
            self._stats['storage_protocol'] = 'FC'

        return self._stats


text:
import * as ts from 'typescript';
import { AngularCompilerPlugin } from '@ngtools/webpack';
import { readTsconfig } from '../utilities/read-tsconfig';
import { requireProjectModule } from '../utilities/require-project-module';
const webpackMerge = require('webpack-merge');
import { CliConfig } from './config';
import { BuildOptions } from './build-options';
import {
  getBrowserConfig,
  getCommonConfig,
  getDevConfig,
  getProdConfig,
  getStylesConfig,
  getServerConfig,
  getNonAotConfig,
  getAotConfig
} from './webpack-configs';
import * as path from 'path';

export interface WebpackConfigOptions<T extends BuildOptions = BuildOptions> {
  projectRoot: string;
  buildOptions: T;
  appConfig: any;
  tsConfig: any;
  supportES2015: boolean;
}

export class NgCliWebpackConfig<T extends BuildOptions = BuildOptions> {
  public config: any;
  public wco: WebpackConfigOptions<T>;
  constructor(buildOptions: T, appConfig: any) {

    this.validateBuildOptions(buildOptions);

    const configPath = CliConfig.configFilePath();
    const projectRoot = path.dirname(configPath);

    appConfig = this.addAppConfigDefaults(appConfig);
    buildOptions = this.addTargetDefaults(buildOptions);
    buildOptions = this.mergeConfigs(buildOptions, appConfig, projectRoot);

    const tsconfigPath = path.resolve(projectRoot, appConfig.root, appConfig.tsconfig);
    const tsConfig = readTsconfig(tsconfigPath);

    const projectTs = requireProjectModule(projectRoot, 'typescript') as typeof ts;

    const supportES2015 = tsConfig.options.target !== projectTs.ScriptTarget.ES3
                        && tsConfig.options.target !== projectTs.ScriptTarget.ES5;

    this.wco = { projectRoot, buildOptions, appConfig, tsConfig, supportES2015 };
  }

  public buildConfig() {
    const platformConfig = this.wco.appConfig.platform === 'server' ?
      getServerConfig(this.wco) : getBrowserConfig(this.wco);

    let webpackConfigs = [
      getCommonConfig(this.wco),
      platformConfig,
      getStylesConfig(this.wco),
      this.getTargetConfig(this.wco)
    ];

    if (this.wco.appConfig.main || this.wco.appConfig.polyfills) {
      const typescriptConfigPartial = this.wco.buildOptions.aot
        ? getAotConfig(this.wco)
        : getNonAotConfig(this.wco);
      webpackConfigs.push(typescriptConfigPartial);
    }

    this.config = webpackMerge(webpackConfigs);
    return this.config;
  }

  public getTargetConfig(webpackConfigOptions: WebpackConfigOptions<T>): any {
    switch (webpackConfigOptions.buildOptions.target) {
      case 'development':
        return getDevConfig(webpackConfigOptions);
      case 'production':
        return getProdConfig(webpackConfigOptions);
    }
  }

  // Validate build options
  public validateBuildOptions(buildOptions: BuildOptions) {
    buildOptions.target = buildOptions.target || 'development';
    if (buildOptions.target !== 'development' && buildOptions.target !== 'production') {
      throw new Error("Invalid build target. Only 'development' and 'production' are available.");
    }

    if (buildOptions.buildOptimizer
      && !(buildOptions.aot || buildOptions.target === 'production')) {
      throw new Error('The `--build-optimizer` option cannot be used without `--aot`.');
    }
  }

  // Fill in defaults for build targets
  public addTargetDefaults(buildOptions: T): T {
    const targetDefaults: { [target: string]: Partial<BuildOptions> } = {
      development: {
        environment: 'dev',
        outputHashing: 'media',
        sourcemaps: true,
        extractCss: false,
        namedChunks: true,
        aot: false,
        buildOptimizer: false
      },
      production: {
        environment: 'prod',
        outputHashing: 'all',
        sourcemaps: false,
        extractCss: true,
        namedChunks: false,
        aot: true
      }
    };

    let merged = Object.assign({}, targetDefaults[buildOptions.target], buildOptions);

    // Use Build Optimizer on prod AOT builds by default when AngularCompilerPlugin is supported.
    const buildOptimizerDefault = {
      buildOptimizer: buildOptions.target == 'production' && buildOptions.aot !== false
        && AngularCompilerPlugin.isSupported()
    };

    merged = Object.assign({}, buildOptimizerDefault, merged);

    // Default vendor chunk to false when build optimizer is on.
    const vendorChunkDefault = {
      vendorChunk: !merged.buildOptimizer
    };

    merged = Object.assign({}, vendorChunkDefault, merged);

    return merged;
  }

  // Fill in defaults from .angular-cli.json
  public mergeConfigs(buildOptions: T, appConfig: any, projectRoot: string): T {
    const mergeableOptions: Partial<BuildOptions> = {
      outputPath: path.resolve(projectRoot, appConfig.outDir),
      deployUrl: appConfig.deployUrl,
      baseHref: appConfig.baseHref
    };

    return Object.assign({}, mergeableOptions, buildOptions);
  }

  public addAppConfigDefaults(appConfig: any) {
    const appConfigDefaults: any = {
      testTsconfig: appConfig.tsconfig,
      scripts: [],
      styles: []
    };

    // can't use Object.assign here because appConfig has a lot of getters/setters
    for (let key of Object.keys(appConfigDefaults)) {
      appConfig[key] = appConfig[key] || appConfigDefaults[key];
    }

    return appConfig;
  }
}


text:
<?php
namespace Neos\FluidAdaptor\Core\Widget\Exception;

use Neos\FluidAdaptor\Core\Widget;

/**
 * An exception if the widget controller has been changed
 */
class InvalidControllerException extends Widget\Exception
{
}


text:
typedef struct person {
	uid_t uid;			/* user id */
	char *dir;			/* user's home directory */
	char *homephone;		/* pointer to home phone no. */
	char *name;			/* login name */
	char *office;			/* pointer to office name */
	char *officephone;		/* pointer to office phone no. */
	char *realname;			/* pointer to full name */
	char *shell;			/* user's shell */
	time_t mailread;		/* last time mail was read */
	time_t mailrecv;		/* last time mail was received */
	struct where *whead, *wtail;	/* list of where user is or has been */
} PERSON;

enum status { LASTLOG, LOGGEDIN };

typedef struct where {
	struct where *next;		/* next place user is or has been */
	enum status info;		/* type/status of request */
	short writable;			/* tty is writable */
	time_t loginat;			/* time of (last) login */
	time_t idletime;		/* how long idle (if logged in) */
	char tty[UT_LINESIZE+1];	/* null terminated tty line */
	char host[UT_HOSTSIZE+1];	/* null terminated remote host name */
} WHERE;

#include "extern.h"


text:
Rails.configuration.stripe = {
  publishable_key: ENV['STRIPE_PUBLISHABLE_KEY'],
  secret_key: ENV['STRIPE_SECRET_KEY']
}

Stripe.api_key = Rails.configuration.stripe[:secret_key]

Stripe.set_app_info('Rails PaidUp', version: PaidUp::VERSION, url: 'https://www.gemvein.com/museum/cases/paid_up')

Money.rounding_mode = BigDecimal::ROUND_HALF_UP


text:
package ru.otus.base;

import ru.otus.base.dataSets.UserDataSet;

import java.util.List;

/**
 * @author v.chibrikov
 */
public interface DBService {
    String getLocalStatus();

    void save(UserDataSet dataSet);

    UserDataSet read(long id);

    UserDataSet readByName(String name);

    List<UserDataSet> readAll();

    void shutdown();
}


text:
<!DOCTYPE html>

  <title></title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="styles/bites.css">


text:
package content

import (
	"bytes"
	"compress/gzip"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/url"
	"strings"
	"sync"

	"github.com/Masterminds/semver/v3"
	"github.com/rancher/rancher/pkg/api/steve/catalog/types"
	v1 "github.com/rancher/rancher/pkg/apis/catalog.cattle.io/v1"
	"github.com/rancher/rancher/pkg/catalogv2"
	"github.com/rancher/rancher/pkg/catalogv2/git"
	"github.com/rancher/rancher/pkg/catalogv2/helm"
	helmhttp "github.com/rancher/rancher/pkg/catalogv2/http"
	catalogcontrollers "github.com/rancher/rancher/pkg/generated/controllers/catalog.cattle.io/v1"
	"github.com/rancher/rancher/pkg/settings"
	corecontrollers "github.com/rancher/wrangler/pkg/generated/controllers/core/v1"
	"github.com/rancher/wrangler/pkg/schemas/validation"
	"github.com/sirupsen/logrus"
	"helm.sh/helm/v3/pkg/repo"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/discovery"
)

type Manager struct {
	configMaps   corecontrollers.ConfigMapCache
	secrets      corecontrollers.SecretCache
	clusterRepos catalogcontrollers.ClusterRepoCache
	discovery    discovery.DiscoveryInterface
	IndexCache   map[string]indexCache
	lock         sync.RWMutex
}

type indexCache struct {
	index    *repo.IndexFile
	revision string
}

func NewManager(
	discovery discovery.DiscoveryInterface,
	configMaps corecontrollers.ConfigMapCache,
	secrets corecontrollers.SecretCache,
	clusterRepos catalogcontrollers.ClusterRepoCache) *Manager {
	return &Manager{
		discovery:    discovery,
		configMaps:   configMaps,
		secrets:      secrets,
		clusterRepos: clusterRepos,
		IndexCache:   map[string]indexCache{},
	}
}

type repoDef struct {
	typedata *metav1.TypeMeta
	metadata *metav1.ObjectMeta
	spec     *v1.RepoSpec
	status   *v1.RepoStatus
}

func (c *Manager) getRepo(namespace, name string) (repoDef, error) {
	if namespace == "" {
		cr, err := c.clusterRepos.Get(name)
		if err != nil {
			return repoDef{}, err
		}
		return repoDef{
			typedata: &cr.TypeMeta,
			metadata: &cr.ObjectMeta,
			spec:     &cr.Spec,
			status:   &cr.Status,
		}, nil
	}

	panic("namespace should never be empty")
}

func (c *Manager) readBytes(cm *corev1.ConfigMap) ([]byte, error) {
	var (
		bytes = cm.BinaryData["content"]
		err   error
	)

	for {
		next := cm.Annotations["catalog.cattle.io/next"]
		if next == "" {
			break
		}
		cm, err = c.configMaps.Get(cm.Namespace, next)
		if err != nil {
			return nil, err
		}
		bytes = append(bytes, cm.BinaryData["content"]...)
	}

	return bytes, nil
}

func (c *Manager) Index(namespace, name string, skipFilter bool) (*repo.IndexFile, error) {
	r, err := c.getRepo(namespace, name)
	if err != nil {
		return nil, err
	}

	cm, err := c.configMaps.Get(r.status.IndexConfigMapNamespace, r.status.IndexConfigMapName)
	if err != nil {
		return nil, err
	}

	k8sVersion, err := c.k8sVersion()
	if err != nil {
		return nil, err
	}

	c.lock.RLock()
	if cache, ok := c.IndexCache[fmt.Sprintf("%s/%s", r.status.IndexConfigMapNamespace, r.status.IndexConfigMapName)]; ok {
		if cm.ResourceVersion == cache.revision {
			c.lock.RUnlock()
			return c.filterReleases(deepCopyIndex(cache.index), k8sVersion, skipFilter), nil
		}
	}
	c.lock.RUnlock()

	if len(cm.OwnerReferences) == 0 || cm.OwnerReferences[0].UID != r.metadata.UID {
		return nil, validation.Unauthorized
	}

	data, err := c.readBytes(cm)
	if err != nil {
		return nil, err
	}

	gz, err := gzip.NewReader(bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}
	defer gz.Close()

	data, err = ioutil.ReadAll(gz)
	if err != nil {
		return nil, err
	}

	index := &repo.IndexFile{}
	if err := json.Unmarshal(data, index); err != nil {
		return nil, err
	}

	c.lock.Lock()
	c.IndexCache[fmt.Sprintf("%s/%s", r.status.IndexConfigMapNamespace, r.status.IndexConfigMapName)] = indexCache{
		index:    index,
		revision: cm.ResourceVersion,
	}
	c.lock.Unlock()

	return c.filterReleases(deepCopyIndex(index), k8sVersion, skipFilter), nil
}

func (c *Manager) k8sVersion() (*semver.Version, error) {
	info, err := c.discovery.ServerVersion()
	if err != nil {
		return nil, err
	}
	return semver.NewVersion(info.GitVersion)
}

func deepCopyIndex(src *repo.IndexFile) *repo.IndexFile {
	deepcopy := repo.IndexFile{
		APIVersion: src.APIVersion,
		Generated:  src.Generated,
		Entries:    map[string]repo.ChartVersions{},
	}
	keys := deepcopy.PublicKeys
	copy(keys, src.PublicKeys)
	for k, entries := range src.Entries {
		for _, chart := range entries {
			cpMeta := *chart.Metadata
			cpChart := &repo.ChartVersion{
				Metadata: &cpMeta,
				Created:  chart.Created,
				Removed:  chart.Removed,
				Digest:   chart.Digest,
				URLs:     make([]string, len(chart.URLs)),
			}

			copy(cpChart.URLs, chart.URLs)
			deepcopy.Entries[k] = append(deepcopy.Entries[k], cpChart)
		}
	}
	return &deepcopy
}

func (c *Manager) filterReleases(index *repo.IndexFile, k8sVersion *semver.Version, skipFilter bool) *repo.IndexFile {
	if !settings.IsRelease() || skipFilter {
		return index
	}

	rancherVersion, err := semver.NewVersion(settings.ServerVersion.Get())
	if err != nil {
		logrus.Errorf("failed to parse server version %s: %v", settings.ServerVersion.Get(), err)
		return index
	}
	rancherVersionWithoutPrerelease, err := rancherVersion.SetPrerelease("")
	if err != nil {
		logrus.Errorf("failed to remove prerelease from %s: %v", settings.ServerVersion.Get(), err)
		return index
	}

	for rel, versions := range index.Entries {
		newVersions := make([]*repo.ChartVersion, 0, len(versions))
		for _, version := range versions {
			if constraintStr, ok := version.Annotations["catalog.cattle.io/rancher-version"]; ok {
				if constraint, err := semver.NewConstraint(constraintStr); err == nil {
					satisfiesConstraint, errs := constraint.Validate(rancherVersion)
					// Check if the reason for failure is because it is ignroing prereleases
					constraintDoesNotMatchPrereleases := false
					for _, err := range errs {
						// Comes from error in https://github.com/Masterminds/semver/blob/60c7ae8a99210a90a9457d5de5f6dcbc4dab8e64/constraints.go#L93
						if strings.Contains(err.Error(), "the constraint is only looking for release versions") {
							constraintDoesNotMatchPrereleases = true
							break
						}
					}
					if constraintDoesNotMatchPrereleases {
						satisfiesConstraint = constraint.Check(&rancherVersionWithoutPrerelease)
					}
					if !satisfiesConstraint {
						continue
					}
				} else {
					logrus.Errorf("failed to parse constraint version %s: %v", constraintStr, err)
				}
			}
			if constraintStr, ok := version.Annotations["catalog.cattle.io/kube-version"]; ok {
				if constraint, err := semver.NewConstraint(constraintStr); err == nil {
					if !constraint.Check(k8sVersion) {
						continue
					}
				} else {
					logrus.Errorf("failed to parse constraint kube-version %s from annotation: %v", constraintStr, err)
				}
			}
			if version.KubeVersion != "" {
				if constraint, err := semver.NewConstraint(version.KubeVersion); err == nil {
					if !constraint.Check(k8sVersion) {
						continue
					}
				} else {
					logrus.Errorf("failed to parse constraint for kubeversion %s: %v", version.KubeVersion, err)
				}

			}
			newVersions = append(newVersions, version)
		}

		if len(newVersions) == 0 {
			delete(index.Entries, rel)
		} else {
			index.Entries[rel] = newVersions
		}
	}

	return index
}

func (c *Manager) Icon(namespace, name, chartName, version string) (io.ReadCloser, string, error) {
	index, err := c.Index(namespace, name, true)
	if err != nil {
		return nil, "", err
	}

	chart, err := index.Get(chartName, version)
	if err != nil {
		return nil, "", err
	}

	repo, err := c.getRepo(namespace, name)
	if err != nil {
		return nil, "", err
	}

	if !isHTTP(chart.Icon) && repo.status.Commit != "" {
		return git.Icon(namespace, name, repo.status.URL, chart)
	}

	secret, err := catalogv2.GetSecret(c.secrets, repo.spec, repo.metadata.Namespace)
	if err != nil {
		return nil, "", err
	}

	return helmhttp.Icon(secret, repo.status.URL, repo.spec.CABundle, repo.spec.InsecureSkipTLSverify, repo.spec.DisableSameOriginCheck, chart)
}

func isHTTP(iconURL string) bool {
	u, err := url.Parse(iconURL)
	return err == nil && (u.Scheme == "http" || u.Scheme == "https")
}

func (c *Manager) Chart(namespace, name, chartName, version string, skipFilter bool) (io.ReadCloser, error) {
	index, err := c.Index(namespace, name, skipFilter)
	if err != nil {
		return nil, err
	}

	chart, err := index.Get(chartName, version)
	if err != nil {
		return nil, err
	}

	repo, err := c.getRepo(namespace, name)
	if err != nil {
		return nil, err
	}

	if repo.status.Commit != "" {
		return git.Chart(namespace, name, repo.status.URL, chart)
	}

	secret, err := catalogv2.GetSecret(c.secrets, repo.spec, repo.metadata.Namespace)
	if err != nil {
		return nil, err
	}

	return helmhttp.Chart(secret, repo.status.URL, repo.spec.CABundle, repo.spec.InsecureSkipTLSverify, repo.spec.DisableSameOriginCheck, chart)
}

func (c *Manager) Info(namespace, name, chartName, version string) (*types.ChartInfo, error) {
	chart, err := c.Chart(namespace, name, chartName, version, true)
	if err != nil {
		return nil, err
	}
	defer chart.Close()

	return helm.InfoFromTarball(chart)
}


text:
package com.imethod.service.sys.dao;

import com.imethod.core.bean.PageMaker;
import com.imethod.core.jdbc.mine.IBaseDao;
import com.imethod.service.sys.domain.Org;
import org.springframework.stereotype.Repository;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@Repository
public class OrgDao extends IBaseDao {

    public Org loadById(Long orgId) {
        Map<String, Object> map = new HashMap<>();
        map.put("org_id", orgId);
        Org org = null;
        try {
            org = load(Org.class, map);
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return org;
    }

    String SQL_LIST_ORG = "select * from org where state = 1 ";

    public PageMaker list(Long pageIndex, Long pageSize) {
        return this.queryPageList(SQL_LIST_ORG, pageIndex, pageSize, new HashMap<>());
    }

}


text:
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <link rel="profile" href="http://microformats.org/profile/hcard" />

Dr. Gregory House M.D.

        Dr
        Gregory
        House
        MD


text:
#include "dpaa_sys.h"
#include <process.h>
#include <fsl_qman.h>
#include <fsl_bman.h>

int bman_alloc_bpid_range(u32 *result, u32 count, u32 align, int partial)
{
	return process_alloc(dpaa_id_bpid, result, count, align, partial);
}

void bman_release_bpid_range(u32 bpid, u32 count)
{
	process_release(dpaa_id_bpid, bpid, count);
}

int bman_reserve_bpid_range(u32 bpid, u32 count)
{
	return process_reserve(dpaa_id_bpid, bpid, count);
}

int qman_alloc_fqid_range(u32 *result, u32 count, u32 align, int partial)
{
	return process_alloc(dpaa_id_fqid, result, count, align, partial);
}

void qman_release_fqid_range(u32 fqid, u32 count)
{
	process_release(dpaa_id_fqid, fqid, count);
}

int qman_reserve_fqid_range(u32 fqid, unsigned int count)
{
	return process_reserve(dpaa_id_fqid, fqid, count);
}

int qman_alloc_pool_range(u32 *result, u32 count, u32 align, int partial)
{
	return process_alloc(dpaa_id_qpool, result, count, align, partial);
}

void qman_release_pool_range(u32 pool, u32 count)
{
	process_release(dpaa_id_qpool, pool, count);
}

int qman_reserve_pool_range(u32 pool, u32 count)
{
	return process_reserve(dpaa_id_qpool, pool, count);
}

int qman_alloc_cgrid_range(u32 *result, u32 count, u32 align, int partial)
{
	return process_alloc(dpaa_id_cgrid, result, count, align, partial);
}

void qman_release_cgrid_range(u32 cgrid, u32 count)
{
	process_release(dpaa_id_cgrid, cgrid, count);
}

int qman_reserve_cgrid_range(u32 cgrid, u32 count)
{
	return process_reserve(dpaa_id_cgrid, cgrid, count);
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	<package name="departmentHead" namespace="/" extends="struts-default">
		<default-action-ref name="index" />

		<!-- Pages -->
		<action name="departmentHead">
			<result>
				jsp/departmentHead/departmentHead.jsp
			</result>
		</action>

		<action name="departmentHeadInfo">
			<result>
				jsp/departmentHead/departmentHeadInfo.jsp
			</result>
		</action>

		<action name="departmentHeadTeacher">
			<result>
				jsp/departmentHead/departmentHeadTeacher.jsp
			</result>
		</action>

		<action name="departmentHeadTeacherDetail">
			<result>
				jsp/departmentHead/departmentHeadTeacherDetail.jsp
			</result>
		</action>

		<action name="departmentHeadStudent">
			<result>
				jsp/departmentHead/departmentHeadStudent.jsp
			</result>
		</action>

		<action name="departmentHeadStudentDetail">
			<result>
				jsp/departmentHead/departmentHeadStudentDetail.jsp
			</result>
		</action>

		<action name="departmentHeadStudentGrade">
			<result>
				jsp/departmentHead/departmentHeadStudentGrade.jsp
			</result>
		</action>
		<action name="departmentHeadSubjectDetail">
			<result>
				jsp/departmentHead/departmentHeadSubject.jsp
			</result>
		</action>
		<action name="departmentHeadSubjectDetail">
			<result>
				jsp/departmentHead/departmentHeadSubjectDetail.jsp
			</result>
		</action>

		<action name="departmentHeadSubjectManage">
			<result>
				jsp/departmentHead/departmentHeadSubjectManage.jsp
			</result>
		</action>

		<action name="departmentHeadGroup">
			<result>
				jsp/departmentHead/departmentHeadGroup.jsp
			</result>
		</action>

		<action name="studentGradeManage">
			<result>
				jsp/departmentHead/studentGradeManage.jsp
			</result>
		</action>

		<!-- actions -->
		<action name="DepartmentHeadStudentGrade"
			class="com.find1x.gpms.action.DepartmentHeadStudentGradeAction">
			<result>
				jsp/departmentHead/departmentHeadStudentGrade.jsp
			</result>
		</action>

		<action name="DepartmentHeadSubjectManage"
			class="com.find1x.gpms.action.teacherSubjectManageAction">
			<result>
				jsp/departmentHead/departmentHeadSubjectManage.jsp
			</result>
		</action>

		<action name="DepartmentChangeIssue" class="com.find1x.gpms.action.ChangeIssueAction">
			<result>
				jsp/departmentHead/departmentHeadSubjectManage.jsp
			</result>
		</action>

		<action name="DepartmentHeadGroup" class="com.find1x.gpms.action.DepartmentHeadGroupAction">
			<result>
				jsp/departmentHead/departmentHeadTeacher.jsp
			</result>
		</action>

	</package>
</struts>


text:
<!DOCTYPE HTML>

    <title>471</title>

471

Kalugen sits upon his throne wearing elaborate robes of olive-green satin-silk bordered in gold. Emeralds hang from
    his ears and fingers like dewdrops. He has a small, cruel, thick-lipped mouth. 'Let us speak frankly,' he says in a
    cold voice. 'I am not much interested in the contest tomorrow. I have made arrangements with several other magi and
    thus gained numerous concessions. I do not need to win tomorrow, so I have decided to have a little
    sport...' Suddenly he sits bolt upright and claps his hands down on the arms of the throne. 'Let's have a game! I
    like playing games. What do you want to play? How about Old Man of the Mountain? Or there's Prey's Roosters, but
    that's not really as much fun . . .'

If you suggest playing Old Man of the Mountain, turn to 162.

If you ask to play Prey's Roosters, turn to 328.


text:
package io.gravitee.rest.api.management.rest.resource;

import io.gravitee.common.http.MediaType;
import io.gravitee.repository.management.model.ApplicationStatus;
import io.gravitee.rest.api.management.rest.security.Permission;
import io.gravitee.rest.api.management.rest.security.Permissions;
import io.gravitee.rest.api.model.ApplicationEntity;
import io.gravitee.rest.api.model.NewApplicationEntity;
import io.gravitee.rest.api.model.application.ApplicationListItem;
import io.gravitee.rest.api.model.application.ApplicationSettings;
import io.gravitee.rest.api.model.application.SimpleApplicationSettings;
import io.gravitee.rest.api.model.permissions.RolePermission;
import io.gravitee.rest.api.model.permissions.RolePermissionAction;
import io.gravitee.rest.api.service.ApplicationService;
import io.gravitee.rest.api.service.common.GraviteeContext;
import io.gravitee.rest.api.service.exceptions.ForbiddenAccessException;
import io.gravitee.rest.api.service.notification.ApplicationHook;
import io.gravitee.rest.api.service.notification.Hook;
import io.swagger.annotations.*;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author Nicolas GERAUD (nicolas.geraud at graviteesource.com)
 * @author GraviteeSource Team
 */
@Api(tags = { "Applications" })
public class ApplicationsResource extends AbstractResource {

    @Context
    private ResourceContext resourceContext;

    @Inject
    private ApplicationService applicationService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(
        value = "List all the applications accessible to authenticated user",
        notes = "User must have MANAGEMENT_APPLICATION[READ] and PORTAL_APPLICATION[READ] permission to list applications."
    )
    @ApiResponses(
        {
            @ApiResponse(code = 200, message = "User's applications", response = ApplicationEntity.class, responseContainer = "List"),
            @ApiResponse(code = 500, message = "Internal server error"),
        }
    )
    @Permissions({ @Permission(value = RolePermission.ENVIRONMENT_APPLICATION, acls = RolePermissionAction.READ) })
    public List<ApplicationListItem> getApplications(
        @QueryParam("group") final String group,
        @QueryParam("query") final String query,
        @QueryParam("status") @DefaultValue("ACTIVE") final String status
    ) {
        Set<ApplicationListItem> applications;

        if (!isAdmin() && ApplicationStatus.ARCHIVED.name().equalsIgnoreCase(status)) {
            throw new ForbiddenAccessException();
        }

        if (query != null && !query.trim().isEmpty()) {
            applications = applicationService.findByNameAndStatus(isAdmin() ? null : getAuthenticatedUser(), query, status);
        } else if (isAdmin()) {
            applications =
                group != null
                    ? applicationService.findByGroupsAndStatus(Collections.singletonList(group), status)
                    : applicationService.findByStatus(status);
        } else {
            applications = applicationService.findByUser(getAuthenticatedUser());
            if (group != null && !group.isEmpty()) {
                applications =
                    applications
                        .stream()
                        .filter(app -> app.getGroups() != null && app.getGroups().contains(group))
                        .collect(Collectors.toSet());
            }
        }

        applications.forEach(application -> this.addPictureUrl(application));

        return applications
            .stream()
            .sorted(
                (o1, o2) ->
                    ApplicationStatus.ACTIVE.name().equalsIgnoreCase(status)
                        ? String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName())
                        : o2.getUpdatedAt().compareTo(o1.getUpdatedAt())
            )
            .collect(Collectors.toList());
    }

    private void addPictureUrl(ApplicationListItem application) {
        final UriBuilder ub = uriInfo.getBaseUriBuilder();
        final UriBuilder uriBuilder = ub
            .path("organizations")
            .path(GraviteeContext.getCurrentOrganization())
            .path("environments")
            .path(GraviteeContext.getCurrentEnvironment())
            .path("applications")
            .path(application.getId())
            .path("picture");
        // force browser to get if updated
        uriBuilder.queryParam("hash", application.getUpdatedAt().getTime());
        application.setPicture(null);
        application.setPictureUrl(uriBuilder.build().toString());
    }

    /**
     * Create a new application for the authenticated user.
     *
     * @param application
     * @return
     */
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(
        value = "Create an application",
        notes = "User must have MANAGEMENT_APPLICATION[CREATE] permission to create an application."
    )
    @ApiResponses(
        {
            @ApiResponse(code = 201, message = "Application successfully created", response = ApplicationEntity.class),
            @ApiResponse(code = 500, message = "Internal server error"),
        }
    )
    @Permissions({ @Permission(value = RolePermission.ENVIRONMENT_APPLICATION, acls = RolePermissionAction.CREATE) })
    public Response createApplication(
        @ApiParam(name = "application", required = true) @Valid @NotNull(
            message = "An application must be provided"
        ) final NewApplicationEntity application
    ) {
        // To preserve backward compatibility, ensure that we have at least default settings for simple application type
        if (
            application.getSettings() == null ||
            (application.getSettings().getoAuthClient() == null && application.getSettings().getApp() == null)
        ) {
            ApplicationSettings settings = new ApplicationSettings();
            SimpleApplicationSettings simpleAppSettings = new SimpleApplicationSettings();
            simpleAppSettings.setType(application.getType());
            simpleAppSettings.setClientId(application.getClientId());
            settings.setApp(simpleAppSettings);
            application.setSettings(settings);
        }

        ApplicationEntity newApplication = applicationService.create(application, getAuthenticatedUser());
        if (newApplication != null) {
            return Response.created(this.getLocationHeader(newApplication.getId())).entity(newApplication).build();
        }

        return Response.serverError().build();
    }

    @GET
    @Path("/hooks")
    @ApiOperation("Get the list of available hooks")
    @ApiResponses({ @ApiResponse(code = 200, message = "List of hooks"), @ApiResponse(code = 500, message = "Internal server error") })
    @Produces(MediaType.APPLICATION_JSON)
    public Hook[] getApplicationHooks() {
        return ApplicationHook.values();
    }

    @Path("{application}")
    public ApplicationResource getApplicationResource() {
        return resourceContext.getResource(ApplicationResource.class);
    }
}


text:
.theme-explorer .file-preview .table {
    margin: 0;
}

.theme-explorer .explorer-frame td {
    vertical-align: middle;
    text-align: left;
}

.explorer-frame .file-preview-text {
    display: inline-block;
    color: #428bca;
    border: 1px solid #ddd;
    font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
    outline: none;
    padding: 8px;
    resize: none;
}

.explorer-frame .file-preview-html {
    display: inline-block;
    border: 1px solid #ddd;
    padding: 8px;
    overflow: auto;
}

.explorer-frame .file-preview-other {
    text-align: center;
}

.explorer-frame .file-other-icon {
    font-size: 4.2em;
}

.theme-explorer .explorer-frame .kv-file-content {
    width: 80px;
    height: 80px;
    padding: 5px;
    text-align: center;
}

.theme-explorer .file-actions-cell {
    width: 100px;
    padding: 0;
}

.theme-explorer .file-thumb-progress .progress {
    display: block;
    margin-top: 5px;
}

.theme-explorer .file-thumb-progress .progress, .theme-explorer .file-thumb-progress .progress-bar {
    height: 13px;
    font-size: 11px;
    line-height: 13px;
}

.theme-explorer .file-actions-cell {
    position: relative;
}

.theme-explorer .file-upload-indicator, .theme-explorer .file-drag-handle {
    position: absolute;
    text-align: center;
    top: 0;
    right: 0;
    padding-left: 5px;
    padding-right: 2px;
    border-right: none;
    border-top: none;
    border-left: 1px solid #8a6d3b;
    border-bottom: 1px solid #8a6d3b;
    border-bottom-left-radius: 11px;
    font-size: 12px;
}

.theme-explorer .explorer-caption {
    display: block;
    color: #777;
}

.theme-explorer .file-actions {
    text-align: center;
}

.theme-explorer .kvsortable-ghost {
    opacity: 0.6;
    background: #e1edf7;
    border: 2px solid #a1abff;
}

.theme-explorer .file-upload-indicator {
    font-size: 13px;
    padding-left: 6px;
    background-color: #fcf8e3;
    border-color: #faebcc;
}

.theme-explorer .file-drag-handle {
    right: -2px;
    background-color: #d9edf7;
    border-color: #bce8f1;
}

.theme-explorer .file-preview-error .file-upload-indicator {
    background-color: #f2dede;
    border-color: #ebccd1;
}

.theme-explorer .file-preview-success .file-upload-indicator {
    background-color: #dff0d8;
    border-color: #d6e9c6;
}

.theme-explorer .file-preview-loading .file-upload-indicator {
    background-color: #e5e5e5;
    border-color: #777;
}

.theme-explorer .file-error-message ul {
    padding-left: 15px;
}

.theme-explorer .file-error-message .close {
    margin-top: -5px;
    margin-right: -5px;
}

/*
 * mobile responsive styling
 */
@media only screen and (max-width: 500px) {
    .theme-explorer .table, .theme-explorer .table tbody, .theme-explorer .table tr, .theme-explorer .table td {
        display: block;
        width: 100% !important;
    }

    .theme-explorer .table {
        border: none;
    }

    .theme-explorer .table tr {
        margin-top: 5px;
    }

    .theme-explorer .table tr:first-child {
        margin-top: 0;
    }

    .theme-explorer .table td {
        text-align: center;
    }

    .theme-explorer .table .kv-file-content {
        border-bottom: none;
        padding: 4px;
        margin: 0;
    }

    .theme-explorer .table .kv-file-content .file-preview-image {
        max-width: 100%;
        font-size: 20px;
    }

    .theme-explorer .file-details-cell {
        border-top: none;
        border-bottom: none;
        padding-top: 0;
        margin: 0;
    }

    .theme-explorer .file-actions-cell {
        border-top: none;
        padding-bottom: 4px;
    }

    .theme-explorer .explorer-frame .explorer-caption {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        left: 0;
        right: 0;
        margin: auto;
    }

    .theme-explorer .file-upload-indicator, .theme-explorer .file-drag-handle {
        right: 0;
        bottom: 0;
        border-top-left-radius: 40px;
        border-bottom-left-radius: 0;
        padding: 12px 3px 0 6px;
    }

    .theme-explorer .file-actions-cell .btn-xs {
        font-size: 0.9em;
        padding: 2px 7px;
        margin-right: 3px;
        cursor: pointer;
    }
}


text:
module Paginative
  module ModelExtension
    extend ActiveSupport::Concern

    included do
      include Paginative::OrderingHelpers

      def self.by_distance_from(latitude, longitude, distance=0, limit=25)
        return [] unless latitude.present? && longitude.present?
        distance_sql = send(:distance_sql, latitude.to_f, longitude.to_f, {:units => :km, select_bearing: false})

        self.where("#{distance_sql} >  ?", distance).offset(0).limit(limit)
      end

      def self.with_name_from(name="", limit=25, order="asc")
        return self.order("name DESC").where("lower(name) < ?", name.downcase).offset(0).limit(limit) if order == "desc"
        self.order(name: :asc).where("lower(#{self.table_name}.name) > ?", name.downcase).offset(0).limit(limit)
      end

      def self.with_id_from(id=0, limit=25)
        self.order(id: :asc).where("id > ?", id).limit(limit)
      end

      def self.with_field_from(field="", value="", limit=25, order="asc")
        order ||= "asc"

        # Wrap and flatten whatever comes in, if it's a single value, we end up with an array.
        # If it's an array, stays an array.
        fields = Array.wrap(field).flatten
        values = Array.wrap(value).flatten
        zipped = fields.zip(values)
        fields, values = prune_fields(zipped).transpose

        q = self
        if fields.present? && fields.any?
          return raise "Wrong number of values. Expected 2, got #{values.try(:length)}. You must pass a value for each field that you are sorting by" unless values.length <= 2 && values.length == fields.length

          mapped_fields = map_fields(fields)
          q = q.order(sanitized_ordering(self.table_name, mapped_fields, order))

          mapped_fields.each_with_index do |field, idx|
            if idx == 0
              value = values[idx]
              operator = sort_operator(idx, mapped_fields.count, order)

              q = q.where("#{field} #{operator} ?", value)
            else
              previous_field = mapped_fields[idx - 1]
              previous_value = values[idx - 1]
              value = values[idx]
              operator = sort_operator(idx, mapped_fields.count, order)

              q = q.where("#{previous_field} != ? OR #{field} #{operator} ?", previous_value, value)
            end
          end
        end

        return q.limit(limit)
      end

      private

      # Steps through the provided paginated fields, zipped with their values, and removes those not
      # in the `paginative_fields` hash as specified with `allow_paginative_on`.
      def self.prune_fields(zipped)
        zipped.select{ |f, v| self.paginative_fields.has_key? f.to_sym }.tap do |pruned|
          unless pruned.nil?
            items = zipped.map(&:first) - pruned.map(&:first)
            Rails.logger.warn "Paginative ignored unpermitted field: #{items}"
          end
        end
      end

      # Takes the pruned fields as an array, and returns the mapped versions.
      def self.map_fields(fields)
        fields.map{ |f| self.paginative_fields[f.to_sym] }
      end

      # Returns the appropriate order given sort direction and current field in the collection.
      # We don't want to use inclusive paging if we are at the last field being paginated, so either lt or gt is used.
      def self.sort_operator(index, count, direction)
        if direction.try(:downcase) == "desc"
          index < (count - 1) ? '<=' : '<'
        else
          index < (count - 1) ? '>=' : '>'
        end
      end
    end

    module ClassMethods
      # Sets the paginative fields set of the class to the specified columns.
      def allow_paginative_on(*mappings)
        cattr_accessor :paginative_fields
        self.paginative_fields = process_fields(mappings)
      end

      private

      # Process specified mappings to either scope to the table name of the current class
      # or to use the mappings provided.
      def process_fields(mappings)
        result = {}

        mappings.each do |mapping|
          if mapping.is_a?(Hash)
            result.merge!(mapping)
          else
            result[mapping] = self_map(mapping)
          end
        end

        result
      end

      # Returns a string scoping the specified field to the current class' table.
      def self_map(field)
        "#{self.table_name}.#{field}"
      end
    end
  end
end


text:
<?php

use yii\helpers\Html;
//use yii\widgets\ActiveForm;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use kartik\builder\FormGrid;
use kartik\datecontrol\DateControl;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use kartik\widgets\DepDrop;

// table reference
use app\models\RefSukan;
use app\models\RefAcara;
use app\models\RefKejohananDiwakili;
use app\models\RefKejohananPencapaian;

// contant values
use app\models\general\Placeholder;
use app\models\general\GeneralLabel;
use app\models\general\GeneralVariable;
use app\models\general\GeneralMessage;

/* @var $this yii\web\View */
/* @var $model app\models\PermohonanEBiasiswaPenyertaanKejohanan */
/* @var $form yii\widgets\ActiveForm */
?>

* <?= GeneralLabel::mandatoryField?>

    <?php $form = ActiveForm::begin(['type'=>ActiveForm::TYPE_VERTICAL, 'staticOnly'=>$readonly, 'id'=>$model->formName()]); ?>
    <?php
        echo FormGrid::widget([
    'model' => $model,
    'form' => $form,
    'autoGenerateColumns' => true,
    'rows' => [
        [
            'columns'=>12,
            'autoGenerateColumns'=>false, // override columns setting
            'attributes' => [

                'sukan' => [
                    'type'=>Form::INPUT_WIDGET,
                    'widgetClass'=>'\kartik\widgets\Select2',
                    'options'=>[
                        'data'=>ArrayHelper::map(RefSukan::find()->where(['=', 'aktif', 1])->all(),'id', 'desc'),
                        'options' => ['placeholder' => Placeholder::sukan],
                        'pluginOptions' => [
                            'allowClear' => true
                        ],],
                    'columnOptions'=>['colspan'=>5]],
                'tarikh_mula' => [
                    'type'=>Form::INPUT_WIDGET,
                    'widgetClass'=> DateControl::classname(),
                    'ajaxConversion'=>false,
                    'options'=>[
                        'pluginOptions' => [
                            'autoclose'=>true,
                        ]
                    ],
                    'columnOptions'=>['colspan'=>3]],
                'tarikh_akhir' => [
                    'type'=>Form::INPUT_WIDGET,
                    'widgetClass'=> DateControl::classname(),
                    'ajaxConversion'=>false,
                    'options'=>[
                        'pluginOptions' => [
                            'autoclose'=>true,
                        ]
                    ],
                    'columnOptions'=>['colspan'=>3]],

            ],
        ],
        [
            'columns'=>12,
            'autoGenerateColumns'=>false, // override columns setting
            'attributes' => [

                'anjuran' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>5],'options'=>['maxlength'=>80]],
                'kejohanan_mewakili' => [
                    'type'=>Form::INPUT_WIDGET,
                    'widgetClass'=>'\kartik\widgets\Select2',
                    'options'=>[
                        'data'=>ArrayHelper::map(RefKejohananDiwakili::find()->where(['=', 'aktif', 1])->all(),'id', 'desc'),
                        'options' => ['placeholder' => Placeholder::kejohananMewakili],
                        'pluginOptions' => [
                            'allowClear' => true
                        ],],
                    'columnOptions'=>['colspan'=>5]],
                'acara' => [
                    'type'=>Form::INPUT_WIDGET,
                    'widgetClass'=>'\kartik\widgets\DepDrop',
                    'options'=>[
                        'type'=>DepDrop::TYPE_SELECT2,
                        'data'=>ArrayHelper::map(RefAcara::find()->where(['=', 'aktif', 1])->all(),'id', 'desc'),
                        'options'=>['prompt'=>'',],
                        'select2Options'=>['pluginOptions'=>['allowClear'=>true]],
                        'pluginOptions' => [
                            'depends'=>[Html::getInputId($model, 'sukan')],
                            'placeholder' => Placeholder::acara,
                            'url'=>Url::to(['/ref-acara/subacaras'])],
                        ],
                    'columnOptions'=>['colspan'=>4]],

            ],
        ],
        [
            'columns'=>12,
            'autoGenerateColumns'=>false, // override columns setting
            'attributes' => [

                'nama_kejohanan' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>5],'options'=>['maxlength'=>80]],
                'tempat' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>4],'options'=>['maxlength'=>90]],
                 'pencapaian' => [
                    'type'=>Form::INPUT_WIDGET,
                    'widgetClass'=>'\kartik\widgets\Select2',
                    'options'=>[
                        'data'=>ArrayHelper::map(RefKejohananPencapaian::find()->where(['=', 'aktif', 1])->all(),'id', 'desc'),
                        'options' => ['placeholder' => Placeholder::pencapaian],
                        'pluginOptions' => [
                            'allowClear' => true
                        ],],
                    'columnOptions'=>['colspan'=>3]],
            ],
        ],
    ]
]);
    ?>

        <?php if(!$readonly): ?>
        <?= Html::submitButton($model->isNewRecord ? GeneralLabel::create : GeneralLabel::update, ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
        <?php endif; ?>

    <?php ActiveForm::end(); ?>

<?php
$script = <<< JS

$('form#{$model->formName()}').on('beforeSubmit', function (e) {

    var form = $(this);

     // submit form
     $.ajax({
          url: form.attr('action'),
          type: "POST",
            data:  new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
          success: function (response) {
               // do something with response

                if(response != 1){
                    //alert("error");
                    //$(document).find('#modal').html(response);
                    $('#modalContent').html(response);
                } else {
                    $(document).find('#modal').modal('hide');
                    form.trigger("reset");
                    $.pjax.defaults.timeout = 100000;
                    $.pjax.reload({container:'#permohonanEBiasiswaPenyertaanKejohananGrid'});
                }
          }
     });
     return false;
});

JS;

$this->registerJs($script);
?>