Because of legacy encodings used by earlier JDK versions, we
need to be careful when accessing encoding names via JDK
classes.
497774
public static String findEncodingFor(Writer w)
    {
        if (w instanceof OutputStreamWriter) {
            String enc = ((OutputStreamWriter) w).getEncoding();
            /* [WSTX-146]: It is important that we normalize this, since
             *  older JDKs return legacy encoding names ("UTF8" instead of
             *  canonical "UTF-8")
             */
            return normalize(enc);
        }
        return null;
    }
192240
private static int typeCode(Object a) {
        if (a instanceof java.lang.Integer) return INT;
        if (a instanceof java.lang.Double) return DOUBLE;
        if (a instanceof java.lang.Long) return LONG;
        if (a instanceof java.lang.Character) return CHAR;
        if (a instanceof java.lang.Float) return FLOAT;
        if ((a instanceof java.lang.Byte) || (a instanceof java.lang.Short)) return INT;
        return OTHER;
    }
1317355
@FFDCIgnore(NumberFormatException.class)
    private static boolean determineIsJava8Before161(String version) {
        try {
            return version != null 
                && version.startsWith("1.8.0_")
                && Integer.parseInt(version.substring(6)) < 161;
        } catch (NumberFormatException ex) {
            //no-op
        }
        return false;
    }
