Example usage for java.util Calendar setTimeZone

List of usage examples for java.util Calendar setTimeZone

Introduction

In this page you can find the example usage for java.util Calendar setTimeZone.

Prototype

public void setTimeZone(TimeZone value) 

Source Link

Document

Sets the time zone with the given time zone value.

Usage

From source file:facebook4j.internal.util.z_F4JInternalStringUtilTest.java

@Test
public void formatISO8601Datetime() throws Exception {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2012);
    cal.set(Calendar.MONTH, 5);/*w  w w  . jav a2 s  . c  o  m*/
    cal.set(Calendar.DAY_OF_MONTH, 15);
    cal.set(Calendar.HOUR_OF_DAY, 16);
    cal.set(Calendar.MINUTE, 17);
    cal.set(Calendar.SECOND, 18);
    cal.set(Calendar.MILLISECOND, 0);

    cal.setTimeZone(TimeZone.getTimeZone("JST"));
    String actual1 = z_F4JInternalStringUtil.formatISO8601Datetime(cal);
    assertThat(actual1, is("2012-06-15T16:17:18+0900"));

    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    String actual2 = z_F4JInternalStringUtil.formatISO8601Datetime(cal);
    assertThat(actual2, is("2012-06-15T07:17:18+0000")); //16-9=7

    JSONObject json = new JSONObject(
            "{\"datetime1\": \"" + actual1 + "\", \"datetime2\": \"" + actual2 + "\"}");
    Date d1 = z_F4JInternalParseUtil.getISO8601Datetime("datetime1", json);
    Date d2 = z_F4JInternalParseUtil.getISO8601Datetime("datetime2", json);
    assertThat(d1, is(d2));
}

From source file:org.osaf.cosmo.scheduler.ForwardLookingNotificationJob.java

@Override
protected Report generateReport(JobExecutionContext context) throws JobExecutionException {

    TimeZone tz = timezone == null ? null : TimeZoneUtils.getTimeZone(timezone);
    Locale loc = locale == null ? Locale.getDefault() : new Locale(locale);

    // start date is the start of the day of the fire time

    Calendar cal = new GregorianCalendar();
    if (tz != null)
        cal.setTimeZone(tz);

    cal.setTime(context.getFireTime());//www.ja v a  2  s .  com
    cal.set(Calendar.AM_PM, Calendar.AM);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);

    Date startDate = new Date(cal.getTime().getTime());

    // End date is either 1 day or 1 week later
    // depending on report type
    if (REPORT_TYPE_DAILY.equals(reportType))
        cal.add(Calendar.DAY_OF_YEAR, 1);
    else
        cal.add(Calendar.WEEK_OF_YEAR, 1);

    cal.add(Calendar.SECOND, -1);

    Date endDate = cal.getTime();

    if (log.isDebugEnabled()) {
        log.debug("startDate=" + startDate);
        log.debug("endDate = " + endDate);
    }

    // get results
    List<UpcomingResult> upcomingItems = new ArrayList<UpcomingResult>();
    List<NowResult> nowItems = new ArrayList<NowResult>();

    Iterator<String> it = getCollectionUids().iterator();
    while (it.hasNext()) {
        String colUid = it.next();

        // We have to handle changes to underlying collections.
        // A collection could have been deleted, or access to the
        // collection has been removed. In both cases, remove the
        // collection from the list so that the next job run
        // won't attempt to access it.
        try {
            getCollectionResults(colUid, startDate, endDate, tz, upcomingItems, nowItems);
        } catch (ItemSecurityException ise) {
            // user is not authorized for collection,
            // remove collection for next execution
            log.info("user " + getUsername() + " not authorized for collection " + colUid
                    + ", removing from schedule " + context.getJobDetail().getName());
            it.remove();
        } catch (ItemNotFoundException infe) {
            // collection not found, remove collection for next execution
            log.info("collection " + colUid + " not found removing from schedule " + getUsername() + ":"
                    + context.getJobDetail().getName());
            it.remove();
        }
    }

    // sort results
    Comparator<UpcomingResult> comparator = new UpcomingResultComparator(false, tz);
    Collections.sort(upcomingItems, comparator);

    // return results
    ForwardLookingReport report = new ForwardLookingReport(getUser());
    report.setStartDate(startDate);
    report.setTimezone(tz == null ? TimeZone.getDefault() : tz);
    report.setLocale(loc);
    report.setReportType(reportType);
    report.setUpcomingItems(upcomingItems);
    report.setNowItems(nowItems);
    return report;
}

