Load a list of all the supported encodings.

System property "encodings" formatted using URL syntax may define an
external encodings list. Thanks to Sergey Ushakov for the code
contribution!
@xsl.usage internal
487104
private static EncodingInfo[] loadEncodingInfo()
    {
        try
        {
            InputStream is; 
                
            SecuritySupport ss = SecuritySupport.getInstance();
            is = ss.getResourceAsStream(ObjectFactory.findClassLoader(),
                                            ENCODINGS_FILE);
            
            // j2objc: if resource wasn't found, load defaults from string.
            if (is == null) {
                is = new ByteArrayInputStream(
                    ENCODINGS_FILE_STR.getBytes(StandardCharsets.UTF_8));
            }

            Properties props = new Properties();
            if (is != null) {
                props.load(is);
                is.close();
            } else {
                // Seems to be no real need to force failure here, let the
                // system do its best... The issue is not really very critical,
                // and the output will be in any case _correct_ though maybe not
                // always human-friendly... :)
                // But maybe report/log the resource problem?
                // Any standard ways to report/log errors (in static context)?
            }

            int totalEntries = props.size();

            List encodingInfo_list = new ArrayList();
            Enumeration keys = props.keys();
            for (int i = 0; i < totalEntries; ++i)
            {
                String javaName = (String) keys.nextElement();
                String val = props.getProperty(javaName);
                int len = lengthOfMimeNames(val);

                String mimeName;
                char highChar;
                if (len == 0)
                {
                    // There is no property value, only the javaName, so try and recover
                    mimeName = javaName;
                    highChar = '\u0000'; // don't know the high code point, will need to test every character
                }
                else
                {
                    try {
                        // Get the substring after the Mime names
                        final String highVal = val.substring(len).trim();
                        highChar = (char) Integer.decode(highVal).intValue();
                    }
                    catch( NumberFormatException e) {
                        highChar = 0;
                    }
                    String mimeNames = val.substring(0, len);
                    StringTokenizer st =
                        new StringTokenizer(mimeNames, ",");
                    for (boolean first = true;
                        st.hasMoreTokens();
                        first = false)
                    {
                        mimeName = st.nextToken();
                        EncodingInfo ei = new EncodingInfo(mimeName, javaName, highChar);
                        encodingInfo_list.add(ei);
                        _encodingTableKeyMime.put(mimeName.toUpperCase(), ei);
                        if (first)
                            _encodingTableKeyJava.put(javaName.toUpperCase(), ei);
                    }
                }
            }
            // Convert the Vector of EncodingInfo objects into an array of them,
            // as that is the kind of thing this method returns.
            EncodingInfo[] ret_ei = new EncodingInfo[encodingInfo_list.size()];
            encodingInfo_list.toArray(ret_ei);
            return ret_ei;
        }
        catch (java.net.MalformedURLException mue)
        {
            throw new org.apache.xml.serializer.utils.WrappedRuntimeException(mue);
        }
        catch (java.io.IOException ioe)
        {
            throw new org.apache.xml.serializer.utils.WrappedRuntimeException(ioe);
        }
    }
863846
def load_children(self):
        

        # Containers
        children = list()
        statuses = list()
        version = None
        titles = list()
        descriptions = list()
        platforms = list()
        idents = list()

        # Element load
        for element in self.xml_element:
            uri, tag = Element.get_namespace_and_tag(element.tag)
            if tag == 'version':
                if version is None:
                    version = Version(element)
                else:
                    error_msg = 'version element found more than once'
                    raise CardinalityException(error_msg)
            elif tag == 'status':
                statuses.append(Status(element))
            elif tag == 'title':
                titles.append(Title(element))
            elif tag == 'description':
                descriptions.append(Description(element))
            elif tag == 'platform':
                platforms.append(Platform(element))
            elif tag == 'ident':
                idents.append(Ident(element))

        # List construction
        children.extend(statuses)
        if version is not None:
            children.append(version)
        children.extend(titles)
        children.extend(descriptions)
        children.extend(platforms)
        children.extend(idents)

        return children
947429
function serialize($charset_encoding='')
		{
			if ($charset_encoding != '')
				$this->content_type = 'text/xml; charset=' . $charset_encoding;
			else
				$this->content_type = 'text/xml';
			if ($GLOBALS['xmlrpc_null_apache_encoding'])
			{
				$result = "<methodResponse xmlns:ex=\"".$GLOBALS['xmlrpc_null_apache_encoding_ns']."\">\n";
			}
			else
			{
			$result = "<methodResponse>\n";
			}
			if($this->errno)
			{
				// G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
				// by xml-encoding non ascii chars
				$result .= "<fault>\n" .
"<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
"</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "</string></value>\n</member>\n" .
"</struct>\n</value>\n</fault>";
			}
			else
			{
				if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval'))
				{
					if (is_string($this->val) && $this->valtyp == 'xml')
					{
						$result .= "<params>\n<param>\n" .
							$this->val .
							"</param>\n</params>";
					}
					else
					{
						/// @todo try to build something serializable?
						die('cannot serialize xmlrpcresp objects whose content is native php values');
					}
				}
				else
				{
					$result .= "<params>\n<param>\n" .
						$this->val->serialize($charset_encoding) .
						"</param>\n</params>";
				}
			}
			$result .= "\n</methodResponse>";
			$this->payload = $result;
			return $result;
		}
