com.LSH.client.LSH.java Source code

Java tutorial

Introduction

Here is the source code for com.LSH.client.LSH.java

Source

package com.LSH.client;

import com.LSH.client.DataType.PutLinkData;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.rpc.AsyncCallback;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;

/**
 * Created by @author AlNat on 26.11.2016.
 * Licensed by Apache License, Version 2.0
 *
 * ??,    ? UI
 */
@SuppressWarnings("Convert2Lambda")
public class LSH implements EntryPoint {

    private static final String errorCode = "Error!"; //  
    private static final int COOKIE_TIMEOUT = 1000 * 60 * 60 * 24; // ?   - 1000 ?, 60 ?, 60 , 24 ? - ?
    private static final String cookieName = "LSHLogin"; // ?  ? 
    private String login; //   ?

    /* ?  ? ? ? */
    private final TextBox simpleOriginalLink = new TextBox(); // ? ??
    private final Button simpleShortButton = new Button("Get Short Link"); //    ??
    private final Button simpleCopyButton = new Button("Copy to clipboard"); //     
    private final HTML simpleShortText = new HTML("Your shortlink  "); // ?   ??
    private final HTML simpleShortLink = new HTML(""); //  ??

    /* ?  ? ? ?? */
    private final Button complexShortButton = new Button("Get Short Link"); //    ??
    private final Button complexCopyButton = new Button("Copy to clipboard"); //     
    private final HTML complexShortText = new HTML("Your shortlink  "); // ?   ??
    private final HTML complexShortLink = new HTML(""); //  ??

    private final HTML complexText = new HTML("Link:"); // ?   ?  ??
    private final TextBox complexOriginalLink = new TextBox(); // ? ??

    private final HTML complexTimeText = new HTML("Set link live duration:"); // ?   ?   ??
    private final ListBox complexTime = new ListBox(); //  ? ?   ??
    private final HTML complexCountText = new HTML("Set count of visits:<br>(0 for unlimited)"); // ?   ? - 
    private final IntegerBox complexCount = new IntegerBox(); //   - 

    private final HTML complexNameText = new HTML(
            "Customize link:<br>(i, l, o, 1, 0, _(1-st) - illegal)<br>Max length - 11 symbols"); // ?   ? ? ??
    private final TextBox complexName = new TextBox(); //   ? ??
    private final HTML complexPasswordText = new HTML("Set password:"); // ?   ? ? ??
    private final TextBox complexPassword = new PasswordTextBox(); //   ? ??

    /* ?  ?  */
    private final LoginDialog dialog = new LoginDialog(); //  ?  ?
    private final HTML loginLabel = new HTML(); //  ?  
    private final Button loginButton = new Button("Login"); //  
    private final Button logoutButton = new Button("Log out"); //  

    /**
     * ?   UI
     */
    public void onModuleLoad() {

        /*  ? ? */

        String linkWidth = String.valueOf(Window.getClientWidth() / 4);

        // HP = HorizontalPanel; VP = VerticalPanel
        final HorizontalPanel simpleDataHP = new HorizontalPanel(); //  ?  ??
        final HorizontalPanel simpleAnswerHP = new HorizontalPanel(); //  ?  
        final VerticalPanel simpleVP = new VerticalPanel(); //  ? ? ,  

        simpleShortButton.addClickHandler(new SimpleClickHandler()); // ??    
        simpleOriginalLink.addKeyDownHandler(new EnterKeyListener(simpleShortButton)); // ??    ? Enter
        simpleCopyButton.addClickHandler(new CopyClickHandler("simpleAnswer")); // ??       ?

        simpleOriginalLink.setWidth(linkWidth); // ?  ?
        simpleDataHP.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); // 
        simpleDataHP.setSpacing(5); // ?

        //  
        simpleDataHP.add(simpleOriginalLink);
        simpleDataHP.add(simpleShortButton);

        // ?, ?
        simpleAnswerHP.setSpacing(5);
        simpleAnswerHP.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

        //  
        simpleAnswerHP.add(simpleShortText);
        simpleAnswerHP.add(simpleShortLink);
        simpleAnswerHP.add(simpleCopyButton);

        //  
        simpleVP.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        simpleVP.setSpacing(10);
        simpleVP.add(simpleDataHP);
        simpleVP.add(simpleAnswerHP);

        // ?   ?
        simpleShortText.setVisible(false);
        simpleCopyButton.setVisible(false);

