Example usage for java.text DateFormat SHORT

List of usage examples for java.text DateFormat SHORT

Introduction

In this page you can find the example usage for java.text DateFormat SHORT.

Prototype

int SHORT

To view the source code for java.text DateFormat SHORT.

Click Source Link

Document

Constant for short style pattern.

Usage

From source file:eu.esdihumboldt.hale.io.html.HtmlMappingExporter.java

@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter)
        throws IOProviderConfigurationException, IOException {
    this.reporter = reporter;

    context = new VelocityContext();
    cellIds = new Identifiers<Cell>(Cell.class, false);

    alignment = getAlignment();// w  ww . jav a 2 s  .c o  m

    URL headlinePath = this.getClass().getResource("bg-headline.png"); //$NON-NLS-1$
    URL cssPath = this.getClass().getResource("style.css"); //$NON-NLS-1$
    URL linkPath = this.getClass().getResource("int_link.png"); //$NON-NLS-1$
    URL tooltipIcon = this.getClass().getResource("tooltip.gif"); //$NON-NLS-1$
    final String filesSubDir = FilenameUtils
            .removeExtension(FilenameUtils.getName(getTarget().getLocation().getPath())) + "_files"; //$NON-NLS-1$
    final File filesDir = new File(FilenameUtils.getFullPath(getTarget().getLocation().getPath()), filesSubDir);

    filesDir.mkdirs();
    context.put(FILE_DIRECTORY, filesSubDir);

    try {
        init();
    } catch (Exception e) {
        return reportError(reporter, "Initializing error", e);
    }
    File cssOutputFile = new File(filesDir, "style.css");
    FileUtils.copyFile(getInputFile(cssPath), cssOutputFile);

    // create headline picture
    File headlineOutputFile = new File(filesDir, "bg-headline.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(headlinePath), headlineOutputFile);

    File linkOutputFile = new File(filesDir, "int_link.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(linkPath), linkOutputFile);

    File tooltipIconFile = new File(filesDir, "tooltip.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(tooltipIcon), tooltipIconFile);

    File htmlExportFile = new File(getTarget().getLocation().getPath());
    if (projectInfo != null) {
        Date date = new Date();
        DateFormat dfm = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);

        // associate variables with information data
        String exportDate = dfm.format(date);
        context.put(EXPORT_DATE, exportDate);

        if (projectInfo.getCreated() != null) {
            String created = dfm.format(projectInfo.getCreated());
            context.put(CREATED_DATE, created);
        }

        context.put(PROJECT_INFO, projectInfo);
    }

    if (alignment != null) {
        Collection<TypeCellInfo> typeCellInfos = new ArrayList<TypeCellInfo>();
        Collection<? extends Cell> cells = alignment.getTypeCells();
        Iterator<? extends Cell> it = cells.iterator();
        while (it.hasNext()) {
            final Cell cell = it.next();
            // this is the collection of type cell info
            TypeCellInfo typeCellInfo = new TypeCellInfo(cell, alignment, cellIds, filesSubDir);
            typeCellInfos.add(typeCellInfo);
        }
        // put the full collection of type cell info to the context (for the
        // template)
        context.put(TYPE_CELL_INFOS, typeCellInfos);
        createImages(filesDir);
    }

    context.put(TOOLTIP, getParameter(TOOLTIP).as(boolean.class));

    Template template;
    try {
        template = velocityEngine.getTemplate(templateFile.getName(), "UTF-8");
    } catch (Exception e) {
        return reportError(reporter, "Could not load template", e);
    }

    FileWriter fileWriter = new FileWriter(htmlExportFile);
    template.merge(context, fileWriter);
    fileWriter.close();

    reporter.setSuccess(true);
    return reporter;
}

From source file:net.naonedbus.fragment.impl.ItineraireFragment.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mDateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
    mIconPadding = getResources().getDimensionPixelSize(R.dimen.itinerary_icon_padding);

    if (savedInstanceState != null) {
        mFromLocation.set((Location) savedInstanceState.getParcelable(BUNDLE_LOCATION_FROM));
        mToLocation.set((Location) savedInstanceState.getParcelable(BUNDLE_LOCATION_TO));

        mDateTime.setMillis(savedInstanceState.getLong(BUNDLE_DATE_TIME));
        mArriveBy = savedInstanceState.getBoolean(BUNDLE_ARRIVE_BY);
        mIconFromResId = savedInstanceState.getInt(BUNDLE_ICON_FROM);
        mIconToResId = savedInstanceState.getInt(BUNDLE_ICON_TO);
        mIconFromColor = savedInstanceState.getInt(BUNDLE_COLOR_FROM);
        mIconToColor = savedInstanceState.getInt(BUNDLE_COLOR_TO);

        final List<Parcelable> results = savedInstanceState.getParcelableArrayList(BUNDLE_RESULTS);
        for (final Parcelable parcelable : results) {
            mItineraryWrappers.add((ItineraryWrapper) parcelable);
        }//  ww w  . j a  va 2s.  co m

    }
}

From source file:org.apache.syncope.client.console.SyncopeSession.java

public DateFormat getDateFormat() {
    final Locale locale = getLocale() == null ? Locale.ENGLISH : getLocale();

    return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
}

From source file:de.jcup.egradle.eclipse.ide.execution.GradleExecutionDelegate.java

/**
 * Execute and give output by given progress monitor
 * //  w  w  w . j  ava 2  s .c om
 * @param monitor
 *            - progress monitor
 * @throws Exception
 */
public void execute(IProgressMonitor monitor) throws Exception {
    processExecutionResult = new ProcessExecutionResult();
    try {
        GradleRootProject rootProject = context.getRootProject();
        String commandString = context.getCommandString();
        String progressDescription = "Executing gradle commands:" + commandString + " in "
                + context.getRootProject().getFolder().getAbsolutePath();

        File folder = rootProject.getFolder();
        String rootProjectFolderName = folder.getName();
        String executionStartTime = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                .format(new Date());

        monitor.beginTask(progressDescription, context.getAmountOfWorkToDo());
        if (monitor.isCanceled()) {
            return;
        }
        beforeExecutionDone(monitor);
        if (monitor.isCanceled()) {
            return;
        }
        outputHandler.output("\n" + executionStartTime + " " + progressDescription);
        outputHandler.output("Root project '" + rootProjectFolderName + "' executing " + commandString);

        if (monitor.isCanceled()) {
            outputHandler.output("[CANCELED]");
            processExecutionResult.setCanceledByuser(true);
            return;
        }
        ProgressMonitorCancelStateProvider cancelStateProvider = new ProgressMonitorCancelStateProvider(
                monitor);
        context.register(cancelStateProvider);

        processExecutionResult = executor.execute(context);
        if (processExecutionResult.isOkay()) {
            outputHandler.output("[OK]");
        } else {
            outputHandler.output("[FAILED]");
        }
        afterExecutionDone(monitor);
    } catch (Exception e) {
        throw new InvocationTargetException(e);
    } finally {
        monitor.done();
    }

}

From source file:org.grails.gsp.GroovyPageWritable.java

protected Writer doWriteTo(OutputContext outputContext, Writer out) throws IOException {
    if (shouldShowGroovySource(outputContext)) {
        // Set it to TEXT
        outputContext.setContentType(GROOVY_SOURCE_CONTENT_TYPE); // must come before response.getOutputStream()
        writeGroovySourceToResponse(metaInfo, out);
    } else {//from  ww  w.ja v a 2  s . c om
        boolean debugTemplates = shouldDebugTemplates(outputContext);

        // Set it to HTML by default
        if (metaInfo.getCompilationException() != null) {
            throw metaInfo.getCompilationException();
        }

        // Set up the script context
        AbstractTemplateVariableBinding parentBinding = null;
        boolean hasRequest = outputContext != null;
        boolean newParentCreated = false;

        if (hasRequest) {
            parentBinding = outputContext.getBinding();
            if (parentBinding == null) {
                parentBinding = outputContext.createAndRegisterRootBinding();
                newParentCreated = true;
            }
        }

        if (allowSettingContentType && hasRequest) {
            // only try to set content type when evaluating top level GSP
            boolean contentTypeAlreadySet = outputContext.isContentTypeAlreadySet();
            if (!contentTypeAlreadySet) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Writing output with content type: " + metaInfo.getContentType());
                }
                outputContext.setContentType(metaInfo.getContentType()); // must come before response.getWriter()
            }
        }

        GroovyPageBinding binding = createBinding(parentBinding);
        if (hasRequest) {
            outputContext.setBinding(binding);
        }

        GroovyPage page = null;
        try {
            page = (GroovyPage) metaInfo.getPageClass().newInstance();
        } catch (Exception e) {
            throw new GroovyPagesException("Problem instantiating page class", e);
        }
        page.setBinding(binding);
        binding.setOwner(page);

        page.initRun(out, outputContext, metaInfo);

        int debugId = 0;
        long debugStartTimeMs = 0;
        if (debugTemplates) {
            debugId = incrementAndGetDebugTemplatesIdCounter(outputContext);
            out.write("<!-- GSP #");
            out.write(String.valueOf(debugId));
            out.write(" START template: ");
            out.write(page.getGroovyPageFileName());
            out.write(" precompiled: ");
            out.write(String.valueOf(metaInfo.isPrecompiledMode()));
            out.write(" lastmodified: ");
            out.write(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                    .format(new Date(metaInfo.getLastModified())));
            out.write(" -->");
            debugStartTimeMs = System.currentTimeMillis();
        }
        try {
            page.run();
        } finally {
            page.cleanup();
            if (hasRequest) {
                if (newParentCreated) {
                    outputContext.setBinding(null);
                } else {
                    outputContext.setBinding(parentBinding);
                }
            }
        }
        if (debugTemplates) {
            out.write("<!-- GSP #");
            out.write(String.valueOf(debugId));
            out.write(" END template: ");
            out.write(page.getGroovyPageFileName());
            out.write(" rendering time: ");
            out.write(String.valueOf(System.currentTimeMillis() - debugStartTimeMs));
            out.write(" ms -->");
        }
    }
    return out;
}

