com.websystique.springmvc.youtube_api.Function.java Source code

Java tutorial

Introduction

Here is the source code for com.websystique.springmvc.youtube_api.Function.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.websystique.springmvc.youtube_api;

import javax.xml.parsers.*;

import org.apache.commons.lang3.StringUtils;
import org.jdom.Element;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.*;

import com.websystique.springmvc.model.VideoModel;
import com.websystique.springmvc.service.IVideoService;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 *
 * @author saber
 */
public class Function {
    @Autowired
    private IVideoService VideoService;

    /**
     * Constructor par default
     */
    public Function() {

    }

    public String chuyenchuoistring(String s) {
        String regex = "?;.";
        String[] charArray = new String[s.length()];
        String[] stringArray = new String[s.length()];
        char[] delimArray = new char[regex.length()];
        int i = 0;
        // Outer loop
        outer: for (int k = 0; k < s.length(); k++) {
            // Inner loop
            inner: for (int j = 0; j < delimArray.length; j++) {
                // The if checks the current character in the string with each
                // delimiter character and proceeds till it checks all the
                // delimiters
                if (s.charAt(k) != regex.charAt(j)) {
                    continue inner;
                } else {
                    // Else block is reached when any of the character in the
                    // string is a delimiter
                    // Check if the current array position is null(which means
                    // nothing is assigned so far) and move to the next position
                    // only if it is not null
                    if (stringArray[i] != null) {
                        i++;
                    }

                    // Assign the delimiter in the output array
                    stringArray[i] = Character.toString(s.charAt(k));
                    // Increment to the next position in the array
                    i++;
                    continue outer;
                }
            }
            // This if is to avoid null being appended to the string
            if (stringArray[i] == null) {
                stringArray[i] = "";
            }
            // Add the character(since it is not a delimiter) to the current
            // index i
            stringArray[i] += Character.toString(s.charAt(k));
        }

        String[] splitStrArr = new String[i + 1];
        int m = 0;
        s = "";
        do {
            splitStrArr[m] = stringArray[m];
            if (splitStrArr[m] != null) {
                if (splitStrArr[m].equals(".") || splitStrArr[m].equals("?") || splitStrArr[m].equals(";")) {
                    s += " " + splitStrArr[m] + "####";
                } else {
                    s += splitStrArr[m];
                }
            }

            // System.out.println(splitStrArr[m]);
            m++;
        } while (m <= i);
        System.out.println(s);
        return s;
    }

