Example usage for java.util TimeZone getTimeZone

List of usage examples for java.util TimeZone getTimeZone

Introduction

In this page you can find the example usage for java.util TimeZone getTimeZone.

Prototype

public static TimeZone getTimeZone(ZoneId zoneId) 

Source Link

Document

Gets the TimeZone for the given zoneId .

Usage

From source file:com.astifter.circatext.YahooJSONParser.java

public Weather getWeather(String data, Address address) throws JSONException {
    Weather weather = new Weather();

    // We create out JSONObject from the data
    JSONObject jObj = new JSONObject(data);

    JSONObject queryObj = getObject("query", jObj);
    try {/*from w  w w .  j  a  va  2 s .c  o m*/
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        weather.time = sdf.parse(getString("created", queryObj));
    } catch (Throwable t) {
        weather.time = null;
    }
    JSONObject resultsObj = getObject("results", queryObj);
    JSONObject channelObj = getObject("channel", resultsObj);
    JSONObject itemObj = getObject("item", channelObj);
    JSONObject condition = getObject("condition", itemObj);

    weather.currentCondition.setCondition(getString("text", condition));
    int code = getInt("code", condition);
    weather.currentCondition.setWeatherId(code);
    weather.currentCondition.setDescr(Weather.translateYahoo(code));
    float temperatureF = getFloat("temp", condition);
    float temperatureC = (temperatureF - 32f) / 1.8f;
    weather.temperature.setTemp(temperatureC);
    try {
        // Tue, 04 Aug 2015 10:59 pm CEST
        Locale l = Locale.ENGLISH;
        SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy hh:mm a", l);
        String date = getString("date", condition).replace("pm", "PM").replace("am", "AM");
        weather.lastupdate = sdf.parse(date);
    } catch (Throwable t) {
        weather.lastupdate = null;
    }

    Location loc = new Location();
    loc.setCountry(address.getCountryCode());
    loc.setCity(address.getLocality());
    weather.location = loc;

    return weather;
}

From source file:eu.annocultor.converters.solr.SolrPeriodsTagger.java

static Date endOfDay(Date date) {
    if (date == null) {
        return null;
    }/*from w  w w .  java2s.c  o  m*/
    Calendar calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    return calendar.getTime();
}

From source file:com.modelmetrics.cloudconverter.importxls.services.ExcelFileParserServiceImpl.java

/**
 * Parses an XLS file into a WrapperBean
 * /*from   w ww.j  a v a  2s. com*/
 * @param file
 * @return WrapperBean
 * @throws ParseException
 */
