<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.jmeter.protocol.http.sampler;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.io.IOUtils;
import org.apache.jmeter.protocol.http.control.CacheManager;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.util.HTTPConstants;
import org.apache.jmeter.samplers.Interruptible;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;

/**
 * Commons HTTPClient based soap sampler
 */
public class SoapSampler extends HTTPSampler2 implements Interruptible { // Implemented by parent class
    private static final Logger log = LoggingManager.getLoggerForClass();

    private static final long serialVersionUID = 240L;

    public static final String XML_DATA = "HTTPSamper.xml_data"; //$NON-NLS-1$

    public static final String URL_DATA = "SoapSampler.URL_DATA"; //$NON-NLS-1$

    public static final String SOAP_ACTION = "SoapSampler.SOAP_ACTION"; //$NON-NLS-1$

    public static final String SEND_SOAP_ACTION = "SoapSampler.SEND_SOAP_ACTION"; //$NON-NLS-1$

    public static final String XML_DATA_FILE = "SoapSampler.xml_data_file"; //$NON-NLS-1$

    private static final String DOUBLE_QUOTE = "\""; //$NON-NLS-1$

    private static final String SOAPACTION = "SOAPAction"; //$NON-NLS-1$

    private static final String ENCODING = "utf-8"; //$NON-NLS-1$ TODO should this be variable?

    private static final String DEFAULT_CONTENT_TYPE = "text/xml"; //$NON-NLS-1$

    public void setXmlData(String data) {
        setProperty(XML_DATA, data);
    }

    public String getXmlData() {
        return getPropertyAsString(XML_DATA);
    }

    /**
     * it's kinda obvious, but we state it anyways. Set the xml file with a
     * string path.
     *
     * @param filename
     */
    public void setXmlFile(String filename) {
        setProperty(XML_DATA_FILE, filename);
    }

    /**
     * Get the file location of the xml file.
     *
     * @return String file path.
     */
    public String getXmlFile() {
        return getPropertyAsString(XML_DATA_FILE);
    }

    public String getURLData() {
        return getPropertyAsString(URL_DATA);
    }

    public void setURLData(String url) {
        setProperty(URL_DATA, url);
    }

    public String getSOAPAction() {
        return getPropertyAsString(SOAP_ACTION);
    }

    public String getSOAPActionQuoted() {
        String action = getSOAPAction();
        StringBuilder sb = new StringBuilder(action.length()+2);
        sb.append(DOUBLE_QUOTE);
        sb.append(action);
        sb.append(DOUBLE_QUOTE);
        return sb.toString();
    }

    public void setSOAPAction(String action) {
        setProperty(SOAP_ACTION, action);
    }

    public boolean getSendSOAPAction() {
        return getPropertyAsBoolean(SEND_SOAP_ACTION);
    }

    public void setSendSOAPAction(boolean action) {
        setProperty(SEND_SOAP_ACTION, String.valueOf(action));
    }

