Example usage for org.apache.commons.lang.time DateFormatUtils formatUTC

List of usage examples for org.apache.commons.lang.time DateFormatUtils formatUTC

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateFormatUtils formatUTC.

Prototype

public static String formatUTC(Date date, String pattern) 

Source Link

Document

Formats a date/time into a specific pattern using the UTC time zone.

Usage

From source file:org.jcommon.com.facebook.utils.FacebookUtils.java

public static String formatTime(String time) {
    time = time.replaceAll("\"", "");
    Long l = Long.valueOf(time);
    time = DateFormatUtils.formatUTC(new Date(l * 1000),
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    return time;/*www  .j  a v a  2s. co  m*/
}

From source file:org.opencredo.cloud.storage.azure.rest.AzureRestServiceUtil.java

/**
 * @return Returns current time string in RFC1123 pattern.
 *///ww  w  . j a  v a  2  s  .c o m
public static String currentTimeStringInRFC1123() {
    return DateFormatUtils.formatUTC(System.currentTimeMillis(), RFC1123_DATE_PATTERN);
}

From source file:org.waterforpeople.mapping.app.web.KMLGenerator.java

private HashMap<String, String> loadContextBindings(AccessPoint waterAP, AccessPoint sanitationAP) {
    // log.info(waterAP.getCommunityCode());
    try {//  w  w  w .j a v a2 s  .c o m
        HashMap<String, String> contextBindingsMap = new HashMap<String, String>();
        if (waterAP.getCollectionDate() != null) {
            String timestamp = DateFormatUtils.formatUTC(waterAP.getCollectionDate(),
                    DateFormatUtils.ISO_DATE_FORMAT.getPattern());
            String formattedDate = DateFormat.getDateInstance(DateFormat.SHORT)
                    .format(waterAP.getCollectionDate());
            contextBindingsMap.put("collectionDate", formattedDate);
            contextBindingsMap.put("timestamp", timestamp);
            String collectionYear = new SimpleDateFormat("yyyy").format(waterAP.getCollectionDate());
            contextBindingsMap.put("collectionYear", collectionYear);
        } else {
            // TODO: This block is a problem. We should never have data
            // without a collectionDate so this is a hack so it display
            // properly until I can sort out what to do with this data.
            String timestamp = DateFormatUtils.formatUTC(new Date(),
                    DateFormatUtils.ISO_DATE_FORMAT.getPattern());
            String formattedDate = DateFormat.getDateInstance(DateFormat.SHORT).format(new Date());
            contextBindingsMap.put("collectionDate", formattedDate);
            contextBindingsMap.put("timestamp", timestamp);
            String collectionYear = new SimpleDateFormat("yyyy").format(new Date());
            contextBindingsMap.put("collectionYear", collectionYear);
        }
        contextBindingsMap.put("communityCode", encodeNullDefault(waterAP.getCommunityCode(), "Unknown"));
        contextBindingsMap.put("communityName", encodeNullDefault(waterAP.getCommunityName(), "Unknown"));
        contextBindingsMap.put("typeOfWaterPointTechnology",
                encodeNullDefault(waterAP.getTypeTechnologyString(), "Unknown"));
        contextBindingsMap.put("constructionDateOfWaterPoint",
                encodeNullDefault(waterAP.getConstructionDateYear(), "Unknown"));
        contextBindingsMap.put("numberOfHouseholdsUsingWaterPoint",
                encodeNullDefault(waterAP.getNumberOfHouseholdsUsingPoint(), "Unknown"));
        contextBindingsMap.put("costPer20ML", encodeNullDefault(waterAP.getCostPer(), "Unknown"));
        contextBindingsMap.put("farthestHouseholdFromWaterPoint",
                encodeNullDefault(waterAP.getFarthestHouseholdfromPoint(), "Unknown"));
        contextBindingsMap.put("currentManagementStructureOfWaterPoint",
                encodeNullDefault(waterAP.getCurrentManagementStructurePoint(), "Unknown"));
        contextBindingsMap.put("waterSystemStatus", encodeStatusString(waterAP.getPointStatus()));
        contextBindingsMap.put("photoUrl", encodeNullDefault(waterAP.getPhotoURL(), "Unknown"));
        contextBindingsMap.put("waterPointPhotoCaption",
                encodeNullDefault(waterAP.getPointPhotoCaption(), "Unknown"));
        contextBindingsMap.put("primarySanitationTechnology",
                encodeNullDefault(sanitationAP.getTypeTechnologyString(), "Unknown"));
        contextBindingsMap.put("percentageOfHouseholdsWithImprovedSanitation",
                encodeNullDefault(sanitationAP.getNumberOfHouseholdsUsingPoint(), "Unknown"));
        contextBindingsMap.put("photoOfPrimarySanitationtechnology",
                encodeNullDefault(sanitationAP.getPhotoURL(), "Unknown"));
        contextBindingsMap.put("sanitationPhotoCaption",
                encodeNullDefault(sanitationAP.getPointPhotoCaption(), "Unknown"));
        contextBindingsMap.put("footer", encodeNullDefault(waterAP.getFooter(), "Unknown"));
        contextBindingsMap.put("longitude", encodeNullDefault(waterAP.getLongitude().toString(), "Unknown"));
        contextBindingsMap.put("latitude", encodeNullDefault(waterAP.getLatitude().toString(), "Unknown"));
        contextBindingsMap.put("altitude", encodeNullDefault(waterAP.getAltitude().toString(), "0.0"));
        contextBindingsMap.put("pinStyle", encodePinStyle(waterAP.getPointType(), waterAP.getPointStatus()));
        return contextBindingsMap;
    } catch (NullPointerException nex) {
        log.log(Level.SEVERE, "Could not load context bindings", nex);
    }
    return null;
}

From source file:org.waterforpeople.mapping.app.web.KMLGenerator.java

public String generatePlacemarks(String vmName, String countryCode, String display) {
    StringBuilder sb = new StringBuilder();
    AccessPointDao apDAO = new AccessPointDao();
    List<AccessPoint> entries = null;
    if (countryCode.equals(Constants.ALL_RESULTS))
        entries = apDAO.list(Constants.ALL_RESULTS);
    else//w w  w  .  ja v a2  s .  co m
        entries = apDAO.searchAccessPoints(countryCode, null, null, null, null, null, null, null, null, null,
                null, Constants.ALL_RESULTS);

    // loop through accessPoints and bind to variables
    int i = 0;
    try {
        for (AccessPoint ap : entries) {
            if (!ap.getPointType().equals(AccessPoint.AccessPointType.SANITATION_POINT)) {
                try {
                    VelocityContext context = new VelocityContext();
                    String pmContents = bindPlacemark(ap,
                            display.equalsIgnoreCase(GOOGLE_EARTH_DISPLAY) ? "placemarkGoogleEarth.vm"
                                    : "placemarkExternalMap.vm",
                            display, null);

                    if (ap.getCollectionDate() != null) {
                        String timestamp = DateFormatUtils.formatUTC(ap.getCollectionDate(),
                                DateFormatUtils.ISO_DATE_FORMAT.getPattern());
                        String formattedDate = DateFormat.getDateInstance(DateFormat.SHORT)
                                .format(ap.getCollectionDate());
                        context.put("collectionDate", formattedDate);
                        context.put("timestamp", timestamp);
                        String collectionYear = new SimpleDateFormat("yyyy").format(ap.getCollectionDate());
                        context.put("collectionYear", collectionYear);
                    } else {
                        String timestamp = DateFormatUtils.formatUTC(new Date(),
                                DateFormatUtils.ISO_DATE_FORMAT.getPattern());
                        String formattedDate = DateFormat.getDateInstance(DateFormat.SHORT).format(new Date());
                        context.put("collectionDate", formattedDate);
                        context.put("timestamp", timestamp);
                    }
                    if (ap.getCommunityName() == null) {
                        context.put("communityName", "Unknown");
                    } else {
                        context.put("communityName", ap.getCommunityName());
                    }
                    if (ap.getCommunityCode() != null)
                        context.put("communityCode", ap.getCommunityCode());
                    else
                        context.put("communityCode", "Unknown" + new Date());
                    // Need to check this
                    if (ap.getPointType() != null) {
                        if (Boolean.parseBoolean(PropertyUtil.getProperty(DYNAMIC_SCORING_FLAG))) {

                        } else {
                            encodeStatusString(ap, context);
                            context.put("pinStyle", encodePinStyle(ap.getPointType(), ap.getPointStatus()));
                        }
                    } else {
                        context.put("pinStyle", "waterpushpinblk");
                    }
                    context.put("latitude", ap.getLatitude());
                    context.put("longitude", ap.getLongitude());
                    if (ap.getAltitude() == null)
                        context.put("altitude", 0.0);
                    else
                        context.put("altitude", ap.getAltitude());

                    context.put("balloon", pmContents);
                    String placemarkStr = mergeContext(context, vmName);
                    sb.append(placemarkStr);
                    i++;
                } catch (Exception e) {
                    log.log(Level.INFO, "Error generating placemarks: " + ap.getCommunityCode(), e);
                }
            }
        }
    } catch (Exception ex) {
        log.log(Level.SEVERE, "Bad access point: " + entries.get(i + 1).toString());
    }
    return sb.toString();
}

From source file:org.waterforpeople.mapping.app.web.KMLGenerator.java

public String bindPlacemark(SurveyedLocale ap, String vmName, String display) throws Exception {
    if (ap.getCountryCode() == null) {
        ap.setCountryCode("Unknown");
    }// www  .j a  v a2  s .co  m

    VelocityContext context = new VelocityContext();
    context.put("organization", ORGANIZATION);
    if (display != null) {
        context.put("display", display);
    }
    context.put("countryCode", ap.getCountryCode());
    if (ap.getLastSurveyedDate() != null) {
        String timestamp = DateFormatUtils.formatUTC(ap.getLastSurveyedDate(),
                DateFormatUtils.ISO_DATE_FORMAT.getPattern());
        String formattedDate = null;
        if ("true".equals(useLongDates)) {
            formattedDate = LONG_DATE_FORMAT.get().format(ap.getLastSurveyedDate());
        } else {
            formattedDate = DateFormat.getDateInstance(DateFormat.SHORT).format(ap.getLastSurveyedDate());
        }
        context.put("collectionDate", formattedDate);
        context.put("timestamp", timestamp);
        String collectionYear = new SimpleDateFormat("yyyy").format(ap.getLastSurveyedDate());
        context.put("collectionYear", collectionYear);
    } else {
        String timestamp = DateFormatUtils.formatUTC(ap.getCreatedDateTime(),
                DateFormatUtils.ISO_DATE_FORMAT.getPattern());
        String formattedDate = null;
        if ("true".equals(useLongDates)) {
            formattedDate = LONG_DATE_FORMAT.get().format(ap.getCreatedDateTime());
        } else {
            formattedDate = DateFormat.getDateInstance(DateFormat.SHORT).format(ap.getCreatedDateTime());
        }
        context.put("collectionDate", formattedDate);
        context.put("timestamp", timestamp);
    }

    if (ap.getIdentifier() != null) {
        context.put("identifier", ap.getIdentifier());
    } else {
        context.put("identifier", "Unknown" + new Date());
    }

    boolean foundPhoto = false;
    boolean foundStatus = false;
    if (ap.getSurveyalValues() != null) {
        // TODO: handle case where we have multiple values (with different
        // dates) for same question/metric
        List<SurveyalValue> valuesToBind = new ArrayList<SurveyalValue>(ap.getSurveyalValues());
        for (SurveyalValue val : ap.getSurveyalValues()) {
            if (val.getQuestionType() != null) {
                if (!"free_text".equalsIgnoreCase(val.getQuestionType())
                        && !"option".equalsIgnoreCase(val.getQuestionType())) {
                    valuesToBind.remove(val);
                }
            }
            if (val.getStringValue() == null) {
                valuesToBind.remove(val);
            } else if (val.getStringValue().trim().toLowerCase().endsWith(".jpg")
                    || val.getStringValue().trim().toLowerCase().endsWith(".jpeg")) {
                String urlBase = val.getStringValue();
                if (urlBase.contains("/")) {
                    urlBase = urlBase.substring(urlBase.lastIndexOf("/") + 1);
                }
                if (!urlBase.toLowerCase().startsWith("http")) {
                    if (urlBase.endsWith("/")) {
                        urlBase = urlBase.substring(0, urlBase.length() - 1);
                    }
                    urlBase = PropertyUtil.getProperty("photo_url_root") + urlBase;
                }
                context.put("photoUrl", urlBase);
                foundPhoto = true;
                valuesToBind.remove(val);
            } else if (ap.getCurrentStatus() == null) {
                if (val.getMetricName() != null
                        && val.getMetricName().trim().toLowerCase().contains("status")) {
                    context.put("waterSystemStatus", val.getStringValue());
                    foundStatus = true;
                }
            }
        }

        context.put("surveyalValues", valuesToBind);
    }

    if (ap.getCurrentStatus() != null) {
        try {
            context.put("waterSystemStatus",
                    encodeStatusString(AccessPoint.Status.valueOf(ap.getCurrentStatus())));
        } catch (Exception e) {
            context.put("waterSystemStatus", "Unknown");
        }
    } else {
        if (!foundStatus) {
            context.put("waterSystemStatus", "Unknown");
        }
    }
    // TODO: parameterize the default logo
    if (!foundPhoto) {
        context.put("photoUrl", "http://waterforpeople.s3.amazonaws.com/images/wfplogo.jpg");
    }

    context.put("latitude", ap.getLatitude());
    context.put("longitude", ap.getLongitude());

    if (ap.getLocaleType() != null) {
        context.put("type", ap.getLocaleType());
    } else {
        context.put("type", "water");
    }

    String output = mergeContext(context, vmName);
    context = null;
    return output;
}

From source file:org.waterforpeople.mapping.app.web.KMLGenerator.java

public String bindPlacemark(AccessPoint ap, String vmName, String display, StandardType standardType)
        throws Exception {
    // if (ap.getCountryCode() != null && !ap.getCountryCode().equals("MW"))
    // {// w  w w.  j  a v a 2  s  .c om
    if (display != null && display.trim().equalsIgnoreCase(GOOGLE_EARTH_DISPLAY)) {
        vmName = "placemarkGoogleEarth.vm";
    }
    if (ap.getCountryCode() == null)
        ap.setCountryCode("Unknown");
    if (ap.getCountryCode() != null) {

        VelocityContext context = new VelocityContext();
        context.put("organization", ORGANIZATION);
        if (display != null) {
            context.put("display", display);
        }
        context.put("countryCode", ap.getCountryCode());
        if (ap.getCollectionDate() != null) {
            String timestamp = DateFormatUtils.formatUTC(ap.getCollectionDate(),
                    DateFormatUtils.ISO_DATE_FORMAT.getPattern());
            String formattedDate = DateFormat.getDateInstance(DateFormat.SHORT).format(ap.getCollectionDate());
            context.put("collectionDate", formattedDate);
            context.put("timestamp", timestamp);
            String collectionYear = new SimpleDateFormat("yyyy").format(ap.getCollectionDate());
            context.put("collectionYear", collectionYear);
        } else {
            String timestamp = DateFormatUtils.formatUTC(ap.getCreatedDateTime(),
                    DateFormatUtils.ISO_DATE_FORMAT.getPattern());
            String formattedDate = DateFormat.getDateInstance(DateFormat.SHORT).format(ap.getCreatedDateTime());
            context.put("collectionDate", formattedDate);
            context.put("timestamp", timestamp);
        }

        if (ap.getCommunityCode() != null)
            context.put("communityCode", ap.getCommunityCode());
        else
            context.put("communityCode", "Unknown" + new Date());

        if (ap.getWaterForPeopleProjectFlag() != null) {
            context.put("waterForPeopleProject", encodeBooleanDisplay(ap.getWaterForPeopleProjectFlag()));
        } else {
            context.put("waterForPeopleProject", "null");
        }

        if (ap.getCurrentProblem() != null) {
            context.put("currentProblem", ap.getCurrentProblem());
        } else {
            context.put("currentProblem", ap.getCurrentProblem());
        }

        if (ap.getWaterForPeopleRole() != null) {
            context.put("waterForPeopleRole", ap.getWaterForPeopleRole());
        } else {
            context.put("waterForPeopleRole", "null");
        }

        if (ap.getPhotoURL() != null && ap.getPhotoURL().trim() != "")
            context.put("photoUrl", ap.getPhotoURL());
        else
            context.put("photoUrl", "http://waterforpeople.s3.amazonaws.com/images/wfplogo.jpg");
        if (ap.getPointType() != null) {
            if (ap.getPointType().equals(AccessPoint.AccessPointType.WATER_POINT)) {
                context.put("typeOfPoint", "Water");
                context.put("type", "water");
            } else if (ap.getPointType().equals(AccessPointType.SANITATION_POINT)) {
                context.put("typeOfPoint", "Sanitation");
                context.put("type", "sanitation");
            } else if (ap.getPointType().equals(AccessPointType.PUBLIC_INSTITUTION)) {
                context.put("typeOfPoint", "Public Institutions");
                context.put("type", "public_institutions");
            } else if (ap.getPointType().equals(AccessPointType.HEALTH_POSTS)) {
                context.put("typeOfPoint", "Health Posts");
                context.put("type", "health_posts");
            } else if (ap.getPointType().equals(AccessPointType.SCHOOL)) {
                context.put("typeOfPoint", "School");
                context.put("type", "school");
            }
        } else {
            context.put("typeOfPoint", "Water");
            context.put("type", "water");
        }

        if (ap.getTypeTechnologyString() == null) {
            context.put("primaryTypeTechnology", "Unknown");
        } else {
            context.put("primaryTypeTechnology", ap.getTypeTechnologyString());
        }

        if (ap.getHasSystemBeenDown1DayFlag() == null) {
            context.put("down1DayFlag", "Unknown");
        } else {
            context.put("down1DayFlag", encodeBooleanDisplay(ap.getHasSystemBeenDown1DayFlag()));
        }

        if (ap.getInstitutionName() == null) {
            context.put("institutionName", "Unknown");
        } else {
            context.put("institutionName", ap.getInstitutionName());
        }

        if (ap.getExtimatedPopulation() != null) {
            context.put("estimatedPopulation", ap.getExtimatedPopulation());
        } else {
            context.put("estimatedPopulation", "null");
        }

        if (ap.getConstructionDateYear() == null || ap.getConstructionDateYear().trim().equals("")) {
            context.put("constructionDateOfWaterPoint", "Unknown");
        } else {
            String constructionDateYear = ap.getConstructionDateYear();
            if (constructionDateYear.contains(".0")) {
                constructionDateYear = constructionDateYear.replace(".0", "");
            }
            context.put("constructionDateOfWaterPoint", constructionDateYear);
        }
        if (ap.getNumberOfHouseholdsUsingPoint() != null) {
            context.put("numberOfHouseholdsUsingWaterPoint", ap.getNumberOfHouseholdsUsingPoint());
        } else {
            context.put("numberOfHouseholdsUsingWaterPoint", "null");
        }
        if (ap.getCostPer() == null) {
            context.put("costPer", "N/A");
        } else {
            context.put("costPer", ap.getCostPer());
        }
        if (ap.getFarthestHouseholdfromPoint() == null
                || ap.getFarthestHouseholdfromPoint().trim().equals("")) {
            context.put("farthestHouseholdfromWaterPoint", "N/A");
        } else {
            context.put("farthestHouseholdfromWaterPoint", ap.getFarthestHouseholdfromPoint());
        }
        if (ap.getCurrentManagementStructurePoint() == null) {
            context.put("currMgmtStructure", "N/A");
        } else {
            context.put("currMgmtStructure", ap.getCurrentManagementStructurePoint());
        }
        if (ap.getPointPhotoCaption() == null || ap.getPointPhotoCaption().trim().equals("")) {
            context.put("waterPointPhotoCaption", defaultPhotoCaption);
        } else {
            context.put("waterPointPhotoCaption", ap.getPointPhotoCaption());
        }
        if (ap.getCommunityName() == null) {
            context.put("communityName", "Unknown");
        } else {
            context.put("communityName", ap.getCommunityName());
        }

        if (ap.getHeader() == null) {
            context.put("header", "Water For People");
        } else {
            context.put("header", ap.getHeader());
        }

        if (ap.getFooter() == null) {
            context.put("footer", "Water For People");
        } else {
            context.put("footer", ap.getFooter());
        }

        if (ap.getPhotoName() == null) {
            context.put("photoName", "Water For People");
        } else {
            context.put("photoName", ap.getPhotoName());
        }

        // if (ap.getCountryCode() == "RW") {

        if (ap.getMeetGovtQualityStandardFlag() == null) {
            context.put("meetGovtQualityStandardFlag", "N/A");
        } else {
            context.put("meetGovtQualityStandardFlag",
                    encodeBooleanDisplay(ap.getMeetGovtQualityStandardFlag()));
        }
        // } else {
        // context.put("meetGovtQualityStandardFlag", "unknown");
        // }
        if (ap.getMeetGovtQuantityStandardFlag() == null) {
            context.put("meetGovtQuantityStandardFlag", "N/A");
        } else {
            context.put("meetGovtQuantityStandardFlag",
                    encodeBooleanDisplay(ap.getMeetGovtQuantityStandardFlag()));
        }

        if (ap.getWhoRepairsPoint() == null) {
            context.put("whoRepairsPoint", "N/A");
        } else {
            context.put("whoRepairsPoint", ap.getWhoRepairsPoint());
        }

        if (ap.getSecondaryTechnologyString() == null) {
            context.put("secondaryTypeTechnology", "N/A");
        } else {
            context.put("secondaryTypeTechnology", ap.getSecondaryTechnologyString());
        }

        if (ap.getProvideAdequateQuantity() == null) {
            context.put("provideAdequateQuantity", "N/A");
        } else {
            context.put("provideAdequateQuantity", encodeBooleanDisplay(ap.getProvideAdequateQuantity()));
        }

        if (ap.getBalloonTitle() == null) {
            context.put("title", "Water For People");
        } else {
            context.put("title", ap.getBalloonTitle());
        }

        if (ap.getProvideAdequateQuantity() == null) {
            context.put("provideAdequateQuantity", "N/A");
        } else {
            context.put("provideAdequateQuantity", encodeBooleanDisplay(ap.getProvideAdequateQuantity()));
        }

        if (ap.getQualityDescription() != null) {
            context.put("qualityDescription", ap.getQualityDescription());
        }
        if (ap.getQuantityDescription() != null) {
            context.put("quantityDescription", ap.getQuantityDescription());
        }

        if (ap.getSub1() != null) {
            context.put("sub1", ap.getSub1());
        }
        if (ap.getSub2() != null) {
            context.put("sub2", ap.getSub2());
        }
        if (ap.getSub3() != null) {
            context.put("sub3", ap.getSub3());
        }
        if (ap.getSub4() != null) {
            context.put("sub4", ap.getSub4());
        }
        if (ap.getSub5() != null) {
            context.put("sub5", ap.getSub5());
        }
        if (ap.getSub6() != null) {
            context.put("sub6", ap.getSub6());
        }

        if (ap.getAccessPointCode() != null) {
            context.put("accessPointCode", ap.getAccessPointCode());
        }

        if (ap.getAccessPointUsage() != null) {
            context.put("accessPointUsage", ap.getAccessPointUsage());
        }

        if (ap.getDescription() != null)
            context.put("description", ap.getDescription());
        else
            context.put("description", "Unknown");

        // Need to check this
        if (ap.getPointType() != null) {
            if (Boolean.parseBoolean(PropertyUtil.getProperty(DYNAMIC_SCORING_FLAG))) {
                TreeMap<String, String> combinedScore = fetchLevelOfServiceScoreStatus(ap);
                for (Map.Entry<String, String> entry : combinedScore.entrySet()) {
                    context.put(entry.getKey(), entry.getValue());
                    String style = null;
                    if (standardType != null) {
                        if (standardType.equals(StandardType.WaterPointLevelOfService) && entry.getKey()
                                .equals(StandardType.WaterPointLevelOfService.toString() + "-pinStyle")) {
                            style = entry.getValue();
                        } else if (standardType.equals(StandardType.WaterPointSustainability) && entry.getKey()
                                .equals(StandardType.WaterPointSustainability.toString() + "-pinStyle")) {
                            style = entry.getValue();
                        }
                    }
                    context.put("pinStyle", style);
                }
            } else {
                encodeStatusString(ap, context);
                context.put("pinStyle", encodePinStyle(ap.getPointType(), ap.getPointStatus()));
            }
        } else {
            context.put("pinStyle", "waterpushpinblk");
        }
        String output = mergeContext(context, vmName);
        context = null;
        return output;

    }
    return null;

}

From source file:org.waterforpeople.mapping.app.web.WaterForPeopleMappingGoogleServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String showKML = req.getParameter("showKML");
    @SuppressWarnings("unused")
    String processFile = req.getParameter("processFile");
    String showRegion = req.getParameter("showRegion");
    String action = req.getParameter("action");
    String countryCode = req.getParameter("countryCode");
    if (showKML != null) {
        Long kmlKey = null;/*w  w w  .  ja va 2s  .c om*/
        if (req.getParameter("kmlID") != null) {
            kmlKey = Long.parseLong(req.getParameter("kmlID"));
        }
        if (kmlKey != null) {
            KMLDAO kmlDAO = new KMLDAO();
            String kmlString = kmlDAO.getKML(kmlKey);
            resp.setContentType("application/vnd.google-earth.kml+xml");
            resp.getWriter().println(kmlString);

        } else {
            KMLGenerator kmlGen = new KMLGenerator();
            String placemarksDocument = null;
            String timestamp = DateFormatUtils.formatUTC(new Date(),
                    DateFormatUtils.ISO_DATE_FORMAT.getPattern());
            if (countryCode != null) {
                placemarksDocument = kmlGen.generateDocument("PlacemarksNewLook.vm", countryCode);
                resp.setHeader("Content-Disposition",
                        "inline; filename=waterforpeoplemapping_" + countryCode + "_" + timestamp + ".kmz;");
            } else {
                placemarksDocument = kmlGen.generateDocument("PlacemarksNewLook.vm");
                resp.setHeader("Content-Disposition",
                        "inline; filename=waterforpeoplemapping_" + timestamp + "_.kmz;");
            }
            // ToDo implement kmz compression now that kmls are so big
            // application/vnd.google-earth.kmz
            resp.setContentType("application/vnd.google-earth.kmz+xml");
            ServletOutputStream out = resp.getOutputStream();

            ByteArrayOutputStream os = ZipUtil.generateZip(placemarksDocument, "waterforpeoplemapping.kml");
            out.write(os.toByteArray());
            out.flush();

        }
    } else if (showRegion != null) {
        KMLGenerator kmlGen = new KMLGenerator();
        String placemarksDocument = kmlGen.generateRegionDocumentString("Regions.vm");
        resp.setContentType("application/vnd.google-earth.kml+xml");
        resp.getWriter().println(placemarksDocument);

    } else if ("getLatestMap".equals(action)) {
        MapFragmentDao mfDao = new MapFragmentDao();
        List<MapFragment> mfList = mfDao.searchMapFragments(null, null, null,
                FRAGMENTTYPE.GLOBAL_ALL_PLACEMARKS, "all", "createdDateTime", "desc");
        Blob map = mfList.get(0).getBlob();
        resp.setContentType("application/vnd.google-earth.kmz+xml");
        ServletOutputStream out = resp.getOutputStream();
        resp.setHeader("Content-Disposition", "inline; filename=waterforpeoplemapping.kmz;");
        out.write(map.getBytes());
        out.flush();
    }
}