From source file:it.geosolutions.geobatch.imagemosaic.GranuleRemoverOnlineTest.java

/**
 * GranuleRemover used to throw NPE when applied over a still not existent layer.
 *///from w  w w .ja  v  a2  s.  com
@Test
public void removeFromNewLayer() throws Exception {
    removeStore();

    //=== Add first set of granules
    {
        ImageMosaicCommand imc = recreateIMC("20121004", "20121005", "20121006", "20121007", "20121008");
        // serialize

        GranuleRemover remover = new GranuleRemover();

        Calendar cal = new GregorianCalendar(2012, 9, 7);
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));

        remover.setBaseDate(cal);
        remover.setDaysAgo(2);
        remover.enrich(imc);
        LOGGER.info("remove " + imc.getDelFiles());
    }

    //== Cleanup
    //        removeStore();
}

From source file:org.opennms.netmgt.syslogd.SyslogMessageTest.java

@Test
public void testCustomParserNms5242() throws Exception {
    final Locale startLocale = Locale.getDefault();
    try {/* w  ww.  ja  v a  2  s. com*/
        Locale.setDefault(Locale.FRANCE);
        final InputStream stream = new ByteArrayInputStream(("<?xml version=\"1.0\"?>\n"
                + "<syslogd-configuration>\n" + "    <configuration\n" + "            syslog-port=\"10514\"\n"
                + "            new-suspect-on-message=\"false\"\n"
                + "            parser=\"org.opennms.netmgt.syslogd.CustomSyslogParser\"\n"
                + "            forwarding-regexp=\"^((.+?) (.*))\\n?$\"\n"
                + "            matching-group-host=\"2\"\n" + "            matching-group-message=\"3\"\n"
                + "            discard-uei=\"DISCARD-MATCHING-MESSAGES\"\n" + "            />\n" + "\n"
                + "    <hideMessage>\n" + "        <hideMatch>\n"
                + "            <match type=\"substr\" expression=\"TEST\"/>\n" + "        </hideMatch>\n"
                + "    </hideMessage>\n" + "</syslogd-configuration>\n").getBytes());
        final SyslogdConfigFactory config = new SyslogdConfigFactory(stream);

        final SyslogParser parser = new CustomSyslogParser(config,
                "<0>Mar 14 17:10:25 petrus sudo:  cyrille : user NOT in sudoers ; TTY=pts/2 ; PWD=/home/cyrille ; USER=root ; COMMAND=/usr/bin/vi /etc/aliases");
        assertTrue(parser.find());
        final SyslogMessage message = parser.parse();
        LOG.debug("message = {}", message);
        final Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.set(Calendar.MONTH, Calendar.MARCH);
        cal.set(Calendar.DAY_OF_MONTH, 14);
        cal.set(Calendar.HOUR_OF_DAY, 17);
        cal.set(Calendar.MINUTE, 10);
        cal.set(Calendar.SECOND, 25);
        cal.set(Calendar.MILLISECOND, 0);
        assertEquals(SyslogFacility.KERNEL, message.getFacility());
        assertEquals(SyslogSeverity.EMERGENCY, message.getSeverity());
        assertNull(message.getMessageID());
        assertEquals(cal.getTime(), message.getDate());
        assertEquals("petrus", message.getHostName());
        assertEquals("sudo", message.getProcessName());
        assertEquals(0, message.getProcessId().intValue());
        assertEquals(
                "cyrille : user NOT in sudoers ; TTY=pts/2 ; PWD=/home/cyrille ; USER=root ; COMMAND=/usr/bin/vi /etc/aliases",
                message.getMessage());
    } finally {
        Locale.setDefault(startLocale);
    }
}

From source file:org.codehaus.mojo.mrm.impl.maven.DiskArtifactStore.java

/**
 * {@inheritDoc}//w w w  .  java2 s.  c  o  m
 */
