Example usage for java.text SimpleDateFormat setTimeZone

List of usage examples for java.text SimpleDateFormat setTimeZone

Introduction

In this page you can find the example usage for java.text SimpleDateFormat setTimeZone.

Prototype

public void setTimeZone(TimeZone zone) 

Source Link

Document

Sets the time zone for the calendar of this DateFormat object.

Usage

From source file:io.ignitr.springboot.common.error.IgnitionErrorAttributes.java

/**
 * Adds the timestamp to the error response.
 *
 * @param errorAttributes error attributes collection
 *//*w ww  .  j a v  a2  s. c  o m*/
private void addTimestamp(Map<String, Object> errorAttributes) {
    final SimpleDateFormat sdf = new SimpleDateFormat(ISO_DATE_FORMAT);
    sdf.setTimeZone(UTC_TIMEZONE);

    errorAttributes.put("timestamp", sdf.format(new Date()));
}

From source file:se.vgregion.services.calendar.CalendarServiceImpl.java

@Override
public CalendarEvents getCalendarEventsFromIcalUrl(String url, CalendarEventsPeriod period, String type)
        throws CalendarServiceException {
    CalendarEvents calendarEvents = new CalendarEvents();
    calendarEvents.setCalendarItems(new ArrayList<CalendarItem>());

    Interval queryInterval = new Interval(period.getStartDate(), period.getEndDate());

    try {/*from   ww w . j av  a  2s .  c o m*/
        Calendar calendar = parseIcalUrl(url);

        Iterator<VEvent> itr = calendar.getComponents(Component.VEVENT).iterator();

        while (itr.hasNext()) {
            VEvent vEvent = itr.next();

            Date startDate = vEvent.getStartDate().getDate();
            Date endDate = vEvent.getEndDate().getDate();

            boolean wholeDays = !(startDate instanceof net.fortuna.ical4j.model.DateTime);
            if (wholeDays) {
                // Whole day event. Have had timezone problems with whole day events. Workaround it.
                String datePartStart = startDate.toString();
                String datePartEnd = endDate.toString();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                sdf.setTimeZone(TimeZone.getDefault());
                try {
                    java.util.Date startParsed = sdf.parse(datePartStart);
                    java.util.Date endParsed = sdf.parse(datePartEnd);

                    startDate = new net.fortuna.ical4j.model.DateTime(startParsed);
                    // Subtract a millisecond so we don't regard the event as taking place on the next day. Now we
                    // end the event one millisecond before the day turns.
                    endDate = new net.fortuna.ical4j.model.DateTime(endParsed.getTime() - 1);
                } catch (ParseException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }

            Interval interval = new Interval(startDate.getTime(), endDate.getTime());

            if (interval.overlaps(queryInterval)) {
                CalendarItem item = new CalendarItem();
                item.setInterval(interval);
                item.setTitle(vEvent.getSummary().getValue());
                item.setCalendarType(type);
                item.setWholeDays(wholeDays);
                calendarEvents.getCalendarItems().add(item);
            }
        }
    } catch (IOException ioe) {
        throw new CalendarServiceException(ioe);
    } catch (ParserException pe) {
        throw new CalendarServiceException(pe);
    }

    return calendarEvents;
}

From source file:com.funambol.exchange.util.DateTools.java

/**
 * <p>// www  . jav a  2  s  .com
 * Converts a date in day format("yyyy-MM-dd") to WebDAV format
 * ("yyyy-MM-dd'T'KK:mm:ss'.000Z'").
 * </p>
 * <p>
 * If the timezone parameter is <i>null</i> the timezone of the output date
 * is considered GMT.
 * </p>
 * <p>
 * If the isAStartDate is true then the time in GMT of the output date will
 * be 00:00:00 else 24:00:00.
 * </p>
 * 
 * @param date
 * @param timezone
 * @param isAStartDate
 * @return the date in WebDav format
 * @throws XmlParseException
 */
public static String convertDayInWebDavDateFormat(String date, TimeZone timezone, boolean isAStartDate)
        throws XmlParseException {
    SimpleDateFormat formatter;

    Date dt;
    String wedDavDate, value;
    String timePart = null;
    if (date != null && date.length() > 0) {
        if (isAStartDate) {
            timePart = "T00:00:00.000Z";
        } else {
            timePart = "T24:00:00.000Z";
        }

        date = date.replace("-", "");
        value = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8) + timePart;

        formatter = new SimpleDateFormat(DATE_FORMAT_WEBDAV);
        if (timezone == null) {
            timezone = TimeZone.getTimeZone("GMT");
        }
        formatter.setTimeZone(timezone);
        try {
            dt = formatter.parse(value);
        } catch (ParseException e) {
            throw new XmlParseException("Error converting date", e);
        }
        formatter.setTimeZone(TimeZone.getTimeZone("GMT"));

        wedDavDate = formatter.format(dt);

    } else {
        wedDavDate = null;
    }

    return wedDavDate;
}

