com.Administration.client.Administration.java Source code

Java tutorial

Introduction

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

Source

package com.Administration.client;

import com.Administration.client.DataType.LinkData;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.i18n.client.DateTimeFormat;

import com.google.gwt.cell.client.*;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.SimplePager;

import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;

import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.ProvidesKey;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;

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

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

    private String login; //  
    private String password; //  ?
    private PasswordDialog dialog; //   ?    ?

    private HTML label; //  ? 
    private HTML loginLabel; //  ? 
    private Button logoutButton; //  

    private CellTable<LinkData> cellTable; // 
    private LinkedList<LinkData> list; // 
    private ListDataProvider<LinkData> dataProvider; //  
    private ListHandler<LinkData> sortHandler; // 
    private SimplePager pager; // Pager -  ? 

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

        label = new HTML(); //   ?  ?  
        label.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

        loginLabel = new HTML(); //   ?  ?    
        loginLabel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

        dialog = new PasswordDialog(); //   
        list = new LinkedList<>(); //  ? ? 

        ProvidesKey<LinkData> KEY_PROVIDER = new ProvidesKey<LinkData>() { //    -   ??   
            @Override
            public Object getKey(LinkData item) {
                return item == null ? null : item.getId();
            }
        };
        cellTable = new CellTable<>(KEY_PROVIDER); //  ? 

        dataProvider = new ListDataProvider<>(); //    
        dataProvider.addDataDisplay(cellTable); // ?,   ????   ? 

        sortHandler = new ListHandler<>(list); //  ?
        cellTable.addColumnSortHandler(sortHandler); //  ?   

        SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
        pager = new SimplePager(SimplePager.TextLocation.CENTER, pagerResources, false, 0, true); //  pager -  ?
        pager.setDisplay(cellTable); // ?,  pager ?  ? 

        initTable(); //   ? 
        cellTable.setWidth("100%");
        cellTable.setHeight("80%");
        cellTable.setAutoHeaderRefreshDisabled(true);
        cellTable.setAutoFooterRefreshDisabled(true);

        //  ?  
        VerticalPanel VP = new VerticalPanel();
        VP.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        VP.add(cellTable);
        VP.add(pager);

        logoutButton = new Button("Logout");

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

        logoutButton.addClickHandler(new ClickHandler() { //  
            @Override
            public void onClick(ClickEvent event) { //  

                Cookies.removeCookie(cookieName); // ?   

                //  ?  ???
                loginLabel.setHTML("");
                loginLabel.setVisible(false);
                label.setHTML("");
                cellTable.setVisible(false);
                pager.setVisible(false);
                logoutButton.setVisible(false);

                dataProvider.getList().clear(); // ? 

                dialog.show(); //   
                dialog.center();

            }
        });
        logoutButton.setVisible(false);

        //  
        RootPanel.get("Login").add(loginHP);
        RootPanel.get("Data").add(VP);
        RootPanel.get("Data").add(label);

        //    ? 
        cellTable.setVisible(false);
        pager.setVisible(false);

        dialog.Login();
    }

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

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

        /**
         * ?
         */
        PasswordDialog() {

            setHTML("Please, input login and password");
            setAnimationEnabled(true);
            setGlassEnabled(true);

            // 
            final HorizontalPanel panel = new HorizontalPanel();
            final Button button = new Button("Let me in");

            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) {
                        button.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) {
                        button.click(); // ?      Enter
                    }
                }
            });

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

            //      
            panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
            panel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
            panel.add(loginTextBox);
            panel.add(passwordTextBox);
            panel.add(button);

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

                    login = loginTextBox.getText();
                    password = getMD5(passwordTextBox.getText()); //  ? ? ?

                    //   ?
                    AdministrationServiceInterface.App.getInstance().isUser(login, password,
                            new AsyncCallback<Boolean>() {
                                @Override
                                public void onFailure(Throwable caught) { //   
                                    label.setHTML("<h3>Server error!</h3><br>");
                                }

                                @Override
                                public void onSuccess(Boolean result) { // ? ? 
                                    if (result) { // ?   ?   ,  ?     
                                        GoodLogin(login);
                                    } else { //  ?  
                                        label.setHTML("<h3>Incorrect username or password!</h3><br>");
                                    }
                                }
                            });

                }
            });

            setWidget(panel); // ? 

        }

        /**
         * ? ?
         * @param userLogin  ?
         */
        void GoodLogin(String userLogin) {
            PutLoginCookie(userLogin); //    ,   

            //  ?  ? 
            loginLabel.setHTML("You're login as <br><h6>" + userLogin + "</h6>");
            label.setHTML("");
            loginLabel.setVisible(true);
            logoutButton.setVisible(true);

            PasswordDialog.this.hide();
            login = userLogin;

            //      ?
            GetData();
        }

        /**
         * ?, ??,   
         * @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 { //    ? 
                PasswordDialog.this.show();
                PasswordDialog.this.center();
            }

        }

    }

    /**
     * ? ?  ? ?
     */
    private void GetData() {

        //   ?    ??
        AdministrationServiceInterface.App.getInstance().getData(login, new AsyncCallback<LinkData[]>() {
            @Override
            public void onFailure(Throwable caught) { // ?  ? ???
                label.setHTML("<h3>Server error!</h3><br>");
            }

            @Override
            public void onSuccess(LinkData[] result) { //  
                AddData(result);
            }
        });

    }

    /**
     * ? ?   
     * @param linksData 
     */
    private void AddData(LinkData[] linksData) {

        label.setHTML(""); // ? 

        Collections.addAll(list, linksData); //  
        dataProvider.setList(list); // ?   

        sortHandler.setList(dataProvider.getList()); //  ?

        cellTable.setVisible(true); //    ? 
        pager.setVisible(true);

    }

    /**
     * ? ? 
     */
    private void initTable() {

        //  ?  
        Column<LinkData, String> codeColumn = new Column<LinkData, String>(new TextCell()) { // C  ? - ? ?
            @Override
            public String getValue(LinkData object) { // ? ? ?  ?
                return object.getCode();
            }
        };

        codeColumn.setSortable(true); //  ?
        sortHandler.setComparator(codeColumn, new Comparator<LinkData>() { // ? 
            //  ,   ? 
            @Override
            public int compare(LinkData o1, LinkData o2) { // ? ??
                if (o1 == o2) {
                    return 0;
                }

                if (o1 != null) {
                    return (o2 != null) ? o1.getCode().compareTo(o2.getCode()) : 1;
                }

                return -1;
            }
        });

        cellTable.addColumn(codeColumn, "Short Link"); //   ?   

        // ? ??
        Column<LinkData, String> originalLinkColumn = new Column<LinkData, String>(new EditTextCell()) {
            @Override
            public String getValue(LinkData object) {
                return object.getLink();
            }
        };

        originalLinkColumn.setSortable(true);
        sortHandler.setComparator(originalLinkColumn, new Comparator<LinkData>() {
            @Override
            public int compare(LinkData o1, LinkData o2) {
                if (o1 == o2) {
                    return 0;
                }

                if (o1 != null) {
                    return (o2 != null) ? o1.getLink().compareTo(o2.getLink()) : 1;
                }

                return -1;
            }
        });

        cellTable.addColumn(originalLinkColumn, "Original Link");

        originalLinkColumn.setFieldUpdater(new FieldUpdater<LinkData, String>() { //  ? ?
            @Override
            public void update(int index, final LinkData object, final String value) { // ??   ?

                // ?  ?
                AdministrationServiceInterface.App.getInstance().setOriginalLink(object.getId(), value,
                        new AsyncCallback<Boolean>() {
                            @Override
                            public void onFailure(Throwable caught) { // ?  ? ???
                                label.setHTML("<h4>Connection error!<br>Can't update data!<h4>"); //   ?
                            }

                            @Override
                            public void onSuccess(Boolean result) { // ? ?  
                                if (!result) { // ? ?  ? ?  
                                    label.setHTML("<h4>Server error!<h4>"); //  
                                } else { //  ?   ? 
                                    object.setLink(value);
                                    dataProvider.refresh();
                                }
                            }
                        });

            }
        });

        DateTimeFormat dateFormat = DateTimeFormat.getFormat("dd MMM yyyy"); //   

        // ? ??
        Column<LinkData, Date> createDateColumn = new Column<LinkData, Date>(new DateCell(dateFormat)) {
            @Override
            public Date getValue(LinkData object) {
                return object.getCreateDate();
            }
        };

        createDateColumn.setSortable(true);
        sortHandler.setComparator(createDateColumn, new Comparator<LinkData>() {
            @Override
            public int compare(LinkData o1, LinkData o2) {
                if (o1 == o2) {
                    return 0;
                }

                if (o1 != null) {
                    return (o2 != null) ? o1.getCreateDate().compareTo(o2.getCreateDate()) : 1;
                }

                return -1;
            }
        });

        cellTable.addColumn(createDateColumn, "Create date");

        DatePickerCell cell = new DatePickerCell(dateFormat); // ?? ? 

        //  ?
        Column<LinkData, Date> expiredDateColumn = new Column<LinkData, Date>(cell) {
            @Override
            public Date getValue(LinkData object) {
                return object.getExpiredDate();
            }
        };

        expiredDateColumn.setSortable(true);
        sortHandler.setComparator(expiredDateColumn, new Comparator<LinkData>() {
            @Override
            public int compare(LinkData o1, LinkData o2) {
                if (o1 == o2) {
                    return 0;
                }

                if (o1 != null) {
                    return (o2 != null) ? o1.getExpiredDate().compareTo(o2.getExpiredDate()) : 1;
                }

                return -1;
            }
        });

        cellTable.addColumn(expiredDateColumn, "Expired Date");

        expiredDateColumn.setFieldUpdater(new FieldUpdater<LinkData, Date>() {
            @Override
            public void update(int index, final LinkData object, final Date value) {
                AdministrationServiceInterface.App.getInstance().setExpiredDate(object.getId(), value,
                        new AsyncCallback<Boolean>() {
                            @Override
                            public void onFailure(Throwable caught) {
                                label.setHTML("<h4>Connection error!<br>Can't update data!<h4>");
                            }

                            @Override
                            public void onSuccess(Boolean result) {
                                if (!result) {
                                    label.setHTML("<h4>Server error!<h4>");
                                } else {
                                    object.setExpiredDate(value);
                                    dataProvider.refresh();
                                }
                            }
                        });
            }
        });

        // - 
        Column<LinkData, Number> currentCountColumn = new Column<LinkData, Number>(new NumberCell()) {
            @Override
            public Number getValue(LinkData object) {
                return object.getCurrentCount();
            }
        };

        currentCountColumn.setSortable(true);
        sortHandler.setComparator(currentCountColumn, new Comparator<LinkData>() {
            @Override
            public int compare(LinkData o1, LinkData o2) {
                if (o1 == o2) {
                    return 0;
                }

                if (o1 != null) {
                    return (o2 != null) ? o1.getCurrentCount().compareTo(o2.getCurrentCount()) : 1;
                }

                return -1;
            }
        });

        currentCountColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);

        cellTable.addColumn(currentCountColumn, "Current visits");

        //  ?,  GWT   EditNumberCell. .
        //  ?  ? ?. ? ??  ?.

        // ? - 
        Column<LinkData, String> maxCountColumn = new Column<LinkData, String>(new EditTextCell()) {
            @Override
            public String getValue(LinkData object) {

                Integer t = object.getMaxCount();

                if (t == 0) {
                    return "Infinity";
                } else {
                    return t.toString(); //   GWT!!!
                }

            }
        };

        maxCountColumn.setSortable(true);
        sortHandler.setComparator(maxCountColumn, new Comparator<LinkData>() {
            @Override
            public int compare(LinkData o1, LinkData o2) {
                if (o1 == o2) {
                    return 0;
                }

                if (o1 != null) {
                    return (o2 != null) ? o1.getMaxCount().compareTo(o2.getMaxCount()) : 1;
                }

                return -1;
            }
        });

        maxCountColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);

        cellTable.addColumn(maxCountColumn, "Max Visits");

        maxCountColumn.setFieldUpdater(new FieldUpdater<LinkData, String>() {
            @Override
            public void update(int index, final LinkData object, final String value) {

                final Integer t;
                if (value.equals("Infinity")) {
                    t = 0;
                } else {
                    t = Integer.parseInt(value);
                }

                if (t < 0) {
                    label.setHTML("Wrong maximum count!");
                }

                AdministrationServiceInterface.App.getInstance().setMaxCount(object.getId(), t,
                        new AsyncCallback<Boolean>() {
                            @Override
                            public void onFailure(Throwable caught) {
                                label.setHTML("<h4>Connection error!<br>Can't update data!<h4>");
                            }

                            @Override
                            public void onSuccess(Boolean result) {
                                if (!result) {
                                    label.setHTML("Server error!");
                                } else {
                                    object.setMaxCount(t);
                                    dataProvider.refresh();
                                }
                            }
                        });

            }
        });

        // 
        Column<LinkData, String> passwordColumn = new Column<LinkData, String>(new EditTextCell()) {
            @Override
            public String getValue(LinkData object) {
                if (object.getPassword().equals("")) {
                    return "";
                } else { //    ? ,   ?   
                    return "*********";
                }
            }
        };

        cellTable.addColumn(passwordColumn, "Password");

        passwordColumn.setFieldUpdater(new FieldUpdater<LinkData, String>() {
            @Override
            public void update(int index, final LinkData object, final String value) {

                final String pass;

                if (value.isEmpty() || value.contains(" ")) { // ? ?   ? ?? ?  ? 
                    pass = null;
                } else {
                    pass = value;
                }

                AdministrationServiceInterface.App.getInstance().setPassword(object.getId(), getMD5(pass),
                        new AsyncCallback<Boolean>() {
                            @Override
                            public void onFailure(Throwable caught) {
                                label.setHTML("<h4>Connection error!<br>Can't update data!<h4>");
                            }

                            @Override
                            public void onSuccess(Boolean result) {
                                if (!result) {
                                    label.setHTML("<h4>Server error!<h4>");
                                } else {
                                    object.setPassword(getMD5(pass));
                                    dataProvider.refresh();
                                }
                            }
                        });

            }
        });

        //  ??
        Column<LinkData, String> deleteColumn = new Column<LinkData, String>(new ButtonCell()) {
            @Override
            public String getValue(LinkData object) {
                return "Delete link"; // + object.getCode(); // + "' link";
            }
        };

        cellTable.addColumn(deleteColumn, "");

        deleteColumn.setFieldUpdater(new FieldUpdater<LinkData, String>() {
            @Override
            public void update(int index, final LinkData object, String value) {

                if (Window.confirm("Shortlink " + object.getCode() + " will be delete!")) {
                    AdministrationServiceInterface.App.getInstance().deleteLink(object.getId(),
                            new AsyncCallback<Boolean>() {
                                @Override
                                public void onFailure(Throwable caught) {
                                    label.setHTML("<h4>Connection error!<br>Can't delete data!<h4>");
                                }

                                @Override
                                public void onSuccess(Boolean result) {
                                    if (!result) {
                                        label.setHTML("<h4>Server error!<h4>");
                                    } else { // ?    ??
                                        dataProvider.getList().remove(object);
                                        dataProvider.refresh();
                                    }
                                }
                            });
                }
            }
        });

    }

    /**
     * ?, ? MD5 ?  ? + ?
     * @param in ? ?
     * @return ? ?  null ? 
     */
    private 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[] messageDigestBytes = md.digest(in.getBytes());
            BigInteger number = new BigInteger(1, messageDigestBytes);
            String hashText = number.toString(16);

            while (hashText.length() < 32) {
                hashText = "0" + hashText;
            }
            return hashText;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

    }

}