Example usage for javax.servlet.http HttpServletResponse setDateHeader

List of usage examples for javax.servlet.http HttpServletResponse setDateHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setDateHeader.

Prototype

public void setDateHeader(String name, long date);

Source Link

Document

Sets a response header with the given name and date-value.

Usage

From source file:eionet.eunis.servlets.DownloadServlet.java

/**
 * Process the actual request.//from  w  w  w  .j  a v a2 s  .com
 *
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not (HEAD).
 * @throws IOException If something fails at I/O level.
 * @throws ServletException
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException, ServletException {

    String requestURI = request.getRequestURI();
    String contextPath = request.getContextPath();
    String pathInfo = request.getPathInfo();
    String servletPath = request.getServletPath();

    // Create the abstract file reference to the requested file.
    File file = null;
    String fileRelativePath = StringUtils.substringAfter(request.getRequestURI(), request.getContextPath());
    fileRelativePath = StringUtils.replace(fileRelativePath, "%20", " ");
    if (StringUtils.isNotEmpty(fileRelativePath) && StringUtils.isNotEmpty(appHome)) {
        file = new File(appHome, fileRelativePath);
    }

    // If file was not found, send 404.
    if (file == null || !file.exists() || file.isDirectory()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;

    // Validate request headers for caching ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set default GZIP support and content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, then determine whether GZIP content encoding is supported by
    // the browser and expand content type with the one and right character encoding.
    // Else, expect for images, determine content disposition. If content type is supported by
    // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    } else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

            if (content) {
                if (acceptsGzip) {
                    // The browser accepts GZIP, so GZIP the content.
                    response.setHeader("Content-Encoding", "gzip");
                    output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
                } else {
                    // Content length is not directly predictable in case of GZIP.
                    // So only add it if there is no means of GZIP, else browser will hang.
                    response.setHeader("Content-Length", String.valueOf(r.length));
                }

                // Copy full range.
                copy(input, output, r.start, r.length);
            }

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Copy single part range.
                copy(input, output, r.start, r.length);
            }

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Cast back to ServletOutputStream to get the easy println methods.
                ServletOutputStream sos = (ServletOutputStream) output;

                // Copy multi part range.
                for (Range r : ranges) {
                    // Add multipart boundary and header fields for every range.
                    sos.println();
                    sos.println("--" + MULTIPART_BOUNDARY);
                    sos.println("Content-Type: " + contentType);
                    sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    copy(input, output, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:org.sakaiproject.calendar.impl.BaseCalendarService.java

protected void handleAccessIcalCommon(HttpServletRequest req, HttpServletResponse res, Reference ref,
        String calRef) throws EntityPermissionException, PermissionException, IOException {

    // Extract the alias name to use for the filename.
    List alias = m_aliasService.getAliases(calRef);
    String aliasName = "schedule.ics";
    if (!alias.isEmpty())
        aliasName = ((Alias) alias.get(0)).getId();

    List<String> referenceList = getCalendarReferences(ref.getContext());
    Time modDate = m_timeService.newTime(0);
    // Ok so we need to check to see if we've handled this reference before.
    // This is to prevent loops when including calendars
    // that currently includes other calendars we only do the check in here.
    if (getUserAgent().equals(req.getHeader("User-Agent"))) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        M_log.warn("Reject internal request for: " + calRef);
        return;//  ww w.  j av a2  s.c o  m
    }
    // update date/time reference
    for (String curCalRef : referenceList) {
        Calendar curCal = findCalendar(curCalRef);
        /*
         * TODO: This null check is required to handle the references 
         * pertaining to external calendar subscriptions as they are 
         * currently broken in (at least) the 2 following ways:
         * 
         * (i) findCalendar will return null rather than a calendar object.
         * (ii) getCalendar(String) will return a calendar object that is 
         * not null, but the corresponding getModified() method returns a
         * date than can not be parsed.  
         *  
         * Clearly such references to need to be improved to make them 
         * consistent with other types as at the moment they have to be
         * excluded as part of this process to find the most recent modified
         * date. 
         */
        if (curCal == null) {
            continue;
        }
        Time curModDate = curCal.getModified();
        if (curModDate != null && curModDate.after(modDate)) {
            modDate = curModDate;
        }
    }
    res.addHeader("Content-Disposition", "inline; filename=\"" + aliasName + "\"");
    res.setContentType(ICAL_MIME_TYPE);
    res.setDateHeader("Last-Modified", modDate.getTime());
    String calendarName = "";
    try {
        calendarName = m_siteService.getSite(ref.getContext()).getTitle();
        boolean isMyDashboard = m_siteService.isUserSite(ref.getContext());
        if (isMyDashboard) {
            calendarName = m_serverConfigurationService.getString(UI_SERVICE, SAKAI);
        }
    } catch (IdUnusedException e) {
    }
    printICalSchedule(calendarName, referenceList, res.getOutputStream());
}

From source file:edu.ucsd.library.dams.api.FileStoreServlet.java

/**
 * Process the actual request.//from w ww  . ja  v a 2  s.  c  o m
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not
 *  (HEAD).
 * @throws IOException If something fails at I/O level.
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException {
    // Validate the requested file -------------------------------------

    // Get requested file by path info.
    /* start ucsd changes */

    // get object and file ids from path
    String objid = null;
    String cmpid = null;
    String fileid = null;
    try {
        // /bb1234567x/1.tif
        // /bb1234567x/1/2.tif
        String[] path = request.getPathInfo().split("/");
        if (path.length == 3) {
            objid = path[1];
            fileid = path[2];
        } else if (path.length == 4) {
            objid = path[1];
            cmpid = path[2];
            fileid = path[3];
        }
    } catch (Exception e) {
        String errorMessage = "Error parsing request pathInfo: " + request.getPathInfo();
        log.error(errorMessage, e);
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage);
        return;
    }

    // make sure required parameters are populated
    if (objid == null || objid.trim().length() == 0 || fileid == null || fileid.trim().length() == 0) {
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Subject and file must be specified in the request URI");
        return;
    }
    String fullFilename = objid + (StringUtils.isNotBlank(cmpid) ? "-" + cmpid : "") + "-" + fileid;

    // first load the FileStore (no point if this doesn't work)
    FileStore fs = null;
    long fsTime = 0;
    try {
        long start = System.currentTimeMillis();
        fs = FileStoreUtil.getFileStore(props, fsDefault);
        fsTime = System.currentTimeMillis() - start;
    } catch (Exception ex) {
        response.setContentType("text/plain");
        response.sendError(response.SC_INTERNAL_SERVER_ERROR, "Error initializing FileStore");
        ex.printStackTrace();
        return;
    }

    // check authorization attribute
    String restricted = null;
    String authorized = (String) request.getAttribute("edu.ucsd.library.dams.api.DAMSAPIServlet.authorized");
    if (authorized == null || !authorized.equals("true")) {
        log.warn("Illegal Access from IP " + request.getRemoteAddr() + " for file " + fullFilename);
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access without authorization.");
        return;
    } else {
        log.info("DAMS Access authorized for IP " + request.getRemoteAddr() + " for file " + fullFilename);
        restricted = (String) request.getAttribute("pas.restricted");
        //Disable browser caching for restricted objects.
        if (restricted != null && restricted.equals("1")) {
            String browser = request.getHeader("User-Agent");
            if (browser != null && browser.indexOf("MSIE") != -1) {
                response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            } else {
                response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            }
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "0");
        }
    }
    /* end ucsd changes */

    // load file metadata
    Map<String, String> meta = null;
    long metaTime = 0;
    try {
        long start = System.currentTimeMillis();
        meta = fs.meta(objid, cmpid, fileid);
        metaTime = System.currentTimeMillis() - start;
    } catch (Exception ex) {
        log.error("File " + fullFilename + " doesn't exist.", ex);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file
    String length = meta.get("Content-Length");
    String lastModStr = meta.get("Last-Modified");
    long lastModified = 0L;
    try {
        lastModified = df.parse(lastModStr).getTime();
    } catch (Exception ex) {
        // error parsing lastmod date... set to now
        lastModified = System.currentTimeMillis();
    }
    String eTag = meta.get("ETag");
    if (eTag == null) {
        eTag = fullFilename + "_" + length + "_" + lastModified;
    }

    // Validate request headers for caching -----------------------------

    // If-None-Match header should contain "*" or ETag. If so, return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified.
    // If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Prepare and initialize response ----------------------------------

    // Get content type by file name and set default GZIP support and
    // content disposition.
    String contentType = getServletContext().getMimeType(fullFilename);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.  For all
    // content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    //If UCSD download
    boolean download = request.getParameter("download") != null;
    if (download) {
        disposition = "attachment";
        contentType = "application/x-download";
    }
    // Else if content type is text, then determine whether GZIP content
    // encoding is supported by the browser and expand content type with
    // the one and right character encoding.
    else if (contentType.startsWith("text")) {
        //String acceptEncoding = request.getHeader("Accept-Encoding");
        //acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    }

    // Else, expect for images, determine content disposition. If content
    // type is supported by the browser, then set to inline, else
    // attachment which will pop a 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    String sFileName = request.getParameter("name");
    if (sFileName == null || (sFileName = sFileName.trim()).length() == 0)
        sFileName = fullFilename;

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + sFileName + "\"");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    /* begin ucsd changes */
    if (restricted == null || !restricted.equals("1")) {
        response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);
    }
    /* end ucsd changes */

    // Send requested file to client ------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;
    long fileTime = 0;
    if (content) {
        try {
            long start = System.currentTimeMillis();
            // Open streams.
            input = fs.getInputStream(objid, cmpid, fileid);
            output = response.getOutputStream();
            response.setContentType(contentType);
            if (acceptsGzip) {
                // The browser accepts GZIP, so GZIP the content.
                response.setHeader("Content-Encoding", "gzip");
                output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
            } else {
                // Content length is not directly predictable in case of
                // GZIP. So only add it if there is no means of GZIP, else
                // browser will hang.
                response.setHeader("Content-Length", length);
            }

            // Copy full range.
            /* begin ucsd changes */
            FileStoreUtil.copy(input, output);
            fileTime = System.currentTimeMillis() - start;
            /* begin ucsd changes */
        } catch (Exception ex) {
            log.error("Error reading " + fullFilename, ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            /* begin ucsd changes */
            log.info("Time in miliseconds to retrival file " + fullFilename + "(" + length + " bytes)"
                    + ": Total " + (fsTime + metaTime + fileTime) + "[FileStore initiation: " + fsTime
                    + "; Metadata query: " + metaTime + "; File download: " + fileTime + "]");
            /* begin ucsd changes */
            // Gently close streams.
            close(output);
            close(input);
        }
    }
}

