Powered by Blogger.

Recent Posts

recentposts

Disqus for hsalearn

Recent Videos

AngularJS

AngularJS version: 1.3.0
https://angularjs.org/
https://builtwith.angularjs.org/
http://plnkr.co/

Two Requirements
  • Add a <script> tag pointing to angular.js.
    • <script scr="angular.js"></script>
  • Add an ng-app attribute in your HTML.
    • ng-app is an Angular directive.
    • The ng is short for Angular.
    • <div ng-app> This area controlled by Angular! </div>



JavaScript Patterns
  • Functions as abstractions
  • Functions to build modules
  • Functions to avoid global variables

Controller Basics

  • Controller directive in HTML (ng-controller)
  • Controller will be a function that Angular invokes
  • Controller takes a $scope parameter
  • Attach model to $scope.


Controller Capabilities

  • Multiple controllers
  • Complex object
  • Nested controllers


*Tip: When load image use ng-scr="Image src" to don't get 404 error.


$http Service

  • Encapsulates HTTP communication
    • GET, POST, PUT, DELETE
  • Can "ask" for $http inside a controller
    • Just add as another parameter to controller function
  • Always returns a promise
    • A promise to deliver a value in the future


GitHub API

  • Available from JavaScript in browser.
  • Returns JSON (easy to convert into objects)
  • No authentication or client key required.


Modules

  • Controllers usually live in modules
    • Avoids the global namespace
  • Working with modules
    • Create a module with a name
    • Register your controllers in the module
    • Tell Angular to use your module with ng-app











Java LinkedHashMap.

How to limit the maximum size of a Map by removing oldest entries when limit reached?

        int MAX_SIZE = 5;
        LinkedHashMap map = new LinkedHashMap<String, String[]>() {
            @Override
            protected boolean removeEldestEntry(final Map.Entry eldest) {
                return size() > MAX_SIZE;
            }
        }; 

Example:
package zdemo;

import java.util.LinkedHashMap;
import java.util.Map;

public class ZDemo {
    public static void main(String[] args) {
        int MAX_SIZE = 5;
        LinkedHashMap map = new LinkedHashMap<String, String[]>() {
            @Override
            protected boolean removeEldestEntry(final Map.Entry eldest) {
                return size() > MAX_SIZE;
            }
        };

        map.put("1", "x");
        System.out.println(map);
        map.put("2", "x");
        System.out.println(map);
        map.put("3", "x");
        System.out.println(map);
        map.put("4", "x");
        System.out.println(map);
        map.put("5", "x");
        System.out.println(map);
        map.put("6", "x");
        System.out.println(map);
        map.put("7", "x");
        System.out.println(map);
        map.put("8", "x");
        System.out.println(map);
        map.put("9", "x");
        System.out.println(map);
        map.put("10", "x");
        System.out.println(map);
    }
}

Output:
run:
{1=x}
{1=x, 2=x}
{1=x, 2=x, 3=x}
{1=x, 2=x, 3=x, 4=x}
{1=x, 2=x, 3=x, 4=x, 5=x}
{2=x, 3=x, 4=x, 5=x, 6=x}
{3=x, 4=x, 5=x, 6=x, 7=x}
{4=x, 5=x, 6=x, 7=x, 8=x}
{5=x, 6=x, 7=x, 8=x, 9=x}
{6=x, 7=x, 8=x, 9=x, 10=x}
BUILD SUCCESSFUL (total time: 0 seconds)





Java String Utility.

Trim space and null.
public static String trim(String str) {
        if (str != null && !str.isEmpty()) {
            String rs = str.trim();
            rs = rs.replaceAll("\\s+", " ");
            return rs;
        }
        return "";
    }

Check string is null or empty.
public static boolean isNulOrEmpty(String value) {
        return value == null || value.trim().isEmpty();
    }

Check string is positive number.
public static boolean isPositiveNumber(String value) {
        if (value != null) {
            value = value.replaceAll("\\s+", "");
            if (!value.isEmpty()) {
                if (value.matches("^[0-9]+$")) {
                    return isNumber(value) && (toBigDecimal(value).longValue() > 0L);
                }
            }
        }
        return true;
    }
    //---------------------
    Check Time (HH:MM): isValidWithPattern(tmpBis, "([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]");
    Check Time (HH:MM:SS): isValidWithPattern(tmpBis, "([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]");

Check validate email address with regular expression.
public static boolean isValidEmailAddress(String email) {
        if (email != null) {
            email = email.replaceAll("\\s+", "");
            if (!email.isEmpty()) {
                String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
                java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
                java.util.regex.Matcher m = p.matcher(email);
                return m.matches();
            }
        }
        return true;
    }