public Set<Artifact> getArtifacts(final String groupId, final String artifactId, final String version) {
    File groupDir = new File(root, groupId.replace('.', '/'));
    File artifactDir = new File(groupDir, artifactId);
    File versionDir = new File(artifactDir, version);
    if (!versionDir.isDirectory()) {
        return Collections.emptySet();
    }
    final Pattern rule;

    abstract class ArtifactFactory {
        abstract Artifact get(File file);
    }

    final ArtifactFactory factory;
    if (version.endsWith("-SNAPSHOT")) {
        rule = Pattern.compile("\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd(version, "-SNAPSHOT")
                + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?\\.([^/]*)");
        factory = new ArtifactFactory() {
            public Artifact get(File file) {
                Matcher matcher = rule.matcher(file.getName());
                if (!matcher.matches()) {
                    return null;
                }
                if (matcher.group(1).equals("SNAPSHOT")) {
                    return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10));
                }
                try {
                    Calendar cal = new GregorianCalendar();
                    cal.setTimeZone(TimeZone.getTimeZone("GMT"));
                    cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(2)));
                    cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(3)) - 1);
                    cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(4)));
                    cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(5)));
                    cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(6)));
                    cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(7)));
                    long timestamp = cal.getTimeInMillis();
                    int buildNumber = Integer.parseInt(matcher.group(8));
                    return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10),
                            timestamp, buildNumber);
                } catch (NullPointerException e) {
                    return null;
                }
            }
        };
    } else {
        rule = Pattern.compile("\\Q" + artifactId + "\\E-\\Q" + version + "\\E(?:-([^.]+))?\\.(.+)");
        factory = new ArtifactFactory() {
            public Artifact get(File file) {
                Matcher matcher = rule.matcher(file.getName());
                if (!matcher.matches()) {
                    return null;
                }
                return new Artifact(groupId, artifactId, version, matcher.group(1), matcher.group(2));
            }
        };
    }
    File[] files = versionDir.listFiles();
    Set<Artifact> result = new HashSet<Artifact>(files.length);
    for (int i = 0; i < files.length; i++) {
        if (!files[i].isFile() || !rule.matcher(files[i].getName()).matches()) {
            continue;
        }
        Artifact artifact = factory.get(files[i]);
        if (artifact != null) {
            result.add(artifact);
        }
    }
    return result;
}

From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java

