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:org.glom.web.server.libglom.Document.java

/**
 * @param elementValue/* www .j a  v  a 2 s.  c o m*/
 * @param glomType
 * @return
 */
private DataItem getNodeTextChildAsValue(final Element element, final GlomFieldType type) {
    final DataItem result = new DataItem();

    final String str = element.getTextContent();

    // Unescape "" to ", because to_file_format() escaped ", as specified by the CSV RFC:
    String unescaped = "";
    if (type == GlomFieldType.TYPE_IMAGE) {
        unescaped = str; // binary data does not have quote characters so we do not bother to escape or unescape it.
    } else {
        unescaped = str.replace(QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT);
    }

    switch (type) {
    case TYPE_BOOLEAN: {
        final boolean value = (unescaped.equals("true"));
        result.setBoolean(value);
        break;
    }
    case TYPE_DATE: {
        final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
        Date value = null;
        try {
            value = dateFormat.parse(unescaped);
        } catch (final ParseException e) {
            // e.printStackTrace();
        }
        result.setDate(value);
        break;
    }
    case TYPE_IMAGE: {
        //Glom (at least since 2.23/24) uses base64 for the images:

        //This is only used on the server-side,
        //either to create a database, during tests,
        //or to return the full data from our OnlineGlomImage service.
        //It is removed before being passed to the client-side.

        /* This does not seem to work with the text from g_base64_encode() that Glom uses,
         * maybe because of the newlines, which are apparently OK:
         * http://en.wikipedia.org/wiki/Base64#MIME
         * final byte[] bytes = com.google.gwt.user.server.Base64Utils.fromBase64(unescaped);
         */

        /* Use org.apache.commons.codec.binary.Base64: */
        final Base64 decoder = new Base64();
        byte[] bytes = (byte[]) decoder.decode(unescaped.getBytes());

        result.setImageData(bytes);

        break;
    }
    case TYPE_NUMERIC: {
        double value = 0;
        try {
            value = Double.valueOf(unescaped);
        } catch (final NumberFormatException e) {
            // e.printStackTrace();
        }

        result.setNumber(value);
        break;
    }
    case TYPE_TEXT:
        result.setText(unescaped);
        break;
    case TYPE_TIME:
        // TODO
        break;
    default:
        Log.error(documentID, "getNodeTextChildAsValue(): unexpected or invalid field type.");
        break;
    }

    return result;
}

From source file:com.appeaser.sublimepickerlibrary.recurrencepicker.RecurrenceOptionCreator.java