From source file:org.waterforpeople.mapping.dataexport.KMLApplet.java

private void writePlacemark(List<PlacemarkDto> placemarkDtoList, ZipOutputStream zipOut) throws Exception {
    if (placemarkDtoList != null) {
        for (PlacemarkDto pm : placemarkDtoList) {
            if (pm != null) {
                if (pm.getCollectionDate() != null && pm.getLatitude() != null && pm.getLatitude() != 0
                        && pm.getLongitude() != null && pm.getLongitude() != 0) {
                    VelocityContext vc = new VelocityContext();
                    String timestamp = DateFormatUtils.formatUTC(pm.getCollectionDate(),
                            DateFormatUtils.ISO_DATE_FORMAT.getPattern());
                    vc.put("timestamp", timestamp);
                    vc.put("pinStyle", pm.getPinStyle());
                    vc.put("balloon", pm.getPlacemarkContents());
                    vc.put("longitude", pm.getLongitude());
                    vc.put("latitude", pm.getLatitude());
                    vc.put("altitude", pm.getAltitude());
                    vc.put("communityCode", pm.getCommunityCode());
                    vc.put("communityName", pm.getCommunityCode());
                    String placemark = mergeContext(vc, "template/PlacemarksNewLook.vm");
                    zipOut.write(placemark.getBytes("UTF-8"));
                }//from   w  ww .ja  v a  2  s  .c o m
            }
        }
    }
}