754374
public static function loadKeyFromX509Resource($res): array
    {
        $key = \openssl_get_publickey($res);

        $details = \openssl_pkey_get_details($key);
        if (isset($details['key'])) {
            $values = self::loadKeyFromPEM($details['key']);
            \openssl_x509_export($res, $out);
            $x5c = \preg_replace('#-.*-#', '', $out);
            $x5c = \preg_replace('~\R~', PHP_EOL, $x5c);
            $x5c = \trim($x5c);
            $values['x5c'] = [$x5c];

            $values['x5t'] = Base64Url::encode(\openssl_x509_fingerprint($res, 'sha1', true));
            $values['x5t#256'] = Base64Url::encode(\openssl_x509_fingerprint($res, 'sha256', true));

            return $values;
        }

        throw new \InvalidArgumentException('Unable to load the certificate');
    }
1141695
def _load_external(self, url):
        
        if url.startswith("//"):
            # then we have to rely on the base_url
            if self.base_url and "https://" in self.base_url:
                url = "https:" + url
            else:
                url = "http:" + url

        if url.startswith("http://") or url.startswith("https://"):
            css_body = self._load_external_url(url)
        else:
            stylefile = url
            if not os.path.isabs(stylefile):
                stylefile = os.path.abspath(
                    os.path.join(self.base_path or "", stylefile)
                )
            if os.path.exists(stylefile):
                with codecs.open(stylefile, encoding="utf-8") as f:
                    css_body = f.read()
            elif self.base_url:
                url = urljoin(self.base_url, url)
                return self._load_external(url)
            else:
                raise ExternalNotFoundError(stylefile)

        return css_body
978887
public function encodings()
    {
        $encodings = [];
        $added = [];

        foreach ($this->candidates as $candidate) {
            foreach ($candidate->encodings() as $encoding) {
                if (isset($added[$encoding])) {
                    continue;
                }
                $encodings[] = $encoding;
                $added[$encoding] = true;
            }
        }

        return $encodings;
    }
1367177
public void normalizeDatastreams(DigitalObject obj,
            int transContext,
            String characterEncoding)            throws UnsupportedEncodingException {
        if (transContext == AS_IS) {
            return;
        }
        if (obj.hasContentModel( Models.SERVICE_DEPLOYMENT_3_0)) {
            Iterator<String> datastreams = obj.datastreamIdIterator();
            while (datastreams.hasNext()) {
                String dsid = datastreams.next();

                if (dsid.equals("WSDL") || dsid.equals("SERVICE-PROFILE")) {
                    for (Datastream d : obj.datastreams(dsid)) {
                        if (!(d instanceof DatastreamXMLMetadata)) {
                            logger.warn(obj.getPid()
                                    + " : Refusing to normalize URLs in datastream "
                                    + dsid + " because it is not inline XML");
                            continue;
                        }

                        DatastreamXMLMetadata xd = (DatastreamXMLMetadata) d;
                        if (logger.isDebugEnabled())
                            logger.debug("{} : normalising URLs in {}",
                                    obj.getPid(), dsid);
                        String origContent = new String(xd.xmlContent, "UTF-8");
                        String normal = normalizeInlineXML(origContent,
                                        transContext);
                        if (!normal.equals(origContent) || !"UTF-8".equalsIgnoreCase(characterEncoding)){
                            xd.xmlContent = normal.getBytes(characterEncoding);
                        }
                        xd.DSSize = xd.xmlContent.length;
                    }
                }
            }
        }
    }
440528
public function getEncodings()
    {
        if (null !== $this->encodings) {
            return $this->encodings;
        }
        $charsets = $this->headers->getParameterListAsObject('ACCEPT_ENCODINGS');

        return $this->encodings = $encodings->getParameterKeys();
    }
1148567
def add_charset
      if !body.empty?
        # Only give a warning if this isn't an attachment, has non US-ASCII and the user
        # has not specified an encoding explicitly.
        if @defaulted_charset && !body.raw_source.ascii_only? && !self.attachment?
          warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n"
          warn(warning)
        end
        header[:content_type].parameters['charset'] = @charset
      end
    end