void initializeLayout() {
    int weekButtonUnselectedTextColor, weekButtonSelectedTextColor, weekButtonSelectedCircleColor;

    final TypedArray a = getContext().obtainStyledAttributes(R.styleable.RecurrenceOptionCreator);
    try {/*w  ww .ja  va2s .  co m*/
        mHeaderBackgroundColor = a.getColor(R.styleable.RecurrenceOptionCreator_spHeaderBackground, 0);

        int endDateFormat = a.getInt(R.styleable.RecurrenceOptionCreator_spEndDateFormat, 1);

        mEndDateFormatter = DateFormat.getDateInstance(
                endDateFormat == 0 ? DateFormat.SHORT : DateFormat.MEDIUM, Locale.getDefault());

        weekButtonUnselectedTextColor = a.getColor(
                R.styleable.RecurrenceOptionCreator_spWeekButtonUnselectedTextColor, SUtils.COLOR_ACCENT);
        weekButtonSelectedTextColor = a.getColor(
                R.styleable.RecurrenceOptionCreator_spWeekButtonSelectedTextColor,
                SUtils.COLOR_TEXT_PRIMARY_INVERSE);
        weekButtonSelectedCircleColor = a.getColor(
                R.styleable.RecurrenceOptionCreator_spWeekButtonSelectedCircleColor, SUtils.COLOR_ACCENT);
    } finally {
        a.recycle();
    }

    mResources = getResources();

    LayoutInflater.from(getContext()).inflate(R.layout.recurrence_picker, this);

    mRecurrencePicker = findViewById(R.id.recurrence_picker);

    mDateOnlyPicker = (RecurrenceEndDatePicker) findViewById(R.id.date_only_picker);
    mDateOnlyPicker.setVisibility(View.GONE);

    // OK/Cancel buttons
    mButtonLayout = (DecisionButtonLayout) findViewById(R.id.roc_decision_button_layout);
    mButtonLayout.applyOptions(mButtonLayoutCallback);

    SUtils.setViewBackground(findViewById(R.id.freqSpinnerHolder), mHeaderBackgroundColor,
            SUtils.CORNER_TOP_LEFT | SUtils.CORNER_TOP_RIGHT);

    /** EFrequency Spinner {Repeat daily, Repeat weekly, Repeat monthly, Repeat yearly} **/

    mFreqSpinner = (Spinner) findViewById(R.id.freqSpinner);
    mFreqSpinner.setOnItemSelectedListener(this);

    ArrayAdapter<CharSequence> freqAdapter = ArrayAdapter.createFromResource(getContext(),
            R.array.recurrence_freq, R.layout.roc_freq_spinner_item);
    freqAdapter.setDropDownViewResource(R.layout.roc_spinner_dropdown_item);
    mFreqSpinner.setAdapter(freqAdapter);

    Drawable freqSpinnerBg = ContextCompat.getDrawable(getContext(), R.drawable.abc_spinner_mtrl_am_alpha);
    PorterDuffColorFilter cfFreqSpinner = new PorterDuffColorFilter(SUtils.COLOR_TEXT_PRIMARY_INVERSE,
            PorterDuff.Mode.SRC_IN);
    if (freqSpinnerBg != null) {
        freqSpinnerBg.setColorFilter(cfFreqSpinner);
        SUtils.setViewBackground(mFreqSpinner, freqSpinnerBg);
    }

    mInterval = (EditText) findViewById(R.id.interval);
    mInterval.addTextChangedListener(new minMaxTextWatcher(1, INTERVAL_DEFAULT, INTERVAL_MAX) {
        @Override
        void onChange(int v) {
            if (mIntervalResId != -1 && mInterval.getText().toString().length() > 0) {
                mModel.interval = v;
                updateIntervalText();
                mInterval.requestLayout();
            }
        }
    });
    mIntervalPreText = (TextView) findViewById(R.id.intervalPreText);
    mIntervalPostText = (TextView) findViewById(R.id.intervalPostText);

    /** End Spinner {Forever, Until a date, For a number of events} **/

    mEndNeverStr = mResources.getString(R.string.recurrence_end_continously);
    mEndDateLabel = mResources.getString(R.string.recurrence_end_date_label);
    mEndCountLabel = mResources.getString(R.string.recurrence_end_count_label);

    mEndSpinnerArray.add(mEndNeverStr);
    mEndSpinnerArray.add(mEndDateLabel);
    mEndSpinnerArray.add(mEndCountLabel);
    mEndSpinner = (Spinner) findViewById(R.id.endSpinner);
    mEndSpinner.setOnItemSelectedListener(this);

    mEndSpinnerAdapter = new EndSpinnerAdapter(getContext(), mEndSpinnerArray, R.layout.roc_end_spinner_item,
            R.id.spinner_item, R.layout.roc_spinner_dropdown_item);
    mEndSpinner.setAdapter(mEndSpinnerAdapter);

    mEndCount = (EditText) findViewById(R.id.endCount);
    mEndCount.addTextChangedListener(new minMaxTextWatcher(1, COUNT_DEFAULT, COUNT_MAX) {
        @Override
        void onChange(int v) {
            if (mModel.endCount != v) {
                mModel.endCount = v;
                updateEndCountText();
                mEndCount.requestLayout();
            }
        }
    });
    mPostEndCount = (TextView) findViewById(R.id.postEndCount);

    mEndDateTextView = (TextView) findViewById(R.id.endDate);
    mEndDateTextView.setOnClickListener(this);

    SUtils.setViewBackground(mEndDateTextView,
            SUtils.createButtonBg(getContext(), SUtils.COLOR_BUTTON_NORMAL, SUtils.COLOR_CONTROL_HIGHLIGHT));

    // set default & checked state colors
    WeekButton.setStateColors(weekButtonUnselectedTextColor, weekButtonSelectedTextColor);

    // AOSP code handled this differently. It has been refactored to
    // let Android decide if we have enough space to show
    // all seven 'WeekButtons' inline. In this case, 'mWeekGroup2'
    // will be null (see @layout-w460dp/week_buttons).
    mWeekGroup = (LinearLayout) findViewById(R.id.weekGroup);
    mWeekGroup2 = (LinearLayout) findViewById(R.id.weekGroup2);

    // Only non-null when available width is < 460dp
    // Used only for positioning 'WeekButtons' in two rows
    // of 4 & 3.
    View eighthWeekDay = findViewById(R.id.week_day_8);
    if (eighthWeekDay != null)
        eighthWeekDay.setVisibility(View.INVISIBLE);

    // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7
    //String[] dayOfWeekString = new DateFormatSymbols().getWeekdays();

    mMonthRepeatByDayOfWeekStrs = new String[7][];
    // from Time.SUNDAY as 0 through Time.SATURDAY as 6
    mMonthRepeatByDayOfWeekStrs[0] = mResources.getStringArray(R.array.repeat_by_nth_sun);
    mMonthRepeatByDayOfWeekStrs[1] = mResources.getStringArray(R.array.repeat_by_nth_mon);
    mMonthRepeatByDayOfWeekStrs[2] = mResources.getStringArray(R.array.repeat_by_nth_tues);
    mMonthRepeatByDayOfWeekStrs[3] = mResources.getStringArray(R.array.repeat_by_nth_wed);
    mMonthRepeatByDayOfWeekStrs[4] = mResources.getStringArray(R.array.repeat_by_nth_thurs);
    mMonthRepeatByDayOfWeekStrs[5] = mResources.getStringArray(R.array.repeat_by_nth_fri);
    mMonthRepeatByDayOfWeekStrs[6] = mResources.getStringArray(R.array.repeat_by_nth_sat);

    // In Time.java day of week order e.g. Sun = 0
    int idx = RecurrenceUtils.getFirstDayOfWeek();

    // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7
    String[] dayOfWeekString = new DateFormatSymbols().getShortWeekdays();

    // CheckableDrawable's width & height
    int expandedWidthHeight = mResources.getDimensionPixelSize(R.dimen.week_button_state_on_circle_size);

    WeekButton[] tempWeekButtons = new WeekButton[7];
    tempWeekButtons[0] = (WeekButton) findViewById(R.id.week_day_1);
    tempWeekButtons[1] = (WeekButton) findViewById(R.id.week_day_2);
    tempWeekButtons[2] = (WeekButton) findViewById(R.id.week_day_3);
    tempWeekButtons[3] = (WeekButton) findViewById(R.id.week_day_4);
    tempWeekButtons[4] = (WeekButton) findViewById(R.id.week_day_5);
    tempWeekButtons[5] = (WeekButton) findViewById(R.id.week_day_6);
    tempWeekButtons[6] = (WeekButton) findViewById(R.id.week_day_7);

    for (int i = 0; i < mWeekByDayButtons.length; i++) {
        mWeekByDayButtons[idx] = tempWeekButtons[i];
        SUtils.setViewBackground(mWeekByDayButtons[idx],
                new CheckableDrawable(weekButtonSelectedCircleColor, false, expandedWidthHeight));
        mWeekByDayButtons[idx].setTextColor(weekButtonUnselectedTextColor);
        mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]);
        mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]);
        mWeekByDayButtons[idx].setOnCheckedChangeListener(this);

        if (++idx >= 7) {
            idx = 0;
        }
    }

    mMonthRepeatByRadioGroup = (RadioGroup) findViewById(R.id.monthGroup);
    mMonthRepeatByRadioGroup.setOnCheckedChangeListener(this);
    mRepeatMonthlyByNthDayOfWeek = (RadioButton) findViewById(R.id.repeatMonthlyByNthDayOfTheWeek);
    mRepeatMonthlyByNthDayOfMonth = (RadioButton) findViewById(R.id.repeatMonthlyByNthDayOfMonth);
}