677999
private void resolveTypeTemplates() {
        Collections.sort(context.getClassesAlreadyDone(), new Comparator<Java4CppType>() {

            @Override
            public int compare(Java4CppType t1, Java4CppType t2) {
                Class<?> o1 = t1.getRawClass();
                Class<?> o2 = t2.getRawClass();
                if (o1.isArray() && o2.isArray()) {
                    int idx1 = o1.getName().lastIndexOf('[');
                    int idx2 = o2.getName().lastIndexOf('[');
                    if (idx1 == idx2) {
                        return o1.getName().compareTo(o2.getName());
                    }
                    return idx1 < idx2 ? -1 : 1;
                } else if (o1.isArray() && !o2.isArray()) {
                    return 1;
                } else if (!o1.isArray() && o2.isArray()) {
                    return -1;
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (Java4CppType type : context.getClassesAlreadyDone()) {
            context.executeTypeTemplate(type);
        }
    }
336641
private String getEncoding(String escapeSequences) {
        String encoding = null;

        if (escapeSequences.equals("%/@")) {
            // UCS-2 level 1
            encoding = "UTF-16BE";
        } else if (escapeSequences.equals("%/C")) {
            // UCS-2 level 2
            encoding = "UTF-16BE";
        } else if (escapeSequences.equals("%/E")) {
            // UCS-2 level 3
            encoding = "UTF-16BE";
        }

        return encoding;
    }
206246
public static String urlDecode(String s) {
        try {
            return URLDecoder.decode(s, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("get a jdk that actually supports utf-8", e);
        }
    }
194493
@Override
    public String getJvmConverter(String encoding) {
        if (null != encoding) {
            String converter = this.converterMap.get(encoding.toLowerCase());
            if (null != converter) {
                return converter;
            }
        }
        return encoding;
    }
339612
static Set<String> getJavaDefaultTypes() {
        if (javaDefaultTypes == null) {
            javaDefaultTypes = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(
                    "AbstractMethodError",
                    "Appendable",
                    "ArithmeticException",
                    "ArrayIndexOutOfBoundsException",
                    "ArrayStoreException",
                    "AssertionError",
                    "AutoCloseable",
                    "Boolean",
                    "BootstrapMethodError",
                    "Byte",
                    "Character",
                    "CharSequence",
                    "Class",
                    "ClassCastException",
                    "ClassCircularityError",
                    "ClassFormatError",
                    "ClassLoader",
                    "ClassNotFoundException",
                    "ClassValue",
                    "Cloneable",
                    "CloneNotSupportedException",
                    "Comparable",
                    "Compiler",
                    "Deprecated",
                    "Double",
                    "Enum",
                    "EnumConstantNotPresentException",
                    "Error",
                    "Exception",
                    "ExceptionInInitializerError",
                    "Float",
                    "FunctionalInterface",
                    "IllegalAccessError",
                    "IllegalAccessException",
                    "IllegalArgumentException",
                    "IllegalCallerException",
                    "IllegalMonitorStateException",
                    "IllegalStateException",
                    "IllegalThreadStateException",
                    "IncompatibleClassChangeError",
                    "IndexOutOfBoundsException",
                    "InheritableThreadLocal",
                    "InstantiationError",
                    "InstantiationException",
                    "Integer",
                    "InternalError",
                    "InterruptedException",
                    "Iterable",
                    "LayerInstantiationException",
                    "LinkageError",
                    "Long",
                    "Math",
                    "Module",
                    "ModuleLayer",
                    "NegativeArraySizeException",
                    "NoClassDefFoundError",
                    "NoSuchFieldError",
                    "NoSuchFieldException",
                    "NoSuchMethodError",
                    "NoSuchMethodException",
                    "NullPointerException",
                    "Number",
                    "NumberFormatException",
                    "Object",
                    "OutOfMemoryError",
                    "Override",
                    "Package",
                    "Process",
                    "ProcessBuilder",
                    "ProcessHandle",
                    "Readable",
                    "ReflectiveOperationException",
                    "Runnable",
                    "Runtime",
                    "RuntimeException",
                    "RuntimePermission",
                    "SafeVarargs",
                    "SecurityException",
                    "SecurityManager",
                    "Short",
                    "StackOverflowError",
                    "StackTraceElement",
                    "StackWalker",
                    "StrictMath",
                    "String",
                    "StringBuffer",
                    "StringBuilder",
                    "StringIndexOutOfBoundsException",
                    "SuppressWarnings",
                    "System",
                    "Thread",
                    "ThreadDeath",
                    "ThreadGroup",
                    "ThreadLocal",
                    "Throwable",
                    "TypeNotPresentException",
                    "UnknownError",
                    "UnsatisfiedLinkError",
                    "UnsupportedClassVersionError",
                    "UnsupportedOperationException",
                    "VerifyError",
                    "VirtualMachineError",
                    "Void",
                    "boolean",
                    "byte",
                    "char",
                    "double",
                    "float",
                    "int",
                    "long",
                    "short",
                    "void")));
        }
        return javaDefaultTypes;
    }
940422
private static boolean isJDBCClass(@SlashedClassName String name) {
        String clsName = SignatureUtils.stripSignature(name);

        return (clsName.startsWith("java.sql.") || clsName.startsWith("javax.sql.")) && !clsName.endsWith("Exception");
    }
735711
@Override
    public void sawOpcode(int seen) {
        if (seen == Const.INVOKEVIRTUAL) {
            if ("equals".equals(getNameConstantOperand()) && "(Ljava/lang/Object;)Z".equals(getSigConstantOperand())) {
                OpcodeStack.Item item = stack.getStackItem(1);
                ClassDescriptor c = DescriptorFactory.createClassDescriptorFromSignature(item.getSignature());
                check(c);

            } else if ("java/lang/Class".equals(getClassConstantOperand())
                    && ("isInstance".equals(getNameConstantOperand()) || "cast".equals(getNameConstantOperand()))) {
                OpcodeStack.Item item = stack.getStackItem(1);
                if ("Ljava/lang/Class;".equals(item.getSignature())) {
                    Object value = item.getConstant();
                    if (value instanceof String) {
                        ClassDescriptor c = DescriptorFactory.createClassDescriptor((String) value);
                        check(c);
                    }
                }

            }

        } else if (seen == Const.INSTANCEOF || seen == Const.CHECKCAST) {
            check(getClassDescriptorOperand());
        }

    }
38481
private KryoTranscoder getTranscoder( final ClassLoader classLoader ) {
        if ( _transcoder == null ) {
            final int initialBufferSize = getSysPropValue( PROP_INIT_BUFFER_SIZE, KryoTranscoder.DEFAULT_INITIAL_BUFFER_SIZE );
            final int maxBufferSize = getSysPropValue( PROP_ENV_MAX_BUFFER_SIZE, KryoTranscoder.DEFAULT_MAX_BUFFER_SIZE );
            final String defaultSerializerFactory = getSysPropValue( PROP_ENV_DEFAULT_FACTORY, KryoTranscoder.DEFAULT_SERIALIZER_FACTORY_CLASS );
            _transcoder = new KryoTranscoder( classLoader, _customConverterClassNames, _copyCollectionsForSerialization,
                    initialBufferSize, maxBufferSize, defaultSerializerFactory );
        }
        return _transcoder;
    }
928555
public void init ()
    {
        try {
            if (!Boolean.getBoolean("com.samskivert.util.JDK14Logger.noFormatter")) {
                OneLineLogFormatter.configureDefaultHandler();
            }
            boolean reportedUTF8Missing = false;
            for (Handler handler : java.util.logging.Logger.getLogger("").getHandlers()) {
                try {
                    handler.setEncoding("UTF-8");
                } catch (UnsupportedEncodingException e) {
                    // JVMs are required to support UTF-8 so this shouldn't happen, but if it does,
                    // tell somebody that things are really fucked
                    if (!reportedUTF8Missing) {
                        reportedUTF8Missing = true;
                        System.err.println("Unable to find UTF-8 encoding. " +
                                           "This JVM ain't right: " + e.getMessage());
                    }
                }
            }
        } catch (SecurityException se) {
            // running in sandbox; no custom logging; no problem!
        }
    }
660969
static ByteBuffer unescapeBytes(final CharSequence input)
    {
        int pos = 0, len = input.length();
        final byte[] result = new byte[len];
        ByteBuffer buffer = ByteBuffer.wrap(result);
        for (int i = 0; i < len; i++)
        {
            char c = input.charAt(i);
            if (c == '\\')
            {
                if (i + 1 < len)
                {
                    ++i;
                    c = input.charAt(i);
                    if (isOctal(c))
                    {
                        // Octal escape.
                        int code = digitValue(c);
                        if (i + 1 < len && isOctal(input.charAt(i + 1)))
                        {
                            ++i;
                            code = code * 8 + digitValue(input.charAt(i));
                        }
                        if (i + 1 < len && isOctal(input.charAt(i + 1)))
                        {
                            ++i;
                            code = code * 8 + digitValue(input.charAt(i));
                        }
                        result[pos++] = (byte) code;
                    }
                    else
                    {
                        switch (c)
                        {
                            case 'a':
                                result[pos++] = 0x07;
                                break;
                            case 'b':
                                result[pos++] = '\b';
                                break;
                            case 'f':
                                result[pos++] = '\f';
                                break;
                            case 'n':
                                result[pos++] = '\n';
                                break;
                            case 'r':
                                result[pos++] = '\r';
                                break;
                            case 't':
                                result[pos++] = '\t';
                                break;
                            case 'v':
                                result[pos++] = 0x0b;
                                break;
                            case '\\':
                                result[pos++] = '\\';
                                break;
                            case '\'':
                                result[pos++] = '\'';
                                break;
                            case '"':
                                result[pos++] = '\"';
                                break;

                            case 'x':
                                // hex escape
                                int code = 0;
                                if (i + 1 < len && isHex(input.charAt(i + 1)))
                                {
                                    ++i;
                                    code = digitValue(input.charAt(i));
                                }
                                else
                                {
                                    throw new InvalidEscapeSequenceException(
                                            "Invalid escape sequence: '\\x' with no digits");
                                }
                                if (i + 1 < len && isHex(input.charAt(i + 1)))
                                {
                                    ++i;
                                    code = code * 16 + digitValue(input.charAt(i));
                                }
                                result[pos++] = (byte) code;
                                break;

                            default:
                                throw new InvalidEscapeSequenceException(
                                        "Invalid escape sequence: '\\" + c + '\'');
                        }
                    }
                }
                else
                {
                    throw new InvalidEscapeSequenceException(
                            "Invalid escape sequence: '\\' at end of string.");
                }
            }
            else
            {
                result[pos++] = (byte) c;
            }
        }
        buffer.limit(pos);
        return buffer;
    }
755744
public final void mDigits() throws RecognitionException {
		try {
			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1323:7: ( Digit ( ( DigitOrUnderscore )* Digit )? )
			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1323:9: Digit ( ( DigitOrUnderscore )* Digit )?
			{
			mDigit(); 

			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1323:15: ( ( DigitOrUnderscore )* Digit )?
			int alt18=2;
			int LA18_0 = input.LA(1);
			if ( ((LA18_0 >= '0' && LA18_0 <= '9')||LA18_0=='_') ) {
				alt18=1;
			}
			switch (alt18) {
				case 1 :
					// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1323:16: ( DigitOrUnderscore )* Digit
					{
					// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1323:16: ( DigitOrUnderscore )*
					loop17:
					while (true) {
						int alt17=2;
						int LA17_0 = input.LA(1);
						if ( ((LA17_0 >= '0' && LA17_0 <= '9')) ) {
							int LA17_1 = input.LA(2);
							if ( ((LA17_1 >= '0' && LA17_1 <= '9')||LA17_1=='_') ) {
								alt17=1;
							}

						}
						else if ( (LA17_0=='_') ) {
							alt17=1;
						}

						switch (alt17) {
						case 1 :
							// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:
							{
							if ( (input.LA(1) >= '0' && input.LA(1) <= '9')||input.LA(1)=='_' ) {
								input.consume();
							}
							else {
								MismatchedSetException mse = new MismatchedSetException(null,input);
								recover(mse);
								throw mse;
							}
							}
							break;

						default :
							break loop17;
						}
					}

					mDigit(); 

					}
					break;

			}

			}

		}
		finally {
			// do for sure before leaving
		}
	}
1175863
public final void mJavaLetterOrDigit() throws RecognitionException {
		try {
			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1388:2: ( ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '$' | '_' ) |{...}?~ ( '\\u0000' .. '\\u007F' | '\\uD800' .. '\\uDBFF' ) |{...}? ( '\\uD800' .. '\\uDBFF' ) ( '\\uDC00' .. '\\uDFFF' ) )
			int alt28=3;
			int LA28_0 = input.LA(1);
			if ( (LA28_0=='$'||(LA28_0 >= '0' && LA28_0 <= '9')||(LA28_0 >= 'A' && LA28_0 <= 'Z')||LA28_0=='_'||(LA28_0 >= 'a' && LA28_0 <= 'z')) ) {
				alt28=1;
			}
			else if ( ((LA28_0 >= '\u0080' && LA28_0 <= '\uD7FF')||(LA28_0 >= '\uDC00' && LA28_0 <= '\uFFFF')) ) {
				alt28=2;
			}
			else if ( ((LA28_0 >= '\uD800' && LA28_0 <= '\uDBFF')) ) {
				alt28=3;
			}

			else {
				NoViableAltException nvae =
					new NoViableAltException("", 28, 0, input);
				throw nvae;
			}

			switch (alt28) {
				case 1 :
					// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1388:4: ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '$' | '_' )
					{
					if ( input.LA(1)=='$'||(input.LA(1) >= '0' && input.LA(1) <= '9')||(input.LA(1) >= 'A' && input.LA(1) <= 'Z')||input.LA(1)=='_'||(input.LA(1) >= 'a' && input.LA(1) <= 'z') ) {
						input.consume();
					}
					else {
						MismatchedSetException mse = new MismatchedSetException(null,input);
						recover(mse);
						throw mse;
					}
					}
					break;
				case 2 :
					// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1389:9: {...}?~ ( '\\u0000' .. '\\u007F' | '\\uD800' .. '\\uDBFF' )
					{
					if ( !((Character.isJavaIdentifierPart(input.LA(1)))) ) {
						throw new FailedPredicateException(input, "JavaLetterOrDigit", "Character.isJavaIdentifierPart(input.LA(1))");
					}
					if ( (input.LA(1) >= '\u0080' && input.LA(1) <= '\uD7FF')||(input.LA(1) >= '\uDC00' && input.LA(1) <= '\uFFFF') ) {
						input.consume();
					}
					else {
						MismatchedSetException mse = new MismatchedSetException(null,input);
						recover(mse);
						throw mse;
					}
					}
					break;
				case 3 :
					// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1391:9: {...}? ( '\\uD800' .. '\\uDBFF' ) ( '\\uDC00' .. '\\uDFFF' )
					{
					if ( !((Character.isJavaIdentifierPart(Character.toCodePoint((char)input.LA(-1), (char)input.LA(1))))) ) {
						throw new FailedPredicateException(input, "JavaLetterOrDigit", "Character.isJavaIdentifierPart(Character.toCodePoint((char)input.LA(-1), (char)input.LA(1)))");
					}
					if ( (input.LA(1) >= '\uD800' && input.LA(1) <= '\uDBFF') ) {
						input.consume();
					}
					else {
						MismatchedSetException mse = new MismatchedSetException(null,input);
						recover(mse);
						throw mse;
					}
					if ( (input.LA(1) >= '\uDC00' && input.LA(1) <= '\uDFFF') ) {
						input.consume();
					}
					else {
						MismatchedSetException mse = new MismatchedSetException(null,input);
						recover(mse);
						throw mse;
					}
					}
					break;

			}
		}
		finally {
			// do for sure before leaving
		}
	}
1066069
private static String getEncodingToUse(String encoding)
    {
        //get encoding
        String updatedEncoding=encoding;
        if(updatedEncoding==null)
        {
            updatedEncoding=IOHelper.getDefaultEncoding();
        }
        
        return updatedEncoding;
    }
596824
@TCB
  private static int longestPrefixOfGoodCodeunits(String s) {
    int n = s.length(), i;
    for (i = 0; i < n; ++i) {
      char ch = s.charAt(i);
      if (ch < 0x20) {
        if (IS_BANNED_ASCII[ch]) {
          return i;
        }
      } else if (0xd800 <= ch) {
        if (ch <= 0xdfff) {
          if (i+1 < n && Character.isSurrogatePair(ch, s.charAt(i+1))) {
            ++i;  // Skip over low surrogate since we know it's ok.
          } else {
            return i;
          }
        } else if ((ch & 0xfffe) == 0xfffe) {
          return i;
        }
      }
    }
    return -1;
  }