<commit_before>/**
 * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wso2.carbon.wsdl2form;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.deployment.util.PhasesInfo;
import org.apache.axis2.description.*;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonException;
import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.carbon.utils.deployment.GhostDeployerUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class WSDL2FormGenerator {

    public static final String TRYIT_SG_NAME = "TryItMockServiceGroup";
    private static final String PROXY_TIMER = "_PROXY_TIMER_";
    public static final String LAST_TOUCH_TIME = "_LAST_TOUCH_TIME_";
    public static final String SERVICE_NOT_FOUND = "SERVICE_NOT_FOUND";
    public static final String SERVICE_INACTIVE = "SERVICE_INACTIVE";
    public static final String UNSUPPORTED_LANG = "UNSUPPORTED_LANG";
    public static final String SUCCESS = "SUCCESSFULL";

    public static final String SERVICE_QUERY_PARAM = "service";
    public static final String OPERATION_PARAM = "operation";
    public static final String ENDPOINT_QUERY_PARAM = "endpoint";
    public static final String LANGUAGE_QUERY_PARAM = "lang";
    public static final String LOCALHOST_QUERY_PARAM = "localhost";
    public static final String CONTENT_TYPE_QUERY_PARAM = "content-type";

    /*Touch time.*/
    public final static long PERIOD = 20 * 60 * 1000;
    private static final String PORT = "port";

    private static final WSDL2FormGenerator INSTANCE = new WSDL2FormGenerator();

    private static Log log = LogFactory.getLog(WSDL2FormGenerator.class);

    public static WSDL2FormGenerator getInstance() {
        return INSTANCE;
    }

    /**
     * @param result        Result object containing the generated form
     * @param configCtx     ConfigurationContext of the tenant. In standalone mode, this should be
     *                      main ConfigurationContext.
     * @param tryitURL      URL of the service that need to be tried out.
     * @param serviceName   Name of the service when multiple services are available in the WSDL. If
     *                      {@code serviceName} is {@code null}, then the fist service in the WSDL
     *                      will be used.
     * @param operationName Operation of the service that need to be tried out. If this is {@code
     *                      null}, all operations will be available.
     * @param endpointName  If you need to generate get the tryit form only for specific endpoint
     *                      only, then you can specify it here. It could be <i>SOAP11Endpoint,
     *                      SOAP12Endpoint</i> or <i>HTTPEndpoint etc</i>.
     * @param fullPage      set {@code true} if you want to get a full html page. {@code false} will
     *                      create a div.
     *
     * @return URL for the mocked service.
     * @throws CarbonException Throws when an error occurred during the execution
     */
    public String getInternalTryit(Result result, ConfigurationContext configCtx, String tryitURL,
                                   String serviceName, String operationName, String endpointName,
                                   boolean fullPage) throws CarbonException {
        try {
            URL url = new URL(tryitURL);
            String serviceContextRoot = configCtx.getServiceContextPath();
            String contextRoot = CarbonUtils.getServerConfiguration().getFirstProperty("WebContextRoot");
            if (!serviceContextRoot.endsWith("/")) {
                serviceContextRoot = serviceContextRoot + "/";
            }
            if (!contextRoot.endsWith("/")) {
                contextRoot = contextRoot + "/";
            }
            AxisService axisService = getAxisService(tryitURL, serviceContextRoot, configCtx);
            if (axisService != null) {
                if (axisService.isActive()) {

                    // This is a fix for Mashup-861. If the transport is disabled we redirect the user to
                    // the alternative transport
                    if (!axisService.isEnableAllTransports() &&
                            !axisService.isExposedTransport(url.getProtocol())) {
                        String redirectURL;
                        if (ServerConstants.HTTP_TRANSPORT.equals(url.getProtocol()) &&
                                axisService.isExposedTransport(ServerConstants.HTTPS_TRANSPORT)) {
                            TransportInDescription httpsTransport = configCtx.getAxisConfiguration()
                                    .getTransportIn(ServerConstants.HTTPS_TRANSPORT);
                            Parameter parameter = httpsTransport.getParameter("proxyPort");
                            String port = "";
                            if (parameter != null && !"-1".equals(parameter.getValue())) {
                                String value = (String) parameter.getValue();
                                if (!"443".equals(value)) {
                                    port = value;
                                }
                            } else {
                                port = Integer.toString(CarbonUtils.getTransportPort(configCtx,
                                        ServerConstants.HTTPS_TRANSPORT));
                            }
                            redirectURL =
                                    ServerConstants.HTTPS_TRANSPORT + "://" + url.getHost() + ":" +
                                            port + url.getPath() + "?" + url.getQuery();
                            return redirectURL;
                        } else if (ServerConstants.HTTPS_TRANSPORT.equals(url.getProtocol()) &&
                                axisService.isExposedTransport(ServerConstants.HTTP_TRANSPORT)) {
                            TransportInDescription httpsTransport = configCtx.getAxisConfiguration()
                                    .getTransportIn(ServerConstants.HTTP_TRANSPORT);
                            Parameter parameter = httpsTransport.getParameter("proxyPort");
                            String port = "";
                            if (parameter != null && !"-1".equals(parameter.getValue())) {
                                String value = (String) parameter.getValue();
                                if (!"80".equals(value)) {
                                    port = value;
                                }
                            } else {
                                port = Integer.toString(CarbonUtils.getTransportPort(configCtx,
                                        ServerConstants.HTTP_TRANSPORT));
                            }
                            redirectURL =
                                    ServerConstants.HTTP_TRANSPORT + "://" + url.getHost() + ":" +
                                            port + url.getPath() + "?" + url.getQuery();
                            return redirectURL;
                        }
                    }

                    Map<String, String> paramMap = new HashMap<String, String>();
                    DOMSource xmlSource = Util.getSigStream(axisService, null);

                    String tenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(tryitURL);
                    String multitenantPrefix = contextRoot;
                    if(tenantDomain != null) {
                         multitenantPrefix = contextRoot + "t/" + tenantDomain + "/";
                    }

                    String proxyContextPath = CarbonUtils.getProxyContextPath(false);
                    paramMap.put("js-csrf-protection", proxyContextPath + multitenantPrefix + "carbon/admin/js/csrfPrevention.js");
                    paramMap.put("js-global-params", proxyContextPath + multitenantPrefix + "carbon/global-params.js");
                    paramMap.put("proxyAddress",
                            proxyContextPath + contextRoot + "carbon/admin/jsp/WSRequestXSSproxy_ajaxprocessor.jsp");
                    paramMap.put("js-service-stub", proxyContextPath + url.getPath() + "?stub");
                    paramMap.put("services-path", serviceContextRoot);

                    Util.generateTryit(xmlSource, result, paramMap);

                    return WSDL2FormGenerator.SUCCESS;
                } else {
                    throw new CarbonException(WSDL2FormGenerator.SERVICE_INACTIVE);
                }
            } else {
                throw new CarbonException(WSDL2FormGenerator.SERVICE_NOT_FOUND);
            }
        } catch (MalformedURLException e) {
            log.error(e.getMessage(), e);
            throw new CarbonException(e);
        } catch (OMException e) {
            log.error(e.getMessage(), e);
            throw new CarbonException(e);
        } catch (ParserConfigurationException e) {
            log.error(e.getMessage(), e);
            throw new CarbonException(e);
        } catch (TransformerException e) {<commit_msg>CCOMMONS-18 - Requests sent by TryIt over HTTPS does not send CSRF token<commit_after>/**
 * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wso2.carbon.wsdl2form;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.deployment.util.PhasesInfo;
import org.apache.axis2.description.*;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonException;
import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.carbon.utils.deployment.GhostDeployerUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class WSDL2FormGenerator {

    public static final String TRYIT_SG_NAME = "TryItMockServiceGroup";
    private static final String PROXY_TIMER = "_PROXY_TIMER_";
    public static final String LAST_TOUCH_TIME = "_LAST_TOUCH_TIME_";
    public static final String SERVICE_NOT_FOUND = "SERVICE_NOT_FOUND";
    public static final String SERVICE_INACTIVE = "SERVICE_INACTIVE";
    public static final String UNSUPPORTED_LANG = "UNSUPPORTED_LANG";
    public static final String SUCCESS = "SUCCESSFULL";

    public static final String SERVICE_QUERY_PARAM = "service";
    public static final String OPERATION_PARAM = "operation";
    public static final String ENDPOINT_QUERY_PARAM = "endpoint";
    public static final String LANGUAGE_QUERY_PARAM = "lang";
    public static final String LOCALHOST_QUERY_PARAM = "localhost";
    public static final String CONTENT_TYPE_QUERY_PARAM = "content-type";

    /*Touch time.*/
    public final static long PERIOD = 20 * 60 * 1000;
    private static final String PORT = "port";

    private static final WSDL2FormGenerator INSTANCE = new WSDL2FormGenerator();

    private static Log log = LogFactory.getLog(WSDL2FormGenerator.class);

    public static WSDL2FormGenerator getInstance() {
        return INSTANCE;
    }

    /**
     * @param result        Result object containing the generated form
     * @param configCtx     ConfigurationContext of the tenant. In standalone mode, this should be
     *                      main ConfigurationContext.
     * @param tryitURL      URL of the service that need to be tried out.
     * @param serviceName   Name of the service when multiple services are available in the WSDL. If
     *                      {@code serviceName} is {@code null}, then the fist service in the WSDL
     *                      will be used.
     * @param operationName Operation of the service that need to be tried out. If this is {@code
     *                      null}, all operations will be available.
     * @param endpointName  If you need to generate get the tryit form only for specific endpoint
     *                      only, then you can specify it here. It could be <i>SOAP11Endpoint,
     *                      SOAP12Endpoint</i> or <i>HTTPEndpoint etc</i>.
     * @param fullPage      set {@code true} if you want to get a full html page. {@code false} will
     *                      create a div.
     *
     * @return URL for the mocked service.
     * @throws CarbonException Throws when an error occurred during the execution
     */
    public String getInternalTryit(Result result, ConfigurationContext configCtx, String tryitURL,
                                   String serviceName, String operationName, String endpointName,
                                   boolean fullPage) throws CarbonException {
        try {
            URL url = new URL(tryitURL);
            String serviceContextRoot = configCtx.getServiceContextPath();
            String contextRoot = CarbonUtils.getServerConfiguration().getFirstProperty("WebContextRoot");
            if (!serviceContextRoot.endsWith("/")) {
                serviceContextRoot = serviceContextRoot + "/";
            }
            if (!contextRoot.endsWith("/")) {
                contextRoot = contextRoot + "/";
            }
            AxisService axisService = getAxisService(tryitURL, serviceContextRoot, configCtx);
            if (axisService != null) {
                if (axisService.isActive()) {

                    // This is a fix for Mashup-861. If the transport is disabled we redirect the user to
                    // the alternative transport
                    if (!axisService.isEnableAllTransports() &&
                            !axisService.isExposedTransport(url.getProtocol())) {
                        String redirectURL;
                        if (ServerConstants.HTTP_TRANSPORT.equals(url.getProtocol()) &&
                                axisService.isExposedTransport(ServerConstants.HTTPS_TRANSPORT)) {
                            TransportInDescription httpsTransport = configCtx.getAxisConfiguration()
                                    .getTransportIn(ServerConstants.HTTPS_TRANSPORT);
                            Parameter parameter = httpsTransport.getParameter("proxyPort");
                            String port = "";
                            if (parameter != null && !"-1".equals(parameter.getValue())) {
                                String value = (String) parameter.getValue();
                                if (!"443".equals(value)) {
                                    port = value;
                                }
                            } else {
                                port = Integer.toString(CarbonUtils.getTransportPort(configCtx,
                                        ServerConstants.HTTPS_TRANSPORT));
                            }
                            redirectURL =
                                    ServerConstants.HTTPS_TRANSPORT + "://" + url.getHost() + ":" +
                                            port + url.getPath() + "?" + url.getQuery();
                            return redirectURL;
                        } else if (ServerConstants.HTTPS_TRANSPORT.equals(url.getProtocol()) &&
                                axisService.isExposedTransport(ServerConstants.HTTP_TRANSPORT)) {
                            TransportInDescription httpsTransport = configCtx.getAxisConfiguration()
                                    .getTransportIn(ServerConstants.HTTP_TRANSPORT);
                            Parameter parameter = httpsTransport.getParameter("proxyPort");
                            String port = "";
                            if (parameter != null && !"-1".equals(parameter.getValue())) {
                                String value = (String) parameter.getValue();
                                if (!"80".equals(value)) {
                                    port = value;
                                }
                            } else {
                                port = Integer.toString(CarbonUtils.getTransportPort(configCtx,
                                        ServerConstants.HTTP_TRANSPORT));
                            }
                            redirectURL =
                                    ServerConstants.HTTP_TRANSPORT + "://" + url.getHost() + ":" +
                                            port + url.getPath() + "?" + url.getQuery();
                            return redirectURL;
                        }
                    }

                    Map<String, String> paramMap = new HashMap<String, String>();
                    DOMSource xmlSource = Util.getSigStream(axisService, null);

                    String tenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(tryitURL);
                    String multitenantPrefix = contextRoot;
                    if(tenantDomain != null) {
                         multitenantPrefix = contextRoot + "t/" + tenantDomain + "/";
                    }

                    String proxyContextPath = CarbonUtils.getProxyContextPath(false);
                    paramMap.put("js-csrf-protection", 
                            proxyContextPath + multitenantPrefix + "carbon/admin/js/csrfPrevention.js");
                    paramMap.put("js-global-params", proxyContextPath + multitenantPrefix + "carbon/global-params.js");
                    paramMap.put("proxyAddress",
                            proxyContextPath + contextRoot + "carbon/admin/jsp/WSRequestXSSproxy_ajaxprocessor.jsp");
                    paramMap.put("js-service-stub", proxyContextPath + url.getPath() + "?stub");
                    paramMap.put("services-path", serviceContextRoot);

                    Util.generateTryit(xmlSource, result, paramMap);

                    return WSDL2FormGenerator.SUCCESS;
                } else {
                    throw new CarbonException(WSDL2FormGenerator.SERVICE_INACTIVE);
                }
            } else {
                throw new CarbonException(WSDL2FormGenerator.SERVICE_NOT_FOUND);
            }
        } catch (MalformedURLException e) {
            log.error(e.getMessage(), e);
            throw new CarbonException(e);
        } catch (OMException e) {
            log.error(e.getMessage(), e);
            throw new CarbonException(e);
        } catch (ParserConfigurationException e) {
            log.error(e.getMessage(), e);
            throw new CarbonException(e);
        } catch (TransformerException e) {
{'fraction_non_alphanumeric': 0.08420254124786648, 'fraction_numerical': 0.005310070168784373, 'mean_word_length': 1.9263318534961154, 'pattern_counts': {'":': 8, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 20}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 36, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7666225', 'n_tokens_mistral': 5238, 'n_tokens_neox': 5027, 'n_words': 1299}