Check validate string with regular expression.
public static boolean isValidWithPattern(String value, String pattern) {
        if (value != null) {
            if (!value.isEmpty()) {
                java.util.regex.Pattern p = java.util.regex.Pattern.compile(pattern);
                java.util.regex.Matcher m = p.matcher(value);
                return m.matches();
            }
        }
        return true;
    } 



--------------------

--------------------

Java Operator System Utility.

Get name of operator system.
    public static String getOsName() {
        System.getProperty("os.name");
    }

Check operator system is Windows?
    public static boolean isWindows() {
        return getOsName().startsWith("Windows");
    }

Get text from clipboard.
    public static String getTextFromClipBoard() {
        String text = "";
        try {
            text = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
            return text;
        } catch (UnsupportedFlavorException | IOException ex) {
            Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex);
        }
        return text;
    }

Set text to clipboard.
    public static void setTextToClipBoard(String value) {
        StringSelection text = new StringSelection(value);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(text, text);
    }






JSCH - Java Secure Channel.

Introduction:

JSch is a pure Java implementation of SSH2. JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. To read more about JSch please follow the link http://www.jcraft.com/jsch/

Please note JSch is not an FTP client. JSch is an SSH client (with an included SFTP implementation).

The SSH protocol is a protocol to allow secure connections to a server, for shell access, file transfer or port forwarding. For this, the server must have an SSH server (usually on port 22, but that can vary). SFTP is a binary file transfer protocol which is usually tunneled over SSH, and not related to FTP (other than by name).

If you want to use JSch to download/upload files, you need to install and activate an SSH/SFTP server on your computer (respective the computer you want to access).

For FTP, you have to use other Java libraries (Apache Commons FTPClient seems to be famous, from the questions here).

By the way, the known hosts file for JSch is a file listing the public keys of the SSH hosts, not the file listing their IP addresses (which is the Windows config file you are trying to supply here).

How does it work?


JSCH - SFPT Download File Example:


package zdemo;

/**
 *
 * @author hsalearn.blogspot.com
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JSCH_SFTP_DOWNLOAD_EXAMPLE {

    public static void main(String[] args) {
        String SFTPHOST = "192.168.1.98";
        int SFTPPORT = 22;
        String SFTPUSER = "bnson";
        String SFTPPASS = "123456789";
        String SFTPWORKINGDIR = "/sftp/bnson/";
        //---------------
        Session session;
        Channel channel;
        ChannelSftp channelSftp;
        //---------------
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR);
            
            byte[] buffer = new byte[1024];
            BufferedInputStream bis = new BufferedInputStream(channelSftp.get("image_download.jpg"));
            
            File newFile = new File("D:\\tmp\\test\\image_download.jpg");
            OutputStream os = new FileOutputStream(newFile);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            
            int readCount;
            while ((readCount = bis.read(buffer)) > 0) {
                System.out.println("Writing: ");
                bos.write(buffer, 0, readCount);
            }
            
            bis.close();
            bos.close();
            System.out.println("Download success.");
        } catch (JSchException | SftpException | IOException ex) {
            Logger.getLogger(JSCH_SFTP_DOWNLOAD_EXAMPLE.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

JSCH - SFPT Upload File Example:

package zdemo;
/**
 *
 * @author bnson
 */
import java.io.File;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author hsalearn.blogspot.com
 *
 */
public class JSCH_SFTP_UPLOAD_EXAMPLE {

    public static void main(String[] args) {
        String SFTPHOST = "192.168.1.98";
        int SFTPPORT = 22;
        String SFTPUSER = "bnson";
        String SFTPPASS = "123456789";
        String SFTPWORKINGDIR = "/sftp/bnson/";
        String FILETOTRANSFER = "D:\\picture\\Girl\\001\\74258.jpg";
        //---------------
        Session session;
        Channel channel;
        ChannelSftp channelSftp;
        //---------------
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR);
            