From source file:org.glom.libglom.Document.java

private void setNodeTextChildAsValue(final Element element, final DataItem value, final GlomFieldType type) {
    String str = "";

    switch (type) {
    case TYPE_BOOLEAN: {
        str = value.getBoolean() ? "true" : "false";
        break;//w  ww  .  j  av  a 2 s .  c o  m
    }
    case TYPE_DATE: {
        // TODO: This is not really the format used by the Glom document:
        final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
        str = dateFormat.format(value.getDate());
        break;
    }
    case TYPE_IMAGE: {
        str = ""; // TODO
        break;
    }
    case TYPE_NUMERIC: {
        str = getStringForDecimal(value.getNumber());
        break;
    }
    case TYPE_TEXT:
        str = value.getText();
        break;
    case TYPE_TIME:
        str = ""; // TODO
        break;
    default:
        Logger.log(documentID + ": setNodeTextChildAsValue(): unexpected or invalid field type.");
        break;
    }

    final String escaped = str.replace(QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT);
    element.setTextContent(escaped);
}

From source file:op.care.supervisor.PnlHandover.java

private void createContentPanel4Day(final LocalDate day, final CollapsiblePane cpDay) {

    final JPanel dayPanel = new JPanel(new VerticalLayout());

    OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));
    OPDE.getMainframe().setBlocked(true);

    SwingWorker worker = new SwingWorker() {

        @Override/*from  w w  w. j  av  a2  s . c o  m*/
        protected Object doInBackground() throws Exception {

            //                final JPanel dayPanel = new JPanel(new VerticalLayout());
            dayPanel.setOpaque(false);

            ArrayList<Handovers> listHO = HandoversTools.getBy(day, (Homes) cmbHomes.getSelectedItem());
            ArrayList<NReport> listNR = NReportTools.getNReports4Handover(day,
                    (Homes) cmbHomes.getSelectedItem());

            Collections.sort(listNR, myComparator);

            int max = listHO.size() + listNR.size();
            int i = 0; // for zebra pattern and progress
            for (final Handovers handover : listHO) {
                OPDE.getDisplayManager()
                        .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), i, max));

                String title = "<html><table border=\"0\">" + "<tr valign=\"top\">"
                        + "<td width=\"100\" align=\"left\">"
                        + DateFormat.getTimeInstance(DateFormat.SHORT).format(handover.getPit()) + " "
                        + SYSTools.xx("misc.msg.Time.short") + "</td>"
                        + "<td width=\"100\" align=\"center\">--</td>" + "<td width=\"400\" align=\"left\">"
                        + handover.getText() + "</td>" +

                        "<td width=\"100\" align=\"left\">" + handover.getUser().getFullname() + "</td>"
                        + "</tr>" + "</table>" + "</html>";

                final DefaultCPTitle pnlSingle = new DefaultCPTitle(SYSTools.toHTMLForScreen(title),
                        new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent evt) {
                                EntityManager em = OPDE.createEM();
                                if (Handover2UserTools.containsUser(em, handover, OPDE.getLogin().getUser())) {
                                    em.close();
                                    return;
                                }
                                try {
                                    em.getTransaction().begin();
                                    Handovers myHO = em.merge(handover);
                                    Handover2User connObj = em.merge(
                                            new Handover2User(myHO, em.merge(OPDE.getLogin().getUser())));
                                    myHO.getUsersAcknowledged().add(connObj);
                                    em.getTransaction().commit();

                                    createCP4Day(day);
                                    buildPanel();

                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }
                            }
                        });

                final JButton btnInfo = new JButton(SYSConst.icon22info);
                btnInfo.setPressedIcon(SYSConst.icon22infoPressed);
                btnInfo.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnInfo.setAlignmentY(Component.TOP_ALIGNMENT);
                btnInfo.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnInfo.setContentAreaFilled(false);
                btnInfo.setBorder(null);
                btnInfo.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        OPDE.getDisplayManager().setProgressBarMessage(
                                new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));
                        OPDE.getMainframe().setBlocked(true);

                        SwingWorker worker = new SwingWorker() {

                            @Override
                            protected Object doInBackground() throws Exception {
                                SYSFilesTools.print(Handover2UserTools.getAsHTML(handover), false);
                                return null;
                            }

                            @Override
                            protected void done() {
                                try {
                                    get();
                                } catch (Exception ex1) {
                                    OPDE.fatal(ex1);
                                }
                                OPDE.getDisplayManager().setProgressBarMessage(null);
                                OPDE.getMainframe().setBlocked(false);
                            }

                        };
                        worker.execute();

                    }
                });
                pnlSingle.getRight().add(btnInfo);

                EntityManager em = OPDE.createEM();
                pnlSingle.getButton()
                        .setIcon(Handover2UserTools.containsUser(em, handover, OPDE.getLogin().getUser())
                                ? SYSConst.icon22ledGreenOn
                                : SYSConst.icon22ledRedOn);
                em.close();

                pnlSingle.getButton().setVerticalTextPosition(SwingConstants.TOP);

                JPanel zebra = new JPanel();
                zebra.setLayout(new BoxLayout(zebra, BoxLayout.LINE_AXIS));
                zebra.setOpaque(true);
                if (i % 2 == 0) {
                    zebra.setBackground(SYSConst.orange1[SYSConst.light2]);
                } else {
                    zebra.setBackground(Color.WHITE);
                }
                zebra.add(pnlSingle.getMain());
                i++;
                dayPanel.add(zebra);
            }
            for (final NReport nreport : listNR) {
                OPDE.getDisplayManager()
                        .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), i, max));

                String title = "<html><table border=\"0\">" + "<tr valign=\"top\">"
                        + "<td width=\"100\" align=\"left\">"
                        + DateFormat.getTimeInstance(DateFormat.SHORT).format(nreport.getPit()) + " "
                        + SYSTools.xx("misc.msg.Time.short") + "<br/>" + nreport.getMinutes() + " "
                        + SYSTools.xx("misc.msg.Minute(s)") + "</td>" + "<td width=\"100\" align=\"left\">"
                        + ResidentTools.getTextCompact(nreport.getResident()) + "</td>"
                        + "<td width=\"400\" align=\"left\">" + nreport.getText() + "</td>" +

                        "<td width=\"100\" align=\"left\">" + nreport.getUser().getFullname() + "</td>"
                        + "</tr>" + "</table>" + "</html>";

                final DefaultCPTitle pnlSingle = new DefaultCPTitle(SYSTools.toHTMLForScreen(title),
                        new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent evt) {
                                EntityManager em = OPDE.createEM();
                                if (NR2UserTools.containsUser(em, nreport, OPDE.getLogin().getUser())) {
                                    em.close();
                                    return;
                                }

                                try {
                                    em.getTransaction().begin();
                                    NReport myNR = em.merge(nreport);
                                    NR2User connObj = em
                                            .merge(new NR2User(myNR, em.merge(OPDE.getLogin().getUser())));
                                    myNR.getUsersAcknowledged().add(connObj);
                                    em.getTransaction().commit();
                                    createCP4Day(day);
                                    buildPanel();
                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }
                            }
                        });

                final JButton btnInfo = new JButton(SYSConst.icon22info);
                btnInfo.setPressedIcon(SYSConst.icon22infoPressed);
                btnInfo.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnInfo.setAlignmentY(Component.TOP_ALIGNMENT);
                btnInfo.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnInfo.setContentAreaFilled(false);
                btnInfo.setBorder(null);
                btnInfo.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {

                        SYSFilesTools.print(NR2UserTools.getAsHTML(nreport), false);

                        //                            OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));
                        //                            OPDE.getMainframe().setBlocked(true);
                        //
                        //                            SwingWorker worker = new SwingWorker() {
                        //
                        //                                @Override
                        //                                protected Object doInBackground() throws Exception {
                        //
                        //                                    return null;
                        //                                }
                        //
                        //                                @Override
                        //                                protected void done() {
                        //                                    OPDE.getDisplayManager().setProgressBarMessage(null);
                        //                                    OPDE.getMainframe().setBlocked(false);
                        //                                }
                        //
                        //                            };
                        //                            worker.execute();

                    }
                });
                pnlSingle.getRight().add(btnInfo);

                EntityManager em = OPDE.createEM();
                pnlSingle.getButton()
                        .setIcon(NR2UserTools.containsUser(em, nreport, OPDE.getLogin().getUser())
                                ? SYSConst.icon22ledGreenOn
                                : SYSConst.icon22ledRedOn);
                em.close();

                pnlSingle.getButton().setVerticalTextPosition(SwingConstants.TOP);

                JPanel zebra = new JPanel();
                zebra.setLayout(new BoxLayout(zebra, BoxLayout.LINE_AXIS));
                zebra.setOpaque(true);
                if (i % 2 == 0) {
                    zebra.setBackground(SYSConst.orange1[SYSConst.light2]);
                } else {
                    zebra.setBackground(Color.WHITE);
                }
                zebra.add(pnlSingle.getMain());
                i++;

                dayPanel.add(zebra);
            }
            final String key = DateFormat.getDateInstance().format(day.toDate());
            synchronized (cacheHO) {
                cacheHO.put(key, listHO);
            }
            synchronized (cacheNR) {
                cacheNR.put(key, listNR);
            }
            return null;

        }

        @Override
        protected void done() {
            try {
                get();
            } catch (Exception ex2) {
                OPDE.fatal(ex2);
            }
            cpDay.setContentPane(dayPanel);
            OPDE.getDisplayManager().setProgressBarMessage(null);
            OPDE.getMainframe().setBlocked(false);
        }
    };
    worker.execute();

}

