code: public static String toValidPackageName(String pkg)
     {
        if (pkg == null)
        {
           throw new IllegalArgumentException("Package should not be null");
        }
        // Sanitizing package name
        StringBuilder sb = new StringBuilder(pkg.length());
        for (int i = 0; i < pkg.length(); i++)
        {
           char c = pkg.charAt(i);
           // remove dots from the beginning and the end of the package
           if (c == '.' && (i == 0 || i == pkg.length() - 1))
           {
              continue;
           }
           if (c == '.' || Character.isJavaIdentifierPart(c))
           {
              sb.append(c);
           }
        }
        String packageName = sb.toString();
        StringBuilder result = new StringBuilder();
        String[] tokens = packageName.split("[.]");
        for (String token : tokens)
        {
           if (result.length() > 0 && result.charAt(result.length() - 1) != '.')
           {
              result.append('.');
           }
           if (JLSValidator.isReservedWord(token))
           {
              result.append(token).append('_');
           }
           else if (isNumber(token))
           {
              // skip tokens as numbers and remove the appended '.' if exist
              if (result.length() > 0)
                 result.deleteCharAt(result.length() - 1);
           }
           else
           {
              result.append(token);
           }
        }
        return result.toString();
     }
docs: Converts a given package name to a valid/parseable package name (without reserved words)