From source file:org.sakaiproject.time.impl.BasicTimeService.java

/**
 * Final initialization, once all dependencies are set.
 *///from   ww  w. j av a2  s  .  co m
public void init() {
    /** The time zone for our GMT times. */
    M_tz = TimeZone.getTimeZone("GMT");

    M_log.info("init()");

    /**
     * a calendar to clone for GMT time construction
     */
    M_GCal = getCalendar(M_tz, 0, 0, 0, 0, 0, 0, 0);

    // Note: formatting for GMT time representations
    M_fmtA = (DateFormat) (new SimpleDateFormat("yyyyMMddHHmmssSSS"));
    M_fmtB = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
    M_fmtC = DateFormat.getTimeInstance(DateFormat.SHORT);
    M_fmtD = DateFormat.getDateInstance(DateFormat.MEDIUM);
    M_fmtE = (DateFormat) (new SimpleDateFormat("yyyyMMddHHmmss"));
    M_fmtG = (DateFormat) (new SimpleDateFormat("yyyy/DDD/HH/")); // that's year, day of year, hour

    M_fmtA.setTimeZone(M_tz);
    M_fmtB.setTimeZone(M_tz);
    M_fmtC.setTimeZone(M_tz);
    M_fmtD.setTimeZone(M_tz);
    M_fmtE.setTimeZone(M_tz);
    M_fmtG.setTimeZone(M_tz);

    //register the Cache
    M_userTzCache = memoryService.newCache("org.sakaiproject.time.impl.BasicTimeService.userTimezoneCache");
}