        /*  ? ? */
        //  ? ?
        final HorizontalPanel complexLinkHP = new HorizontalPanel(); //  ?  ??
        final HorizontalPanel complexDataHP = new HorizontalPanel(); // 
        final HorizontalPanel complexOptionalData = new HorizontalPanel(); //  
        final HorizontalPanel complexAnswerHP = new HorizontalPanel(); // 

        final VerticalPanel complexVP = new VerticalPanel(); //  ,  
        final VerticalPanel complexOptionalVP = new VerticalPanel(); //  ,  

        EnterKeyListener complexKey = new EnterKeyListener(complexShortButton); //  ?   Enter
        complexCopyButton.addClickHandler(new CopyClickHandler("complexAnswer"));

        // ?     ??
        complexTime.addItem("1 hour");
        complexTime.addItem("12 hours");
        complexTime.addItem("1 day");
        complexTime.addItem("1 week");
        complexTime.addItem("1 month");
        complexTime.addItem("Unlimited");
        complexTime.setSelectedIndex(3);

        // ??  ?
        complexOriginalLink.setWidth(linkWidth);
        complexCount.setWidth("40px");
        complexCount.setValue(10);

        complexShortButton.addClickHandler(new ComplexClickHandler()); //   ?  
        // ?  ?  Enter  ? ?
        complexOriginalLink.addKeyDownHandler(complexKey);
        complexName.addKeyDownHandler(complexKey);
        complexCount.addKeyDownHandler(complexKey);
        complexTime.addKeyDownHandler(complexKey);
        complexPassword.addKeyDownHandler(complexKey);

        // ??     ?
        complexLinkHP.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        complexLinkHP.setSpacing(5);
        complexLinkHP.add(complexText);
        complexLinkHP.add(complexOriginalLink);

        complexDataHP.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        complexDataHP.setSpacing(5);
        complexDataHP.add(complexTimeText);
        complexDataHP.add(complexTime);
        complexDataHP.add(complexCountText);
        complexDataHP.add(complexCount);

        complexCount.setAlignment(ValueBoxBase.TextAlignment.CENTER); // ? ? 
        complexCount.setMaxLength(5); // ?? - ?

        complexOptionalData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        complexOptionalData.setSpacing(5);
        complexOptionalData.add(complexNameText);
        complexOptionalData.add(complexName);
        complexOptionalData.add(complexPasswordText);
        complexOptionalData.add(complexPassword);

        complexAnswerHP.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        complexAnswerHP.setSpacing(5);
        complexAnswerHP.add(complexShortText);
        complexAnswerHP.add(complexShortLink);
        complexAnswerHP.add(complexCopyButton);

        complexVP.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        complexVP.setSpacing(5);
        complexVP.add(complexLinkHP);
        complexVP.add(complexDataHP);

        complexOptionalVP.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        complexOptionalVP.setSpacing(5);
        complexOptionalVP.add(complexOptionalData);
        complexOptionalVP.add(complexShortButton);
        complexOptionalVP.add(complexAnswerHP);

        //   
        complexShortText.setVisible(false);
        complexCopyButton.setVisible(false);

        /* ?? ? ?  */

        loginButton.addClickHandler(new ClickHandler() { //        
            @Override
            public void onClick(ClickEvent event) {
                dialog.Login();
            }
        });

        logoutButton.addClickHandler(new ClickHandler() { //  
            @Override
            public void onClick(ClickEvent event) { //  
                Cookies.removeCookie(cookieName); // ?   

                //   ?  ? ???
                loginButton.setVisible(true);
                loginLabel.setHTML("");
                loginLabel.setVisible(false);
                logoutButton.setVisible(false);
            }
        });

        // ??     
        final HorizontalPanel loginHP = new HorizontalPanel();
        loginHP.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        loginHP.setSpacing(5);
        loginHP.add(loginLabel);
        loginHP.add(logoutButton);
        loginHP.add(loginButton);

        logoutButton.setVisible(false);
        dialog.hide(); //     ?

