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:edu.ku.brc.specify.config.DateConverter.java

/**
 *
 *//*from   w ww .  j  ava 2  s . com*/
public DateConverter() {
    String currentFormat = "MM/DD/YYYY";//AppPreferences.getRemote().get("ui.formatting.scrdateformat", null);
    if (currentFormat.startsWith("MM") || currentFormat.startsWith("mm")) {
        preferMonthDay = true;
    } else if (currentFormat.startsWith("DD") || currentFormat.startsWith("dd")) {
        preferMonthDay = false;
    } else {
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); //for default locale; SHORT -> completely numeric
        Calendar result = new GregorianCalendar();
        result.set(2000, 3, 1);
        String dtstr = df.format(result.getTime());
        int moIdx = dtstr.indexOf("4");
        int dayIdx = dtstr.indexOf("1");
        preferMonthDay = moIdx < dayIdx;
    }

    //System.out.println(df.)
    //preferMonthDay = /*loc == Locale.CANADA || */loc == Locale.US;            
}

From source file:org.waterforpeople.mapping.app.web.KMLGenerator.java

public String generatePlacemarks(String vmName, String countryCode, String display) {
    StringBuilder sb = new StringBuilder();
    AccessPointDao apDAO = new AccessPointDao();
    List<AccessPoint> entries = null;
    if (countryCode.equals(Constants.ALL_RESULTS))
        entries = apDAO.list(Constants.ALL_RESULTS);
    else/*from w  ww  . j ava 2s. c  o  m*/
        entries = apDAO.searchAccessPoints(countryCode, null, null, null, null, null, null, null, null, null,
                null, Constants.ALL_RESULTS);

    // loop through accessPoints and bind to variables
    int i = 0;
    try {
        for (AccessPoint ap : entries) {
            if (!ap.getPointType().equals(AccessPoint.AccessPointType.SANITATION_POINT)) {
                try {
                    VelocityContext context = new VelocityContext();
                    String pmContents = bindPlacemark(ap,
                            display.equalsIgnoreCase(GOOGLE_EARTH_DISPLAY) ? "placemarkGoogleEarth.vm"
                                    : "placemarkExternalMap.vm",
                            display, null);

                    if (ap.getCollectionDate() != null) {
                        String timestamp = DateFormatUtils.formatUTC(ap.getCollectionDate(),
                                DateFormatUtils.ISO_DATE_FORMAT.getPattern());
                        String formattedDate = DateFormat.getDateInstance(DateFormat.SHORT)
                                .format(ap.getCollectionDate());
                        context.put("collectionDate", formattedDate);
                        context.put("timestamp", timestamp);
                        String collectionYear = new SimpleDateFormat("yyyy").format(ap.getCollectionDate());
                        context.put("collectionYear", collectionYear);
                    } else {
                        String timestamp = DateFormatUtils.formatUTC(new Date(),
                                DateFormatUtils.ISO_DATE_FORMAT.getPattern());
                        String formattedDate = DateFormat.getDateInstance(DateFormat.SHORT).format(new Date());
                        context.put("collectionDate", formattedDate);
                        context.put("timestamp", timestamp);
                    }
                    if (ap.getCommunityName() == null) {
                        context.put("communityName", "Unknown");
                    } else {
                        context.put("communityName", ap.getCommunityName());
                    }
                    if (ap.getCommunityCode() != null)
                        context.put("communityCode", ap.getCommunityCode());
                    else
                        context.put("communityCode", "Unknown" + new Date());
                    // Need to check this
                    if (ap.getPointType() != null) {
                        if (Boolean.parseBoolean(PropertyUtil.getProperty(DYNAMIC_SCORING_FLAG))) {

                        } else {
                            encodeStatusString(ap, context);
                            context.put("pinStyle", encodePinStyle(ap.getPointType(), ap.getPointStatus()));
                        }
                    } else {
                        context.put("pinStyle", "waterpushpinblk");
                    }
                    context.put("latitude", ap.getLatitude());
                    context.put("longitude", ap.getLongitude());
                    if (ap.getAltitude() == null)
                        context.put("altitude", 0.0);
                    else
                        context.put("altitude", ap.getAltitude());

                    context.put("balloon", pmContents);
                    String placemarkStr = mergeContext(context, vmName);
                    sb.append(placemarkStr);
                    i++;
                } catch (Exception e) {
                    log.log(Level.INFO, "Error generating placemarks: " + ap.getCommunityCode(), e);
                }
            }
        }
    } catch (Exception ex) {
        log.log(Level.SEVERE, "Bad access point: " + entries.get(i + 1).toString());
    }
    return sb.toString();
}