From source file:com.kth.baasio.baassample.utils.EtcUtils.java

public static String getSimpleDateString(long millis) {
    String time = null;//from ww  w . j ava 2s. co  m

    if (Locale.getDefault().equals(Locale.KOREA) || Locale.getDefault().equals(Locale.KOREAN)) {
        SimpleDateFormat formatter = new SimpleDateFormat("M d? a h mm", Locale.getDefault());
        time = formatter.format(new Date(millis));
    } else {
        time = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault())
                .format(new Date(millis));
    }

    return time;
}

From source file:com.mobicage.rogerthat.FriendsLocationActivity.java

private void displayLocations() {
    T.UI();/*from w w w. j  a  va  2 s . c o m*/
    mLoadingProgressbar.setVisibility(View.GONE);
    mLoadingLayout.setVisibility(View.GONE);
    mFriendMap.setVisibility(View.VISIBLE);
    // Calculate bounds
    double maxLat = Double.MIN_VALUE;
    double minLat = Double.MAX_VALUE;
    double maxLon = Double.MIN_VALUE;
    double minLon = Double.MAX_VALUE;
    for (LocationResultRequestTO fl : mLocations) {
        if (fl.location.latitude > maxLat)
            maxLat = fl.location.latitude;
        if (fl.location.latitude < minLat)
            minLat = fl.location.latitude;
        if (fl.location.longitude > maxLon)
            maxLon = fl.location.longitude;
        if (fl.location.longitude < minLon)
            minLon = fl.location.longitude;
    }
    mFriendMap.getController().zoomToSpan((int) ((maxLat - minLat)), (int) ((maxLon - minLon)));
    GeoPoint center = new GeoPoint((int) ((maxLat + minLat) / 2), (int) ((maxLon + minLon) / 2));
    mFriendMap.getController().setCenter(center);
    for (LocationResultRequestTO fl : mLocations) {
        if (mAdded.contains(fl.friend))
            continue;
        mAdded.add(fl.friend);

        if (fl.friend.equals(mMyIdentity.getEmail())) {
            DrawableItemizedOverlay overlay = new DrawableItemizedOverlay(getAvatar(mMyIdentity), this);
            GeoPoint point = new GeoPoint((int) (fl.location.latitude), (int) (fl.location.longitude));
            Date date = new Date(fl.location.timestamp * 1000);
            OverlayItem overlayitem = new OverlayItem(point, mMyIdentity.getName(),
                    getString(R.string.friend_map_marker,
                            DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(date),
                            fl.location.accuracy));
            overlay.addOverlay(overlayitem);
            mFriendMap.getOverlays().add(overlay);
        } else {
            Friend friend = mFriendsPlugin.getStore().getExistingFriend(fl.friend);

            DrawableItemizedOverlay overlay = new DrawableItemizedOverlay(getAvatar(friend), this);
            GeoPoint point = new GeoPoint((int) (fl.location.latitude), (int) (fl.location.longitude));
            Date date = new Date(fl.location.timestamp * 1000);
            OverlayItem overlayitem = new OverlayItem(point, friend.getDisplayName(),
                    getString(R.string.friend_map_marker,
                            DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(date),
                            fl.location.accuracy));
            overlay.addOverlay(overlayitem);
            mFriendMap.getOverlays().add(overlay);
        }
    }
    if (mAdded.size() == 1 && mAdded.get(0).equals(mMyIdentity.getEmail()))
        UIUtils.showLongToast(this,
                getString(R.string.your_location_displayed_friend_have_contacted_for_their_location));
}