@SuppressWarnings("unchecked")
public List<ExcelWorksheetWrapperBean> parseXLS(File file) throws ParseException {

    //TODO DB -- validate that dates are working with TZ and SFDC properly.  Use sample input v1 

    // keeps date fields real.
    TimeZone.setDefault(TimeZone.getTimeZone("-0"));

    List<ExcelWorksheetWrapperBean> wrapperBeans = new ArrayList<ExcelWorksheetWrapperBean>();

    try {

        Workbook workbook;

        workbook = Workbook.getWorkbook(file);

        Sheet[] sheets = workbook.getSheets();
        for (Sheet sheet : sheets) {
            ExcelWorksheetWrapperBean bean = new ExcelWorksheetWrapperBean();

            bean.setSheetName(StringUtils.applyConstraints(sheet.getName()));

            int totalRows = sheet.getRows();
            for (int i = 0; i < totalRows; i++) {
                Cell[] cells = sheet.getRow(i);

                List<Object> list = new ArrayList<Object>();
                for (int j = 0; j < cells.length; j++) {

                    Cell c = cells[j];

                    // log.debug("cell format is: (i,j) (" + i + ", " + j +
                    // "):
                    // " + c.getCellFormat().getFormat().getFormatString());

                    String value = c.getContents();
                    if (i == 0) {
                        // parse column names
                        bean.getNames().add(StringUtils.applyConstraints(value));
                        bean.getLabels().add(value);
                    }
                    if (i == 1) {
                        // parse data types
                        CellType type = c.getType();

                        if (type.equals(CellType.DATE) || type.equals(CellType.DATE_FORMULA)) {
                            if (value.contains(":")) {
                                bean.getTypes().add(Constants.DATETIME);
                            } else {
                                bean.getTypes().add(Constants.DATE);
                            }
                        } else if (type.equals(CellType.BOOLEAN) || type.equals(CellType.BOOLEAN_FORMULA)) {

                            bean.getTypes().add(Constants.CHECKBOX);
                        } else if (type.equals(CellType.LABEL) || type.equals(CellType.STRING_FORMULA)) {

                            if (GenericValidator.isEmail(value)) {
                                bean.getTypes().add(Constants.EMAIL);
                            } else if (StringUtils.isPhoneNumber(value)) {
                                bean.getTypes().add(Constants.PHONE_NUMBER);
                            } else if (StringUtils.isURL(value)) {
                                bean.getTypes().add(Constants.URL);
                            } else {
                                bean.getTypes().add(Constants.TEXT);
                            }
                        } else if (type.equals(CellType.NUMBER) || type.equals(CellType.NUMBER_FORMULA)) {
                            log.debug("Number: " + value + " : format : "
                                    + c.getCellFormat().getFormat().getFormatString());
                            if (value.contains("%")) {
                                bean.getTypes().add(Constants.PERCENTAGE);
                            } else if (value.contains("$")) {
                                bean.getTypes().add(Constants.CURRENCY);
                            } else if (value.contains(",") || value.contains(".")) {
                                bean.getTypes().add(Constants.DOUBLE);
                            } else {
                                bean.getTypes().add(Constants.INT);
                            }
                        } else {
                            // default.
                            bean.getTypes().add(Constants.TEXT);
                        }
                    }
                    if (i >= 1) {
                        // parse data values

                        CellType type = c.getType();

                        if (type.equals(CellType.BOOLEAN) || type.equals(CellType.BOOLEAN_FORMULA)) {
                            list.add(((BooleanCell) c).getValue());
                        } else if (type.equals(CellType.DATE) || type.equals(CellType.DATE_FORMULA)) {

                            Date aux = ((DateCell) c).getDate();
                            list.add(aux);

                            // }
                        } else if (type.equals(CellType.LABEL) || type.equals(CellType.STRING_FORMULA)) {

                            list.add(value);
                        } else if (type.equals(CellType.EMPTY)) {

                            list.add(null);
                        } else if (type.equals(CellType.NUMBER) || type.equals(CellType.NUMBER_FORMULA)) {
                            if (value.contains("%")) {
                                // otherwise "percentages" show up in SFDC
                                // as
                                // 0.78 when it should be 78%.
                                list.add(((NumberCell) c).getValue() * 100);
                            } else {
                                list.add(((NumberCell) c).getValue());
                            }
                        }
                        if (i == 1) {
                            bean.getExamples().add(value);
                        }
                    }

                }
                //TODO DB make sure this is working for worksheets that have no row with DATA (Think Erin's email)
                if (i >= 1) {
                    /*
                     * RSC 2009-06-02 Check to be sure there is data in a list
                     */
                    boolean notEmpty = false;
                    for (Object o : list) {
                        if (o != null && o.toString().trim().length() != 0) {
                            notEmpty = true;
                            break;
                        }
                    }
                    if (!notEmpty) {
                        throw new RuntimeException(
                                "Found an empty row.  Your spreadsheet should not contain an empty row. Check sheet "
                                        + sheet.getName() + ", row " + (i + 1) + ".");
                    }
                    bean.getData().add(list);
                    bean.setOverride(Boolean.FALSE);
                }
            }
            wrapperBeans.add(bean);

        }

    } catch (BiffException e) {
        throw new ParseException("Could not read file");
    } catch (IOException e) {
        throw new ParseException("Input/Output error");
    } catch (IndexOutOfBoundsException e) {
        throw new ParseException("Columns and data do not match");
    } catch (NullPointerException e) {
        throw new ParseException("A reference in the file has a null value");
    }

    return wrapperBeans;
}

From source file:com.persistent.cloudninja.scheduler.TenantDBBandwidthGenerator.java

@Override
public boolean execute() {
    StopWatch watch = new StopWatch();
    boolean retVal = true;
    try {/*from  ww  w.  j  a v  a2  s  . c  o m*/
        watch.start();
        LOGGER.debug("In generator");
        TenantDBBandwidthQueue queue = (TenantDBBandwidthQueue) getWorkQueue();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        String currentTime = dateFormat.format(calendar.getTime());
        queue.enqueue(currentTime);
        LOGGER.info("Generator : msg added is " + currentTime);
        watch.stop();
        taskCompletionDao.updateTaskCompletionDetails(watch.getTotalTimeSeconds(),
                "GenerateMeterTenantDBBandwidthWork", "");
    } catch (StorageException e) {
        retVal = false;
        LOGGER.error(e.getMessage(), e);
    }
    return retVal;
}

From source file:ch.cyberduck.core.b2.B2AuthorizedUrlProvider.java