From source file:org.apache.karaf.services.mavenproxy.internal.MavenProxyServletTest.java

@Test
public void testDownloadMetadata() throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override/*from  ww  w  .j a v a 2  s. c  o  m*/
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String result = null;
            if ("/repo1/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata>\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0</latest>\n"
                        + "    <release>2.14.0</release>\n" + "    <versions>\n"
                        + "      <version>1.6.1</version>\n" + "      <version>1.6.2</version>\n"
                        + "      <version>1.6.3</version>\n" + "      <version>1.6.4</version>\n"
                        + "      <version>2.0-M2</version>\n" + "      <version>2.0-M3</version>\n"
                        + "      <version>2.0.0</version>\n" + "      <version>2.1.0</version>\n"
                        + "      <version>2.2.0</version>\n" + "      <version>2.3.0</version>\n"
                        + "      <version>2.4.0</version>\n" + "      <version>2.5.0</version>\n"
                        + "      <version>2.6.0</version>\n" + "      <version>2.7.0</version>\n"
                        + "      <version>2.7.1</version>\n" + "      <version>2.7.2</version>\n"
                        + "      <version>2.7.3</version>\n" + "      <version>2.7.4</version>\n"
                        + "      <version>2.7.5</version>\n" + "      <version>2.8.0</version>\n"
                        + "      <version>2.8.1</version>\n" + "      <version>2.8.2</version>\n"
                        + "      <version>2.8.3</version>\n" + "      <version>2.8.4</version>\n"
                        + "      <version>2.8.5</version>\n" + "      <version>2.8.6</version>\n"
                        + "      <version>2.9.0-RC1</version>\n" + "      <version>2.9.0</version>\n"
                        + "      <version>2.9.1</version>\n" + "      <version>2.9.2</version>\n"
                        + "      <version>2.9.3</version>\n" + "      <version>2.9.4</version>\n"
                        + "      <version>2.9.5</version>\n" + "      <version>2.9.6</version>\n"
                        + "      <version>2.9.7</version>\n" + "      <version>2.9.8</version>\n"
                        + "      <version>2.10.0</version>\n" + "      <version>2.10.1</version>\n"
                        + "      <version>2.10.2</version>\n" + "      <version>2.10.3</version>\n"
                        + "      <version>2.10.4</version>\n" + "      <version>2.10.5</version>\n"
                        + "      <version>2.10.6</version>\n" + "      <version>2.10.7</version>\n"
                        + "      <version>2.11.0</version>\n" + "      <version>2.11.1</version>\n"
                        + "      <version>2.11.2</version>\n" + "      <version>2.11.3</version>\n"
                        + "      <version>2.11.4</version>\n" + "      <version>2.12.0</version>\n"
                        + "      <version>2.12.1</version>\n" + "      <version>2.12.2</version>\n"
                        + "      <version>2.12.3</version>\n" + "      <version>2.12.4</version>\n"
                        + "      <version>2.13.0</version>\n" + "      <version>2.13.1</version>\n"
                        + "      <version>2.13.2</version>\n" + "      <version>2.14.0</version>\n"
                        + "    </versions>\n" + "    <lastUpdated>20140918132816</lastUpdated>\n"
                        + "  </versioning>\n" + "</metadata>\n" + "\n";
            } else if ("/repo2/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata modelVersion=\"1.1.0\">\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0.redhat-620034</latest>\n"
                        + "    <release>2.14.0.redhat-620034</release>\n" + "    <versions>\n"
                        + "      <version>2.10.0.redhat-60074</version>\n"
                        + "      <version>2.12.0.redhat-610312</version>\n"
                        + "      <version>2.12.0.redhat-610328</version>\n"
                        + "      <version>2.12.0.redhat-610355</version>\n"
                        + "      <version>2.12.0.redhat-610378</version>\n"
                        + "      <version>2.12.0.redhat-610396</version>\n"
                        + "      <version>2.12.0.redhat-610399</version>\n"
                        + "      <version>2.12.0.redhat-610401</version>\n"
                        + "      <version>2.12.0.redhat-610402</version>\n"
                        + "      <version>2.12.0.redhat-611403</version>\n"
                        + "      <version>2.12.0.redhat-611405</version>\n"
                        + "      <version>2.12.0.redhat-611406</version>\n"
                        + "      <version>2.12.0.redhat-611408</version>\n"
                        + "      <version>2.12.0.redhat-611409</version>\n"
                        + "      <version>2.12.0.redhat-611410</version>\n"
                        + "      <version>2.12.0.redhat-611411</version>\n"
                        + "      <version>2.12.0.redhat-611412</version>\n"
                        + "      <version>2.14.0.redhat-620031</version>\n"
                        + "      <version>2.14.0.redhat-620033</version>\n"
                        + "      <version>2.14.0.redhat-620034</version>\n" + "    </versions>\n"
                        + "    <lastUpdated>20141019130841</lastUpdated>\n" + "  </versioning>\n"
                        + "</metadata>\n" + "\n";
            }
            if (result == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                baseRequest.setHandled(true);
                response.getOutputStream().close();
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getOutputStream().write(result.getBytes());
                response.getOutputStream().close();
            }
        }
    });
    server.start();

    try {
        int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp",
                "http://relevant.not/repo1@id=repo1,http://relevant.not/repo2@id=repo2", "http", "localhost",
                localPort, "fuse", "fuse", null);
        MavenProxyServlet servlet = new MavenProxyServlet(resolver, 5, null, null, null);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml");
        //            EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/LATEST/camel-core-LATEST.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }
        }).anyTimes();
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.init();
        servlet.doGet(request, response);

        latch.await();

        shaded.org.apache.maven.artifact.repository.metadata.Metadata m = new MetadataXpp3Reader()
                .read(new ByteArrayInputStream(baos.toByteArray()), false);
        assertEquals("2.14.0.redhat-620034", m.getVersioning().getLatest());
        assertTrue(m.getVersioning().getVersions().contains("2.10.4"));
        assertTrue(m.getVersioning().getVersions().contains("2.12.0.redhat-610399"));

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java