From source file:no.firestorm.weathernotificatonservice.WeatherNotificationService.java

/**
 * Shows a notification with information about the error, either NoLocation
 * or DownloadError (default)/*  ww  w  .  jav a  2  s  . c o  m*/
 * 
 * @param e
 *            Exception
 */
private void makeNotification(Exception e) {
    int tickerIcon, contentIcon;
    CharSequence tickerText, contentTitle, contentText, contentTime;
    final DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
    contentIcon = android.R.drawable.stat_notify_error;
    final Context context = WeatherNotificationService.this;
    contentTime = df.format(new Date());
    long when = (new Date()).getTime();

    if (e instanceof NoLocationException) {
        setShortAlarm();
        tickerText = WeatherNotificationService.this.getString(R.string.location_error);
        contentTitle = WeatherNotificationService.this.getString(R.string.location_error);
    } else {
        if (e instanceof NetworkErrorException)
            updateAlarm();
        else
            setShortAlarm();

        // Network error has occurred
        // Set title
        tickerText = WeatherNotificationService.this.getString(R.string.download_error);
        contentTitle = WeatherNotificationService.this.getString(R.string.download_error);
    }

    final Date lastTime = WeatherNotificationSettings.getLastUpdateTime(WeatherNotificationService.this);
    Float temperatureF = null;
    if (lastTime != null) {
        temperatureF = Float.parseFloat(WeatherNotificationSettings.getSavedLastTemperature(context));
        contentText = String.format("%s %.1f C %s %s", context.getString(R.string.last_temperature),
                temperatureF, context.getString(R.string._tid_), df.format(lastTime));
        tickerIcon = TempToDrawable.getDrawableFromTemp(temperatureF);

    } else {
        contentText = WeatherNotificationService.this.getString(R.string.press_for_update);
        tickerIcon = android.R.drawable.stat_notify_error;
    }

    makeNotification(tickerIcon, contentIcon, tickerText, contentTitle, contentText, contentTime, when,
            temperatureF);

}