From source file:org.etudes.mneme.impl.AssessmentStorageSample.java

protected void fakeIt() {
    if (!fakedAlready) {
        fakedAlready = true;//w  w  w.j  av  a 2s  . c  om

        Date now = new Date();

        AssessmentImpl a = newAssessment();
        a.initId("a1");
        a.setPublished(Boolean.TRUE);
        a.setContext("mercury");
        a.getCreatedBy().setUserId("admin");
        a.setTries(3);
        a.setQuestionGrouping(QuestionGrouping.question);
        a.setRandomAccess(Boolean.TRUE);
        a.setTimeLimit(1200l * 1000l);
        a.setTitle("Ann Arbor");
        a.setType(AssessmentType.test);
        // a.getAccess().setPassword("password");
        a.getCreatedBy().setUserId("admin");
        a.getCreatedBy().setDate(now);
        a.getModifiedBy().setUserId("admin");
        a.getModifiedBy().setDate(now);
        try {
            a.getDates().setOpenDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("10/01/07"));
            ((AssessmentDatesImpl) a.getDates())
                    .initDueDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("12/22/07"));
        } catch (ParseException e) {
        }
        a.getGrading().setAutoRelease(Boolean.FALSE);
        a.getGrading().setGradebookIntegration(Boolean.FALSE);
        a.getGrading().setAnonymous(Boolean.FALSE);
        a.getPresentation().setText("This is assessment one.");
        a.getReview().setShowCorrectAnswer(ReviewShowCorrect.yes);
        a.getReview().setShowFeedback(Boolean.TRUE);
        a.getReview().setShowSummary(Boolean.FALSE);
        a.getReview().setTiming(ReviewTiming.graded);
        a.setMinScoreSet(Boolean.FALSE);
        a.getSubmitPresentation().setText("Thanks for all the fish!");

        Part p = a.getParts().addPart();
        p.setRandomize(Boolean.FALSE);
        p.setTitle("Part one");
        ((PartImpl) p).initId("p1");
        p.addPickDetail(this.questionService.getQuestion("q1"));
        p.addPickDetail(this.questionService.getQuestion("q3"));
        p.addPickDetail(this.questionService.getQuestion("q4"));
        p.getPresentation().setText("This is part one.");

        p = a.getParts().addPart();
        p.setRandomize(Boolean.FALSE);
        p.setTitle("Part two");
        ((PartImpl) p).initId("p2");

        p.addPickDetail(this.questionService.getQuestion("q5"));
        p.addPickDetail(this.questionService.getQuestion("q7"));
        p.addPickDetail(this.questionService.getQuestion("q8"));
        p.getPresentation().setText("This is part two.");

        a.clearChanged();
        a.clearMint();
        ((AssessmentGradingImpl) (a.getGrading())).initAutoRelease(a.getGrading().getAutoRelease());
        ((AssessmentGradingImpl) (a.getGrading()))
                .initGradebookIntegration(a.getGrading().getGradebookIntegration());
        a.initTitle(a.getTitle());
        a.initPublished(a.getPublished());
        this.assessments.put(a.getId(), a);

        //

        a = newAssessment();
        a.setType(AssessmentType.assignment);
        a.initId("a2");
        a.setPublished(Boolean.TRUE);
        a.setContext("mercury");
        a.getCreatedBy().setUserId("admin");
        a.setTries(5);
        a.setQuestionGrouping(QuestionGrouping.question);
        a.setRandomAccess(Boolean.TRUE);
        // a.setTimeLimit(1200l * 1000l);
        a.setTitle("Boston");
        // a.getAccess().setPassword("password");
        a.getCreatedBy().setUserId("admin");
        a.getCreatedBy().setDate(now);
        a.getModifiedBy().setUserId("admin");
        a.getModifiedBy().setDate(now);
        try {
            a.getDates().setOpenDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("09/01/07"));
            ((AssessmentDatesImpl) a.getDates())
                    .initDueDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("12/15/07"));
        } catch (ParseException e) {
        }
        a.getGrading().setAutoRelease(Boolean.TRUE);
        a.getGrading().setGradebookIntegration(Boolean.FALSE);
        a.getGrading().setAnonymous(Boolean.TRUE);
        a.getPresentation().setText("This is assessment two.");
        a.getReview().setShowCorrectAnswer(ReviewShowCorrect.yes);
        a.getReview().setShowFeedback(Boolean.TRUE);
        a.getReview().setShowSummary(Boolean.FALSE);
        a.getReview().setTiming(ReviewTiming.submitted);
        a.setMinScoreSet(Boolean.FALSE);
        a.getSubmitPresentation().setText("Have a nice day!");

        Part p2 = a.getParts().addPart();
        p2.addDrawDetail(this.poolService.getPool("b1"), 2);
        p2.setTitle("Part one");
        ((PartImpl) p2).initId("p3");
        p2.getPresentation().setText("This is part one.");

        a.clearChanged();
        a.clearMint();
        ((AssessmentGradingImpl) (a.getGrading())).initAutoRelease(a.getGrading().getAutoRelease());
        ((AssessmentGradingImpl) (a.getGrading()))
                .initGradebookIntegration(a.getGrading().getGradebookIntegration());
        a.initTitle(a.getTitle());
        a.initPublished(a.getPublished());
        this.assessments.put(a.getId(), a);

        //

        a = newAssessment();
        a.setType(AssessmentType.test);
        a.initId("a3");
        a.setPublished(Boolean.TRUE);
        a.setContext("mercury");
        a.getCreatedBy().setUserId("admin");
        a.setTries(5);
        a.setQuestionGrouping(QuestionGrouping.question);
        a.setRandomAccess(Boolean.TRUE);
        // a.setTimeLimit(1200l * 1000l);
        a.setTitle("Detroit");
        // a.getAccess().setPassword("password");
        a.getCreatedBy().setUserId("admin");
        a.getCreatedBy().setDate(now);
        a.getModifiedBy().setUserId("admin");
        a.getModifiedBy().setDate(now);
        a.getGrading().setAutoRelease(Boolean.TRUE);
        a.getGrading().setGradebookIntegration(Boolean.FALSE);
        a.getGrading().setAnonymous(Boolean.TRUE);
        a.getPresentation().setText("This is assessment three.");
        a.getReview().setShowCorrectAnswer(ReviewShowCorrect.yes);
        a.getReview().setShowFeedback(Boolean.TRUE);
        a.getReview().setShowSummary(Boolean.FALSE);
        a.getReview().setTiming(ReviewTiming.submitted);
        a.setMinScoreSet(Boolean.FALSE);
        a.getSubmitPresentation().setText("Have a nice day!");

        p = a.getParts().addPart();
        p.addPickDetail(this.questionService.getQuestion("q3"));
        p.addPickDetail(this.questionService.getQuestion("q4"));
        p.setTitle("Part one");
        ((PartImpl) p).initId("p4");
        p.getPresentation().setText("This is part 1.");

        a.clearChanged();
        a.clearMint();
        ((AssessmentGradingImpl) (a.getGrading())).initAutoRelease(a.getGrading().getAutoRelease());
        ((AssessmentGradingImpl) (a.getGrading()))
                .initGradebookIntegration(a.getGrading().getGradebookIntegration());
        a.initTitle(a.getTitle());
        a.initPublished(a.getPublished());
        this.assessments.put(a.getId(), a);
    }
}