@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Void none, final PasswordCallback callback)
        throws BackgroundException {
    if (file.isVolume()) {
        return DescriptiveUrl.EMPTY;
    }//from   w  w w.jav a2s  .c o  m
    if (file.isFile()) {
        final String download = String.format("%s/file/%s/%s", session.getClient().getDownloadUrl(),
                URIEncoder.encode(containerService.getContainer(file).getName()),
                URIEncoder.encode(containerService.getKey(file)));
        try {
            final int seconds = 604800;
            // Determine expiry time for URL
            final Calendar expiry = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            expiry.add(Calendar.SECOND, seconds);
            final String token = session.getClient()
                    .getDownloadAuthorization(new B2FileidProvider(session)
                            .getFileid(containerService.getContainer(file), new DisabledListProgressListener()),
                            StringUtils.EMPTY, seconds);
            return new DescriptiveUrl(URI.create(String.format("%s?Authorization=%s", download, token)),
                    DescriptiveUrl.Type.signed,
                    MessageFormat.format(LocaleFactory.localizedString("{0} URL"),
                            LocaleFactory.localizedString("Pre-Signed", "S3")) + " ("
                            + MessageFormat.format(LocaleFactory.localizedString("Expires {0}", "S3") + ")",
                                    UserDateFormatterFactory.get().getMediumFormat(expiry.getTimeInMillis())));
        } catch (B2ApiException e) {
            throw new B2ExceptionMappingService().map(e);
        } catch (IOException e) {
            throw new DefaultIOExceptionMappingService().map(e);
        }
    }
    return DescriptiveUrl.EMPTY;
}

From source file:com.netflix.fenzo.triggers.CronTrigger.java

/**
 * @warn method description missing//from  w w w. j ava  2  s . c  o  m
 *
 * @return
 */
@Override
@JsonIgnore
public ScheduleBuilder getScheduleBuilder() {
    return cronSchedule(cronExpression).withMisfireHandlingInstructionDoNothing()
            .inTimeZone(TimeZone.getTimeZone(timeZoneId));
}

From source file:org.lieuofs.commune.biz.GestionCommuneTest.java

@Test
public void rechercheLaTourDeTreme() {
    // numro OFS 2154 : la Tour de Trme a t incluse dans Bulle le 1er janvier 2006
    CommuneCritere critere = new CommuneCritere();
    critere.setCodeCanton("FR");
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
    cal.set(2005, Calendar.DECEMBER, 31);
    critere.setDateValidite(cal.getTime());
    List<ICommuneSuisse> communes = gestionnaire.rechercher(critere);
    boolean trouve = false;
    for (ICommuneSuisse commune : communes) {
        if (2154 == commune.getNumeroOFS()) {
            trouve = true;//from www.j  a v  a 2s  .  c o  m
            break;
        }
    }
    assertTrue("Le 31 dcembre 2005 la Tour-de-Trme est une commune fribourgeoise", trouve);
    cal.add(Calendar.DATE, 1);
    critere.setDateValidite(cal.getTime());
    communes = gestionnaire.rechercher(critere);
    trouve = false;
    for (ICommuneSuisse commune : communes) {
        if (2154 == commune.getNumeroOFS()) {
            trouve = true;
            break;
        }
    }
    assertTrue("Le 1er janvier 2006 la Tour-de-Trme n'est plus une commune fribourgeoise", !trouve);
}

From source file:com.persistent.cloudninja.controller.TenantUsageController.java

/**
 * List the tenant Metering information.
 * @param cookie containing tenant ID//  w  w  w  . ja  va2s. c o m
 * @throws SystemException
 * @return ModelAndView mapped to Tenant Metering List
 */
@RequestMapping("{tenantId}/showTenantMeteringPage.htm")
public ModelAndView showTenantMeteringPage(HttpServletRequest request,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie, Model model)
        throws SystemException {
    if (cookie == null) {
        cookie = request.getAttribute("cookieNameAttr").toString();
    }
    String tenantId = AuthFilterUtils.getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_TENANTID_PREFIX,
            cookie);
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    int month = calendar.get(Calendar.MONTH) + 1;
    int year = calendar.get(Calendar.YEAR);

    List<Metering> list = meteringService.getMeteringService(tenantId, month, year);
    MeteringListDTO meteringDTO = new MeteringListDTO();
    meteringDTO.setMeteringList(list);

    return new ModelAndView("tenantMeteringPage", "meteringDTO", meteringDTO);
}

From source file:com.rackspacecloud.blueflood.tracker.Tracker.java

private Tracker() {
    // set dateFormatter to GMT since collectionTime for metrics should always be GMT/UTC
    dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
}

From source file:edu.harvard.iq.safe.lockss.impl.DaemonStatusDataUtil.java

public static String getStdFrmtdTime(Date date, String timezoneId) {
    return FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss zz", TimeZone.getTimeZone(timezoneId)).format(date);
}