From source file:com.relecotech.common.controller.AcceptParameterController.java

@RequestMapping(value = "/{name}", method = RequestMethod.GET)
//public String getMovie(@PathVariable String name, ModelMap model) {
public @ResponseBody ModelAndView getParameter(@PathVariable String name) throws ParserConfigurationException {
    //String param =name;
    try {/* w  w w.  j a v  a  2 s  .  c  om*/
        Map<String, String> valueMap = new HashMap<String, String>();
        String[] data = name.split("&");
        for (String str : data) {
            String[] mapPair = str.split("=");
            valueMap.put(mapPair[0], mapPair[1]);
        }
        String logoutUrl = "https://" + valueMap.get("URL") + ".com";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SAMLCredential credential = (SAMLCredential) authentication.getCredentials();
        TimeZone timeZone = TimeZone.getTimeZone(valueMap.get("timeZone").replace("*", "/"));

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm a");
        dateFormat.setTimeZone(timeZone);

        Calendar calobj = Calendar.getInstance(timeZone);
        String SystemCurrentTime = dateFormat.format(calobj.getTime());
        Date SystemCurrentDateTime = dateFormat.parse(SystemCurrentTime);
        // Date SystemCurrentDateTime = calobj.getTime();

        //SFDC Meeting DATE/TIME 
        String sfdcMeetingTime = valueMap.get("d").replace("*", "/");
        System.out.println("sfdcMeetingTime=" + sfdcMeetingTime);
        Date sfdcMeetingDateTime = dateFormat.parse(sfdcMeetingTime);
        //TIME Before Meeting can satarted 
        Date sfdcMeetingBeforeDateTime = dateFormat
                .parse(AddSubtractTime.getSubtractedTime(sfdcMeetingTime, timeZone));
        //TIME after Meeting cannot be satarted 
        Date sfdcMeetingAfterDateTime = dateFormat
                .parse(AddSubtractTime.getAddedTime(sfdcMeetingTime, timeZone));

        System.out.println("SystemCurrentDateTime=" + SystemCurrentDateTime);
        System.out.println("sfdcMeetingDateTime=" + sfdcMeetingDateTime);
        System.out.println("sfdcMeetingAfterDateTime=" + sfdcMeetingAfterDateTime);
        System.out.println("sfdcMeetingBeforeDateTime=" + sfdcMeetingBeforeDateTime);
        if (SystemCurrentDateTime.after(sfdcMeetingBeforeDateTime)
                && SystemCurrentDateTime.before(sfdcMeetingAfterDateTime)) {
            APIGenerator aPIGenerator = new APIGenerator();
            System.out.println("converted id=" + SalesforceIDConverter.convertID(valueMap.get("code")));
            System.out.println((credential.getAttributeAsString("ContactId")));
            if (valueMap.get("code")
                    .matches(SalesforceIDConverter.convertID(credential.getAttributeAsString("ContactId")))) {

                System.out.println("valuemap=" + valueMap);

                System.out.println("logout url=" + logoutUrl);
                String create = "attendeePW=ap" + "&meetingID=" + valueMap.get("name") + "&moderatorPW=newuser"
                        + "&name=" + valueMap.get("name") + "&logoutURL=" + logoutUrl;
                System.out.println("create parameter=" + create);
                XmlParser.runAPI(aPIGenerator.createAPI("create", create));
                // String join = "fullName=" + valueMap.get("fullName") + "&meetingID=" + valueMap.get("meetingID") + "&password=newuser";
                String join = "fullName=" + credential.getAttributeAsString("username") + "&meetingID="
                        + valueMap.get("name") + "&password=newuser";
                System.out.println("joinparam=" + join);
                aPIGenerator.createAPI("join", join);
                return new ModelAndView("redirect:" + aPIGenerator.apiWithChecksum);

            } else {
                Map<String, String> responceMap = XmlParser.runAPI(
                        aPIGenerator.createAPI("isMeetingRunning", "meetingID=" + valueMap.get("name")));
                String join = "fullName=" + credential.getAttributeAsString("username") + "&meetingID="
                        + valueMap.get("name") + "&password=ap";
                if (responceMap.get("running").matches("true")) {

                    aPIGenerator.createAPI("join", join);
                    return new ModelAndView("redirect:" + aPIGenerator.apiWithChecksum);
                } else {
                    String student = "<center>  <h1>Wait! Presenter has not joined meeting yet!</h1>\n"
                            //                                +"<img src=\"${pageContext.request.contextPath}/images/bbbtime.jpg\" style=\"width:304px;height:228px\"/> "
                            + "     <h2>\n" + "           Please try after few minutes.\n" + "        \n"
                            + "<br>Meeting Date/Time:" + dateFormat.format(sfdcMeetingDateTime) + "<br><a href="
                            + logoutUrl + ">Back</a>" + "    </h2></center> ";
                    // return new ModelAndView("redirect:" + "/student.jsp");
                    return new ModelAndView("student", "student", student);
                }
            }

        } else {
            //                
            if (SystemCurrentDateTime.compareTo(sfdcMeetingDateTime) == -1) {

                String wait = "<center> <h1>Too Early for Meeting!</h1><br></center>\n"
                        //                             +"<img src=\"${pageContext.request.contextPath}/images/bbbtime.jpg\" style=\"width:304px;height:228px\"/> "
                        + "  <center>  <h2>Meeting is not yet open.<br>\n"
                        + "  Please check meeting schedule time. \n<br>" + "<br>Meeting Date/Time:"
                        + dateFormat.format(sfdcMeetingDateTime) + "</h2><h3>System Current Date/Time:"
                        + dateFormat.format(SystemCurrentDateTime)
                        + "<br>*Meeting will open 15 minutes before scheduled time</h3><a href=" + logoutUrl
                        + ">Back</a>" + "  </center> ";
                return new ModelAndView("wait", "wait", wait);
            }
            //for Past Date
            if (SystemCurrentDateTime.compareTo(sfdcMeetingDateTime) == 1) {
                String wait = "<center> <h1>Meeting is Over!</h1><br></center>\n"
                        //                             +"<img src=\"${pageContext.request.contextPath}/images/bbbtime.jpg\" style=\"width:304px;height:228px\"/> "
                        + "  <center>  <h2>Meeting can not open.<br>\n"
                        + "        Meeting was scheduled on - \n<br>" + "<br>Meeting Date/Time:"
                        + dateFormat.format(sfdcMeetingDateTime) + "</h2><h3><br>System Current Date/Time:"
                        + dateFormat.format(SystemCurrentDateTime) + "<br><a href=" + logoutUrl + ">Back</a>"
                        + "  </h3>  </center> ";
                return new ModelAndView("wait", "wait", wait);

            }
            //                
        }

    } catch (Exception ex) {
        System.out.println("Exception=" + ex);
    }

    return null;
}

