/*
Parse the map descriptor.
Return an array of tokens.
Copy from com.ibm.ws.security.registry.ldap.CertificateMapper
967913
public static String[] parseFilterDescriptor(String mapDesc) throws CertificateMapperException {
        if (mapDesc == null || mapDesc.isEmpty()) {
            String msg = Tr.formatMessage(tc, WIMMessageKey.INVALID_CERTIFICATE_FILTER, mapDesc);
            throw new CertificateMapperException(WIMMessageKey.INVALID_CERTIFICATE_FILTER, msg);
        }

        int prev_idx, cur_idx, end_idx;
        ArrayList<String> list = new ArrayList<String>();
        for (prev_idx = cur_idx = 0, end_idx = mapDesc.length(); cur_idx < end_idx; prev_idx = cur_idx) {
            boolean isSquareBrace = false;
            if (mapDesc.contains("$[")) {
                isSquareBrace = true;
                cur_idx = mapDesc.indexOf("$[", prev_idx);
            } else {
                cur_idx = mapDesc.indexOf("${", prev_idx);
            }
            if (cur_idx == -1) {
                if (prev_idx < end_idx) {
                    list.add(mapDesc.substring(prev_idx));
                }
                break;
            }
            if (prev_idx < cur_idx) {
                list.add(mapDesc.substring(prev_idx, cur_idx));
            }
            prev_idx = cur_idx;
            if (isSquareBrace) {
                cur_idx = mapDesc.indexOf("]", prev_idx);
            } else {
                cur_idx = mapDesc.indexOf("}", prev_idx);
            }
            if (cur_idx == -1) {
                String msg = Tr.formatMessage(tc, WIMMessageKey.INVALID_CERTIFICATE_FILTER, mapDesc);
                throw new CertificateMapperException(WIMMessageKey.INVALID_CERTIFICATE_FILTER, msg);
            }
            cur_idx++;
            list.add(mapDesc.substring(prev_idx, cur_idx));
        }
        String[] mapDescEles = new String[list.size()];
        for (int idx = 0; idx < list.size(); idx++) {
            mapDescEles[idx] = list.get(idx);
        }
        return mapDescEles;
    }
33911
protected void validateCertificate(X509Certificate[] chain) throws com.ibm.wsspi.security.wim.exception.CertificateMapFailedException {
        // validate the certificate array
        if (chain == null || chain.length == 0) {
            throw new com.ibm.wsspi.security.wim.exception.CertificateMapFailedException();
        }

        for (X509Certificate cert : chain) {
            if (cert == null) {
                throw new com.ibm.wsspi.security.wim.exception.CertificateMapFailedException();
            }
        }
    }
493562
private Map<String, String> parseMap() {
        final Map<String, String> map = new HashMap<>();
        for (String pair : browserInput.split("&")) {
            String[] kv = pair.split("=");
            map.put(kv[0], kv[1]);
        }
        return map;
    }
1184723
public void parseMember(Map map) {
    String key = T.getString();
    check(TokenType.STRING, "a string");
    check(TokenType.COLON, ":");
    Object val = parseValue();
    map.put(key, val);
  }
418240
Map<String,Long> getContext(String... tokens) throws IOException {
    Objects.requireNonNull(tokens);
    TermsEnum iterator = getIterator();
    Map<String,Long> result = new HashMap<>();
    BytesRef byteRef;
    int i = 0;
    while ((byteRef = iterator.next()) != null) {
      String term = new String(byteRef.bytes, byteRef.offset, byteRef.length);
      for (String token : tokens) {
        if (term.contains(" " + token + " ")) {
          String[] split = term.split(" ");
          if (split.length == 3) {
            long count = getCount(Arrays.asList(split[0], split[1], split[2]));
            result.put(term, count);
          }
        }
      }
      /*if (i++ > 1_000_000) { // comment in for faster testing with subsets of the data
        break;
      }*/
    }
    return result;
  }