From source file:com.concursive.connect.web.portal.PortalUtils.java

public static void populateObject(Object bean, ActionRequest request) {
    String nestedAttribute = "_";

    Enumeration en = request.getParameterNames();
    String paramName = null;//www.  j  av  a2  s .  c  om
    while (en.hasMoreElements()) {
        paramName = (String) en.nextElement();

        // a form has been submitted and requested to be auto-populated,
        // so we do that here..going through every element and trying
        // to call a setXXX() method on the bean object passed in for the value
        // of the request parameter currently being checked.
        String[] paramValues = request.getParameterValues(paramName);
        if (paramValues.length > 1) {
            ObjectUtils.setParam(bean, paramName, paramValues, nestedAttribute);
        } else {
            ObjectUtils.setParam(bean, paramName, paramValues[0], nestedAttribute);
        }
    }

    // TODO: currently for ticket and ticket history
    //ObjectUtils.invokeMethod(bean, "setRequestItems", new HttpRequestContext(request));
    // Check for valid user
    User thisUser = (User) request.getAttribute(Constants.REQUEST_USER);
    if (thisUser != null) {
        // Populate date/time fields using the user's timezone and locale
        if (thisUser.getTimeZone() != null) {
            ArrayList timeParams = (ArrayList) ObjectUtils.getObject(bean, "TimeZoneParams");
            if (timeParams != null) {
                Calendar cal = Calendar.getInstance();
                Iterator i = timeParams.iterator();
                while (i.hasNext()) {
                    // The property that can be set
                    String name = (String) i.next();
                    // See if it is in the request
                    String value = request.getParameter(name);
                    if (value != null) {
                        // See if time is in request too
                        String hourValue = request.getParameter(name + "Hour");
                        if (hourValue == null) {
                            // Date fields: 1-1 mapping between HTML field and Java property
                            ObjectUtils.setParam(bean, name,
                                    DateUtils.getUserToServerDateTimeString(
                                            TimeZone.getTimeZone(thisUser.getTimeZone()), DateFormat.SHORT,
                                            DateFormat.LONG, value, thisUser.getLocale()));
                        } else {
                            // Date & Time fields: 4-1 mapping between HTML fields and Java property
                            try {
                                Timestamp timestamp = DatabaseUtils.parseDateToTimestamp(value,
                                        thisUser.getLocale());
                                cal.setTimeInMillis(timestamp.getTime());
                                int hour = Integer.parseInt(hourValue);
                                int minute = Integer.parseInt(request.getParameter(name + "Minute"));
                                String ampmString = request.getParameter(name + "AMPM");
                                if (ampmString != null) {
                                    int ampm = Integer.parseInt(ampmString);
                                    if (ampm == Calendar.AM) {
                                        if (hour == 12) {
                                            hour = 0;
                                        }
                                    } else {
                                        if (hour < 12) {
                                            hour += 12;
                                        }
                                    }
                                }
                                cal.set(Calendar.HOUR_OF_DAY, hour);
                                cal.set(Calendar.MINUTE, minute);
                                cal.setTimeZone(TimeZone.getTimeZone(thisUser.getTimeZone()));
                                ObjectUtils.setParam(bean, name, new Timestamp(cal.getTimeInMillis()));
                            } catch (Exception dateE) {
                            }
                        }
                    }
                }
            }
        }

        // Populate number fields using the user's locale
        if (thisUser.getLocale() != null) {
            ArrayList numberParams = (ArrayList) ObjectUtils.getObject(bean, "NumberParams");
            if (numberParams != null) {
                NumberFormat nf = NumberFormat.getInstance(thisUser.getLocale());
                Iterator i = numberParams.iterator();
                while (i.hasNext()) {
                    // The property that can be set
                    String name = (String) i.next();
                    // See if it is in the request
                    String value = (String) request.getParameter(name);
                    if (value != null && !"".equals(value)) {
                        try {
                            // Parse the value
                            ObjectUtils.setParam(bean, name, nf.parse(value).doubleValue());
                        } catch (Exception e) {
                            //e.printStackTrace(System.out);
                        }
                    }
                }
            }
        }
    }
}