From source file:com.microsoft.valda.oms.OmsAppender.java

private void sendLog(LoggingEvent event)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException {
    //create JSON message
    JSONObject obj = new JSONObject();
    obj.put("LOGBACKLoggerName", event.getLoggerName());
    obj.put("LOGBACKLogLevel", event.getLevel().toString());
    obj.put("LOGBACKMessage", event.getFormattedMessage());
    obj.put("LOGBACKThread", event.getThreadName());
    if (event.getCallerData() != null && event.getCallerData().length > 0) {
        obj.put("LOGBACKCallerData", event.getCallerData()[0].toString());
    } else {/*from   w w  w .  j  a  va 2  s  .  c  o m*/
        obj.put("LOGBACKCallerData", "");
    }
    if (event.getThrowableProxy() != null) {
        obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
    } else {
        obj.put("LOGBACKStackTrace", "");
    }
    if (inetAddress != null) {
        obj.put("LOGBACKIPAddress", inetAddress.getHostAddress());
    } else {
        obj.put("LOGBACKIPAddress", "0.0.0.0");
    }
    String json = obj.toJSONString();

    String Signature = "";
    String encodedHash = "";
    String url = "";

    // Todays date input for OMS Log Analytics
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String timeNow = dateFormat.format(calendar.getTime());

    // String for signing the key
    String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs";
    byte[] decodedBytes = Base64.decodeBase64(sharedKey);
    Mac hasher = Mac.getInstance("HmacSHA256");
    hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256"));
    byte[] hash = hasher.doFinal(stringToSign.getBytes());

    encodedHash = DatatypeConverter.printBase64Binary(hash);
    Signature = "SharedKey " + customerId + ":" + encodedHash;

    url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
    URL objUrl = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Log-Type", logType);
    con.setRequestProperty("x-ms-date", timeNow);
    con.setRequestProperty("Authorization", Signature);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(json);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new HTTPException(responseCode);
    }
}

