cms.service.account.HTMLGenerator.java Source code

Java tutorial

Introduction

Here is the source code for cms.service.account.HTMLGenerator.java

Source

/**
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * Founder admin@love320.com
 * 
 * http://www.love320.com
 */
package cms.service.account;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//????
@Component
public class HTMLGenerator {

    //?XHTML
    public final String generate(final String url) {
        // isBlank??0(whitespace) ? 
        if (StringUtils.isBlank(url))
            return null;

        //URL
        Pattern pattern = Pattern.compile("(http://|https://){1}[\\w\\.\\-/:]+");
        Matcher matcher = pattern.matcher(url);
        if (!matcher.find())
            return null;

        //
        StringBuffer sb = new StringBuffer();

        try {
            //?XHMTL
            URL _url = new URL(url);
            URLConnection urlconnection = _url.openConnection();

            //System.out.println(urlconnection.getContentType());

            //?XHMTL
            BufferedReader in = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "UTF-8"));

            String inputLine;//XHML,SB
            while ((inputLine = in.readLine()) != null) {
                sb.append(inputLine + "\n");
                //System.out.println(inputLine);
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return sb.toString();
    }

    //??
    public int save(String urlstr, String htmlName) {
        //System.out.println("?"+urlstr);
        String src = generate(urlstr);

        //System.out.println("html:"+src.toString());

        File file = new File(this.getClass().getResource("/").getPath() + "../../html/" + htmlName);
        try {
            FileUtils.writeStringToFile(file, src, "UTF-8");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //return Math.abs(src.hashCode());//
        return src.length();//??
    }
}