Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.math.BigInteger;

import java.security.MessageDigest;
import java.util.UUID;

public class Main {
    /**
     * Get filename from url.
     *
     * @param url url
     * @return filename or null if no available filename
     */
    private static String getFilenameFromUrl(String url) {
        String filename = md5(url) + ".down";

        int index = url.lastIndexOf("/");
        if (index > 0) {
            String tmpFilename = url.substring(index);
            int qmarkIndex = tmpFilename.indexOf("?");
            if (qmarkIndex > 0) {
                tmpFilename = tmpFilename.substring(0, qmarkIndex - 1);
            }

            /* if filename contains '.', then the filename has file extension */
            if (tmpFilename.contains(".")) {
                filename = tmpFilename;
            }
        }

        return filename;
    }

    private static String md5(String origin) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(origin.getBytes("UTF-8"));
            BigInteger bi = new BigInteger(1, md.digest());

            return bi.toString(16);
        } catch (Exception e) {
            return getUuid();
        }
    }

    private static String getUuid() {
        return UUID.randomUUID().toString().trim().replaceAll("-", "");
    }
}