From source file:hudson.plugins.sauce_ondemand.PluginImpl.java

/**
 * Creates a HMAC token which is used as part of the Javascript inclusion that embeds the Sauce results
 *
 * @param username  the Sauce user id/*from   w ww .  j a  v  a2  s .c om*/
 * @param accessKey the Sauce access key
 * @param jobId     the Sauce job id
 * @return the HMAC token
 * @throws java.security.NoSuchAlgorithmException
 *
 * @throws java.security.InvalidKeyException
 *
 * @throws java.io.UnsupportedEncodingException
 *
 */
public String calcHMAC(String username, String accessKey, String jobId)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    Calendar calendar = Calendar.getInstance();

    SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    String key = username + ":" + accessKey + ":" + format.format(calendar.getTime());
    byte[] keyBytes = key.getBytes();
    SecretKeySpec sks = new SecretKeySpec(keyBytes, HMAC_KEY);
    Mac mac = Mac.getInstance(sks.getAlgorithm());
    mac.init(sks);
    byte[] hmacBytes = mac.doFinal(jobId.getBytes());
    byte[] hexBytes = new Hex().encode(hmacBytes);
    return new String(hexBytes, "ISO-8859-1");
}

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

/**
 * Parses the response received by making call to REST API.
 * It parses and gets the total no. roles and their instances.
 * /*from  w  w  w .j  a va 2s  .co m*/
 * @param roleInfo
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 * @throws ParseException
 */