public void simpleInvitionIcalLink() {
    // Create a TimeZone
    TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    TimeZone timezone = registry.getTimeZone("America/Mexico_City");
    VTimeZone tz = timezone.getVTimeZone();

    // Start Date is on: April 1, 2008, 9:00 am
    java.util.Calendar startDate = new GregorianCalendar();
    startDate.setTimeZone(timezone);
    startDate.set(java.util.Calendar.MONTH, java.util.Calendar.APRIL);
    startDate.set(java.util.Calendar.DAY_OF_MONTH, 1);
    startDate.set(java.util.Calendar.YEAR, 2008);
    startDate.set(java.util.Calendar.HOUR_OF_DAY, 9);
    startDate.set(java.util.Calendar.MINUTE, 0);
    startDate.set(java.util.Calendar.SECOND, 0);

    // End Date is on: April 1, 2008, 13:00
    java.util.Calendar endDate = new GregorianCalendar();
    endDate.setTimeZone(timezone);//from  ww w . j  a v  a2s. com
    endDate.set(java.util.Calendar.MONTH, java.util.Calendar.APRIL);
    endDate.set(java.util.Calendar.DAY_OF_MONTH, 1);
    endDate.set(java.util.Calendar.YEAR, 2008);
    endDate.set(java.util.Calendar.HOUR_OF_DAY, 13);
    endDate.set(java.util.Calendar.MINUTE, 0);
    endDate.set(java.util.Calendar.SECOND, 0);

    // Create the event
    String eventName = "Progress Meeting";
    DateTime start = new DateTime(startDate.getTime());
    DateTime end = new DateTime(endDate.getTime());
    VEvent meeting = new VEvent(start, end, eventName);

    // add timezone info..
    meeting.getProperties().add(tz.getTimeZoneId());

    // generate unique identifier..
    UidGenerator ug;
    try {
        ug = new UidGenerator("uidGen");

        Uid uid = ug.generateUid();
        meeting.getProperties().add(uid);
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // add attendees..
    Attendee dev1 = new Attendee(URI.create("mailto:dev1@mycompany.com"));
    dev1.getParameters().add(Role.REQ_PARTICIPANT);
    dev1.getParameters().add(new Cn("Developer 1"));
    meeting.getProperties().add(dev1);

    Attendee dev2 = new Attendee(URI.create("mailto:dev2@mycompany.com"));
    dev2.getParameters().add(Role.OPT_PARTICIPANT);
    dev2.getParameters().add(new Cn("Developer 2"));
    meeting.getProperties().add(dev2);

    // Create a calendar
    net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
    icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
    icsCalendar.getProperties().add(CalScale.GREGORIAN);
    icsCalendar.getProperties().add(Version.VERSION_2_0);

    // Add the event and print
    icsCalendar.getComponents().add(meeting);

    Organizer orger = new Organizer(URI.create("seba.wagner@gmail.com"));
    orger.getParameters().add(new Cn("Sebastian Wagner"));
    meeting.getProperties().add(orger);

    icsCalendar.getProperties().add(Method.REQUEST);

    System.out.println(icsCalendar);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    CalendarOutputter outputter = new CalendarOutputter();
    try {
        outputter.output(icsCalendar, bout);
        iCalMimeBody = bout.toByteArray();

        sendIcalMessage();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ValidationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.openmrs.module.webservices.rest.web.ConversionUtilTest.java

/**
 * @see ConversionUtil#convert(Object,Type)
 * @verifies String to Date conversion for multiple formatted date/dateTime strings
 *//*  www  .jav a2 s .  com*/
@Test
public void convert_shouldReturnEqualsDateFromString() throws Exception {
    Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("2011-05-01T00:00:00.000");
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.setTimeZone(TimeZone.getDefault());
    Date expected = cal.getTime();
    String[] dateFormats = { "2011-05-01", "2011-05-01 00:00:00", "2011-05-01T00:00:00.000",
            "2011-05-01T00:00:00.000" };
    for (int i = 0; i < dateFormats.length; i++) {
        Date result = (Date) ConversionUtil.convert(dateFormats[i], Date.class);
        Assert.assertEquals(result, expected);
    }
}

From source file:org.wikipedia.nirvana.nirvanabot.MockNirvanaBot.java

private Revision parseRevision(MockNirvanaWiki wiki, JSONObject revisionJson) {
    long revid = (Long) revisionJson.get("revid");
    long timestamp = (Long) revisionJson.get("timestamp");
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(timestamp);//from   www.ja  v  a2  s  . c  o m
    c.setTimeZone(TimeZone.getTimeZone("UTC"));
    String title = (String) revisionJson.get("title");
    String summary = (String) revisionJson.get("summary");
    String user = (String) revisionJson.get("user");
    boolean minor = (Boolean) revisionJson.get("minor");
    boolean bot = (Boolean) revisionJson.get("bot");
    boolean rvnew = (Boolean) revisionJson.get("rvnew");
    int size = (int) (long) (Long) revisionJson.get("size");
    Revision r = wiki.new Revision(revid, c, title, summary, user, minor, bot, rvnew, size);
    return r;
}

From source file:org.orekit.SolarInputs97to05.java

public double getAp(AbsoluteDate date) {
    double result = Double.NaN;
    try {//  www.  j  av  a  2s .  co  m
        findClosestLine(date);
        Calendar cal = new GregorianCalendar();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.setTime(date.toDate(TimeScalesFactory.getUTC()));
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        for (int i = 0; i < 8; i++) {
            if ((hour >= (i * 3)) && (hour < ((i + 1) * 3))) {
                result = currentParam.ap[i];
            }
        }
    } catch (OrekitException e) {
        // nothing
    }
    return result;
}

From source file:org.sufficientlysecure.keychain.ui.adapter.SubkeysAddedAdapter.java

public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        // Not recycled, inflate a new view
        convertView = mInflater.inflate(R.layout.view_key_adv_subkey_item, parent, false);
        final ViewHolder holder = new ViewHolder();
        holder.vKeyId = (TextView) convertView.findViewById(R.id.subkey_item_key_id);
        holder.vKeyDetails = (TextView) convertView.findViewById(R.id.subkey_item_details);
        holder.vKeyExpiry = (TextView) convertView.findViewById(R.id.subkey_item_expiry);
        holder.vCertifyIcon = (ImageView) convertView.findViewById(R.id.subkey_item_ic_certify);
        holder.vSignIcon = (ImageView) convertView.findViewById(R.id.subkey_item_ic_sign);
        holder.vEncryptIcon = (ImageView) convertView.findViewById(R.id.subkey_item_ic_encrypt);
        holder.vAuthenticateIcon = (ImageView) convertView.findViewById(R.id.subkey_item_ic_authenticate);

        holder.vDelete = (ImageButton) convertView.findViewById(R.id.subkey_item_delete_button);
        holder.vDelete.setVisibility(View.VISIBLE); // always visible

        // not used:
        ImageView vEdit = (ImageView) convertView.findViewById(R.id.subkey_item_edit_image);
        vEdit.setVisibility(View.GONE);
        ImageView vStatus = (ImageView) convertView.findViewById(R.id.subkey_item_status);
        vStatus.setVisibility(View.GONE);

        convertView.setTag(holder);//  ww w.  j a  va 2  s  .  c o  m
    }

    final ViewHolder holder = (ViewHolder) convertView.getTag();

    // save reference to model item
    holder.mModel = getItem(position);

    String algorithmStr = KeyFormattingUtils.getAlgorithmInfo(mActivity, holder.mModel.mAlgorithm,
            holder.mModel.mKeySize, holder.mModel.mCurve);

    boolean isMasterKey = mNewKeyring && position == 0;
    if (isMasterKey) {
        holder.vKeyId.setTypeface(null, Typeface.BOLD);
        holder.vDelete.setImageResource(R.drawable.ic_change_grey_24dp);
        holder.vDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // swapping out the old master key with newly set master key
                AddSubkeyDialogFragment addSubkeyDialogFragment = AddSubkeyDialogFragment.newInstance(true);
                addSubkeyDialogFragment.setOnAlgorithmSelectedListener(
                        new AddSubkeyDialogFragment.OnAlgorithmSelectedListener() {
                            @Override
                            public void onAlgorithmSelected(SaveKeyringParcel.SubkeyAdd newSubkey) {
                                // calculate manually as the provided position variable
                                // is not always accurate
                                int pos = SubkeysAddedAdapter.this.getPosition(holder.mModel);
                                SubkeysAddedAdapter.this.remove(holder.mModel);
                                SubkeysAddedAdapter.this.insert(newSubkey, pos);
                            }
                        });
                addSubkeyDialogFragment.show(((FragmentActivity) mActivity).getSupportFragmentManager(),
                        "addSubkeyDialog");
            }
        });
    } else {
        holder.vKeyId.setTypeface(null, Typeface.NORMAL);
        holder.vDelete.setImageResource(R.drawable.ic_close_grey_24dp);
        holder.vDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // remove reference model item from adapter (data and notify about change)
                SubkeysAddedAdapter.this.remove(holder.mModel);
            }
        });
    }

    holder.vKeyId.setText(R.string.edit_key_new_subkey);
    holder.vKeyDetails.setText(algorithmStr);

    if (holder.mModel.mExpiry != 0L) {
        Date expiryDate = new Date(holder.mModel.mExpiry * 1000);
        Calendar expiryCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        expiryCal.setTime(expiryDate);
        // convert from UTC to time zone of device
        expiryCal.setTimeZone(TimeZone.getDefault());

        holder.vKeyExpiry.setText(getContext().getString(R.string.label_expiry) + ": "
                + DateFormat.getDateFormat(getContext()).format(expiryCal.getTime()));
    } else {
        holder.vKeyExpiry.setText(
                getContext().getString(R.string.label_expiry) + ": " + getContext().getString(R.string.none));
    }

    int flags = holder.mModel.mFlags;
    if ((flags & KeyFlags.CERTIFY_OTHER) > 0) {
        holder.vCertifyIcon.setVisibility(View.VISIBLE);
    } else {
        holder.vCertifyIcon.setVisibility(View.GONE);
    }
    if ((flags & KeyFlags.SIGN_DATA) > 0) {
        holder.vSignIcon.setVisibility(View.VISIBLE);
    } else {
        holder.vSignIcon.setVisibility(View.GONE);
    }
    if (((flags & KeyFlags.ENCRYPT_COMMS) > 0) || ((flags & KeyFlags.ENCRYPT_STORAGE) > 0)) {
        holder.vEncryptIcon.setVisibility(View.VISIBLE);
    } else {
        holder.vEncryptIcon.setVisibility(View.GONE);
    }
    if ((flags & KeyFlags.AUTHENTICATION) > 0) {
        holder.vAuthenticateIcon.setVisibility(View.VISIBLE);
    } else {
        holder.vAuthenticateIcon.setVisibility(View.GONE);
    }

    return convertView;
}