From source file:com.concursive.connect.web.modules.communications.jobs.EmailUpdatesJob.java

/**
 * Process email updates queue//from w  w w  .ja  v  a  2  s. c o  m
 *
 * @param context
 * @throws JobExecutionException
 */
public void execute(JobExecutionContext context) throws JobExecutionException {
    SchedulerContext schedulerContext = null;
    Connection db = null;
    try {
        schedulerContext = context.getScheduler().getContext();
        db = SchedulerUtils.getConnection(schedulerContext);
        ApplicationPrefs prefs = (ApplicationPrefs) schedulerContext.get("ApplicationPrefs");
        ServletContext servletContext = (ServletContext) schedulerContext.get("ServletContext");
        LOG.debug("EmailUpdatesJob triggered...");
        while (true) {
            //Retrieve retrieve the next item from the email_updates_queue that is scheduled for now.
            EmailUpdatesQueueList queueList = new EmailUpdatesQueueList();
            queueList.setScheduledOnly(true);
            queueList.setMax(1);
            queueList.buildList(db);
            if (queueList.size() == 0) {
                LOG.debug("No more scheduled emails to be processed...");
                break;
            } else {
                EmailUpdatesQueue queue = (EmailUpdatesQueue) queueList.get(0);
                //Lock that record by issuing a successful update which updates the status = 1 to status = 2.
                if (EmailUpdatesQueue.lockQueue(queue, db)) {
                    LOG.debug("Processing scheduled email queue...");

                    // User who needs to be sent an email
                    User user = UserUtils.loadUser(queue.getEnteredBy());

                    //Determine the date range to query the activity stream data
                    Timestamp min = queue.getProcessed();
                    Timestamp max = new Timestamp(System.currentTimeMillis());

                    if (min == null) {
                        //set the min value to be queue's entered date to restrict picking up all the records in the system
                        min = queue.getEntered();
                    }

                    Configuration configuration = ApplicationPrefs.getFreemarkerConfiguration(servletContext);
                    // Determine the message to be sent
                    String message = EmailUpdatesUtils.getEmailHTMLMessage(db, prefs, configuration, queue, min,
                            max);

                    if (message != null) {
                        // Use the user's locale to format the date
                        SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat
                                .getDateInstance(DateFormat.SHORT, user.getLocale());
                        formatter.applyPattern(
                                DateUtils.get4DigitYearDateFormat(formatter.toLocalizedPattern()));
                        String date = formatter.format(max);

                        String subject = "";
                        if (queue.getScheduleOften()) {
                            subject = "Activity Updates for " + date + " - Recent updates";
                        } else if (queue.getScheduleDaily()) {
                            subject = "Activity Updates for " + date + " - Daily update";
                        } else if (queue.getScheduleWeekly()) {
                            subject = "Activity Updates for " + date + " - Weekly update";
                        } else if (queue.getScheduleMonthly()) {
                            subject = "Activity Updates for " + date + " - Monthly update";
                        }
                        //Try to send the email
                        LOG.debug("Sending email...");
                        SMTPMessage email = SMTPMessageFactory.createSMTPMessageInstance(prefs.getPrefs());
                        email.setFrom(prefs.get(ApplicationPrefs.EMAILADDRESS));
                        email.addReplyTo(prefs.get(ApplicationPrefs.EMAILADDRESS));
                        email.addTo(user.getEmail());
                        email.setSubject(subject);
                        email.setType("text/html");
                        email.setBody(message);
                        email.send();
                    } else {
                        LOG.debug("No activities to report. Skipping email.");
                    }

                    //Determine the next schedule date and save the schedule date and status=1
                    LOG.debug("Calculating next run date...");
                    queue.calculateNextRunDate(db);

                    //Set the max date to be the queue's processed date
                    LOG.debug("Updating process date...");
                    queue.updateProcessedDate(db, max);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new JobExecutionException(e.getMessage());
    } finally {
        SchedulerUtils.freeConnection(schedulerContext, db);
    }
}