From source file:op.care.values.PnlValues.java

private JPanel createContentPanel4Year(final ResValueTypes vtype, final int year) {
    final String keyYears = vtype.getID() + ".xtypes." + Integer.toString(year) + ".year";

    java.util.List<ResValue> myValues;
    synchronized (mapType2Values) {
        if (!mapType2Values.containsKey(keyYears)) {
            mapType2Values.put(keyYears, ResValueTools.getResValues(resident, vtype, year));
        }//  w  w  w.j  a  v a  2s  .co m
        if (mapType2Values.get(keyYears).isEmpty()) {
            JLabel lbl = new JLabel(SYSTools.xx("misc.msg.novalue"));
            JPanel pnl = new JPanel();
            pnl.add(lbl);
            return pnl;
        }
        myValues = mapType2Values.get(keyYears);
    }

    JPanel pnlYear = new JPanel(new VerticalLayout());

    pnlYear.setOpaque(false);

    for (final ResValue resValue : myValues) {
        String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"200\" align=\"left\">"
                + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT).format(resValue.getPit())
                + " [" + resValue.getID() + "]</td>" + "<td width=\"340\" align=\"left\">"
                + ResValueTools.getValueAsHTML(resValue) + "</td>" + "<td width=\"200\" align=\"left\">"
                + resValue.getUser().getFullname() + "</td>" + "</tr>" + "</table>" + "</html>";

        final DefaultCPTitle pnlTitle = new DefaultCPTitle(title, null);

        pnlTitle.getMain().setBackground(GUITools.blend(vtype.getColor(), Color.WHITE, 0.1f));
        pnlTitle.getMain().setOpaque(true);

        if (resValue.isObsolete()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22eraser));
        }
        if (resValue.isReplacement()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22edited));
        }
        if (!resValue.getText().trim().isEmpty()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22info));
        }
        if (pnlTitle.getAdditionalIconPanel().getComponentCount() > 0) {
            pnlTitle.getButton().addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    GUITools.showPopup(
                            GUITools.getHTMLPopup(pnlTitle.getButton(), ResValueTools.getInfoAsHTML(resValue)),
                            SwingConstants.NORTH);
                }
            });
        }

        if (!resValue.getAttachedFilesConnections().isEmpty()) {
            /***
             *      _     _         _____ _ _
             *     | |__ | |_ _ __ |  ___(_) | ___  ___
             *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
             *     | |_) | |_| | | |  _| | | |  __/\__ \
             *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
             *
             */
            final JButton btnFiles = new JButton(
                    Integer.toString(resValue.getAttachedFilesConnections().size()), SYSConst.icon22greenStar);
            btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
            btnFiles.setForeground(Color.BLUE);
            btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnFiles.setFont(SYSConst.ARIAL18BOLD);
            btnFiles.setPressedIcon(SYSConst.icon22Pressed);
            btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
            btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnFiles.setContentAreaFilled(false);
            btnFiles.setBorder(null);

            btnFiles.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgFiles(resValue, new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final ResValue myValue = em.find(ResValue.class, resValue.getID());
                            em.close();

                            synchronized (mapType2Values) {
                                mapType2Values.get(keyYears).remove(resValue);
                                mapType2Values.get(keyYears).add(myValue);
                                Collections.sort(mapType2Values.get(keyYears));
                            }

                            createCP4Year(vtype, year);
                            buildPanel();
                        }
                    });
                }
            });
            btnFiles.setEnabled(OPDE.isFTPworking());
            pnlTitle.getRight().add(btnFiles);
        }

        if (!resValue.getAttachedProcessConnections().isEmpty()) {
            /***
             *      _     _         ____
             *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
             *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
             *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
             *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
             *
             */
            final JButton btnProcess = new JButton(
                    Integer.toString(resValue.getAttachedProcessConnections().size()), SYSConst.icon22redStar);
            btnProcess.setToolTipText(SYSTools.xx("misc.btnprocess.tooltip"));
            btnProcess.setForeground(Color.YELLOW);
            btnProcess.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnProcess.setFont(SYSConst.ARIAL18BOLD);
            btnProcess.setPressedIcon(SYSConst.icon22Pressed);
            btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnProcess.setAlignmentY(Component.TOP_ALIGNMENT);
            btnProcess.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnProcess.setContentAreaFilled(false);
            btnProcess.setBorder(null);
            btnProcess.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgProcessAssign(resValue, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o == null) {
                                return;
                            }
                            Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                            ArrayList<QProcess> assigned = result.getFirst();
                            ArrayList<QProcess> unassigned = result.getSecond();

                            EntityManager em = OPDE.createEM();

                            try {
                                em.getTransaction().begin();

                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                ResValue myValue = em.merge(resValue);
                                em.lock(myValue, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                ArrayList<SYSVAL2PROCESS> attached = new ArrayList<SYSVAL2PROCESS>(
                                        resValue.getAttachedProcessConnections());
                                for (SYSVAL2PROCESS linkObject : attached) {
                                    if (unassigned.contains(linkObject.getQProcess())) {
                                        linkObject.getQProcess().getAttachedNReportConnections()
                                                .remove(linkObject);
                                        linkObject.getResValue().getAttachedProcessConnections()
                                                .remove(linkObject);
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                        + myValue.getTitle() + " ID: " + myValue.getID(),
                                                PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                                linkObject.getQProcess()));
                                        em.remove(linkObject);
                                    }
                                }
                                attached.clear();

                                for (QProcess qProcess : assigned) {
                                    java.util.List<QProcessElement> listElements = qProcess.getElements();
                                    if (!listElements.contains(myValue)) {
                                        QProcess myQProcess = em.merge(qProcess);
                                        SYSVAL2PROCESS myLinkObject = em
                                                .merge(new SYSVAL2PROCESS(myQProcess, myValue));
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                        + myValue.getTitle() + " ID: " + myValue.getID(),
                                                PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                        qProcess.getAttachedResValueConnections().add(myLinkObject);
                                        myValue.getAttachedProcessConnections().add(myLinkObject);
                                    }
                                }

                                em.getTransaction().commit();

                                synchronized (mapType2Values) {
                                    mapType2Values.get(keyYears).remove(resValue);
                                    mapType2Values.get(keyYears).add(myValue);
                                    Collections.sort(mapType2Values.get(keyYears));
                                }
                                createCP4Year(vtype, year);

                                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 (RollbackException 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();
                            }
                        }
                    });
                }
            });
            btnProcess.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
            pnlTitle.getRight().add(btnProcess);
        }
        /***
         *      __  __
         *     |  \/  | ___ _ __  _   _
         *     | |\/| |/ _ \ '_ \| | | |
         *     | |  | |  __/ | | | |_| |
         *     |_|  |_|\___|_| |_|\__,_|
         *
         */
        final JButton btnMenu = new JButton(SYSConst.icon22menu);
        btnMenu.setPressedIcon(SYSConst.icon22Pressed);
        btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
        btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnMenu.setContentAreaFilled(false);
        btnMenu.setBorder(null);
        btnMenu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JidePopup popup = new JidePopup();
                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnMenu);
                popup.removeExcludedComponent(btnMenu);
                JPanel pnl = getMenu(resValue);
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });
        btnMenu.setEnabled(!resValue.isObsolete());
        pnlTitle.getRight().add(btnMenu);

        pnlYear.add(pnlTitle.getMain());
        synchronized (linemap) {
            linemap.put(resValue, pnlTitle.getMain());
        }
    }
    return pnlYear;
}