677875
private Map<String, TemplateSourceInfo> retrieveTemplateMap() {
        Map<String, TemplateSourceInfo> templateMap = 
        	new TreeMap<String, TemplateSourceInfo>();
        
        String remoteSource = mRemoteSourceDir;
        if (!remoteSource.endsWith("/")) {
            remoteSource = remoteSource + "/";
        }
        
        try {
            HttpClient tsClient = getTemplateServerClient(remoteSource);

            HttpClient.Response response = tsClient.setURI(createTemplateServerRequest(remoteSource,null))
                .setPersistent(true).getResponse(); 

            if (response != null && response.getStatusCode() == 200) {

                Reader rin = new InputStreamReader
                    (new BufferedInputStream(response.getInputStream()));
            
                StreamTokenizer st = new StreamTokenizer(rin);
                st.resetSyntax();
                st.wordChars('!','{');
                st.wordChars('}','}');
                st.whitespaceChars(0,' ');
                st.parseNumbers();
                st.quoteChar('|');
                st.eolIsSignificant(true);
                String templateName = null; 
                int tokenID = 0;
                // ditching the headers by looking for "\r\n\r\n"
                /* 
                 * no longer needed now that HttpClient is being used but leave
                 * in for the moment.
                 *
                 * while (!((tokenID = st.nextToken()) == StreamTokenizer.TT_EOL 
                 *       && st.nextToken() == StreamTokenizer.TT_EOL) 
                 *       && tokenID != StreamTokenizer.TT_EOF) {
                 * }
                 */
                while ((tokenID = st.nextToken()) != StreamTokenizer.TT_EOF) {
                    if (tokenID == '|' || tokenID == StreamTokenizer.TT_WORD) {
                    
                        templateName = st.sval;
                    }
                    else if (tokenID == StreamTokenizer.TT_NUMBER 
                             && templateName != null) {
                        templateName = templateName.substring(1);
                        //System.out.println(templateName);
                        templateMap.put(templateName.replace('/','.'),
                                        new TemplateSourceInfo(
                                                               templateName,
                                                               remoteSource,
                                                               (long)st.nval));
                        templateName = null;
                    }
                }
            }
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }

        return templateMap;
    }
1332644
static Map<String, String> parseAwsIdentityDocument(String awsIdentityDocument) {
    Map<String, String> map = new HashMap<String, String>();
    @SuppressWarnings("StringSplitter")
    String[] lines = awsIdentityDocument.split(AWS_IDENTITY_DOC_LINE_BREAK_SPLITTER, -1);
    for (String line : lines) {
      @SuppressWarnings("StringSplitter")
      String[] keyValuePair = line.split(AWS_IDENTITY_DOC_COLON_SPLITTER, -1);
      if (keyValuePair.length != 2) {
        continue;
      }
      String key = keyValuePair[0].replaceAll("[\" ]", "");
      String value = keyValuePair[1].replaceAll("[\" ,]", "");
      map.put(key, value);
    }
    return map;
  }
393135
def parse_descriptor(descriptor: str) -> list:
    
    # States:
    #   10 == NORMAL,
    #   20 == OBJECT REFERENCE
    state = 10
    tokens = []
    token = []
    dimensions = 0
    for char in descriptor:
        if state == 10 and char == 'L':
            state = 20
        elif state == 10 and char == '[':
            dimensions += 1
        elif state == 10:
            tokens.append(JVMType(char, dimensions, _HUMAN_NAMES[char]))
            dimensions = 0
        elif state == 20 and char == ';':
            tokens.append(JVMType('L', dimensions, ''.join(token)))
            dimensions = 0
            state = 10
            del token[:]
        elif state == 20:
            token.append(char)
    return tokens
200876
@SuppressWarnings("unchecked")
  private String tokenViaExecCredential(Map<String, Object> execMap) {
    if (execMap == null) {
      return null;
    }
    String apiVersion = (String) execMap.get("apiVersion");
    if (!"client.authentication.k8s.io/v1beta1".equals(apiVersion)
        && !"client.authentication.k8s.io/v1alpha1".equals(apiVersion)) {
      log.error("Unrecognized user.exec.apiVersion: {}", apiVersion);
      return null;
    }
    String command = (String) execMap.get("command");
    JsonElement root = runExec(command, (List) execMap.get("args"), (List) execMap.get("env"));
    if (root == null) {
      return null;
    }
    if (!"ExecCredential".equals(root.getAsJsonObject().get("kind").getAsString())) {
      log.error("Unrecognized kind in response");
      return null;
    }
    if (!apiVersion.equals(root.getAsJsonObject().get("apiVersion").getAsString())) {
      log.error("Mismatched apiVersion in response");
      return null;
    }
    JsonObject status = root.getAsJsonObject().get("status").getAsJsonObject();
    JsonElement token = status.get("token");
    if (token == null) {
      // TODO handle clientCertificateData/clientKeyData
      // (KubeconfigAuthentication is not yet set up for that to be dynamic)
      log.warn("No token produced by {}", command);
      return null;
    }
    log.debug("Obtained a token from {}", command);
    return token.getAsString();
    // TODO cache tokens between calls, up to .status.expirationTimestamp
    // TODO a 401 is supposed to force a refresh,
    // but KubeconfigAuthentication hardcodes AccessTokenAuthentication which does not support that
    // and anyway ClientBuilder only calls Authenticator.provide once per ApiClient;
    // we would need to do it on every request
  }