    public Boolean ExistVideosub(String url) throws Exception {
        Boolean kiemtra = false;
        URL website = new URL(url);
        URLConnection connection = website.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
            if (response.toString() != "") {
                break;
            }
        }
        System.out.println("CHECKing== " + response.toString());
        in.close();
        if (response.toString().length() > 1) {// co sub
            kiemtra = true;
        }
        return kiemtra;
    }

    public int getrandom(int so) {
        Random rand = new Random();
        int value = rand.nextInt(so); // 50 is the maximum andInteger.parseInt(
        return value;
    }

    public String getfilesubtitle(String url) {
        String kq = "";
        try {
            DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
            DocumentBuilder b = f.newDocumentBuilder();
            Document doc = b.parse(url);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("text");
            kq = printNote(nList);
            return kq;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return kq;
    }

    public int demsotu(String cau)

    {
        String str = cau.replace(".", "").replace(";", "").replace("?", "");
        int sotu = StringUtils.countMatches(str.replaceAll("\\s+", " ").trim(), " ") + 1;
        return sotu;
    }

    @SuppressWarnings({ "static-access", "unchecked" })

    private String printNote(NodeList nodeList) {
        List<VideoSub> listsub = new ArrayList<VideoSub>();
        List<VideoSub> savelistsub = new ArrayList<VideoSub>();
        for (int count = 0; count < nodeList.getLength(); count++) {
            VideoSub v = new VideoSub();
            Node tempNode = nodeList.item(count);
            if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
                v.setTextsb(replace_all(replacetext(tempNode.getTextContent().replace("...", "."))));
                if (tempNode.hasAttributes()) {
                    NamedNodeMap nodeMap = tempNode.getAttributes();
                    for (int i = 0; i < nodeMap.getLength(); i++) {
                        Node node = nodeMap.item(i);
                        if (i == 0) {
                            v.setEnd(node.getNodeValue());
                        } else {
                            v.setStart(node.getNodeValue());
                        }
                    }
                }
            }
            listsub.add(v);
        }
        String savetext = "";
        double sodu = 0;
        double savedur = 0;
        String dutext = "";
        double start = 0;
        String kq = "";
        boolean flag = true;// vo lan dau
        boolean flagchamcuoi = false;// vo lan dau
        for (int i = 0; i < listsub.size(); i++) {
            String cau = listsub.get(i).getTextsb();
            if (flag || flagchamcuoi == true) {
                start = Double.parseDouble(listsub.get(i).getStart());
                savedur = Double.parseDouble(listsub.get(i).getEnd());
                flag = false;
                flagchamcuoi = false;
            }

            double dur = Double.parseDouble(listsub.get(i).getEnd());
            if (sodu != 0) {
                savetext += dutext;
                start = Double.parseDouble(listsub.get(i).getStart());
                start -= sodu;
                System.out.println(sodu + "So du" + start);
                dutext = "";
                sodu = 0;
            }
            if (cau.contains("####") == true) {
                float sogiay = (float) dur;
                float phantram = 0;
                int socau = 0;
                int sotu = demsotu(cau);
                String[] savecau = new String[100];
                int[] savesotu = new int[1000];
                double[] phantramsotu = new double[1000];
                for (String retval : cau.split("####")) { // split("\\|;\\s*|\\.\\s*|\\?\\s*")
                    if (retval != "" && retval.length() > 0) {
                        savecau[socau] = retval;
                        savesotu[socau] = (1 + StringUtils.countMatches(retval.trim(), " "));
                        double pt = 0.0;
                        double so1 = (double) savesotu[socau];
                        double so2 = (double) sotu;
                        pt = so1 / so2;
                        phantramsotu[socau] = pt * sogiay;
                        socau++;
                    }
                }

                // *******************************
                char[] array = cau.toCharArray();
                // save cau 1
                VideoSub cau1 = new VideoSub();
                cau1.setTextsb((savetext + " " + savecau[0]).replace("\n", " ").replace("'", " ").trim());
                cau1.setStart(start + "");
                String end = (savedur + phantramsotu[0]) + "";
                cau1.setEnd(end + "");
                if (savecau[0] != ".")
                    savelistsub.add(cau1);
                // add vao
                savetext = "";
                // cap nhat start
                start += Double.parseDouble(cau1.getEnd());

                savedur = 0;
                // save cau giua
                for (int i1 = 1; i1 < socau - 1; i1++) {
                    // add vao
                    VideoSub Cau2 = new VideoSub();
                    Cau2.setTextsb(savecau[i1].replace("\n", " ").replace("'", " ").trim());
                    Cau2.setStart(start + "");
                    Cau2.setEnd(phantramsotu[i1] + "");
                    if (savecau[i1] != ".")
                        savelistsub.add(Cau2);

                    start += phantramsotu[i1];
                }

                // save cau cuoi
                if (array[cau.length() - 5] == '.' || array[cau.length() - 5] == '?'
                        || array[cau.length() - 5] == ';') {
                    flagchamcuoi = true;

                }

                System.out.println(cau);
                if (array[cau.length() - 5] == '.' || array[cau.length() - 5] == ';'
                        || array[cau.length() - 5] == '?') {
                    if (socau - 1 != 0) {
                        VideoSub Cau3 = new VideoSub();
                        Cau3.setTextsb(savecau[socau - 1].replace("\n", " ").replace("'", "-").trim());
                        Cau3.setStart(start + "");
                        Cau3.setEnd(phantramsotu[socau - 1] + "");
                        if (savecau[socau - 1] != ".")
                            savelistsub.add(Cau3);

                        start += phantramsotu[socau - 1];
                    }
                } else {
                    dutext = savecau[socau - 1];
                    sodu = phantramsotu[socau - 1];
                }
            } else {
                savetext += " " + cau;
                savedur += dur;
            }
        }
        // ================Xuat File Json===============
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < savelistsub.size(); i++) {
            JSONObject obj = new JSONObject();
            if (savelistsub.get(i).getTextsb() != ".") {
                String startadd = savelistsub.get(i).getStart();
                String duradd = savelistsub.get(i).getEnd();
                String textadd = savelistsub.get(i).getTextsb();
                obj.put("start", startadd);
                obj.put("dur", duradd);
                obj.put("text", textadd);
                jsonArray.add(obj);
            }

        }
        String out_String = jsonArray.toJSONString();
        out_String = out_String.toString();

        // ================Xuat File Json===============

        return out_String;
    }
    // end

    public String replacetext(String text) {
        text = text.replaceAll("&quot;", "\"");
        text = text.replaceAll("&amp;", "&");
        text = text.replaceAll("&#39;", "'");
        text = text.replaceAll("&lt;", "<");
        text = text.replaceAll("&gt;", ">");
        return text;
    }

    public String replace_escapse(String text) {
        text = text.replaceAll("'", "&#39;");
        text = text.replaceAll("<", "&lt;");
        text = text.replaceAll(">", "&gt;");
        return text;
    }

    public String replace_unescapse(String text) {

        text = text.replaceAll("&#39;", "'");
        text = text.replaceAll("&lt;", "<");
        text = text.replaceAll("&gt;", ">");
        return text;
    }

    public String replace_all(String token) {
        StringBuilder s = new StringBuilder(token.length());
        CharacterIterator it = new StringCharacterIterator(token);
        for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
            switch (ch) {
            case '?':
                s.append("?####");
                break;
            case '.':
                s.append(".####");
                break;
            case ';':
                s.append(";####");
                break;
            default:
                s.append(ch);
                break;
            }
        }

        token = s.toString();
        return token;
    }

}