@Test
public void testDownloadMetadata() throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override//from   w  w w  .ja v a2 s .c  om
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String result = null;
            if ("/repo1/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata>\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0</latest>\n"
                        + "    <release>2.14.0</release>\n" + "    <versions>\n"
                        + "      <version>1.6.1</version>\n" + "      <version>1.6.2</version>\n"
                        + "      <version>1.6.3</version>\n" + "      <version>1.6.4</version>\n"
                        + "      <version>2.0-M2</version>\n" + "      <version>2.0-M3</version>\n"
                        + "      <version>2.0.0</version>\n" + "      <version>2.1.0</version>\n"
                        + "      <version>2.2.0</version>\n" + "      <version>2.3.0</version>\n"
                        + "      <version>2.4.0</version>\n" + "      <version>2.5.0</version>\n"
                        + "      <version>2.6.0</version>\n" + "      <version>2.7.0</version>\n"
                        + "      <version>2.7.1</version>\n" + "      <version>2.7.2</version>\n"
                        + "      <version>2.7.3</version>\n" + "      <version>2.7.4</version>\n"
                        + "      <version>2.7.5</version>\n" + "      <version>2.8.0</version>\n"
                        + "      <version>2.8.1</version>\n" + "      <version>2.8.2</version>\n"
                        + "      <version>2.8.3</version>\n" + "      <version>2.8.4</version>\n"
                        + "      <version>2.8.5</version>\n" + "      <version>2.8.6</version>\n"
                        + "      <version>2.9.0-RC1</version>\n" + "      <version>2.9.0</version>\n"
                        + "      <version>2.9.1</version>\n" + "      <version>2.9.2</version>\n"
                        + "      <version>2.9.3</version>\n" + "      <version>2.9.4</version>\n"
                        + "      <version>2.9.5</version>\n" + "      <version>2.9.6</version>\n"
                        + "      <version>2.9.7</version>\n" + "      <version>2.9.8</version>\n"
                        + "      <version>2.10.0</version>\n" + "      <version>2.10.1</version>\n"
                        + "      <version>2.10.2</version>\n" + "      <version>2.10.3</version>\n"
                        + "      <version>2.10.4</version>\n" + "      <version>2.10.5</version>\n"
                        + "      <version>2.10.6</version>\n" + "      <version>2.10.7</version>\n"
                        + "      <version>2.11.0</version>\n" + "      <version>2.11.1</version>\n"
                        + "      <version>2.11.2</version>\n" + "      <version>2.11.3</version>\n"
                        + "      <version>2.11.4</version>\n" + "      <version>2.12.0</version>\n"
                        + "      <version>2.12.1</version>\n" + "      <version>2.12.2</version>\n"
                        + "      <version>2.12.3</version>\n" + "      <version>2.12.4</version>\n"
                        + "      <version>2.13.0</version>\n" + "      <version>2.13.1</version>\n"
                        + "      <version>2.13.2</version>\n" + "      <version>2.14.0</version>\n"
                        + "    </versions>\n" + "    <lastUpdated>20140918132816</lastUpdated>\n"
                        + "  </versioning>\n" + "</metadata>\n" + "\n";
            } else if ("/repo2/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata modelVersion=\"1.1.0\">\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0.redhat-620034</latest>\n"
                        + "    <release>2.14.0.redhat-620034</release>\n" + "    <versions>\n"
                        + "      <version>2.10.0.redhat-60074</version>\n"
                        + "      <version>2.12.0.redhat-610312</version>\n"
                        + "      <version>2.12.0.redhat-610328</version>\n"
                        + "      <version>2.12.0.redhat-610355</version>\n"
                        + "      <version>2.12.0.redhat-610378</version>\n"
                        + "      <version>2.12.0.redhat-610396</version>\n"
                        + "      <version>2.12.0.redhat-610399</version>\n"
                        + "      <version>2.12.0.redhat-610401</version>\n"
                        + "      <version>2.12.0.redhat-610402</version>\n"
                        + "      <version>2.12.0.redhat-611403</version>\n"
                        + "      <version>2.12.0.redhat-611405</version>\n"
                        + "      <version>2.12.0.redhat-611406</version>\n"
                        + "      <version>2.12.0.redhat-611408</version>\n"
                        + "      <version>2.12.0.redhat-611409</version>\n"
                        + "      <version>2.12.0.redhat-611410</version>\n"
                        + "      <version>2.12.0.redhat-611411</version>\n"
                        + "      <version>2.12.0.redhat-611412</version>\n"
                        + "      <version>2.14.0.redhat-620031</version>\n"
                        + "      <version>2.14.0.redhat-620033</version>\n"
                        + "      <version>2.14.0.redhat-620034</version>\n" + "    </versions>\n"
                        + "    <lastUpdated>20141019130841</lastUpdated>\n" + "  </versioning>\n"
                        + "</metadata>\n" + "\n";
            }
            if (result == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                baseRequest.setHandled(true);
                response.getOutputStream().close();
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getOutputStream().write(result.getBytes());
                response.getOutputStream().close();
            }
        }
    });
    server.start();

    try {
        int localPort = server.getConnectors()[0].getLocalPort();
        List<String> remoteRepos = Arrays
                .asList("http://relevant.not/repo1@id=repo1,http://relevant.not/repo2@id=repo2");
        RuntimeProperties props = new MockRuntimeProperties();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort,
                "fuse", "fuse", null);
        MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(resolver, props, projectDeployer, 5);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml");
        //            EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/LATEST/camel-core-LATEST.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }
        }).anyTimes();
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.start();
        servlet.doGet(request, response);

        latch.await();

        org.apache.maven.artifact.repository.metadata.Metadata m = new MetadataXpp3Reader()
                .read(new ByteArrayInputStream(baos.toByteArray()), false);
        assertEquals("2.14.0.redhat-620034", m.getVersioning().getLatest());
        assertTrue(m.getVersioning().getVersions().contains("2.10.4"));
        assertTrue(m.getVersioning().getVersions().contains("2.12.0.redhat-610399"));

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:org.apache.karaf.cave.server.maven.MavenProxyServletTest.java