236342
function parse_DataSpaceMapEntry(blob) {
	var len = blob.read_shift(4);
	var end = blob.l + len - 4;
	var o = {};
	var cnt = blob.read_shift(4);
	var comps = [];
	/* [MS-OFFCRYPTO] 2.1.6.2 DataSpaceReferenceComponent Structure */
	while(cnt-- > 0) comps.push({ t: blob.read_shift(4), v: blob.read_shift(0, 'lpp4') });
	o.name = blob.read_shift(0, 'lpp4');
	o.comps = comps;
	if(blob.l != end) throw new Error("Bad DataSpaceMapEntry: " + blob.l + " != " + end);
	return o;
}
1339935
private String[] extractAndDecodeHeader(String header) throws IOException {

        byte[] base64Token = header.substring(6).getBytes(CREDENTIALS_CHARSET);
        byte[] decoded;
        try {
            decoded = Base64.decode(base64Token);
        } catch (IllegalArgumentException e) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }

        String token = new String(decoded, CREDENTIALS_CHARSET);

        int delim = token.indexOf(":");

        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        }
        return new String[] {token.substring(0, delim), token.substring(delim + 1)};
    }
720408
public static String getCertIdByKeyStoreMap(String certPath, String certPwd) {
		if (!keyStoreMap.containsKey(certPath)) {
			// 缓存中未查询到,则加载RSA证书
			loadSignCert(certPath, certPwd);
		}
		return getCertIdIdByStore(keyStoreMap.get(certPath));
	}
792978
@Override
    public X509Certificate[] getCertificateChain(String s) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "getCertificateChain: " + s);

        X509Certificate[] rc = getX509KeyManager().getCertificateChain(s);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "getCertificateChain", rc);
        return rc;
    }
313472
public boolean[] getKeyUsageMappedBits() {
        KeyUsageExtension keyUsage = new KeyUsageExtension();
        Boolean val = Boolean.TRUE;

        try {
            if (isSet(getPosition(SSL_CLIENT)) ||
                isSet(getPosition(S_MIME)) ||
                isSet(getPosition(OBJECT_SIGNING)))
                keyUsage.set(KeyUsageExtension.DIGITAL_SIGNATURE, val);

            if (isSet(getPosition(SSL_SERVER)))
                keyUsage.set(KeyUsageExtension.KEY_ENCIPHERMENT, val);

            if (isSet(getPosition(SSL_CA)) ||
                isSet(getPosition(S_MIME_CA)) ||
                isSet(getPosition(OBJECT_SIGNING_CA)))
                keyUsage.set(KeyUsageExtension.KEY_CERTSIGN, val);
        } catch (IOException e) { }
        return keyUsage.getBits();
    }
1356082
private synchronized CodeSource mapSignersToCodeSource(URL url, CodeSigner[] signers) {
        Map map;
        if (url == lastURL) {
            map = lastURLMap;
        } else {
            map = (Map) urlToCodeSourceMap.get(url);
            if (map == null) {
                map = new HashMap();
                urlToCodeSourceMap.put(url, map);
            }
            lastURLMap = map;
            lastURL = url;
        }
        CodeSource cs = (CodeSource) map.get(signers);
        if (cs == null) {
            cs = new VerifierCodeSource(csdomain, url, signers);
            signerToCodeSource.put(signers, cs);
        }
        return cs;
    }
471933
@Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = super.getHeaders();
        if (!mRequestHeaders.isEmpty()) {
            if (headers.isEmpty()) {
                return mRequestHeaders;
            } else {
                headers.putAll(mRequestHeaders);
            }
        }
        return headers;
    }
751369
public static TypeSignature ofMap(TypeSignature keyTypeSignature, TypeSignature valueTypeSignature) {
        requireNonNull(keyTypeSignature, "keyTypeSignature");
        requireNonNull(valueTypeSignature, "valueTypeSignature");
        return ofContainer("map", keyTypeSignature, valueTypeSignature);
    }