        // ?    ?
        RootPanel.get("Login").add(loginHP);
        RootPanel.get("SimpleShort").add(simpleVP);
        RootPanel.get("ComplexShort").add(complexVP);
        RootPanel.get("ComplexShortOptional").add(complexOptionalVP);
    }

    /**
     * ??,        ?  ??
     */
    private class SimpleClickHandler implements ClickHandler {
        public void onClick(ClickEvent event) {

            PutLinkData putLinkData = new PutLinkData(simpleOriginalLink.getText()); //  ?  ?
            putLinkData.setBrowser(Window.Navigator.getUserAgent()); // user-agent ?
            putLinkData.setIp(getIP()); // IP ? ?

            if (login != null) {
                putLinkData.setUserLogin(login); // ?      
            }

            LSHServiceInterface.App.getInstance().getShort(putLinkData, new AsyncCallback<String>() { // ? ?   
                @Override
                public void onFailure(Throwable caught) { //   ? ? ?
                    simpleShortLink.setText("Cannot connect to server!");
                }

                @Override
                public void onSuccess(String result) { //  
                    if (result.startsWith(errorCode)) { // ?      
                        simpleShortLink.setHTML(result);
                    } else {
                        //      ??
                        simpleShortText.setVisible(true);
                        simpleCopyButton.setVisible(true);
                        simpleShortLink.setText(result); //  ? ??
                        simpleShortLink.getElement().setAttribute("id", "simpleAnswer"); //      - ?   
                    }
                }
            });
        }
    }

    /**
     * ??,        ?  ??
     */
    private class ComplexClickHandler implements ClickHandler {
        public void onClick(ClickEvent event) {

            //  ''   ?
            PutLinkData putLinkData;
            if (complexName.getText().isEmpty()) { //  ?  ??  , ?  
                putLinkData = new PutLinkData(complexOriginalLink.getText(), complexTime.getSelectedItemText(),
                        complexCount.getValue());
            } else {
                putLinkData = new PutLinkData(complexOriginalLink.getText(), complexTime.getSelectedItemText(),
                        complexCount.getValue(), complexName.getText());
            }
            putLinkData.setBrowser(Window.Navigator.getUserAgent()); // user-agent ?
            putLinkData.setIp(getIP()); // IP ? ?

            String t = complexPassword.getText();
            if (!t.isEmpty()) {
                putLinkData.setPassword(getMD5(t));
            }

            putLinkData.setUserLogin(login);

            //  ? 
            LSHServiceInterface.App.getInstance().getShort(putLinkData, new AsyncCallback<String>() {
                @Override
                public void onFailure(Throwable caught) {
                    complexShortLink.setText("Cannot connect to server!");
                }

                @Override
                public void onSuccess(String result) {
                    if (result.startsWith(errorCode)) { // ?    
                        complexShortLink.setHTML(result);
                    } else { //   
                        complexShortText.setVisible(true);
                        complexCopyButton.setVisible(true);
                        complexShortLink.setText(result);
                        complexShortLink.getElement().setAttribute("id", "complexAnswer");
                    }
                }
            });
        }
    }

    /**
     * ??,      ?   
     */
    private class CopyClickHandler implements ClickHandler {
        final String id; // ??  ?? ??   ?

        CopyClickHandler(String id) { //  id
            this.id = id;
        }

        @Override
        public void onClick(ClickEvent event) { //  
            copyToClipboard(id); //   ?
        }
    }

    /**
     * -,  (  ?)   Enter
     */
    private static class EnterKeyListener implements KeyDownHandler {
        final Button button; // 

        EnterKeyListener(Button button) {
            this.button = button;
        }

        @Override
        public void onKeyDown(KeyDownEvent event) {

            if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                button.click(); // ?      Enter
            }
        }

    }

    /**
     *   ?    ?
     */
    private class LoginDialog extends DialogBox {

        boolean textFlag = false; //  1  ? ?
        boolean passFlag = false;

        /**
         * ?
         */
        LoginDialog() {

            setHTML("Please, input login and password<br>If you aren't registered, new user will be created");
            setAnimationEnabled(true);
            setGlassEnabled(true);

            // 
            final HorizontalPanel panelData = new HorizontalPanel(); //  
            final HorizontalPanel panelButtons = new HorizontalPanel(); //  
            final HTML label = new HTML(); // ? ? 

            // 
            final Button buttonLogin = new Button("Login"); //  ? 
            final Button buttonCancel = new Button("Cancel"); //  ? 

            final TextBox loginTextBox = new TextBox(); // ?  
            loginTextBox.setText("Login");
            final PasswordTextBox passwordTextBox = new PasswordTextBox(); // ?  ?
            passwordTextBox.setText("Password");

            loginTextBox.addKeyDownHandler(new KeyDownHandler() { // ? ? 
                @Override
                public void onKeyDown(KeyDownEvent event) {
                    if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                        buttonLogin.click(); // ?      Enter
                    }
                }
            });

            loginTextBox.addClickHandler(new ClickHandler() { // ?      
                @Override
                public void onClick(ClickEvent event) {
                    if (!textFlag) {
                        loginTextBox.setText("");
                        textFlag = true;
                    }
                }
            });

            passwordTextBox.addKeyDownHandler(new KeyDownHandler() { // ? ? 
                @Override
                public void onKeyDown(KeyDownEvent event) {
                    if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                        buttonLogin.click(); // ?      Enter
                    }
                }
            });

            passwordTextBox.addClickHandler(new ClickHandler() { // ?      
                @Override
                public void onClick(ClickEvent event) {
                    if (!passFlag) {
                        passwordTextBox.setText("");
                        passFlag = true;
                    }
                }
            });

            //  ? ?   
            panelData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
            panelData.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
            panelData.add(loginTextBox);
            panelData.add(passwordTextBox);

            //    
            panelButtons.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
            panelButtons.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
            panelButtons.add(buttonLogin);
            panelButtons.add(buttonCancel);

            //        ?
            buttonLogin.addClickHandler(new ClickHandler() { // ?  ?  
                public void onClick(ClickEvent event) {

                    final String userLogin = loginTextBox.getText(); //  
                    final String userPassword = getMD5(passwordTextBox.getText()); //  ? ? ?

                    //   ?
                    LSHServiceInterface.App.getInstance().Login(userLogin, userPassword,
                            new AsyncCallback<String>() {
                                @Override
                                public void onFailure(Throwable caught) { //   
                                    label.setHTML("<h4>Server error!</h4><br>");
                                }

                                @Override
                                public void onSuccess(String result) { // ? ? 
                                    if (result.equals("OK")) { // ?   ?   ,  ?   ,  

                                        GoodLogin(userLogin);

                                    } else { //  ?  
                                        String t = result.substring(errorCode.length());
                                        label.setHTML(t);
                                    }
                                }
                            });

                }
            });

            //      ? 
            buttonCancel.addClickHandler(new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    LoginDialog.this.hide();
                }
            });

            //   ?  ?   ?  ?
            VerticalPanel panel = new VerticalPanel();
            panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
            panel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
            panel.add(panelData);
            panel.add(panelButtons);
            panel.add(label);

            setWidget(panel); // ?   ? 
        }

        /**
         * ? ?
         * @param userLogin  ?
         */
        void GoodLogin(String userLogin) {
            //  ?
            login = userLogin;
            loginButton.setVisible(false);
            loginLabel.setVisible(true);
            logoutButton.setVisible(true);
            loginLabel.setHTML(
                    "You're login as <br><a href=\"Administration.html\" color=lightseagreen;>" + login + "</a>");

            PutLoginCookie(userLogin); //    ,   

            LoginDialog.this.hide(); //  
        }

        /**
         * ?, ??,   
         * @return true ? , false ? 
         */
        boolean isLogin() {
            return getCookieLogin() != null;
        }

        /**
         * ?, ?  ? 
         * @return  ? 
         */
        String getCookieLogin() {
            return Cookies.getCookie(cookieName);
        }

        /**
         * ?, ?   ? 
         * @param login ? ?
         */
        void PutLoginCookie(String login) {
            Date expires = new Date((new Date()).getTime() + COOKIE_TIMEOUT);
            Cookies.setCookie(cookieName, login, expires);
        }

        /**
         * ?  
         */
        void Login() {

            if (isLogin()) { // ?   
                GoodLogin(getCookieLogin()); //     ?
            } else { //    
                LoginDialog.this.show();
                LoginDialog.this.center();
            }

        }

    }

    /**
     * ?, ? MD5 ?  ? + ?
     * @param in ? ?
     * @return ? ?  null ? 
     */
    static String getMD5(String in) {

        if (in.isEmpty()) {
            return null;
        }

        String salt = "SaltSalt";
        in = salt.toUpperCase() + in + salt.toLowerCase(); // "" 
        //  https://ru.wikipedia.org/wiki/_(?)

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(in.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashText = number.toString(16);
            while (hashText.length() < 32) {
                hashText = "0" + hashText;
            }
            return hashText;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * ? ?    ?  id
     * @param inName   id
     */
    public static native void copyToClipboard(String inName) /*-{
                                                             var selection = $wnd.getSelection();
                                                             var text =  $doc.getElementById(inName);
                                                             var range = $doc.createRange();
                                                             range.selectNodeContents(text);
                                                             selection.removeAllRanges();
                                                             selection.addRange(range);
                                                             $doc.execCommand('copy');
                                                             selection.removeAllRanges();
                                                             }-*/;

    /**
     * ? ? ip ?
     * @return ip
     */
    private native String getIP() /*-{
                                  return $wnd.userip;
                                  }-*/;

}