    protected int setPostHeaders(PostMethod post) {
        int length=0;// Take length from file
        if (getHeaderManager() != null) {
            // headerManager was set, so let's set the connection
            // to use it.
            HeaderManager mngr = getHeaderManager();
            int headerSize = mngr.size();
            for (int idx = 0; idx < headerSize; idx++) {
                Header hd = mngr.getHeader(idx);
                if (HTTPConstants.HEADER_CONTENT_LENGTH.equalsIgnoreCase(hd.getName())) {// Use this to override file length
                    length = Integer.parseInt(hd.getValue());
                }
                // All the other headers are set up by HTTPSampler2.setupConnection()
            }
        } else {
            // otherwise we use "text/xml" as the default
            post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, DEFAULT_CONTENT_TYPE); //$NON-NLS-1$
        }
        if (getSendSOAPAction()) {
            post.setRequestHeader(SOAPACTION, getSOAPActionQuoted());
        }
        return length;
    }

    /**
     * Send POST data from <code>Entry</code> to the open connection.
     *
     * @param post
     * @throws IOException if an I/O exception occurs
     */
    private String sendPostData(PostMethod post, final int length) {
        // Buffer to hold the post body, except file content
        StringBuilder postedBody = new StringBuilder(1000);
        final String xmlFile = getXmlFile();
        if (xmlFile != null && xmlFile.length() > 0) {
            File xmlFileAsFile = new File(xmlFile);
            if(!(xmlFileAsFile.exists() && xmlFileAsFile.canRead())) {
                throw new IllegalArgumentException(JMeterUtils.getResString("soap_sampler_file_invalid") // $NON-NLS-1$
                        + xmlFileAsFile.getAbsolutePath());
            }
            // We just add placeholder text for file content
            postedBody.append("Filename: ").append(xmlFile).append("\n");
            postedBody.append("<actual file content, not shown here>");
            post.setRequestEntity(new RequestEntity() {
                public boolean isRepeatable() {
                    return true;
                }

                public void writeRequest(OutputStream out) throws IOException {
                    InputStream in = null;
                    try{
                        in = new FileInputStream(xmlFile);
                        IOUtils.copy(in, out);
                        out.flush();
                    } finally {
                        IOUtils.closeQuietly(in);
                    }
                }

                public long getContentLength() {
                    switch(length){
                        case -1:
                            return -1;
                        case 0: // No header provided
                            return (new File(xmlFile)).length();
                        default:
                            return length;
                        }
                }

                public String getContentType() {
                    // TODO do we need to add a charset for the file contents?
                    return DEFAULT_CONTENT_TYPE; // $NON-NLS-1$
                }
            });
        } else {
            postedBody.append(getXmlData());<commit_msg>remove useless brackets<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.jmeter.protocol.http.sampler;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.io.IOUtils;
import org.apache.jmeter.protocol.http.control.CacheManager;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.util.HTTPConstants;
import org.apache.jmeter.samplers.Interruptible;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;

/**
 * Commons HTTPClient based soap sampler
 */
public class SoapSampler extends HTTPSampler2 implements Interruptible { // Implemented by parent class
    private static final Logger log = LoggingManager.getLoggerForClass();

    private static final long serialVersionUID = 240L;

    public static final String XML_DATA = "HTTPSamper.xml_data"; //$NON-NLS-1$

    public static final String URL_DATA = "SoapSampler.URL_DATA"; //$NON-NLS-1$

    public static final String SOAP_ACTION = "SoapSampler.SOAP_ACTION"; //$NON-NLS-1$

    public static final String SEND_SOAP_ACTION = "SoapSampler.SEND_SOAP_ACTION"; //$NON-NLS-1$

    public static final String XML_DATA_FILE = "SoapSampler.xml_data_file"; //$NON-NLS-1$

    private static final String DOUBLE_QUOTE = "\""; //$NON-NLS-1$

    private static final String SOAPACTION = "SOAPAction"; //$NON-NLS-1$

    private static final String ENCODING = "utf-8"; //$NON-NLS-1$ TODO should this be variable?

    private static final String DEFAULT_CONTENT_TYPE = "text/xml"; //$NON-NLS-1$

    public void setXmlData(String data) {
        setProperty(XML_DATA, data);
    }

    public String getXmlData() {
        return getPropertyAsString(XML_DATA);
    }

    /**
     * it's kinda obvious, but we state it anyways. Set the xml file with a
     * string path.
     *
     * @param filename
     */
    public void setXmlFile(String filename) {
        setProperty(XML_DATA_FILE, filename);
    }

    /**
     * Get the file location of the xml file.
     *
     * @return String file path.
     */
    public String getXmlFile() {
        return getPropertyAsString(XML_DATA_FILE);
    }

    public String getURLData() {
        return getPropertyAsString(URL_DATA);
    }

    public void setURLData(String url) {
        setProperty(URL_DATA, url);
    }

    public String getSOAPAction() {
        return getPropertyAsString(SOAP_ACTION);
    }

    public String getSOAPActionQuoted() {
        String action = getSOAPAction();
        StringBuilder sb = new StringBuilder(action.length()+2);
        sb.append(DOUBLE_QUOTE);
        sb.append(action);
        sb.append(DOUBLE_QUOTE);
        return sb.toString();
    }

    public void setSOAPAction(String action) {
        setProperty(SOAP_ACTION, action);
    }

    public boolean getSendSOAPAction() {
        return getPropertyAsBoolean(SEND_SOAP_ACTION);
    }

    public void setSendSOAPAction(boolean action) {
        setProperty(SEND_SOAP_ACTION, String.valueOf(action));
    }

    protected int setPostHeaders(PostMethod post) {
        int length=0;// Take length from file
        if (getHeaderManager() != null) {
            // headerManager was set, so let's set the connection
            // to use it.
            HeaderManager mngr = getHeaderManager();
            int headerSize = mngr.size();
            for (int idx = 0; idx < headerSize; idx++) {
                Header hd = mngr.getHeader(idx);
                if (HTTPConstants.HEADER_CONTENT_LENGTH.equalsIgnoreCase(hd.getName())) {// Use this to override file length
                    length = Integer.parseInt(hd.getValue());
                }
                // All the other headers are set up by HTTPSampler2.setupConnection()
            }
        } else {
            // otherwise we use "text/xml" as the default
            post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, DEFAULT_CONTENT_TYPE); //$NON-NLS-1$
        }
        if (getSendSOAPAction()) {
            post.setRequestHeader(SOAPACTION, getSOAPActionQuoted());
        }
        return length;
    }

    /**
     * Send POST data from <code>Entry</code> to the open connection.
     *
     * @param post
     * @throws IOException if an I/O exception occurs
     */
    private String sendPostData(PostMethod post, final int length) {
        // Buffer to hold the post body, except file content
        StringBuilder postedBody = new StringBuilder(1000);
        final String xmlFile = getXmlFile();
        if (xmlFile != null && xmlFile.length() > 0) {
            File xmlFileAsFile = new File(xmlFile);
            if(!(xmlFileAsFile.exists() && xmlFileAsFile.canRead())) {
                throw new IllegalArgumentException(JMeterUtils.getResString("soap_sampler_file_invalid") // $NON-NLS-1$
                        + xmlFileAsFile.getAbsolutePath());
            }
            // We just add placeholder text for file content
            postedBody.append("Filename: ").append(xmlFile).append("\n");
            postedBody.append("<actual file content, not shown here>");
            post.setRequestEntity(new RequestEntity() {
                public boolean isRepeatable() {
                    return true;
                }

                public void writeRequest(OutputStream out) throws IOException {
                    InputStream in = null;
                    try{
                        in = new FileInputStream(xmlFile);
                        IOUtils.copy(in, out);
                        out.flush();
                    } finally {
                        IOUtils.closeQuietly(in);
                    }
                }

                public long getContentLength() {
                    switch(length){
                        case -1:
                            return -1;
                        case 0: // No header provided
                            return new File(xmlFile).length();
                        default:
                            return length;
                        }
                }

                public String getContentType() {
                    // TODO do we need to add a charset for the file contents?
                    return DEFAULT_CONTENT_TYPE; // $NON-NLS-1$
                }
            });
        } else {
            postedBody.append(getXmlData());
{'fraction_non_alphanumeric': 0.09270833333333334, 'fraction_numerical': 0.004296875, 'mean_word_length': 2.2773629187113293, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 34}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4335116', 'n_tokens_mistral': 4224, 'n_tokens_neox': 4079, 'n_words': 1141}