From source file:org.sakaiproject.calendar.impl.GenericCalendarImporter.java

public List doImport(String importType, InputStream importStream, Map columnMapping,
        String[] customFieldPropertyNames) throws ImportException {
    final List rowList = new ArrayList();
    final Reader scheduleImport;

    try {// ww w . j  a  v  a 2 s  .  c  o  m
        scheduleImport = (Reader) ((Class) readerMap.get(importType)).newInstance();

        // Set the timeservice in the reader.
        scheduleImport.setTimeService(getTimeService());
    }

    catch (InstantiationException e1) {
        String msg = (String) rb.getFormattedMessage("err_import", new Object[] { importType });
        throw new ImportException(msg);
    } catch (IllegalAccessException e1) {
        String msg = (String) rb.getFormattedMessage("err_import", new Object[] { importType });
        throw new ImportException(msg);
    }

    if (scheduleImport == null) {
        throw new ImportException(rb.getString("err_import_unknown"));
    }

    // If no column mapping has been specified, use the default.
    if (columnMapping != null) {
        scheduleImport.setColumnHeaderToAtributeMapping(columnMapping);
    }

    columnMap = scheduleImport.getDefaultColumnMap();

    // Read in the file.
    scheduleImport.importStreamFromDelimitedFile(importStream, new Reader.ReaderImportRowHandler() {
        String frequencyColumn = columnMap.get(FREQUENCY_DEFAULT_COLUMN_HEADER);
        String startTimeColumn = columnMap.get(START_TIME_DEFAULT_COLUMN_HEADER);
        String endTimeColumn = columnMap.get(END_TIME_DEFAULT_COLUMN_HEADER);
        String durationTimeColumn = columnMap.get(DURATION_DEFAULT_COLUMN_HEADER);
        String dateColumn = columnMap.get(DATE_DEFAULT_COLUMN_HEADER);
        String endsColumn = columnMap.get(ENDS_DEFAULT_COLUMN_HEADER);
        String intervalColumn = columnMap.get(INTERVAL_DEFAULT_COLUMN_HEADER);
        String repeatColumn = columnMap.get(REPEAT_DEFAULT_COLUMN_HEADER);

        // This is the callback that is called for each row.
        public void handleRow(Iterator columnIterator) throws ImportException {
            final Map eventProperties = new HashMap();

            // Add all the properties to the map
            while (columnIterator.hasNext()) {
                Reader.ReaderImportCell column = (Reader.ReaderImportCell) columnIterator.next();

                String value = column.getCellValue().trim();
                Object mapCellValue = null;

                // First handle any empy columns.
                if (value.length() == 0) {
                    mapCellValue = null;
                } else {
                    if (frequencyColumn != null && frequencyColumn.equals(column.getColumnHeader())) {
                        mapCellValue = column.getCellValue();
                    } else if (endTimeColumn != null && endTimeColumn.equals(column.getColumnHeader())
                            || (startTimeColumn != null && startTimeColumn.equals(column.getColumnHeader()))) {
                        boolean success = false;

                        try {
                            mapCellValue = timeFormatter().parse(value);
                            success = true;
                        }

                        catch (ParseException e) {
                            // Try another format
                        }

                        if (!success) {
                            try {
                                mapCellValue = timeFormatterWithSeconds().parse(value);
                                success = true;
                            }

                            catch (ParseException e) {
                                // Try another format
                            }
                        }

                        if (!success) {
                            try {
                                mapCellValue = time24HourFormatter().parse(value);
                                success = true;
                            }

                            catch (ParseException e) {
                                // Try another format
                            }
                        }

                        if (!success) {
                            try {
                                mapCellValue = time24HourFormatterWithSeconds().parse(value);
                                success = true;
                            }

                            catch (ParseException e) {
                                // Give up, we've run out of possible formats.
                                String msg = (String) rb.getFormattedMessage("err_time", new Object[] {
                                        Integer.valueOf(column.getLineNumber()), column.getColumnHeader() });
                                throw new ImportException(msg);
                            }
                        }
                    } else if (durationTimeColumn != null
                            && durationTimeColumn.equals(column.getColumnHeader())) {
                        String timeFormatErrorString = (String) rb.getFormattedMessage("err_time",
                                new Object[] { Integer.valueOf(column.getLineNumber()),
                                        column.getColumnHeader() });

                        String parts[] = value.split(":");

                        if (parts.length == 1) {
                            // Convert to minutes to get into one property field.
                            try {
                                mapCellValue = Integer.valueOf(Integer.parseInt(parts[0]));
                            } catch (NumberFormatException ex) {
                                throw new ImportException(timeFormatErrorString);
                            }
                        } else if (parts.length == 2) {
                            // Convert to hours:minutes to get into one property field.
                            try {
                                mapCellValue = Integer
                                        .valueOf(Integer.parseInt(parts[0]) * 60 + Integer.parseInt(parts[1]));
                            } catch (NumberFormatException ex) {
                                throw new ImportException(timeFormatErrorString);
                            }
                        } else {
                            // Not a legal format of mm or hh:mm
                            throw new ImportException(timeFormatErrorString);
                        }
                    } else if (dateColumn != null && dateColumn.equals(column.getColumnHeader())
                            || (endsColumn != null && endsColumn.equals(column.getColumnHeader()))) {
                        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, rb.getLocale());
                        df.setLenient(false);
                        try {
                            mapCellValue = df.parse(value);
                        } catch (ParseException e) {
                            String msg = (String) rb.getFormattedMessage("err_date", new Object[] {
                                    Integer.valueOf(column.getLineNumber()), column.getColumnHeader() });
                            throw new ImportException(msg);
                        }
                    } else if (intervalColumn != null && intervalColumn.equals(column.getColumnHeader())
                            || repeatColumn != null && repeatColumn.equals(column.getColumnHeader())) {
                        try {
                            mapCellValue = Integer.valueOf(column.getCellValue());
                        } catch (NumberFormatException ex) {
                            String msg = (String) rb.getFormattedMessage("err_interval", new Object[] {
                                    Integer.valueOf(column.getLineNumber()), column.getColumnHeader() });
                            throw new ImportException(msg);
                        }
                    } else if (ITEM_TYPE_PROPERTY_NAME.equals(column.getColumnHeader())) {
                        String cellValue = column.getCellValue();
                        if (cellValue != null) {
                            if (cellValue.equals("event.activity")) {
                                mapCellValue = "Activity";
                            } else if (cellValue.equals("event.exam")) {
                                mapCellValue = "Exam";
                            } else if (cellValue.equals("event.meeting")) {
                                mapCellValue = "Meeting";
                            } else if (cellValue.equals("event.academic.calendar")) {
                                mapCellValue = "Academic Calendar";
                            } else if (cellValue.equals("event.cancellation")) {
                                mapCellValue = "Cancellation";
                            } else if (cellValue.equals("event.discussion")) {
                                mapCellValue = "Class section - Discussion";
                            } else if (cellValue.equals("event.lab")) {
                                mapCellValue = "Class section - Lab";
                            } else if (cellValue.equals("event.lecture")) {
                                mapCellValue = "Class section - Lecture";
                            } else if (cellValue.equals("event.smallgroup")) {
                                mapCellValue = "Class section - Small Group";
                            } else if (cellValue.equals("event.class")) {
                                mapCellValue = "Class session";
                            } else if (cellValue.equals("event.computer")) {
                                mapCellValue = "Computer Session";
                            } else if (cellValue.equals("event.deadline")) {
                                mapCellValue = "Deadline";
                            } else if (cellValue.equals("event.conference")) {
                                mapCellValue = "Multidisciplinary Conference";
                            } else if (cellValue.equals("event.quiz")) {
                                mapCellValue = "Quiz";
                            } else if (cellValue.equals("event.special")) {
                                mapCellValue = "Special event";
                            } else if (cellValue.equals("event.assignment")) {
                                mapCellValue = "Web Assignment";
                            } else {
                                mapCellValue = cellValue;
                            }
                        }
                    } else {
                        // Just a string...
                        mapCellValue = column.getCellValue();
                    }
                }

                // Store in the map for later reference.
                eventProperties.put(column.getColumnHeader(), mapCellValue);
            }

            // Add the map of properties for this row to the list of rows.
            rowList.add(eventProperties);
        }
    });

    return getPrototypeEvents(scheduleImport.filterEvents(rowList, customFieldPropertyNames),
            customFieldPropertyNames);
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.CaptureActivity.java