From source file:org.jboss.dashboard.ui.taglib.formatter.Formatter.java

/**
 * Given an object it returns a string representation.
 *//* ww w .  j  av  a  2 s  . co m*/
public String formatObject(Object obj) {
    if (obj == null)
        return null;

    if (obj instanceof String) {
        return (String) obj;
    }
    if (obj instanceof Number) {
        if (numberFormat == null)
            numberFormat = NumberFormat.getNumberInstance(getLocale());
        return numberFormat.format(obj);
    }
    if (obj instanceof Date) {
        if (dateTimeFormat == null)
            dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale());
        String dateStr = dateTimeFormat.format(obj);
        if (dateStr.indexOf("/") == 1)
            dateStr = "0" + dateStr;
        return dateStr;
    }
    return null;
}

From source file:se.streamsource.streamflow.web.application.pdf.CasePdfGenerator.java

public void generateSubmittedForms(Input<SubmittedFormValue, RuntimeException> submittedForms)
        throws IOException {

    ArrayList<SubmittedFormValue> formValues = new ArrayList<SubmittedFormValue>();
    submittedForms.transferTo(Outputs.collection(formValues));

    // Latest forms first please
    Collections.reverse(formValues);

    Set<EntityReference> printedForms = new HashSet<EntityReference>();
    boolean printedHeader = false;
    for (SubmittedFormValue formValue : formValues) {
        if (printedForms.contains(formValue.form().get()))
            continue; // Skip this form - already printed

        Describable form = module.unitOfWorkFactory().currentUnitOfWork().get(Describable.class,
                formValue.form().get().identity());

        // Form PDF section header
        if (!printedHeader) {
            document.changeColor(headingColor);
            document.print(bundle.getString("submittedForms") + ":", valueFontBold);
            document.changeColor(Color.BLACK);
            printedHeader = true;// ww  w.  ja  v a2s .  c om
        }

        document.print(form.getDescription() + ":", valueFontBold).print("", valueFontBold).print("",
                valueFontBold);

        float tabStop = document.calculateTabStop(valueFontBold,
                new String[] { bundle.getString("lastSubmitted"), bundle.getString("lastSubmittedBy") });

        // Submitted by whom and when
        document.printLabelAndTextWithTabStop(bundle.getString("lastSubmitted") + ":", valueFontBold,
                DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale)
                        .format(formValue.submissionDate().get()),
                valueFont, tabStop);
        document.printLabelAndTextWithTabStop(bundle.getString("lastSubmittedBy") + ":", valueFontBold,
                module.unitOfWorkFactory().currentUnitOfWork()
                        .get(Describable.class, formValue.submitter().get().identity()).getDescription(),
                valueFont, tabStop);

        if (formValue.signatures().get() != null && !formValue.signatures().get().isEmpty()) {
            FormSignatureDTO signature = formValue.signatures().get().get(0);
            document.printLabelAndTextWithTabStop(bundle.getString("signedBy") + ":", valueFontBold,
                    signature.signerName().get() + " (" + signature.signerId().get() + ")", valueFont, tabStop);
        }

        for (SubmittedPageValue submittedPageValue : formValue.pages().get()) {
            if (!submittedPageValue.fields().get().isEmpty()) {
                Describable page = module.unitOfWorkFactory().currentUnitOfWork().get(Describable.class,
                        submittedPageValue.page().get().identity());
                document.print(page.getDescription() + (page.getDescription().trim().endsWith(":") ? "" : ":"),
                        valueFontBoldItalic);
                document.print("", valueFont);

                // Fetch and occasionally format field name and value
                for (SubmittedFieldValue submittedFieldValue : submittedPageValue.fields().get()) {

                    FieldValue fieldValue = module.unitOfWorkFactory().currentUnitOfWork()
                            .get(FieldEntity.class, submittedFieldValue.field().get().identity()).fieldValue()
                            .get();

                    if (!empty(submittedFieldValue.value().get())) {
                        String label = module.unitOfWorkFactory().currentUnitOfWork()
                                .get(Describable.class, submittedFieldValue.field().get().identity())
                                .getDescription();
                        String value = "";
                        // convert JSON String if field type AttachmentFieldValue
                        if (fieldValue instanceof AttachmentFieldValue) {
                            AttachmentFieldSubmission attachment = module.valueBuilderFactory()
                                    .newValueFromJSON(AttachmentFieldSubmission.class,
                                            submittedFieldValue.value().get());
                            value = attachment.name().get();

                        } else if (fieldValue instanceof DateFieldValue
                                && !empty(submittedFieldValue.value().get())) {
                            value = new SimpleDateFormat(bundle.getString("date_format"))
                                    .format(DateFunctions.fromString(submittedFieldValue.value().get()));
                        } else if (fieldValue instanceof GeoLocationFieldValue) {
                            LocationDTO locationDTO = module.valueBuilderFactory()
                                    .newValueFromJSON(LocationDTO.class, submittedFieldValue.value().get());
                            value = locationDTO.street().get() + ", " + locationDTO.zipcode().get() + ", "
                                    + locationDTO.city().get();
                            //                        String locationString = locationDTO.location().get();
                            //                        if (locationString != null) {
                            //                           locationString = locationString.replace( ' ', '+' );
                            //                           if (locationString.contains( "(" )) {
                            //                              String[] positions = locationString.split( "\\),\\(");
                            //                              locationString = positions[0].substring( 1, positions[0].length() -1 );
                            //                           }
                            //                        }
                            //                        text += "<a href=\"http://maps.google.com/maps?z=13&t=m&q=" + locationString + "\" alt=\"Google Maps\">Klicka hr fr att visa karta</a>";
                        } else {
                            value = submittedFieldValue.value().get();
                        }
                        document.printLabelAndIndentedText(label + (label.trim().endsWith(":") ? "" : ":"),
                                valueFontBold, value, valueFont, 20.0f);
                    }
                }
                document.print("", valueFont);
            }
        }
        printedForms.add(formValue.form().get());
    }
}