@Test
public void testDownloadMetadata() throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override//  ww w .j  av  a  2 s .c  o  m
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String result = null;
            if ("/repo1/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata>\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0</latest>\n"
                        + "    <release>2.14.0</release>\n" + "    <versions>\n"
                        + "      <version>1.6.1</version>\n" + "      <version>1.6.2</version>\n"
                        + "      <version>1.6.3</version>\n" + "      <version>1.6.4</version>\n"
                        + "      <version>2.0-M2</version>\n" + "      <version>2.0-M3</version>\n"
                        + "      <version>2.0.0</version>\n" + "      <version>2.1.0</version>\n"
                        + "      <version>2.2.0</version>\n" + "      <version>2.3.0</version>\n"
                        + "      <version>2.4.0</version>\n" + "      <version>2.5.0</version>\n"
                        + "      <version>2.6.0</version>\n" + "      <version>2.7.0</version>\n"
                        + "      <version>2.7.1</version>\n" + "      <version>2.7.2</version>\n"
                        + "      <version>2.7.3</version>\n" + "      <version>2.7.4</version>\n"
                        + "      <version>2.7.5</version>\n" + "      <version>2.8.0</version>\n"
                        + "      <version>2.8.1</version>\n" + "      <version>2.8.2</version>\n"
                        + "      <version>2.8.3</version>\n" + "      <version>2.8.4</version>\n"
                        + "      <version>2.8.5</version>\n" + "      <version>2.8.6</version>\n"
                        + "      <version>2.9.0-RC1</version>\n" + "      <version>2.9.0</version>\n"
                        + "      <version>2.9.1</version>\n" + "      <version>2.9.2</version>\n"
                        + "      <version>2.9.3</version>\n" + "      <version>2.9.4</version>\n"
                        + "      <version>2.9.5</version>\n" + "      <version>2.9.6</version>\n"
                        + "      <version>2.9.7</version>\n" + "      <version>2.9.8</version>\n"
                        + "      <version>2.10.0</version>\n" + "      <version>2.10.1</version>\n"
                        + "      <version>2.10.2</version>\n" + "      <version>2.10.3</version>\n"
                        + "      <version>2.10.4</version>\n" + "      <version>2.10.5</version>\n"
                        + "      <version>2.10.6</version>\n" + "      <version>2.10.7</version>\n"
                        + "      <version>2.11.0</version>\n" + "      <version>2.11.1</version>\n"
                        + "      <version>2.11.2</version>\n" + "      <version>2.11.3</version>\n"
                        + "      <version>2.11.4</version>\n" + "      <version>2.12.0</version>\n"
                        + "      <version>2.12.1</version>\n" + "      <version>2.12.2</version>\n"
                        + "      <version>2.12.3</version>\n" + "      <version>2.12.4</version>\n"
                        + "      <version>2.13.0</version>\n" + "      <version>2.13.1</version>\n"
                        + "      <version>2.13.2</version>\n" + "      <version>2.14.0</version>\n"
                        + "    </versions>\n" + "    <lastUpdated>20140918132816</lastUpdated>\n"
                        + "  </versioning>\n" + "</metadata>\n" + "\n";
            } else if ("/repo2/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata modelVersion=\"1.1.0\">\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0.redhat-620034</latest>\n"
                        + "    <release>2.14.0.redhat-620034</release>\n" + "    <versions>\n"
                        + "      <version>2.10.0.redhat-60074</version>\n"
                        + "      <version>2.12.0.redhat-610312</version>\n"
                        + "      <version>2.12.0.redhat-610328</version>\n"
                        + "      <version>2.12.0.redhat-610355</version>\n"
                        + "      <version>2.12.0.redhat-610378</version>\n"
                        + "      <version>2.12.0.redhat-610396</version>\n"
                        + "      <version>2.12.0.redhat-610399</version>\n"
                        + "      <version>2.12.0.redhat-610401</version>\n"
                        + "      <version>2.12.0.redhat-610402</version>\n"
                        + "      <version>2.12.0.redhat-611403</version>\n"
                        + "      <version>2.12.0.redhat-611405</version>\n"
                        + "      <version>2.12.0.redhat-611406</version>\n"
                        + "      <version>2.12.0.redhat-611408</version>\n"
                        + "      <version>2.12.0.redhat-611409</version>\n"
                        + "      <version>2.12.0.redhat-611410</version>\n"
                        + "      <version>2.12.0.redhat-611411</version>\n"
                        + "      <version>2.12.0.redhat-611412</version>\n"
                        + "      <version>2.14.0.redhat-620031</version>\n"
                        + "      <version>2.14.0.redhat-620033</version>\n"
                        + "      <version>2.14.0.redhat-620034</version>\n" + "    </versions>\n"
                        + "    <lastUpdated>20141019130841</lastUpdated>\n" + "  </versioning>\n"
                        + "</metadata>\n" + "\n";
            }
            if (result == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                baseRequest.setHandled(true);
                response.getOutputStream().close();
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getOutputStream().write(result.getBytes());
                response.getOutputStream().close();
            }
        }
    });
    server.start();

    try {
        int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp",
                "http://relevant.not/repo1@id=repo1,http://relevant.not/repo2@id=repo2", "http", "localhost",
                localPort, "fuse", "fuse", null);
        CaveMavenServlet servlet = new CaveMavenServlet(resolver, 5, null, null, null);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml");
        //            EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/LATEST/camel-core-LATEST.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }

            @Override
            public boolean isReady() {
                // TODO Auto-generated method stub
                return true;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {
                // TODO Auto-generated method stub

            }
        }).anyTimes();
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.init();
        servlet.doGet(request, response);

        latch.await();

        shaded.org.apache.maven.artifact.repository.metadata.Metadata m = new MetadataXpp3Reader()
                .read(new ByteArrayInputStream(baos.toByteArray()), false);
        assertEquals("2.14.0.redhat-620034", m.getVersioning().getLatest());
        assertTrue(m.getVersioning().getVersions().contains("2.10.4"));
        assertTrue(m.getVersioning().getVersions().contains("2.12.0.redhat-610399"));

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:com.liferay.lms.servlet.SCORMFileServerServlet.java

/**
 * Procesa los metodos HTTP GET y POST.<br>
 * Busca en la ruta que se le ha pedido el comienzo del directorio
 * "contenidos" y sirve el fichero.//from   w ww.  j  a va  2s  .c o  m
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws ServletException, java.io.IOException {
    String mime_type;
    String charset;
    String patharchivo;
    String uri;

    try {
        User user = PortalUtil.getUser(request);

        if (user == null) {
            String userId = null;
            String companyId = null;
            Cookie[] cookies = ((HttpServletRequest) request).getCookies();
            if (Validator.isNotNull(cookies)) {
                for (Cookie c : cookies) {
                    if ("COMPANY_ID".equals(c.getName())) {
                        companyId = c.getValue();
                    } else if ("ID".equals(c.getName())) {
                        userId = hexStringToStringByAscii(c.getValue());
                    }
                }
            }

            if (userId != null && companyId != null) {
                try {
                    Company company = CompanyLocalServiceUtil.getCompany(Long.parseLong(companyId));
                    Key key = company.getKeyObj();

                    String userIdPlain = Encryptor.decrypt(key, userId);

                    user = UserLocalServiceUtil.getUser(Long.valueOf(userIdPlain));

                    // Now you can set the liferayUser into a thread local
                    // for later use or
                    // something like that.

                } catch (Exception pException) {
                    throw new RuntimeException(pException);
                }
            }
        }

        String rutaDatos = SCORMContentLocalServiceUtil.getBaseDir();

        // Se comprueba que el usuario tiene permisos para acceder.
        // Damos acceso a todo el mundo al directorio "personalizacion",
        // para permitir mostrar a todos la pantalla de identificacion.
        uri = URLDecoder.decode(request.getRequestURI(), "UTF-8");
        uri = uri.substring(uri.indexOf("scorm/") + "scorm/".length());
        patharchivo = rutaDatos + "/" + uri;

        String[] params = uri.split("/");
        long groupId = GetterUtil.getLong(params[1]);
        String uuid = params[2];
        SCORMContent scormContent = SCORMContentLocalServiceUtil.getSCORMContentByUuidAndGroupId(uuid, groupId);

        boolean allowed = false;
        if (user == null) {
            user = UserLocalServiceUtil.getDefaultUser(PortalUtil.getDefaultCompanyId());
        }
        PermissionChecker pc = PermissionCheckerFactoryUtil.create(user);
        allowed = pc.hasPermission(groupId, SCORMContent.class.getName(), scormContent.getScormId(),
                ActionKeys.VIEW);
        if (!allowed) {
            AssetEntry scormAsset = AssetEntryLocalServiceUtil.getEntry(SCORMContent.class.getName(),
                    scormContent.getPrimaryKey());
            long scormAssetId = scormAsset.getEntryId();
            int typeId = new Long((new SCORMLearningActivityType()).getTypeId()).intValue();
            long[] groupIds = user.getGroupIds();
            for (long gId : groupIds) {
                List<LearningActivity> acts = LearningActivityLocalServiceUtil
                        .getLearningActivitiesOfGroupAndType(gId, typeId);
                for (LearningActivity act : acts) {
                    String entryId = LearningActivityLocalServiceUtil.getExtraContentValue(act.getActId(),
                            "assetEntry");
                    if (Validator.isNotNull(entryId) && Long.valueOf(entryId) == scormAssetId) {
                        allowed = pc.hasPermission(gId, LearningActivity.class.getName(), act.getActId(),
                                ActionKeys.VIEW);
                        if (allowed) {
                            break;
                        }
                    }
                }
                if (allowed) {
                    break;
                }
            }

        }
        if (allowed) {

            File archivo = new File(patharchivo);

            // Si el archivo existe y no es un directorio se sirve. Si no,
            // no se hace nada.
            if (archivo.exists() && archivo.isFile()) {

                // El content type siempre antes del printwriter
                mime_type = MimeTypesUtil.getContentType(archivo);
                charset = "";
                if (archivo.getName().toLowerCase().endsWith(".html")
                        || archivo.getName().toLowerCase().endsWith(".htm")) {
                    mime_type = "text/html";
                    if (isISO(FileUtils.readFileToString(archivo))) {
                        charset = "ISO-8859-1";
                    }
                }
                if (archivo.getName().toLowerCase().endsWith(".swf")) {
                    mime_type = "application/x-shockwave-flash";
                }
                if (archivo.getName().toLowerCase().endsWith(".mp4")) {
                    mime_type = "video/mp4";
                }
                if (archivo.getName().toLowerCase().endsWith(".flv")) {
                    mime_type = "video/x-flv";
                }
                response.setContentType(mime_type);
                if (Validator.isNotNull(charset)) {
                    response.setCharacterEncoding(charset);

                }
                response.addHeader("Content-Type",
                        mime_type + (Validator.isNotNull(charset) ? "; " + charset : ""));
                /*if (archivo.getName().toLowerCase().endsWith(".swf")
                      || archivo.getName().toLowerCase().endsWith(".flv")) {
                   response.addHeader("Content-Length",
                String.valueOf(archivo.length()));
                }
                */
                if (archivo.getName().toLowerCase().endsWith("imsmanifest.xml")) {
                    FileInputStream fis = new FileInputStream(patharchivo);

                    String sco = ParamUtil.get(request, "scoshow", "");
                    Document manifest = SAXReaderUtil.read(fis);
                    if (sco.length() > 0) {

                        Element organizatEl = manifest.getRootElement().element("organizations")
                                .element("organization");
                        Element selectedItem = selectItem(organizatEl, sco);
                        if (selectedItem != null) {
                            selectedItem.detach();
                            java.util.List<Element> items = organizatEl.elements("item");
                            for (Element item : items) {

                                organizatEl.remove(item);
                            }
                            organizatEl.add(selectedItem);
                        }
                    }
                    //clean unused resources.
                    Element resources = manifest.getRootElement().element("resources");
                    java.util.List<Element> theResources = resources.elements("resource");
                    Element organizatEl = manifest.getRootElement().element("organizations")
                            .element("organization");
                    java.util.List<String> identifiers = getIdentifierRefs(organizatEl);
                    for (Element resource : theResources) {
                        String identifier = resource.attributeValue("identifier");
                        if (!identifiers.contains(identifier)) {
                            resources.remove(resource);
                        }
                    }
                    response.getWriter().print(manifest.asXML());
                    fis.close();
                    return;

                }

                if (mime_type.startsWith("text") || mime_type.endsWith("javascript")
                        || mime_type.equals("application/xml")) {

                    java.io.OutputStream out = response.getOutputStream();
                    FileInputStream fis = new FileInputStream(patharchivo);

                    byte[] buffer = new byte[512];
                    int i = 0;

                    while (fis.available() > 0) {
                        i = fis.read(buffer);
                        if (i == 512)
                            out.write(buffer);
                        else
                            out.write(buffer, 0, i);

                    }

                    fis.close();
                    out.flush();
                    out.close();
                    return;
                }
                //If not manifest
                String fileName = archivo.getName();
                long length = archivo.length();
                long lastModified = archivo.lastModified();
                String eTag = fileName + "_" + length + "_" + lastModified;
                long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }
                long ifModifiedSince = request.getDateHeader("If-Modified-Since");
                if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }

                // If-Match header should contain "*" or ETag. If not, then return 412.
                String ifMatch = request.getHeader("If-Match");
                if (ifMatch != null && !matches(ifMatch, eTag)) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return;
                }

                // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
                long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
                if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return;
                }

                // Validate and process range -------------------------------------------------------------

                // Prepare some variables. The full Range represents the complete file.
                Range full = new Range(0, length - 1, length);
                List<Range> ranges = new ArrayList<Range>();

                // Validate and process Range and If-Range headers.
                String range = request.getHeader("Range");
                if (range != null) {

                    // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
                    if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
                        response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                        return;
                    }

                    // If-Range header should either match ETag or be greater then LastModified. If not,
                    // then return full file.
                    String ifRange = request.getHeader("If-Range");
                    if (ifRange != null && !ifRange.equals(eTag)) {
                        try {
                            long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                            if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                                ranges.add(full);
                            }
                        } catch (IllegalArgumentException ignore) {
                            ranges.add(full);
                        }
                    }

                    // If any valid If-Range header, then process each part of byte range.
                    if (ranges.isEmpty()) {
                        for (String part : range.substring(6).split(",")) {
                            // Assuming a file with length of 100, the following examples returns bytes at:
                            // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                            long start = sublong(part, 0, part.indexOf("-"));
                            long end = sublong(part, part.indexOf("-") + 1, part.length());

                            if (start == -1) {
                                start = length - end;
                                end = length - 1;
                            } else if (end == -1 || end > length - 1) {
                                end = length - 1;
                            }

                            // Check if Range is syntactically valid. If not, then return 416.
                            if (start > end) {
                                response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                                return;
                            }

                            // Add range.
                            ranges.add(new Range(start, end, length));
                        }
                    }
                }
                boolean acceptsGzip = false;
                String disposition = "inline";

                if (mime_type.startsWith("text")) {
                    //String acceptEncoding = request.getHeader("Accept-Encoding");
                    // acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
                    // mime_type += ";charset=UTF-8";
                }

                // Else, expect for images, determine content disposition. If content type is supported by
                // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
                else if (!mime_type.startsWith("image")) {
                    String accept = request.getHeader("Accept");
                    disposition = accept != null && accepts(accept, mime_type) ? "inline" : "attachment";
                }

                // Initialize response.
                response.reset();
                response.setBufferSize(DEFAULT_BUFFER_SIZE);
                response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("ETag", eTag);
                response.setDateHeader("Last-Modified", lastModified);
                response.setDateHeader("Expires", expires);

                // Send requested file (part(s)) to client ------------------------------------------------

                // Prepare streams.
                RandomAccessFile input = null;
                OutputStream output = null;

                try {
                    // Open streams.
                    input = new RandomAccessFile(archivo, "r");
                    output = response.getOutputStream();

                    if (ranges.isEmpty() || ranges.get(0) == full) {

                        // Return full file.
                        Range r = full;
                        response.setContentType(mime_type);
                        response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

                        if (content) {

                            // Content length is not directly predictable in case of GZIP.
                            // So only add it if there is no means of GZIP, else browser will hang.
                            response.setHeader("Content-Length", String.valueOf(r.length));

                            // Copy full range.
                            copy(input, output, r.start, r.length);
                        }

                    } else if (ranges.size() == 1) {

                        // Return single part of file.
                        Range r = ranges.get(0);
                        response.setContentType(mime_type);
                        response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
                        response.setHeader("Content-Length", String.valueOf(r.length));
                        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                        if (content) {
                            // Copy single part range.
                            copy(input, output, r.start, r.length);
                        }

                    } else {

                        // Return multiple parts of file.
                        response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
                        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                        if (content) {
                            // Cast back to ServletOutputStream to get the easy println methods.
                            ServletOutputStream sos = (ServletOutputStream) output;

                            // Copy multi part range.
                            for (Range r : ranges) {
                                // Add multipart boundary and header fields for every range.
                                sos.println();
                                sos.println("--" + MULTIPART_BOUNDARY);
                                sos.println("Content-Type: " + mime_type);
                                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                                // Copy single part range of multi part range.
                                copy(input, output, r.start, r.length);
                            }

                            // End with multipart boundary.
                            sos.println();
                            sos.println("--" + MULTIPART_BOUNDARY + "--");
                        }
                    }
                } finally {
                    // Gently close streams.
                    close(output);
                    close(input);
                }
            } else {
                //java.io.OutputStream out = response.getOutputStream();
                response.sendError(404);
                //out.write(uri.getBytes());
            }
        } else {
            response.sendError(401);
        }
    } catch (Exception e) {
        System.out.println("Error en el processRequest() de ServidorArchivos: " + e.getMessage());
    }
}

From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Post request/*ww  w .j av a 2  s.  c  om*/
 ***************************************************************************/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    boolean checkedContent = false;
    boolean legend = false;
    String strErrorMessage = "";
    String serverUrl = request.getParameter("url");
    log.info("POST param serverUrl: " + serverUrl);
    if (serverUrl.startsWith("legend")) {
        serverUrl = serverUrl.replace("legend", "");
        serverUrl = serverUrl.replace("?", "&");
        serverUrl = serverUrl.replaceFirst("&", "?");
        legend = true;
    }
    serverUrl = checkTypeRequest(serverUrl);
    // log.info("serverUrl ckecked: " + serverUrl);
    if (!serverUrl.equals("ERROR")) {
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            PostMethod httppost = null;
            try {
                if (log.isDebugEnabled()) {
                    Enumeration<?> e = request.getHeaderNames();
                    while (e.hasMoreElements()) {
                        String name = (String) e.nextElement();
                        String value = request.getHeader(name);
                        log.debug("request header:" + name + ":" + value);
                    }
                }
                HttpClient client = new HttpClient();
                httppost = new PostMethod(serverUrl);
                // PATH
                httppost.setDoAuthentication(false);
                httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler(3, false));
                // FIN_PATH
                // PATH_MAPEAEDITA_SECURITY - AP
                // PATCH_TICKET_MJM-20112405-POST
                String authorizationValue = request.getHeader(AUTHORIZATION); // ADD_SECURITY_20091210
                if (authorizationValue == null) {
                    // The 'Authorization' header must be in this form ->
                    // Authorization: Basic <encodedLogin>
                    // 'encodedLogin' is a string in the form 'user:pass'
                    // that has been encoded by way of the Base64 algorithm.
                    // More info on this can be found at
                    // http://en.wikipedia.org/wiki/Basic_access_authentication
                    String user = (String) request.getSession().getAttribute("user");
                    String pass = (String) request.getSession().getAttribute("pass");
                    if (user != null && pass != null) {
                        String userAndPass = user + ":" + pass;
                        String encodedLogin = new String(
                                org.apache.commons.codec.binary.Base64.encodeBase64(userAndPass.getBytes()));
                        httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin);
                    } else { // MJM - 20110520
                        String ticketParameter = request.getParameter("ticket");
                        if (ticketParameter != null) {
                            ticketParameter = ticketParameter.trim();
                            if (!ticketParameter.isEmpty()) {
                                Ticket ticket = TicketFactory.createInstance();
                                try {
                                    Map<String, String> props = ticket.getProperties(ticketParameter);
                                    user = props.get("user");
                                    pass = props.get("pass");
                                    String userAndPass = user + ":" + pass;
                                    String encodedLogin = new String(org.apache.commons.codec.binary.Base64
                                            .encodeBase64(userAndPass.getBytes()));
                                    httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin);
                                } catch (Exception e) {
                                    log.info("-------------------------------------------");
                                    log.info("EXCEPCTION THROWED BY PROXYREDIRECT CLASS");
                                    log.info("METHOD: doPost");
                                    log.info("TICKET VALUE: " + ticketParameter);
                                    log.info("-------------------------------------------");
                                }
                            }
                        }
                    }
                } else {
                    httppost.addRequestHeader(AUTHORIZATION, authorizationValue);
                }
                // FIN_PATH_TICKET_MJM-20112405-POST
                // FIN_PATH_MAPEAEDITA_SECURITY - AP
                String body = inputStreamAsString(request.getInputStream());
                StringRequestEntity bodyEntity = new StringRequestEntity(body, null, null);
                if (0 == httppost.getParameters().length) {
                    log.debug("No Name/Value pairs found ... pushing as received"); // PATCH
                    httppost.setRequestEntity(bodyEntity); // PATCH
                }
                if (log.isDebugEnabled()) {
                    log.debug("Body = " + body);
                    NameValuePair[] nameValuePairs = httppost.getParameters();
                    log.debug("NameValuePairs found: " + nameValuePairs.length);
                    for (int i = 0; i < nameValuePairs.length; ++i) {
                        log.debug("parameters:" + nameValuePairs[i].toString());
                    }
                }
                if (!legend)
                    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
                if (soap) {
                    httppost.addRequestHeader("SOAPAction", serverUrl);
                }
                client.executeMethod(httppost);
                // PATH_FOLLOW_REDIRECT_POST
                int j = 0;
                String redirectLocation;
                Header locationHeader = httppost.getResponseHeader("location");
                while (locationHeader != null && j < numMaxRedirects) {
                    redirectLocation = locationHeader.getValue();
                    // AGG 20111304 Aadimos el cuerpo de la peticin POST a
                    // la nueva peticin redirigida
                    // String bodyPost = httppost.getResponseBodyAsString();
                    StringRequestEntity bodyEntityPost = new StringRequestEntity(body, null, null);
                    httppost.releaseConnection();
                    httppost = new PostMethod(redirectLocation);
                    // AGG 20110912 Aadidas cabeceras peticin SOAP
                    if (redirectLocation.toLowerCase().contains("wsdl")) {
                        redirectLocation = serverUrl.replace("?wsdl", "");
                        httppost.addRequestHeader("SOAPAction", redirectLocation);
                        httppost.addRequestHeader("Content-type", "text/xml");
                    }
                    httppost.setRequestEntity(bodyEntityPost);
                    client.executeMethod(httppost);
                    locationHeader = httppost.getResponseHeader("location");
                    j++;
                }
                log.info("Number of followed redirections: " + j);
                if (locationHeader != null && j == numMaxRedirects) {
                    log.error("The maximum number of redirects (" + numMaxRedirects + ") is exceed.");
                }
                // FIN_PATH_FOLLOW_REDIRECT_POST
                if (log.isDebugEnabled()) {
                    Header[] responseHeaders = httppost.getResponseHeaders();
                    for (int i = 0; i < responseHeaders.length; ++i) {
                        String headerName = responseHeaders[i].getName();
                        String headerValue = responseHeaders[i].getValue();
                        log.debug("responseHeaders:" + headerName + "=" + headerValue);
                    }
                }
                // dump response to out
                if (httppost.getStatusCode() == HttpStatus.SC_OK) {
                    // PATH_SECURITY_PROXY - AG
                    Header[] respHeaders = httppost.getResponseHeaders();
                    int compSize = httppost.getResponseBody().length;
                    ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(respHeaders));
                    String headersString = headerList.toString();
                    checkedContent = checkContent(headersString, compSize, serverUrl);
                    // FIN_PATH_SECURITY_PROXY - AG
                    if (checkedContent == true) {
                        /*
                         * checks if it has requested an getfeatureinfo to modify the response content
                         * type.
                         */
                        String requesteredUrl = request.getParameter("url");
                        if (GETINFO_PLAIN_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/plain");
                        } else if (GETINFO_GML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("application/gml+xml");
                        } else if (GETINFO_HTML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/html");
                        } else if (requesteredUrl.toLowerCase().contains("mapeaop=geosearch")
                                || requesteredUrl.toLowerCase().contains("mapeaop=geoprint")) {
                            response.setContentType("application/json");
                        } else {
                            response.setContentType("text/xml");
                        }
                        if (legend) {
                            String responseBody = httppost.getResponseBodyAsString();
                            if (responseBody.contains("ServiceExceptionReport")
                                    && serverUrl.contains("LegendGraphic")) {
                                response.sendRedirect("Componente/img/blank.gif");
                            } else {
                                response.setContentLength(responseBody.length());
                                PrintWriter out = response.getWriter();
                                out.print(responseBody);
                                response.flushBuffer();
                            }
                        } else {
                            // Patch_AGG 20112505 Prevents IE cache
                            if (request.getProtocol().compareTo("HTTP/1.0") == 0) {
                                response.setHeader("Pragma", "no-cache");
                            } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) {
                                response.setHeader("Cache-Control", "no-cache");
                            }
                            response.setDateHeader("Expires", -1);
                            // END patch
                            // Copy request to response
                            InputStream st = httppost.getResponseBodyAsStream();
                            final ServletOutputStream sos = response.getOutputStream();
                            IOUtils.copy(st, sos);
                        }
                    } else {
                        strErrorMessage += errorType;
                        log.error(strErrorMessage);
                    }
                } else if (httppost.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                    response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                    response.addHeader(WWW_AUTHENTICATE,
                            httppost.getResponseHeader(WWW_AUTHENTICATE).getValue());
                } else {
                    strErrorMessage = "Unexpected failure: ".concat(httppost.getStatusLine().toString())
                            .concat(" ").concat(httppost.getResponseBodyAsString());
                    log.error("Unexpected failure: " + httppost.getStatusLine().toString());
                }
                httppost.releaseConnection();
                // AGG 20110927 Avoid Throwable (change it with exceptions)
            } catch (Exception e) {
                log.error("Error al tratar el contenido de la peticion: " + e.getMessage(), e);
            } finally {
                if (httppost != null) {
                    httppost.releaseConnection();
                }
            }
        } else {
            strErrorMessage += "Only HTTP(S) protocol supported";
            log.error("Only HTTP(S) protocol supported");
            // throw new
            // ServletException("only HTTP(S) protocol supported");
        }
    }
    // There are errors.
    if (!strErrorMessage.equals("") || serverUrl.equals("ERROR")) {
        if (strErrorMessage.equals("") == true) {
            strErrorMessage = "Error en el parametro url de entrada";
        }
        // String errorXML = strErrorMessage;
        String errorXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><descripcion>" + strErrorMessage
                + "</descripcion></error>";
        response.setContentType("text/xml");
        try {
            PrintWriter out = response.getWriter();
            out.print(errorXML);
            response.flushBuffer();
        } catch (Exception e) {
            log.error(e);
        }
    }
    log.info("-------- End POST method --------");
}

From source file:com.icb123.Controller.BusinessController.java

@RequestMapping(value = "/appoint")
public void customerAppointment(HttpServletRequest request, HttpServletResponse response) {
    try {/*from ww w .ja v a2 s.c  o m*/
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Constants.root = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String sysRootPath = request.getSession().getServletContext().getRealPath("\\");
        SystemStaticArgsSet.setSysRootPath(sysRootPath);
        String requestType = request.getParameter("requestType") == null ? ""
                : request.getParameter("requestType");
        String userCode = request.getParameter("userCode") == null ? "" : request.getParameter("userCode");
        String openid = request.getParameter("openid") == null ? "" : request.getParameter("openid");
        //openid="111111";
        if (StringUtils.isBlank(openid) && StringUtils.isNotBlank(userCode)) {
            openid = WeixinUntil.getUserOoenid(userCode);
        }
        if (weixinCustomerManager.findByOpenid(openid) == null) {
            String accessToken = WeixinUntil.getAccessToken();
            WeixinCustomer wx = customerBusinessManager.getCustomerInfo(openid, accessToken, "");
            weixinCustomerManager.save(wx);
        }
        //System.out.println(PropertiesUtils.getValueByKey("token"));
        Employee emp = (Employee) request.getSession().getAttribute("Employee");
        String empCode = "";
        if (emp != null) {
            empCode = emp.getCode();
        } else {
            if (!"".equals(openid)) {
                empCode = employeeManager.findEmployeeCodeByOpenid(openid);
            }
        }
        if ("1".equals(requestType)) {//
            String paramObj = request.getParameter("paramObj");
            JSONObject json = JSONObject.fromObject(paramObj);
            JSONArray arr = (JSONArray) json.get("service");
            String[] serviceArray = new String[arr.size()];
            serviceArray = (String[]) arr.toArray(serviceArray);
            Map<String, String> result = null;
            if (StringUtils.isNotBlank((String) json.get("userCode"))) {
                openid = WeixinUntil.getUserOoenid((String) json.get("userCode"));
            } else {
                openid = null;
            }
            try {
                result = businessManager.appointmentMaintenance((String) json.get("date"),
                        (String) json.get("timeCode"), (String) json.get("mobile"), (String) json.get("name"),
                        openid, (String) json.get("carCode"), (String) json.get("license"),
                        (String) json.get("code"), (String) json.get("totalPrice"),
                        (String) json.get("address"), (String) json.get("remark"),
                        (String) json.get("appTypeCode"), (String) json.get("type"), serviceArray);
            } catch (Exception e) {
                outPutErrorInfor(BusinessController.class.getName(), "", e);
            }
            OutputUtil.outPutJsonObject(response, result);
        } else if ("2".equals(requestType)) {//         
            String status = request.getParameter("status") == null ? "" : request.getParameter("status");
            String currentPageStr = request.getParameter("currentPage") == null ? ""
                    : request.getParameter("currentPage");
            String sizeStr = request.getParameter("pageSize") == null ? "" : request.getParameter("pageSize");
            String ctime = request.getParameter("ctime") == null ? "" : request.getParameter("ctime");
            String mobile = request.getParameter("smobile") == null ? "" : request.getParameter("smobile");
            String atime = request.getParameter("atime") == null ? "" : request.getParameter("atime");
            try {
                Map<String, String> argMap = new HashMap<String, String>();
                argMap.put("status", status);
                if (StringUtils.isNotBlank(currentPageStr) && StringUtils.isNotBlank(sizeStr)) {
                    int currentPage = Integer.valueOf(currentPageStr);
                    int size = Integer.valueOf(sizeStr);
                    int begin = (currentPage - 1) * size;
                    argMap.put("size", size + "");
                    argMap.put("begin", begin + "");
                    argMap.put("currentPage", currentPageStr);
                    argMap.put("ctime", ctime);
                    argMap.put("atime", atime);
                    argMap.put("mobile", mobile);
                }
                PageBean page = businessManager.selectAppointment(argMap);
                OutputUtil.outPutJsonObject(response, page);
            } catch (Exception e) {
                outPutErrorInfor(BusinessController.class.getName(), "?", e);
            }
        } else if ("3".equals(requestType)) {//
            String appcode = request.getParameter("code") == null ? "" : request.getParameter("code");
            Map map = businessManager.findDetailedAppointment(appcode);
            OutputUtil.outPutJsonObject(response, map);
        } else if ("4".equals(requestType)) {//
            String paramObj = request.getParameter("paramObj");
            JSONObject json = JSONObject.fromObject(paramObj);
            JSONArray arr = (JSONArray) json.get("service");
            String[] serviceArray = new String[arr.size()];
            serviceArray = (String[]) arr.toArray(serviceArray);
            Map<String, String> result = null;
            try {
                result = businessManager.appointmentConfirm((String) json.get("timeCode"),
                        (String) json.get("date"), (String) json.get("time"), (String) json.get("carCode"),
                        (String) json.get("license"), (String) json.get("haveCar"),
                        (String) json.get("modelsCode"), (String) json.get("modelsStr"),
                        (String) json.get("cusCode"), (String) json.get("mobile"), (String) json.get("name"),
                        (String) json.get("address"), (String) json.get("code"), (String) json.get("remark"),
                        (String) json.get("totalPrice"), serviceArray, emp.getCode(),
                        (String) json.get("status"), (String) json.get("wxCode"));
            } catch (Exception e) {
                outPutErrorInfor(BusinessController.class.getName(), "", e);
            }
            OutputUtil.outPutJsonObject(response, result);
        } else if ("5".equals(requestType)) {//?
            String appcode = request.getParameter("code") == null ? "" : request.getParameter("code");
            String reason = request.getParameter("reason") == null ? "" : request.getParameter("reason");
            Map<String, String> result = businessManager.appointmentCancel(appcode, empCode, reason);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("6".equals(requestType)) {//?
            String date = request.getParameter("date") == null ? "" : request.getParameter("date");
            String time = request.getParameter("time") == null ? "" : request.getParameter("time");
            List<Team> list = businessManager.findFreeTeam(date, time);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("7".equals(requestType)) {//
            String appCode = request.getParameter("appCode") == null ? "" : request.getParameter("appCode");
            String teamCode = request.getParameter("teamCode") == null ? "" : request.getParameter("teamCode");
            String[] empArr = request.getParameterValues("emp");
            Map<String, String> result = businessManager.distributeWork(appCode, empCode, teamCode, empArr);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("8".equals(requestType)) {//
            String currentPageStr = request.getParameter("currentPage") == null ? ""
                    : request.getParameter("currentPage");
            String sizeStr = request.getParameter("pageSize") == null ? "" : request.getParameter("pageSize");
            try {
                Map<String, String> argMap = new HashMap<String, String>();
                argMap.put("empCode", empCode);
                if (StringUtils.isNotBlank(currentPageStr) && StringUtils.isNotBlank(sizeStr)) {
                    int currentPage = Integer.valueOf(currentPageStr);
                    int size = Integer.valueOf(sizeStr);
                    int begin = (currentPage - 1) * size;
                    argMap.put("size", size + "");
                    argMap.put("begin", begin + "");
                    argMap.put("currentPage", currentPageStr);
                }
                PageBean page = businessManager.selectPersonalAppointment(argMap);
                OutputUtil.outPutJsonObject(response, page);
            } catch (Exception e) {
                outPutErrorInfor(BusinessController.class.getName(), "", e);
            }
        } else if ("9".equals(requestType)) {//
            String empcode = request.getParameter("code") == null ? "" : request.getParameter("code");
            String position = request.getParameter("position") == null ? "" : request.getParameter("position");
            List<Employee> list = businessManager.findFreeEmp(empcode, position);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("10".equals(requestType)) {//?
            String appcode = request.getParameter("code") == null ? "" : request.getParameter("code");
            Map<String, String> result = businessManager.daleteDistributeWork(appcode, empCode);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("11".equals(requestType)) {//?
            String appcode = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<WorkRecord> list = workRecordManager.findByAppCode(appcode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("12".equals(requestType)) {//???
            String mobile = request.getParameter("mobile") == null ? "" : request.getParameter("mobile");
            Map<String, String> result = sendManager.mobileValidate(mobile);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("13".equals(requestType)) {//?
            String mobile = request.getParameter("mobile") == null ? "" : request.getParameter("mobile");
            String validate = request.getParameter("validate") == null ? "" : request.getParameter("validate");
            Map<String, String> result = businessManager.mobileValidate(mobile, validate);//?
            OutputUtil.outPutJsonObject(response, result);
        } else if ("14".equals(requestType)) {//??
            /*String model=request.getParameter("model") == null ? "": request.getParameter("model");
            String appcode=request.getParameter("code") == null ? "": request.getParameter("code");
            String weixinCode=request.getParameter("weixinCode") == null ? "": request.getParameter("weixinCode");
            Map<String, String> result=businessManager.writeAccessoriesModel(appcode,model,weixinCode);
            OutputUtil.outPutJsonObject(response, result);*/
        } else if ("15".equals(requestType)) {//
            String appcode = request.getParameter("code") == null ? "" : request.getParameter("code");
            String vipCondition = request.getParameter("condition") == null ? ""
                    : request.getParameter("condition");
            Map<String, String> result = businessManager.finishAppointment(appcode, vipCondition);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("16".equals(requestType)) {//??
            String kfpwd = "qweasd";
            String validate = request.getParameter("code") == null ? "" : request.getParameter("code");
            Map<String, String> result = new HashMap<String, String>();
            if (validate.equals(kfpwd)) {
                result.put("flag", "1");
            } else {
                result.put("flag", "-1");
            }
            OutputUtil.outPutJsonObject(response, result);
        } else if ("17".equals(requestType)) {//???
            String mobile = request.getParameter("mobile") == null ? "" : request.getParameter("mobile");
            List<Map<String, Object>> result = businessManager
                    .searchCustomerPensonalAppointmentByMobile(mobile);
            OutputUtil.outPutJsonArrary(response, result);
        } else if ("18".equals(requestType)) {
            //?  
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "No-cache");
            response.setDateHeader("Expires", 0);
            //?  
            response.setContentType("image/jpeg");
            IdentifyingImg img = new IdentifyingImg();
            ImageIO.write(img.creat(), "JPEG", response.getOutputStream());
        } else if ("19".equals(requestType)) {//??
            Map<String, Object> map = weixinCustomerManager.findCustomerInfo(openid);
            OutputUtil.outPutJsonObject(response, map);
        } else if ("20".equals(requestType)) {//????
            List<Map> result = businessManager.findCurrentAppByOpenid(openid);
            OutputUtil.outPutJsonArrary(response, result);
        } else if ("21".equals(requestType)) {//???
            //List<Map> result=businessManager.searchCustomerPensonalAppointmentByOpenid(openid);
            List<CustomerCar> result = businessManager.findHistoryCar(openid);
            OutputUtil.outPutJsonArrary(response, result);
        } else if ("22".equals(requestType)) {//??
            Map<String, String> result = new HashMap<String, String>();
            String path = weixinCustomerManager.creatEwmByWeixinCustomer(openid);
            result.put("path", path);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("23".equals(requestType)) {//???   
            Map<String, String> result = null;
            Customer cus = customerManager.findCustomerByOpenid(openid);
            if (cus != null) {
                result = new HashMap<String, String>();
                result.put("name", cus.getName());
                result.put("mobile", cus.getMobile());
            }
            OutputUtil.outPutJsonObject(response, result);
        } else if ("24".equals(requestType)) {//??
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String mobile = request.getParameter("mobile") == null ? "" : request.getParameter("mobile");
            Map<String, String> result = weixinCustomerManager.saveCustomerInfo(openid, name, mobile);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("25".equals(requestType)) {//??
            List<Map> result = businessManager.findCurrentCar(openid);
            OutputUtil.outPutJsonArrary(response, result);
        } else if ("26".equals(requestType)) {//?
            List<Map<String, String>> list = weixinCustomerManager.findConsumptionRecordByOpenid(openid);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("27".equals(requestType)) {//??
            String busnessType = request.getParameter("type") == null ? "" : request.getParameter("type");
            String totalPrice = request.getParameter("totalPrice") == null ? ""
                    : request.getParameter("totalPrice");
            double pay = integralManager.maxOutIntegral(openid, Integer.valueOf(busnessType),
                    Double.valueOf(totalPrice));
            Map<String, String> map = new HashMap<String, String>();
            map.put("pay", (int) pay + "");
            OutputUtil.outPutJsonObject(response, map);
        } else if ("28".equals(requestType)) {//
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            String busnessType = request.getParameter("type") == null ? "" : request.getParameter("type");
            String pay = request.getParameter("pay") == null ? "" : request.getParameter("pay");
            Map<String, String> map = businessManager.integralPay(code, openid, busnessType, pay);
            OutputUtil.outPutJsonObject(response, map);
        } else if ("29".equals(requestType)) {//?
            String date = request.getParameter("date") == null ? "" : request.getParameter("date");
            List<AppointmentTime> list = businessManager.findAppTime(date);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("30".equals(requestType)) {//?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            String score = request.getParameter("scorce") == null ? "" : request.getParameter("scorce");
            Map<String, String> result = businessManager.saveCustomerScore(code, score);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("31".equals(requestType)) {//?
            String code = request.getParameter("weixinCode") == null ? "" : request.getParameter("weixinCode");
            Map<String, Object> result = weixinCustomerManager.openGiftView(code);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("32".equals(requestType)) {//
            String code = request.getParameter("weixinCode") == null ? "" : request.getParameter("weixinCode");
            String accept = request.getParameter("accept") == null ? "" : request.getParameter("accept");
            List<WeixinAcceptRecord> list = weixinCustomerManager.acceptGift(code, accept);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("33".equals(requestType)) {//??
            String carCdoe = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Map> list = businessManager.findHistoryAppByCarCode(carCdoe);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("100".equals(requestType)) {//???
            String paramObj = request.getParameter("paramObj") == null ? "" : request.getParameter("paramObj");
            JSONObject json = JSONObject.fromObject(paramObj);
            Map<String, String> result = businessManager.inPutFinishInfo(json, emp.getCode());
            OutputUtil.outPutJsonObject(response, result);
        } else if ("101".equals(requestType)) {//
            String appCode = request.getParameter("appCode") == null ? "" : request.getParameter("appCode");
            List<CustomerCarSituation> list = customerManager.findByAppCode(appCode);
            Map<String, List<CustomerCarSituation>> result = new HashMap<String, List<CustomerCarSituation>>();
            result.put("ccs", list);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("102".equals(requestType)) {//?
            String position = request.getParameter("position") == null ? "" : request.getParameter("position");
            List<Employee> list = employeeManager.findEmployeeByPosition(position);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("103".equals(requestType)) {//??
            String appCode = request.getParameter("appCode") == null ? "" : request.getParameter("appCode");
            List<WorkRecord> list = workRecordManager.findByAppCode(appCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("104".equals(requestType)) {//
            List<Team> list = carMaintenanceManager.findAllTeam();
            OutputUtil.outPutJsonArrary(response, list);
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        outPutErrorInfor(BusinessController.class.getName(), "?", e);
    } catch (IOException e) {
        outPutErrorInfor(BusinessController.class.getName(), "?", e);
    }
}