Try to find target encoding in XML declaration.

@param messagePayload XML message payload.
@return charsetName if supported.
191431
private static Charset getTargetCharset(String messagePayload) throws UnsupportedEncodingException {
        String defaultEncoding = System.getProperty(Citrus.CITRUS_FILE_ENCODING_PROPERTY, System.getenv(Citrus.CITRUS_FILE_ENCODING_ENV));
        if (StringUtils.hasText(defaultEncoding)) {
            return Charset.forName(defaultEncoding);
        }

        // trim incoming payload
        String payload = messagePayload.trim();

        char doubleQuote = '\"';
        char singleQuote = '\'';
        // make sure payload has an XML encoding string
        String encodingKey = "encoding";
        if (payload.startsWith("<?xml") && payload.contains(encodingKey) && payload.contains("?>") && (payload.indexOf(encodingKey) < payload.indexOf("?>"))) {

            // extract only encoding part, as otherwise the rest of the complete pay load will be load
            String encoding = payload.substring(payload.indexOf(encodingKey) + encodingKey.length(), payload.indexOf("?>"));

            char quoteChar = doubleQuote;
            int idxDoubleQuote = encoding.indexOf(doubleQuote);
            int idxSingleQuote = encoding.indexOf(singleQuote);

            // check which character is the first one, allowing for <encoding = 'UTF-8'> white spaces
            if (idxSingleQuote >= 0 && (idxDoubleQuote < 0 || idxSingleQuote < idxDoubleQuote)) {
                quoteChar = singleQuote;
            }

            // build encoding using the found character
            encoding = encoding.substring(encoding.indexOf(quoteChar) + 1);
            encoding = encoding.substring(0, encoding.indexOf(quoteChar));

            // check if it has a valid char set
            if (!Charset.availableCharsets().containsKey(encoding)) {
                throw new UnsupportedEncodingException("Found unsupported encoding: '" + encoding + "'");
            }
            
            // should be a valid encoding
            return Charset.forName(encoding);
        }

        // return as encoding the default UTF-8
        return Charset.forName("UTF-8");
    }
215416
public String getText() throws UnsupportedEncodingException {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getText");
    String text = null;
    try {
      text = (String)getPayload().getField(JmsTextBodyAccess.BODY_DATA_VALUE);
    }
    catch (MFPUnsupportedEncodingRuntimeException e) {
      FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsJmsTextMessageImpl.getText", "148");
      throw (UnsupportedEncodingException)e.getCause();
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
      if ((text == null) || text.length() < 257) {
        SibTr.exit(this, tc, "getText", text);
      }
      else {
        SibTr.exit(this, tc, "getText", new Object[]{text.length(), text.substring(0,200)+"..."});
      }
    }
    return text;
  }
