Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.HashMap;

public class Main {
    private static HashMap<String, String> entityTableEncode = null;
    private static final String[] ENTITIES = { ">", "&gt;", "<", "&lt;", "&", "&amp;", "\"", "&quot;", "'",
            "&#039;", "\\", "&#092;", "\u00a9", "&copy;", "\u00ae", "&reg;" };

    public static String encode(String s, String cr) {
        if (entityTableEncode == null) {
            buildEntityTables();
        }
        if (s == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder(s.length() * 2);
        char ch;
        for (int i = 0; i < s.length(); ++i) {
            ch = s.charAt(i);
            if ((ch >= 48 && ch <= 59) || (ch >= 63 && ch <= 90) || (ch >= 97 && ch <= 122) || (ch == ' ')) {
                sb.append(ch);
            } else if (ch == '\n') {
                sb.append(cr);
            } else {
                // cherry pick some safe non-seq chars
                if (ch == '(' || ch == ')' || ch == '+' || ch == '-' || ch == '*' || ch == '_') {
                    sb.append(cr);
                } else {
                    String chEnc = encodeSingleChar(String.valueOf(ch));
                    if (chEnc != null) {
                        sb.append(chEnc);
                    } else {
                        // Not 7 Bit use the unicode system
                        sb.append("&#");
                        sb.append(new Integer(ch).toString());
                        sb.append(';');
                    }
                }
            }
        }
        return sb.toString();
    }

    protected static synchronized void buildEntityTables() {
        entityTableEncode = new HashMap<String, String>(ENTITIES.length);

        for (int i = 0; i < ENTITIES.length; i += 2) {
            if (!entityTableEncode.containsKey(ENTITIES[i])) {
                entityTableEncode.put(ENTITIES[i], ENTITIES[i + 1]);
            }
        }
    }

    private static String encodeSingleChar(String ch) {
        return (String) entityTableEncode.get(ch);
    }
}