private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
    statusView.setVisibility(View.GONE);
    viewfinderView.setVisibility(View.GONE);
    resultView.setVisibility(View.VISIBLE);

    ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
    if (barcode == null) {
        barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.qr_scan));
    } else {/*from  w  w  w . j  a v  a 2s  .  c  o  m*/
        barcodeImageView.setImageBitmap(barcode);
    }

    TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
    formatTextView.setText(rawResult.getBarcodeFormat().toString());

    TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
    typeTextView.setText(resultHandler.getType().toString());

    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
    String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
    TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
    timeTextView.setText(formattedTime);

    TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
    View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
    metaTextView.setVisibility(View.GONE);
    metaTextViewLabel.setVisibility(View.GONE);
    Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata();
    if (metadata != null) {
        StringBuilder metadataText = new StringBuilder(20);
        for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) {
            if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
                metadataText.append(entry.getValue()).append('\n');
            }
        }
        if (metadataText.length() > 0) {
            metadataText.setLength(metadataText.length() - 1);
            metaTextView.setText(metadataText);
            metaTextView.setVisibility(View.VISIBLE);
            metaTextViewLabel.setVisibility(View.VISIBLE);
        }
    }

    TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
    CharSequence displayContents = resultHandler.getDisplayContents();
    contentsTextView.setText(displayContents);
    // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
    int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
    contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);

    TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view);
    supplementTextView.setText("");
    supplementTextView.setOnClickListener(null);
    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(PreferencesActivity.KEY_SUPPLEMENTAL,
            true)) {
        SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView, resultHandler.getResult(),
                historyManager, this);
    }

    int buttonCount = resultHandler.getButtonCount();
    ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
    buttonView.requestFocus();
    for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
        TextView button = (TextView) buttonView.getChildAt(x);
        if (x < buttonCount) {
            button.setVisibility(View.VISIBLE);
            button.setText(resultHandler.getButtonText(x));
            button.setOnClickListener(new ResultButtonListener(resultHandler, x));
        } else {
            button.setVisibility(View.GONE);
        }
    }

    if (copyToClipboard && !resultHandler.areContentsSecure()) {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        if (displayContents != null) {
            clipboard.setText(displayContents);
        }
    }
}

From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java

/** In EJBCA 4.0.0 we changed the date format to ISO 8601. This verifies the that we still accept old requests, but returns UserDataVOWS objects using the new DateFormat 
 * @throws AuthorizationDeniedException */
@Test//  w ww  . ja  va  2 s  .c  om
public void test36EjbcaWsHelperTimeFormatConversion()
        throws CADoesntExistsException, ClassCastException, EjbcaException, AuthorizationDeniedException {
    log.trace(">test36EjbcaWsHelperTimeFormatConversion()");
    final Date nowWithOutSeconds = new Date((new Date().getTime() / 60000) * 60000); // To avoid false negatives.. we will loose precision when we convert back and forth..
    final String oldTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.US)
            .format(nowWithOutSeconds);
    final String newTimeFormatStorage = FastDateFormat
            .getInstance("yyyy-MM-dd HH:mm", TimeZone.getTimeZone("UTC")).format(nowWithOutSeconds);
    final String newTimeFormatRequest = FastDateFormat
            .getInstance("yyyy-MM-dd HH:mm:ssZZ", TimeZone.getTimeZone("CEST")).format(nowWithOutSeconds);
    final String newTimeFormatResponse = FastDateFormat
            .getInstance("yyyy-MM-dd HH:mm:ssZZ", TimeZone.getTimeZone("UTC")).format(nowWithOutSeconds);
    final String relativeTimeFormat = "0123:12:31";
    log.debug("oldTimeFormat=" + oldTimeFormat);
    log.debug("newTimeFormatStorage=" + newTimeFormatStorage);
    log.debug("newTimeFormatRequest=" + newTimeFormatRequest);
    // Convert from UserDataVOWS with US Locale DateFormat to endEntityInformation
    final org.ejbca.core.protocol.ws.objects.UserDataVOWS userDataVoWs = new org.ejbca.core.protocol.ws.objects.UserDataVOWS(
            "username", "password", false, "CN=User U", "CA1", null, null, 10, "P12", "EMPTY", "ENDUSER", null);
    userDataVoWs.setStartTime(oldTimeFormat);
    userDataVoWs.setEndTime(oldTimeFormat);
    final EndEntityInformation endEntityInformation1 = EjbcaWSHelper.convertUserDataVOWS(userDataVoWs, 1, 2, 3,
            4, 5);
    assertEquals("CUSTOM_STARTTIME in old format was not correctly handled (VOWS to VO).", newTimeFormatStorage,
            endEntityInformation1.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_STARTTIME));
    assertEquals("CUSTOM_ENDTIME in old format was not correctly handled (VOWS to VO).", newTimeFormatStorage,
            endEntityInformation1.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_ENDTIME));
    // Convert from UserDataVOWS with standard DateFormat to endEntityInformation
    userDataVoWs.setStartTime(newTimeFormatRequest);
    userDataVoWs.setEndTime(newTimeFormatRequest);
    final EndEntityInformation endEntityInformation2 = EjbcaWSHelper.convertUserDataVOWS(userDataVoWs, 1, 2, 3,
            4, 5);
    assertEquals("ExtendedInformation.CUSTOM_STARTTIME in new format was not correctly handled.",
            newTimeFormatStorage,
            endEntityInformation2.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_STARTTIME));
    assertEquals("ExtendedInformation.CUSTOM_ENDTIME in new format was not correctly handled.",
            newTimeFormatStorage,
            endEntityInformation2.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_ENDTIME));
    // Convert from UserDataVOWS with relative date format to endEntityInformation
    userDataVoWs.setStartTime(relativeTimeFormat);
    userDataVoWs.setEndTime(relativeTimeFormat);
    final EndEntityInformation endEntityInformation3 = EjbcaWSHelper.convertUserDataVOWS(userDataVoWs, 1, 2, 3,
            4, 5);
    assertEquals("ExtendedInformation.CUSTOM_STARTTIME in relative format was not correctly handled.",
            relativeTimeFormat,
            endEntityInformation3.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_STARTTIME));
    assertEquals("ExtendedInformation.CUSTOM_ENDTIME in relative format was not correctly handled.",
            relativeTimeFormat,
            endEntityInformation3.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_ENDTIME));
    // Convert from endEntityInformation with standard DateFormat to UserDataVOWS
    final org.ejbca.core.protocol.ws.objects.UserDataVOWS userDataVoWs1 = EjbcaWSHelper
            .convertEndEntityInformation(endEntityInformation1, "CA1", "EEPROFILE", "CERTPROFILE",
                    "HARDTOKENISSUER", "P12");
    // We expect that the server will respond using UTC
    assertEquals("CUSTOM_STARTTIME in new format was not correctly handled (VO to VOWS).",
            newTimeFormatResponse, userDataVoWs1.getStartTime());
    assertEquals("CUSTOM_ENDTIME in new format was not correctly handled (VO to VOWS).", newTimeFormatResponse,
            userDataVoWs1.getEndTime());
    // Convert from EndEntityInformation with relative date format to UserDataVOWS
    final org.ejbca.core.protocol.ws.objects.UserDataVOWS userDataVoWs3 = EjbcaWSHelper
            .convertEndEntityInformation(endEntityInformation3, "CA1", "EEPROFILE", "CERTPROFILE",
                    "HARDTOKENISSUER", "P12");
    assertEquals("CUSTOM_STARTTIME in relative format was not correctly handled (VO to VOWS).",
            relativeTimeFormat, userDataVoWs3.getStartTime());
    assertEquals("CUSTOM_ENDTIME in relative format was not correctly handled (VO to VOWS).",
            relativeTimeFormat, userDataVoWs3.getEndTime());
    // Try some invalid start time date format
    userDataVoWs.setStartTime("12:32 2011-02-28"); // Invalid
    userDataVoWs.setEndTime("2011-02-28 12:32:00+00:00"); // Valid
    try {
        EjbcaWSHelper.convertUserDataVOWS(userDataVoWs, 1, 2, 3, 4, 5);
        fail("Conversion of illegal time format did not generate exception.");
    } catch (EjbcaException e) {
        assertEquals("Unexpected error code in exception.", ErrorCode.FIELD_VALUE_NOT_VALID, e.getErrorCode());
    }
    // Try some invalid end time date format
    userDataVoWs.setStartTime("2011-02-28 12:32:00+00:00"); // Valid
    userDataVoWs.setEndTime("12:32 2011-02-28"); // Invalid
    try {
        EjbcaWSHelper.convertUserDataVOWS(userDataVoWs, 1, 2, 3, 4, 5);
        fail("Conversion of illegal time format did not generate exception.");
    } catch (EjbcaException e) {
        assertEquals("Unexpected error code in exception.", ErrorCode.FIELD_VALUE_NOT_VALID, e.getErrorCode());
    }
    log.trace("<test36EjbcaWsHelperTimeFormatConversion()");
}

From source file:org.glom.app.libglom.Document.java

private void setNodeTextChildAsValue(final Element element, final DataItem value, final GlomFieldType type) {
    String str = "";

    switch (type) {
    case TYPE_BOOLEAN: {
        str = value.getBoolean() ? "true" : "false";
        break;/*  w w w . j  ava  2 s  .c om*/
    }
    case TYPE_DATE: {
        // TODO: This is not really the format used by the Glom document:
        final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
        str = dateFormat.format(value.getDate());
        break;
    }
    case TYPE_IMAGE: {
        str = ""; // TODO
        break;
    }
    case TYPE_NUMERIC: {
        str = getStringForDecimal(value.getNumber());
        break;
    }
    case TYPE_TEXT:
        str = value.getText();
        break;
    case TYPE_TIME:
        str = ""; // TODO
        break;
    default:
        Log.e("android-glom", documentID + ": setNodeTextChildAsValue(): unexpected or invalid field type.");
        break;
    }

    final String escaped = str.replace(QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT);
    element.setTextContent(escaped);
}

From source file:org.mifos.framework.util.helpers.DateUtils.java

public static String convertToDbFormat(Locale locale, String givenDate) throws InvalidDateException {
    SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);
    String userfmt = convertToCurrentDateFormat(format.toPattern());
    return convertUserToDbFmt(givenDate, userfmt);
}

From source file:com.androidquery.simplefeed.fragments.FeedFragment.java

public String makeTitle(long time) {

    String result = source.getName();

    if (act.isRoot()) {

        String mode = getModeDisplay();
        if (mode != null) {
            result += " - " + mode;
        }//w  w  w .j  a  v a 2s . c  o m
    }

    if (time > 0) {
        result += " - " + DateUtils.formatSameDayTime(time, System.currentTimeMillis(), DateFormat.SHORT,
                DateFormat.SHORT);
    }

    return result;
}