            File f = new File(FILETOTRANSFER);
            channelSftp.put(new FileInputStream(f), f.getName());
            System.out.println("Upload success.");
        } catch (JSchException | SftpException | FileNotFoundException ex) {
            Logger.getLogger(JSCH_SFTP_UPLOAD_EXAMPLE.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}

JSCH - SFPT Download Folder Example:


/*
 * 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 zdemo;

/**
 * @author http://hsalearn.blogspot.com
 */
import java.io.File;
import java.util.ArrayList;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JSCH_SFTP_DOWNLOAD_FOLDER_EXAMPLE {

    static ChannelSftp channelSftp = null;
    static Session session = null;
    static Channel channel = null;
    static String PATHSEPARATOR = "/";

    /**
     * @param args
     */
    public static void main(String[] args) {
        // SFTP Host Name or SFTP Host IP Address
        String SFTPHOST = "ftp.sps-delivery.de"; 
        // SFTP Port Number
        int SFTPPORT = 22; 
        // User Name
        String SFTPUSER = "userName"; 
        // Password
        String SFTPPASS = "Password"; 
        // Source Directory on SFTP server
        String SFTPWORKINGDIR = "/tmp/bnson/test"; 
        String LOCALDIRECTORY = "C:\\System\\bnson\\test\\download"; // Local Target Directory

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            // Create SFTP Session
            session.connect(); 
            // Open SFTP Channel
            channel = session.openChannel("sftp"); 
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            // Change Directory on SFTP Server
            channelSftp.cd(SFTPWORKINGDIR); 

            recursiveFolderDownload(SFTPWORKINGDIR, LOCALDIRECTORY); // Recursive folder content download from SFTP server

        } catch (JSchException | SftpException ex) {
            Logger.getLogger(JSCH_SFTP_DOWNLOAD_FOLDER_EXAMPLE.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (channelSftp != null)
                channelSftp.disconnect();
            if (channel != null)
                channel.disconnect();
            if (session != null)
                session.disconnect();

        }

    }

    /**
     * This method is called recursively to download the folder content from SFTP server
     * 
     * @param sourcePath
     * @param destinationPath
     * @throws SftpException
     */
    @SuppressWarnings("unchecked")
    private static void recursiveFolderDownload(String sourcePath, String destinationPath) throws SftpException {
        // Let list of folder content
        List<ChannelSftp.LsEntry> fileAndFolderList = new ArrayList<>(channelSftp.ls(sourcePath)); 
        
        //Iterate through list of folder content
        for (ChannelSftp.LsEntry item : fileAndFolderList) {
            //Check if it is a file (not a directory).
            if (!item.getAttrs().isDir()) { 
                // Download only if changed later.
                if (!(new File(destinationPath + PATHSEPARATOR + item.getFilename())).exists() || (item.getAttrs().getMTime() > Long.valueOf(new File(destinationPath + PATHSEPARATOR + item.getFilename()).lastModified() / (long) 1000).intValue())) { 
                    File tmp = new File(destinationPath + PATHSEPARATOR + item.getFilename());
                    // Download file from source (source filename, destination filename).
                    channelSftp.get(sourcePath + PATHSEPARATOR + item.getFilename(), tmp.getAbsolutePath()); 
                }
            } else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) {
                 // Empty folder copy.
                new File(destinationPath + PATHSEPARATOR + item.getFilename()).mkdirs();
                // Enter found folder on server to read its contents and create locally.
                recursiveFolderDownload(sourcePath + PATHSEPARATOR + item.getFilename(), destinationPath + PATHSEPARATOR + item.getFilename()); 
            }
        }
    }

}

Java Time Utility.


Get current date or time or date and time with your format.
    /*
        FORMAT DATE AND TIME: "yyyy/MM/dd HH:mm:ss"
        FORMAT DATE: "yyyy-MM-dd"
    */
    public static String getCurrentDateTimeWithFormat(String formatDateTime) {
        DateFormat dateFormat = new SimpleDateFormat(formatDateTime);
        Date date = new Date();
        return dateFormat.format(date);    
    }

Check validate date with format.
    public static boolean isValidDate(String strDate, String format) {
        if (strDate != null && format != null) {
            strDate = strDate.trim();
            format = format.trim();
            if (!strDate.isEmpty() && !format.isEmpty()) {
                try {
                    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
                    if (strDate.trim().length() != dateFormat.toPattern().length()) {
                        return false;
                    }
                    
                    dateFormat.setLenient(false);
                    dateFormat.parse(strDate);
                } catch (ParseException ex) {
                    return false;
                }
            }
        }
        return true;
    }

[FFmpeg] Command Line.


Loop video, mp3, mp4, wmv,...
  • ffmpeg -stream_loop 4 -i video_name.mkv -c copy video_name.mp4

Convert mkv to mp4:
  • ffmpeg -i video_name.mkv -i 001.mp3 -codec copy -shortest video_name.mp4

Merge mkv and mp3 to mp4 with scale video:
  • ffmpeg -i COVER_30_MINS.mkv -i 001.mp3 -acodec copy -shortest -vf scale=1280:720 out003.mp4

Create video from image folder:
  • ffmpeg -r 25 -i Untitled_%03d.png -s:v 1920x1080 -vf "fps=25,format=yuv420p" out.mp4
 
Copyright © 2013. HSA Learn - All Rights Reserved
Template Created by ThemeXpose | Published By Gooyaabi Templates