982683
def content_encoding
      vs = @metas['content-encoding']
      if vs && %r{\A#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?(?:,#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?)*}o =~ (v = vs.join(', '))
        v.scan(RE_TOKEN).map {|content_coding| content_coding.downcase}
      else
        []
      end
    end
1250510
public void decodeQueryTo(MultiMap<String> parameters, Charset encoding) throws UnsupportedEncodingException {
        if (_query == null)
            return;

        if (encoding == null || StandardCharsets.UTF_8.equals(encoding))
            UrlEncoded.decodeUtf8To(_query, parameters);
        else
            UrlEncoded.decodeTo(_query, parameters, encoding);
    }
261224
public static function getSupportedEncodings()
    {
        if (static::$encodings === null) {
            static::$encodings = array_map('strtoupper', mb_list_encodings());

            // FIXME: Converting € (UTF-8) to ISO-8859-16 gives a wrong result
            $indexIso885916 = array_search('ISO-8859-16', static::$encodings, true);
            if ($indexIso885916 !== false) {
                unset(static::$encodings[$indexIso885916]);
            }
        }

        return static::$encodings;
    }
744363
private function loadStoredRoutines(): void
  {
    // Log an empty line.
    $this->io->writeln('');

    // Sort the sources by routine name.
    usort($this->sources, function ($a, $b) {
      return strcmp($a['routine_name'], $b['routine_name']);
    });

    // Process all sources.
    foreach ($this->sources as $filename)
    {
      $routineName = $filename['routine_name'];

      $helper = new RoutineLoaderHelper($this->io,
                                        $filename['path_name'],
                                        $this->phpStratumMetadata[$routineName] ?? null,
                                        $this->replacePairs,
                                        $this->rdbmsOldMetadata[$routineName] ?? null,
                                        $this->sqlMode,
                                        $this->characterSet,
                                        $this->collate);

      try
      {
        $this->phpStratumMetadata[$routineName] = $helper->loadStoredRoutine();
      }
      catch (RoutineLoaderException $e)
      {
        $messages = [$e->getMessage(),
                     sprintf("Failed to load file '%s'", $filename['path_name'])];
        $this->io->error($messages);

        $this->errorFilenames[] = $filename['path_name'];
        unset($this->phpStratumMetadata[$routineName]);
      }
      catch (DataLayerException $e)
      {
        if ($e->isQueryError())
        {
          // Exception is caused by a SQL error. Log the message and the SQL statement with highlighting the error.
          $this->io->error($e->getShortMessage());
          $this->io->text($e->getMarkedQuery());
        }
        else
        {
          $this->io->error($e->getMessage());
        }
      }
    }
  }
1015261
def _get_codepage_char_map(self, encoding):
        
        # Skip things that were loaded previously
        if encoding in self.available_characters:
            return self.available_characters[encoding]
        codepage_char_list = self._get_codepage_char_list(encoding)
        codepage_char_map = dict((utf8, i + 128) for (i, utf8) in enumerate(codepage_char_list))
        self.available_characters[encoding] = codepage_char_map
        return codepage_char_map
1020231
function(data, encoding) {
      if (encoding == null) {
        encoding = 'hex';
      }
      if (Array.isArray(data)) {
        return data;
      }
      switch (encoding) {
        case 'base64':
          return Gibberish.base64.decode(data);
        case 'hex':
          return Gibberish.h2a(data);
        case 'utf8':
          return Gibberish.s2a(data);
        default:
          throw new Error("Encoding not supported");
      }
    }
113750
def encodings(self):
        """"""
        tried = set()
        for e in self.override_encodings:
            if self._usable(e, tried):
                yield e

        # Did the document originally start with a byte-order mark
        # that indicated its encoding?
        if self._usable(self.sniffed_encoding, tried):
            yield self.sniffed_encoding

        # Look within the document for an XML or HTML encoding
        # declaration.
        if self.declared_encoding is None:
            self.declared_encoding = self.find_declared_encoding(
                self.markup, self.is_html)
        if self._usable(self.declared_encoding, tried):
            yield self.declared_encoding

        # Use third-party character set detection to guess at the
        # encoding.
        if self.chardet_encoding is None:
            self.chardet_encoding = chardet_dammit(self.markup)
        if self._usable(self.chardet_encoding, tried):
            yield self.chardet_encoding

        # As a last-ditch effort, try utf-8 and windows-1252.
        for e in ('utf-8', 'windows-1252'):
            if self._usable(e, tried):
                yield e
1140404
public static function get_encodings() {
        $encodings = array();
        $encodings['UTF-8'] = 'UTF-8';
        $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
        if ($winenc != '') {
            $encodings[$winenc] = $winenc;
        }
        $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
        $encodings[$nixenc] = $nixenc;

        foreach (self::typo3()->synonyms as $enc) {
            $enc = strtoupper($enc);
            $encodings[$enc] = $enc;
        }
        return $encodings;
    }