221831
public String extractPayloadJsonAsString(String body) {
        if (body == null) {
            return null;
        }
        String[] pairs = body.split("\\&");
        for (String pair : pairs) {
            String[] elements = pair.split("=");
            if (elements.length == 2 && elements[0].equals("payload")) {
                try {
                    return URLDecoder.decode(elements[1], "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    return elements[1];
                }
            }
        }
        return null;
    }
475871
def get_charset(message, default='ASCII'):
    """"""

    charset = message.get_content_charset()

    if not charset:
        charset = message.get_charset()

    if not charset:
        charset = default

    try:
        codecs.lookup(charset)
    except LookupError:
        charset = default

    return charset
903605
private byte[] encode(Message msg, String apiVersion, String kind) {
    // It is unfortunate that we have to include apiVersion and kind,
    // since we should be able to extract it from the Message, but
    // for now at least, those fields are missing from the proto-buffer.
    Unknown u =
        Unknown.newBuilder()
            .setTypeMeta(TypeMeta.newBuilder().setApiVersion(apiVersion).setKind(kind))
            .setRaw(msg.toByteString())
            .build();
    return Bytes.concat(MAGIC, u.toByteArray());
  }
1090727
@GwtIncompatible("Unnecessary")
  private Charset getInputCharset() {
    if (!config.charset.isEmpty()) {
      if (!Charset.isSupported(config.charset)) {
        throw new FlagUsageException(config.charset +
            " is not a valid charset name.");
      }
      return Charset.forName(config.charset);
    }
    return UTF_8;
  }
476052
public String digest(String message) {
		final byte[] messageAsByteArray;

		try {
			messageAsByteArray = message.getBytes(charsetName);
		} catch (UnsupportedEncodingException e) {
			throw new DigestException("error converting message to byte array: charsetName=" + charsetName, e);
		}

		final byte[] digest = digest(messageAsByteArray);

		switch (outputMode) {
			case BASE64:
				return Base64.encodeBase64String(digest);
			case HEX:
				return Hex.encodeHexString(digest);
			default:
				return null;
		}
	}
178743
public MessageProtocol withCharset(String charset) {
        return new MessageProtocol(contentType, Optional.ofNullable(charset), version);
    }
391856
public static Element getRootElementFromString(String payload)
 throws AlipayApiException {
        if (payload == null || payload.trim().length() < 1) {
            throw new AlipayApiException("XML_PAYLOAD_EMPTY");
        }

        byte[] bytes = null;

        try {
        	payload = StringUtils.stripNonValidXMLCharacters(payload);
			String encodeString = getEncoding(payload);
            bytes = payload.getBytes(encodeString);
        } catch (UnsupportedEncodingException e) {
            throw new AlipayApiException("XML_ENCODE_ERROR", e);
        }

        InputStream in = new ByteArrayInputStream(bytes);
        return getDocument(in).getDocumentElement();
    }
1263324
public static Charset getCharset(MediaType m) {
        String name = (m == null) ? null : m.getParameters().get(MediaType.CHARSET_PARAMETER);
        try {
            return (name == null) ? Charsets.UTF_8 : Charset.forName(name);
        } catch (Exception e) {
            return Charsets.UTF_8;
        }
    }
1013796
public String encoding()
  {
    if (_readEncoding != null)
      return _readEncoding;

    CharSegment value = getHeaderBuffer("Content-Type");

    if (value == null)
      return null;

    int i = value.indexOf("charset");
    if (i < 0)
      return null;

    int len = value.length();
    for (i += 7; i < len && Character.isWhitespace(value.charAt(i)); i++) {
    }

    if (i >= len || value.charAt(i) != '=')
      return null;

    for (i++; i < len && Character.isWhitespace(value.charAt(i)); i++) {
    }

    if (i >= len)
      return null;

    char end = value.charAt(i);
    if (end == '"') {
      int tail;
      for (tail = ++i; tail < len; tail++) {
        if (value.charAt(tail) == end)
          break;
      }

      _readEncoding = Encoding.getMimeName(value.substring(i, tail));

      return _readEncoding;
    }

    int tail;
    for (tail = i; tail < len; tail++) {
      if (Character.isWhitespace(value.charAt(tail))
          || value.charAt(tail) == ';')
        break;
    }

    _readEncoding = Encoding.getMimeName(value.substring(i, tail));

    return _readEncoding;
  }
381677
protected String getCharsetFromBytes(byte buffer[], int len) 
	throws IOException {
		String charsetName = null;
	    UniversalDetector detector = new UniversalDetector(null);
		detector.handleData(buffer, 0, len);
		detector.dataEnd();
	    charsetName = detector.getDetectedCharset();
	    detector.reset();
	    if(isCharsetSupported(charsetName)) {
	    	return mapCharset(charsetName);
	    }
	    return null;
	}
470709
public String buildMessagePayload(TestContext context, String messageType) {
        try {    
            //construct control message payload
            String messagePayload = "";
            if (scriptResourcePath != null) {
                messagePayload = buildMarkupBuilderScript(context.replaceDynamicContentInString(
                        FileUtils.readToString(FileUtils.getFileResource(scriptResourcePath, context), Charset.forName(context.resolveDynamicValue(scriptResourceCharset)))));
            } else if (scriptData != null) {
                messagePayload = buildMarkupBuilderScript(context.replaceDynamicContentInString(scriptData));
            }
            
            return messagePayload;
        } catch (IOException e) {
            throw new CitrusRuntimeException("Failed to build control message payload", e);
        }
    }
1258110
protected final Charset getCharset() {
    return mediaType == null || mediaType.getCharsetParameter() == null
        ? Charsets.ISO_8859_1
        : mediaType.getCharsetParameter();
  }
526365
@Override
    public String getCharacterEncoding() {
        try {
            collaborator.preInvoke(componentMetaData);
            return request.getCharacterEncoding();
        } finally {
            collaborator.postInvoke();
        }
    }
837648
protected byte[] getTransportPayload(AuditEventMessage msg)
	{
		if (msg == null) {
			return null;
		}
		
		byte[] msgBytes = msg.getSerializedMessage(false);
		if (EventUtils.isEmptyOrNull(msgBytes)) {
			return null;
		}
		
		// Format message with transport-specific headers
		StringBuilder sb = new StringBuilder();
		sb.append("<");
		sb.append(TRANSPORT_DEFAULT_PRIORITY);
		sb.append(">");
		
		sb.append(TimestampUtils.getBSDSyslogDate(msg.getDateTime()));
		sb.append(" ");
		sb.append(getSystemHostName());
		sb.append(" ");
		sb.append("<?xml version=\"1.0\" encoding=\"ASCII\"?>");
		sb.append(new String(msgBytes));

		return sb.toString().trim().getBytes();
	}
1044587
public static String encode(String message, int offset) {
		final int len = message.length();
		final char[] plain = message.toCharArray();
		char c;
		for (int i = 0; i < len; i++) {
			c = message.charAt(i);
			if (false == Character.isLetter(c)) {
				continue;
			}
			plain[i] = encodeChar(c, offset);
		}
		return new String(plain);
	}