From source file:net.sf.jasperreports.functions.standard.DateTimeFunctions.java

/**
 * This methods tries to convert a generic object into a java.util.Date instance.
 * Supported types are for now String, Long values (time millis) and Date subtypes
 * like for example java.sql.Date.//w w  w .  j a v  a2s.co  m
 */
private Date convertDateObject(Object dateObject) {
    if (dateObject == null) {
        if (log.isDebugEnabled()) {
            log.debug("The date object can not be null.");
        }
        return null;
    } else if (dateObject instanceof String) {
        // Try to convert using the different style for pattern.
        // We use MEDIUM as the first one because it is the DEFAULT
        int formatTypes[] = new int[] { DateFormat.MEDIUM, DateFormat.SHORT, DateFormat.LONG, DateFormat.FULL };
        for (int formatType : formatTypes) {
            try {
                DateFormat df = DateFormat.getDateInstance(formatType, getReportLocale());
                df.setTimeZone(getReportTimeZone());
                return df.parse((String) dateObject);
            } catch (ParseException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Unable to parse the string as Date using the standard SimpleDateFormat.");
                }
            }
        }
        return null;
    } else if (dateObject instanceof Long) {
        Calendar cal = Calendar.getInstance(getReportTimeZone(), getReportLocale());
        cal.setTimeInMillis((Long) dateObject);
        return cal.getTime();
    } else if (dateObject instanceof Date) {
        return (Date) dateObject;
    }
    if (log.isDebugEnabled()) {
        log.debug("The specified object is not among the allowed types for Date conversion.");
    }
    return null;
}

