All Downloads are FREE. Search and download functionalities are using the official Maven repository.

uno.anahata.mapacho.servlet.DownloadRequest Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Oracle nor the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
package uno.anahata.mapacho.servlet;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import uno.anahata.mapacho.common.app.MapachoArtifact;
import uno.anahata.mapacho.common.os.OSUtils;
import uno.anahata.mapacho.common.runtime.JRE;
import static uno.anahata.mapacho.common.http.HttpParameters.*;

/**
 * The DownloadRequest incapsulates all the data in a request
 * SQE: We need to address query string
 */
@Getter
@Slf4j
public class DownloadRequest {
    
    private String path = null;

    private String requestedVersion = null;

    private String currentVersion = null;

    private String[] os = null;

    private String[] arch = null;

    private String[] locale = null;

    private String[] knownPlatforms = null;

    private String query = null;
    
    private String agent = null;

    private boolean isPlatformRequest = false;

    private Date ifModifiedSince;

    private String encoding = null;

    private HttpServletRequest httpRequest = null;

    // HTTP Compression RFC 2616 : Standard headers
    public static final String ACCEPT_ENCODING = "accept-encoding";

    public DownloadRequest(HttpServletRequest request) {
        httpRequest = request;
        path = request.getRequestURI();
        encoding = request.getHeader(ACCEPT_ENCODING);
        String context_path = request.getContextPath();
        if (context_path != null) {
            path = path.substring(context_path.length());
        }
        if (path == null) {
            path = request.getServletPath(); // This works for *. invocations
        }
        if (path == null) {
            path = "/"; // No path given
        }
        path = path.trim();
        // Append default file for a directory
        if (path.endsWith("/")) {
            path += "launch.jnlp";
        }
        requestedVersion = getParameter(request, ARG_VERSION_ID);
        currentVersion = getParameter(request, ARG_CURRENT_VERSION_ID);
        os = getParameterList(request, ARG_OS);
        arch = getParameterList(request, ARG_ARCH);
        locale = getParameterList(request, ARG_LOCALE);
        knownPlatforms = getParameterList(request, ARG_KNOWN_PLATFORMS);
        String platformVersion = getParameter(request, ARG_PLATFORM_VERSION_ID);
        isPlatformRequest = (platformVersion != null);
        if (isPlatformRequest) {
            requestedVersion = platformVersion;
        }
        query = request.getQueryString();
        long date = request.getDateHeader("If-Modified-Since");
        if (date != -1) {
            date = (date / 1000) * 1000;
            ifModifiedSince = new Date(date);
        }
        agent = request.getHeader("User-Agent");
    }

    public boolean isJar() {
        return path.endsWith(".jar") || path.endsWith(".jar.pack.gz");
    }

    public boolean isJnlp() {
        return path.endsWith(".jnlp");
    }
    
    public boolean isJRE() {
        return path.endsWith("jre");
    }
    
    public JRE getJRE() {
        String chunks[] = requestedVersion.split("_");
        String ver = chunks[0];
        String build = chunks[1];
        String hash = chunks.length > 2 ? chunks[2] : null;
        
        String os1 = os[0];
        String arch1 = arch[0];
        
        if (OSUtils.isMac(os1)) {
            os1 = "macosx";
        }
        os1 = os1.toLowerCase();
        
        if (arch1.contains("64")) {
            arch1 = "x64";
        } else {
            arch1 = "i586";
        }
        
        JRE jre = new JRE();
        jre.setVer(ver);
        jre.setBuild(build);
        jre.setHash(hash);
        jre.setOs(os1);
        jre.setArch(arch1);
        
        return jre;
        
    }
    
    public File getCachedJREFile() {
        JRE jre = getJRE();
        return new File(MapachoServlet.getCacheDirectory(), jre.getEncodedName() + ".tar.gz");
    }
    
    public String getJarPath() {
        String name = path.substring(0, path.indexOf(".jar"));
        String osString = os != null ? os[0] : "";
        String archString = arch != null ? arch[0] : "";
        String localeString = locale != null ? locale[0] : ""; 
        MapachoArtifact ma = new MapachoArtifact(null, name, osString, archString, localeString, requestedVersion, osString != null, null);
        
        return ma.getJarFileName();
    }
    
    public boolean isJarExists() {     
        String jarPath = getJarPath();
        String jarPackGzPath = jarPath + ".pack.gz";
        
        return     httpRequest.getServletContext().getRealPath(jarPath) != null
                || httpRequest.getServletContext().getRealPath(jarPackGzPath) != null;
    }
    
    public File getRequestedVersionJarFile() {        
        return getFile(httpRequest.getServletContext().getRealPath(getJarPath()));
    }

    public File getRequestedVersionJarPackGzFile() {
        return getFile(httpRequest.getServletContext().getRealPath(getJarPath() + ".pack.gz"));
    }
    
    private File getFile(String realPath) {
        if (realPath != null) {
            return new File(realPath);
        } else {
            return null;
        }
    }