private void parseRoleInfo(StringBuffer roleInfo) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, ParseException {
    DocumentBuilder docBuilder = null;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    docBuilder = docBuilderFactory.newDocumentBuilder();
    doc = docBuilder.parse(new InputSource(new StringReader(roleInfo.toString())));

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    NodeList roleList = (NodeList) xPath.evaluate("/Deployment/RoleList/Role/RoleName", doc,
            XPathConstants.NODESET);
    //get all the roles
    String roleName = null;
    List<String> listRoleNames = new ArrayList<String>();
    for (int i = 0; i < roleList.getLength(); i++) {
        Element element = (Element) roleList.item(i);
        roleName = element.getTextContent();
        RoleEntity roleEntity = roleDao.findByRoleName(roleName);
        if (roleEntity == null) {
            roleEntity = new RoleEntity();
            roleEntity.setName(roleName);
            roleDao.add(roleEntity);
        }
        listRoleNames.add(roleName);
    }

    xPathFactory = XPathFactory.newInstance();
    xPath = xPathFactory.newXPath();
    RoleInstancesEntity roleInstancesEntity = null;
    RoleInstancesId roleInstancesId = null;
    for (String name : listRoleNames) {
        roleList = (NodeList) xPath.evaluate(
                "/Deployment/RoleInstanceList/RoleInstance[RoleName='" + name + "']", doc,
                XPathConstants.NODESET);
        //get no. of instances for WorkerRole
        int noOfInstances = roleList.getLength();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        String date = dateFormat.format(calendar.getTime());
        roleInstancesId = new RoleInstancesId(dateFormat.parse(date), name);
        roleInstancesEntity = new RoleInstancesEntity(roleInstancesId, noOfInstances, "UPDATE");
        roleInstancesDao.add(roleInstancesEntity);
    }

}

From source file:com.shampan.db.services.StatusServiceTest.java

public void getCurrentDate() {
    String offset = "+06";
    String gmtOffset = "GMT" + offset;
    System.out.println(gmtOffset);
    long unixSeconds = 1447681923 * 1000L;
    Date date = new Date(unixSeconds);
    SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    sDateFormat.setTimeZone(TimeZone.getTimeZone(gmtOffset));
    String currentDate = sDateFormat.format(date);
    System.out.println(currentDate);
}

From source file:eu.europa.esig.dss.signature.AbstractTestSignature.java

protected void checkSigningDate(DiagnosticData diagnosticData) {
    Date signatureDate = diagnosticData.getSignatureDate();
    Date originalSigningDate = getSignatureParameters().bLevel().getSigningDate();

    try {//from  ww  w.  j  a  va 2s . co  m
        // Time in GMT
        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
        dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
        SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
        Date originalGMTDate = dateFormatLocal.parse(dateFormatGmt.format(originalSigningDate));

        assertEquals(originalGMTDate, signatureDate);
    } catch (ParseException e) {
        fail("Cannot check the signing date");
    }
}

From source file:ddf.catalog.transformer.queryresponse.geojson.GeoJsonQueryResponseTransformerTest.java

private void verifyResult(@SuppressWarnings("rawtypes") Map result) {
    assertThat(toString(result.get("relevance")), is(Double.toString(DEFAULT_RELEVANCE)));
    @SuppressWarnings("rawtypes")
    Map metacard = (Map) result.get("metacard");

    assertThat(metacard.get("properties"), notNullValue());
    @SuppressWarnings("rawtypes")
    Map properties = ((Map) metacard.get("properties"));
    assertThat(properties.size(), is(10));
    assertThat(toString(properties.get(Metacard.TITLE)), is(DEFAULT_TITLE));
    assertThat(toString(properties.get(Metacard.CONTENT_TYPE)), is(DEFAULT_TYPE));
    assertThat(toString(properties.get(Metacard.CONTENT_TYPE_VERSION)), is(DEFAULT_VERSION));
    SimpleDateFormat dateFormat = new SimpleDateFormat(GeoJsonMetacardTransformer.ISO_8601_DATE_FORMAT);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    assertThat(toString(properties.get(Metacard.CREATED)), is(dateFormat.format(NOW)));
    assertThat(toString(properties.get(Metacard.EXPIRATION)), nullValue());
    assertThat(toString(properties.get(Metacard.EFFECTIVE)), nullValue());
    assertThat(toString(properties.get(Metacard.MODIFIED)), is(dateFormat.format(NOW)));
    assertThat(toString(properties.get(Metacard.THUMBNAIL)), is("CA=="));
    assertThat(toString(properties.get(Metacard.METADATA)), is(DEFAULT_XML));
    assertThat(toString(properties.get(Metacard.RESOURCE_URI)), is(DEFAULT_URI));
}