From source file:voldemort.VoldemortClientShell.java

@SuppressWarnings("unchecked")
protected void printObject(Object o) {
    if (o == null) {
        commandOutput.print("null");
    } else if (o instanceof String) {
        commandOutput.print('"');
        commandOutput.print(o);/*from  w w w.j a v  a 2 s .c om*/
        commandOutput.print('"');
    } else if (o instanceof Date) {
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
        commandOutput.print("'");
        commandOutput.print(df.format((Date) o));
        commandOutput.print("'");
    } else if (o instanceof List) {
        List<Object> l = (List<Object>) o;
        commandOutput.print("[");
        for (Object obj : l)
            printObject(obj);
        commandOutput.print("]");
    } else if (o instanceof Map) {
        Map<String, Object> m = (Map<String, Object>) o;
        commandOutput.print('{');
        for (String s : m.keySet()) {
            printObject(s);
            commandOutput.print(':');
            printObject(m.get(s));
            commandOutput.print(", ");
        }
        commandOutput.print('}');
    } else if (o instanceof Object[]) {
        Object[] a = (Object[]) o;
        commandOutput.print(Arrays.deepToString(a));
    } else if (o instanceof byte[]) {
        byte[] a = (byte[]) o;
        commandOutput.print(Arrays.toString(a));
    } else {
        commandOutput.print(o);
    }
}

From source file:com.coact.kochzap.CaptureActivity.java

private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {

    maybeSetClipboard(resultHandler);//from  www .  j  av  a  2s.com

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    if (resultHandler.getDefaultButtonID() != null
            && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) {
        resultHandler.handleButtonPress(resultHandler.getDefaultButtonID());
        return;
    }

    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.launcher_icon));
    } else {
        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);
    TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
    timeTextView.setText(formatter.format(rawResult.getTimestamp()));

    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);
        }
    }

    CharSequence displayContents = resultHandler.getDisplayContents();
    TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
    contentsTextView.setText(displayContents);
    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);
        }
    }

}