    public File getCurrentVersionCacheJarFile() {
        return getCacheJarFile(currentVersion);
    }
    
    public File getRequestedVersionCacheJarFile() {
        return getCacheJarFile(requestedVersion);
    }
    
    public File getRequestedVersionCacheJarPackGzFile() {
        return getCacheJarPackGzFile(requestedVersion);
    }

    public String getCacheDiffBaseName() {
        String diffName = getBaseJarFileName() + "-" + currentVersion + "-to-" + requestedVersion + ".jardiff";
        return diffName;
    }
    
    public File getCacheDiffFile() {
        return new File(MapachoServlet.getCacheDirectory(), getCacheDiffBaseName() + ".pack.gz");
    }
    
    public File getCacheDiffPackGzFile() {
        String diffName = getBaseJarFileName() + "-" + currentVersion + "-to-" + requestedVersion + ".jardiff.pack.gz";
        return new File(MapachoServlet.getCacheDirectory(), diffName);
    }
    
    public String getBaseJarFileName() {
        String fileName = path.substring(path.lastIndexOf("/"), path.length());
        return fileName.substring(0, fileName.indexOf(".jar"));
    }

    public File getCacheJarFile(String version) {
        String actualJarFileName = getBaseJarFileName() + "__V" + version + ".jar";
        return new File(MapachoServlet.getCacheDirectory(), actualJarFileName);
    }
    
    public File getCacheJarPackGzFile(String version) {
        File jar = getCacheJarFile(version);
        File jarPackGz = new File(jar.getParentFile(), jar.getName() + ".pack.gz");
        return jarPackGz;
    }

    private String getParameter(HttpServletRequest req, String key) {
        String res = req.getParameter(key);
        return (res == null) ? null : res.trim();
    }

    /** Converts a space delimitered string to a list of strings */
    static private String[] getStringList(String str) {
        if (str == null) {
            return null;
        }
        ArrayList list = new ArrayList();
        int i = 0;
        int length = str.length();
        StringBuffer sb = null;
        while (i < length) {
            char ch = str.charAt(i);
            if (ch == ' ') {
                // A space was hit. Add string to list
                if (sb != null) {
                    list.add(sb.toString());
                    sb = null;
                }
            } else if (ch == '\\') {
                // It is a delimiter. Add next character
                if (i + 1 < length) {
                    ch = str.charAt(++i);
                    if (sb == null) {
                        sb = new StringBuffer();
                    }
                    sb.append(ch);
                }
            } else {
                if (sb == null) {
                    sb = new StringBuffer();
                }
                sb.append(ch);
            }
            i++; // Next character
        }
        // Make sure to add the last part to the list too
        if (sb != null) {
            list.add(sb.toString());
        }
        if (list.size() == 0) {
            return null;
        }
        String[] results = new String[list.size()];
        return (String[])list.toArray(results);
    }

    /* Split parameter at spaces. Convert '\ ' insto a space */
    private String[] getParameterList(HttpServletRequest req, String key) {
        String res = req.getParameter(key);
        return (res == null) ? null : getStringList(res.trim());
    }

    // Debug
    public String toString() {
        return "DownloadRequest[path=" + path
                + showEntry(" realPath=", getRealPath())
                + showEntry(" ifModifiedSince=", ifModifiedSince)
                + showEntry(" encoding=", encoding)
                + showEntry(" query=", query)
                + showEntry(" version=", requestedVersion)
                + showEntry(" currentVersionId=", currentVersion)
                + showEntry(" os=", os)
                + showEntry(" arch=", arch)
                + showEntry(" locale=", locale)
                + showEntry(" knownPlatforms=", knownPlatforms)
                + " isPlatformRequest=" + isPlatformRequest + "]";
    }

    private String showEntry(String msg, Object value) {
        if (value == null) {
            return "";
        }
        return msg + value;
    }

    private String showEntry(String msg, String value) {
        if (value == null) {
            return "";
        }
        return msg + value;
    }

    private String showEntry(String msg, String[] value) {
        if (value == null) {
            return "";
        }
        return msg + java.util.Arrays.asList(value).toString();
    }

    public boolean isSupportsGzip() {
        return encoding.contains("gzip");
    }

    public boolean isSupportsDeflate() {
        return encoding.contains("deflate");
    }

    public String getRealPath() {
        return getHttpRequest().getServletContext().getRealPath(getPath());
    }

    public boolean fileExists() {
        return getFile().exists();
    }

    public java.io.File getFile() {
        if (isJar()) {
            return getRequestedVersionJarPackGzFile();
        } else {
            log.debug("getFile() realPath" + getRealPath());
            return getRealPath() != null ? new File(getRealPath()) : null;
        }
    }

    public Date getFileLastModified() {
        return fileExists() ? new Date(getFile().lastModified()) : null;
    }

    public String getFileMimeType() {
        return getHttpRequest().getServletContext().getMimeType(path);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy