Example usage for java.util Date toString

List of usage examples for java.util Date toString

Introduction

In this page you can find the example usage for java.util Date toString.

Prototype

public String toString() 

Source Link

Document

Converts this Date object to a String of the form:
 dow mon dd hh:mm:ss zzz yyyy
where:
  • dow is the day of the week ( Sun, Mon, Tue, Wed, Thu, Fri, Sat ).

    Usage

    From source file:org.apache.usergrid.apm.service.ApplicationServiceImpl.java

    @SuppressWarnings("unchecked")
    public List<App> getAppsAddedSince(Date date) {
        log.info("Getting all application added since " + date.toString());
        List<App> apps = null;//from w w w.  j a v  a 2 s  .co m
        Session session = null;
        Transaction transaction = null;
        try {
            session = ServiceFactory.getHibernateSession();
            transaction = session.beginTransaction();
            Query query = session
                    .createQuery("from App as m where m.createdDate > :givenDate and m.deleted != true");
            query.setParameter("givenDate", date);
            apps = (List<App>) query.list();
            transaction.commit();
        } catch (HibernateException e) {
            transaction.rollback();
            throw new HibernateException("Cannot get a list of newly added applications ", e);
        }
    
        return apps;
    }
    

    From source file:eu.europeana.uim.gui.cp.server.RetrievalServiceImpl.java

    @Override
    public MetaDataResultDTO getRecordsForCollection(String collectionId, int offset, int maxSize,
            String constraint) {// w  ww . j  a va2  s  .c o m
        StorageEngine<String> storage = (StorageEngine<String>) getEngine().getRegistry().getStorageEngine();
        if (storage == null) {
            log.log(Level.SEVERE, "Storage connection is null!");
            return null;
        }
    
        String recordId = null;
        if (!constraint.equals("")) {
            recordId = constraint;
        }
    
        int maxNumber = 0;
        List<MetaDataRecord<String>> metaDataRecords = new ArrayList<MetaDataRecord<String>>();
        if (recordId == null) {
            Collection<String> collection = null;
            try {
                collection = storage.getCollection(collectionId);
            } catch (Throwable t) {
                log.log(Level.WARNING, "Could not retrieve collection for id '" + collectionId + "'!", t);
            }
    
            if (collection != null) {
                String[] recordIds = null;
                try {
                    recordIds = storage.getByCollection(collection);
                    maxNumber = recordIds.length;
                } catch (Throwable t) {
                    log.log(Level.WARNING, "Could not retrieve records for collection '" + collectionId + "'!", t);
                    maxNumber = -1;
                }
    
                if (recordIds != null && recordIds.length > 0) {
                    Arrays.sort(recordIds);
                    String[] subset = Arrays.copyOfRange(recordIds, Math.min(offset, recordIds.length - 1),
                            Math.min(offset + maxSize, recordIds.length));
    
                    try {
                        metaDataRecords = storage.getMetaDataRecords(Arrays.asList(subset));
                    } catch (Throwable t) {
                        log.log(Level.WARNING,
                                "Could not retrieve records for Ids '" + Arrays.toString(subset) + "'!", t);
                        maxNumber = -1;
                    }
                }
            }
        } else {
            metaDataRecords = new ArrayList<MetaDataRecord<String>>();
            try {
                metaDataRecords.add(storage.getMetaDataRecord(recordId));
                maxNumber = 1;
            } catch (Throwable t) {
                log.log(Level.WARNING, "Could not retrieve record with Id '" + recordId + "'!", t);
            }
        }
    
        List<MetaDataRecordDTO> results = new ArrayList<MetaDataRecordDTO>();
        for (MetaDataRecord<String> metaDataRecord : metaDataRecords) {
            if (metaDataRecord != null && metaDataRecord.getId() != null) {
                MetaDataRecordDTO record = new MetaDataRecordDTO();
                record.setId(metaDataRecord.getId());
    
                try {
                    Status status = metaDataRecord.getFirstValue(EuropeanaModelRegistry.STATUS);
    
                    if (status != null && status.equals(Status.DELETED)) {
                        record.setDeleted(true);
                    }
    
                    String creationDate = metaDataRecord.getFirstValue(EuropeanaModelRegistry.UIMINGESTIONDATE);
    
                    record.setImportuimdate(creationDate);
    
                    String updateDate = metaDataRecord.getFirstValue(EuropeanaModelRegistry.UIMUPDATEDDATE);
    
                    record.setUpdateuimdate(updateDate);
    
                    Long initialsaveDate = metaDataRecord.getFirstValue(EuropeanaModelRegistry.INITIALSAVE);
    
                    if (initialsaveDate != null) {
                        Date tmpdate = new Date(initialsaveDate);
                        record.setFirstingestiondate(tmpdate.toString());
                    }
    
                    Long updatesaveDate = metaDataRecord.getFirstValue(EuropeanaModelRegistry.UPDATEDSAVE);
    
                    if (updatesaveDate != null) {
                        Date tmpdate = new Date(updatesaveDate);
                        record.setIngestionupdatedate(tmpdate.toString());
                    }
    
                    String edmxml = metaDataRecord.getFirstValue(EuropeanaModelRegistry.EDMRECORD);
    
                    if (edmxml != null) {
                        RDF rdf = (RDF) uctx.unmarshalDocument(new StringReader(edmxml));
    
                        ProxyType cho = rdf.getProxyList().get(0);
    
                        List<eu.europeana.corelib.definitions.jibx.EuropeanaType.Choice> dctypelist = cho
                                .getChoiceList();
                        if (dctypelist != null) {
                            for (eu.europeana.corelib.definitions.jibx.EuropeanaType.Choice dcchoice : dctypelist) {
    
                                if (dcchoice.ifTitle()) {
                                    record.setTitle(dcchoice.getTitle().getString());
                                }
                            }
                        }
                    }
    
                } catch (JiBXException e) {
    
                    e.printStackTrace();
                }
    
                results.add(record);
            }
        }
    
        int deleted_records = 0;
        int active_records = maxNumber;
    
        Collection<String> collection;
        try {
            collection = storage.getCollection(collectionId);
            deleted_records = collection.getValue("Deleted") == null ? 0
                    : Integer.parseInt(collection.getValue("Deleted"));
            active_records = maxNumber - deleted_records;
        } catch (StorageEngineException e) {
            e.printStackTrace();
        }
    
        MetaDataResultDTO response = new MetaDataResultDTO(results, maxNumber, active_records, deleted_records);
    
        return response;
    }
    

    From source file:com.parse.hangout.MapActivity.java

    /**
     * Helper called by onMapReady callback//ww  w. jav a 2  s  . c  o m
     */
    public void setUpMap() {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION }, 1);
            //            return;
        }
        map.setMyLocationEnabled(true);
    
        map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
            public void onCameraChange(CameraPosition position) {
                doMapQuery();
            }
        });
    
        map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
    
            // Use default InfoWindow frame
            @Override
            public View getInfoWindow(Marker arg0) {
                return null;
            }
    
            // Defines the contents of the InfoWindow
            @Override
            public View getInfoContents(Marker marker) {
    
                final ParseUser user = ParseUser.getCurrentUser();
                final HangoutEvent event = markerHangoutEventMap.get(marker);
    
                // Getting view from the layout file info_window_layout
                View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
    
                TextView title = (TextView) v.findViewById(R.id.event_title);
                title.setText(marker.getTitle());
    
                final TextView membersAttending = (TextView) v.findViewById(R.id.members_attending);
                Button joinButton = (Button) v.findViewById(R.id.join_button);
                TextView startTimeEditText = (TextView) v.findViewById(R.id.start_time);
                TextView stopTimeEditText = (TextView) v.findViewById(R.id.stop_time);
    
                // remove irrelevant ui components on marker for the "my location" marker
                if (marker.getTitle().equals("My Location")) {
                    membersAttending.setVisibility(View.GONE);
                    joinButton.setVisibility(View.GONE);
                    startTimeEditText.setVisibility(View.GONE);
                    stopTimeEditText.setVisibility(View.GONE);
                    return v;
                }
    
                // add start and stop times
                Date startTime = event.getStartTime();
                Date stopTime = event.getStopTime();
    
                if (startTime != null) {
                    startTimeEditText.setText("Start Time: " + startTime.toString());
                } else if (startTime == null) {
                    startTimeEditText.setVisibility(View.GONE);
                }
    
                if (stopTime != null) {
                    stopTimeEditText.setText("Stop Time: " + stopTime.toString());
                } else if (stopTime == null) {
                    stopTimeEditText.setVisibility(View.GONE);
                }
    
                int numMembers = 0;
                boolean isUserAttending = false;
    
                ParseQuery<EventMembership> mapQuery = ParseQuery.getQuery(EventMembership.class);
                mapQuery.whereEqualTo("hangoutEvent", event);
    
                // see who is attending this event
                List<EventMembership> memberships = new ArrayList<EventMembership>();
                try {
                    memberships = mapQuery.find();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
    
                for (EventMembership membership : memberships) {
                    if (membership.getEventMember().getObjectId().equals(user.getObjectId())) {
                        isUserAttending = true;
                    }
                }
                numMembers = memberships.size();
    
                membersAttending.setText("Members attending: " + numMembers);
    
                if (isUserAttending == true) {
                    joinButton.setText("Unjoin");
                } else {
                    joinButton.setText("Join");
                }
    
                // Returning the view containing InfoWindow contents
                return v;
    
            }
        });
    
        // listener that handles joining/leaving an event on the map
        map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(final Marker marker) {
    
                View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
    
                final ParseUser user = ParseUser.getCurrentUser();
                final HangoutEvent event = markerHangoutEventMap.get(marker);
    
                ParseQuery<EventMembership> mapQuery = ParseQuery.getQuery(EventMembership.class);
                mapQuery.whereEqualTo("hangoutEvent", event);
                mapQuery.whereEqualTo("member", user);
                mapQuery.include("hangoutEvent");
                mapQuery.findInBackground(new FindCallback<EventMembership>() {
                    @Override
                    public void done(List<EventMembership> objects, ParseException e) {
                        if (objects.size() == 0) {
                            EventMembership membership = new EventMembership();
                            membership.setEvent(event);
                            membership.setEventMember(user);
                            membership.saveInBackground(new SaveCallback() {
                                @Override
                                public void done(ParseException e) {
                                    if (e == null) {
                                        // once the EventMembership is saved,
                                        // refresh the info window to show this user is attending the event
                                        marker.showInfoWindow();
                                    }
                                }
                            });
                        }
                        // leave the event if the user has joined it
                        else if (objects.size() == 1) {
                            objects.get(0).deleteInBackground(new DeleteCallback() {
                                @Override
                                public void done(ParseException e) {
                                    if (e == null) {
                                        // refresh info window once deleted
                                        marker.showInfoWindow();
                                    }
                                }
                            });
    
                        }
                    }
                });
                //test sendNotification() method
                //sendNotification();
            }
        });
    }
    

    From source file:com.ing.connector.interfaces.WExporter.java

    public void run() {
        m_exporterThread.m_iniFileName = m_exporterThread.getFtpRoot() + File.separator + "P"
                + m_exporterThread.getAgencyId() + ".ini";
    
        m_exporterThread.openIni(false);/*from w  w  w .  j av  a 2s .  c  o m*/
        m_exporterThread.writeIni("[Start]" + "\r\n");
    
        Date now = new Date();
        m_exporterThread.writeIni(now.toString() + "\r\n");
    
        m_exporterThread.closeIni();
    
        if (m_exporterThread.open()) {
            //            m_exporterThread.getAgents();            //JFG2.2
            m_exporterThread.getAllPendingCases(); //JFG2.2
    
            if (m_exporterThread.exportRequestedObjects()) {
                m_exporterThread.close();
                m_exporterThread.openIni(true);
                m_exporterThread.writeIni("[End]" + "\r\n");
                com.ing.connector.Registrar.logInfoMessage(m_exporterThread.getClass().getName()
                        + " exported(bkgrnd) to " + m_exporterThread.getFileName());
    
            } else {
                m_exporterThread.close();
                m_exporterThread.openIni(true);
                m_exporterThread.writeIni("[Failed]" + "\r\n");
            }
    
            now = new Date();
            m_exporterThread.writeIni(now.toString() + "\r\n");
            m_exporterThread.closeIni();
        }
    }
    

    From source file:es.itecban.deployment.executionmanager.gui.swf.service.CommonCreationManager.java

    /**
     * Introduces the selected environment name in the flow Introduces the
     * unique plan name (name + environmentname + date) in the flow Introduces
     * the container names array in the flow
     * /*ww  w  .j  a  va  2 s. c  o  m*/
     * @param context
     * @return
     * @throws Exception
     */
    public String selectEnvironment(RequestContext context) throws Exception {
    
        Calendar selectEnv1 = Calendar.getInstance();
        // Web context code
        logger.fine("Getting into selectEnvironment");
        String lock = "selectEnvironment_lock";
        synchronized (lock) {
            String selectedEnvironment = (String) context.getRequestParameters().get("selectedEnvironment");
            context.getFlowScope().put(Constants.FLOW_SELECTED_ENV, selectedEnvironment);
            // concatenation of the plan name
            String planName = (String) context.getFlowScope().get(Constants.FLOW_PLAN_NAME);
            Calendar calendar = Calendar.getInstance();
            Date date = calendar.getTime();
            String planNameUniq = planName + "|" + selectedEnvironment + "|" + date.toString();
    
            // Concatenate the creation user to the name of the plan
            logger.info("Creation user: " + AuthenticationManager.getUserName());
            planNameUniq = planNameUniq + "|" + AuthenticationManager.getUserName();
    
            context.getFlowScope().put(Constants.FLOW_PLAN_UNIQUE_NAME, planNameUniq);
            Calendar selectEnv2 = Calendar.getInstance();
            Utils.getTimeOfExecution(selectEnv1, selectEnv2, "Time of execution selectEnvironment: ");
        }
        lock = null;
        return "yes";
    }
    

    From source file:org.goobi.production.flow.jobs.HistoryAnalyserJob.java

    /**
     * method returns a timestamp from a previous step, iterates through the
     * steps if necessary.//from w  w w .  j  av  a 2 s.c  o m
     *
     * @param inProcess
     *            Process object
     * @param inStep
     *            Task object
     */
    private static Date getTimestampFromPreviousStep(Process inProcess, Task inStep) {
        Date eventTimestamp = null;
        List<Task> tempList = inProcess.getTasks();
    
        for (Task s : tempList) {
            // making sure that we only look for timestamps in the step below
            // this one
            int index = tempList.indexOf(s);
    
            if (s == inStep && index != 0) {
                Task prevStep = tempList.get(index - 1);
    
                if (prevStep.getProcessingEnd() != null) {
                    return prevStep.getProcessingEnd();
                }
    
                if (prevStep.getProcessingTime() != null) {
                    return prevStep.getProcessingTime();
                }
    
                if (prevStep.getProcessingBegin() != null) {
                    return prevStep.getProcessingBegin();
                }
    
                eventTimestamp = getTimestampFromPreviousStep(inProcess, prevStep);
            }
    
        }
    
        if (eventTimestamp == null) {
            if (inProcess.getCreationDate() != null) {
                eventTimestamp = inProcess.getCreationDate();
            } else { // if everything fails we use the current date
                Calendar cal = Calendar.getInstance();
                cal.set(2007, 0, 1, 0, 0, 0);
                eventTimestamp = cal.getTime();
                if (logger.isInfoEnabled()) {
                    logger.info("We had to use 2007-1-1 date '" + eventTimestamp.toString()
                            + "' for a history event as a fallback");
                }
            }
    
        }
        return eventTimestamp;
    }
    

    From source file:com.all.client.model.LocalPlaylist.java

    private String createHashcode(String name, Date creationDate) {
        String createdHashcode = name + creationDate.toString() + new Random().nextLong();
        try {// w ww  . j  a  v a2 s.  c  o  m
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.update(createdHashcode.getBytes());
            createdHashcode = Hashcoder.toHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            log.error(e, e);
        }
        return createdHashcode;
    
    }
    

    From source file:com.att.aro.ui.view.diagnostictab.plot.AlarmPlot.java

    @Override
    public void populate(XYPlot plot, AROTraceData analysis) {
        if (analysis == null) {
            logger.info("analysis data is null");
        } else {/*from w  ww  .  ja va 2  s  .com*/
            alarmDataCollection.removeAllSeries();
            pointerAnnotation.clear();
    
            TraceResultType resultType = analysis.getAnalyzerResult().getTraceresult().getTraceResultType();
            if (resultType.equals(TraceResultType.TRACE_FILE)) {
                logger.info("didn't get analysis trace data!");
    
            } else {
                // Remove old annotation from previous plots
                Iterator<XYPointerAnnotation> pointers = pointerAnnotation.iterator();
                while (pointers.hasNext()) {
                    plot.removeAnnotation(pointers.next());
                }
    
                for (AlarmType eventType : AlarmType.values()) {
                    XYIntervalSeries series = new XYIntervalSeries(eventType);
                    seriesMap.put(eventType, series);
                    alarmDataCollection.addSeries(series);
                }
                TraceDirectoryResult traceresult = (TraceDirectoryResult) analysis.getAnalyzerResult()
                        .getTraceresult();
                List<AlarmInfo> alarmInfos = traceresult.getAlarmInfos();
                List<ScheduledAlarmInfo> pendingAlarms = getHasFiredAlarms(traceresult.getScheduledAlarms());
                Iterator<ScheduledAlarmInfo> iterPendingAlarms = pendingAlarms.iterator();
                double firedTime = 0;
                while (iterPendingAlarms.hasNext()) {
                    ScheduledAlarmInfo scheduledEvent = iterPendingAlarms.next();
                    AlarmType pendingAlarmType = scheduledEvent.getAlarmType();
                    if (pendingAlarmType != null) {
                        firedTime = (scheduledEvent.getTimeStamp() - scheduledEvent.getRepeatInterval()) / 1000;
                        seriesMap.get(pendingAlarmType).add(firedTime, firedTime, firedTime, 1, 0.8, 1);
                        eventMapPending.put(firedTime, scheduledEvent);
                        // logger.fine("populateAlarmScheduledPlot type:\n" +
                        // pendingAlarmType
                        // + "\ntime " + scheduledEvent.getTimeStamp()
                        // + "\nrepeating " + firedTime);
                    }
                }
    
                Iterator<AlarmInfo> iter = alarmInfos.iterator();
                while (iter.hasNext()) {
                    AlarmInfo currEvent = iter.next();
                    if (currEvent != null) {
                        AlarmType alarmType = currEvent.getAlarmType();
                        if (alarmType != null) {
                            firedTime = currEvent.getTimeStamp() / 1000;
    
                            /*
                             * Catching any alarms align to quanta as being
                             * inexactRepeating alarms
                             */
                            if ((currEvent.getTimestampElapsed() / 1000) % 900 < 1) {
                                seriesMap.get(alarmType).add(firedTime, firedTime, firedTime, 1, 0, 0.7);
    
                                // Adding an arrow to mark these
                                // inexactRepeating alarms
                                XYPointerAnnotation xypointerannotation = new XYPointerAnnotation(alarmType.name(),
                                        firedTime, 0.6, 3.92699082D);
                                xypointerannotation.setBaseRadius(20D);
                                xypointerannotation.setTipRadius(1D);
                                pointerAnnotation.add(xypointerannotation);
                                plot.addAnnotation(xypointerannotation);
    
                                // logger.info("SetInexactRepeating alarm type: "
                                // + alarmType
                                // + " time " + firedTime
                                // + " epoch " + currEvent.getTimestampEpoch()
                                // + " elapsed:\n" +
                                // currEvent.getTimestampElapsed()/1000);
                            } else {
                                seriesMap.get(alarmType).add(firedTime, firedTime, firedTime, 1, 0, 0.5);
                            }
                            eventMap.put(firedTime, currEvent);
                        }
                    }
                }
                XYItemRenderer renderer = plot.getRenderer();
                renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.RTC_WAKEUP), Color.red);
    
                renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.RTC), Color.pink);
    
                renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.ELAPSED_REALTIME_WAKEUP), Color.blue);
    
                renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.ELAPSED_REALTIME), Color.cyan);
    
                renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.UNKNOWN), Color.black);
    
                // Assign ToolTip to renderer
                renderer.setBaseToolTipGenerator(new XYToolTipGenerator() {
                    @Override
                    public String generateToolTip(XYDataset dataset, int series, int item) {
                        AlarmInfo info = eventMap.get(dataset.getX(series, item));
                        Date epochTime = new Date();
                        if (info != null) {
    
                            epochTime.setTime((long) info.getTimestampEpoch());
    
                            StringBuffer displayInfo = new StringBuffer(
                                    ResourceBundleHelper.getMessageString("alarm.tooltip.prefix"));
                            displayInfo.append(MessageFormat.format(
                                    ResourceBundleHelper.getMessageString("alarm.tooltip.content"),
                                    info.getAlarmType(), info.getTimeStamp() / 1000, epochTime.toString()));
                            if ((info.getTimestampElapsed() / 1000) % 900 < 1) {
                                displayInfo.append(
                                        ResourceBundleHelper.getMessageString("alarm.tooltip.setInexactRepeating"));
                            }
                            displayInfo.append(ResourceBundleHelper.getMessageString("alarm.tooltip.suffix"));
                            return displayInfo.toString();
                        }
                        ScheduledAlarmInfo infoPending = eventMapPending.get(dataset.getX(series, item));
                        if (infoPending != null) {
    
                            epochTime.setTime(
                                    (long) (infoPending.getTimestampEpoch() - infoPending.getRepeatInterval()));
    
                            StringBuffer displayInfo = new StringBuffer(
                                    ResourceBundleHelper.getMessageString("alarm.tooltip.prefix"));
                            displayInfo.append(MessageFormat.format(
                                    ResourceBundleHelper.getMessageString("alarm.tooltip.contentWithName"),
                                    infoPending.getAlarmType(),
                                    (infoPending.getTimeStamp() - infoPending.getRepeatInterval()) / 1000,
                                    epochTime.toString(), infoPending.getApplication(),
                                    infoPending.getRepeatInterval() / 1000));
                            displayInfo.append(ResourceBundleHelper.getMessageString("alarm.tooltip.suffix"));
                            return displayInfo.toString();
                        }
                        return null;
                    }
                });
    
            }
        }
        plot.setDataset(alarmDataCollection);
        //      return plot;
    }
    

    From source file:org.openmrs.module.drugorderexport.web.controller.DrugOrderFormController.java

    /**
     * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse, java.lang.Object,
     *      org.springframework.validation.BindException)
     *///from   w  w  w .  j  a  va2  s. c  o m
    
    @SuppressWarnings("unchecked")
    protected void doSearch(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
    
        List<Integer> patientIds = null;
        List<Patient> patients = new ArrayList<Patient>();
        List<Object[]> objectsList = new ArrayList<Object[]>();
        List<Integer> drugIds = new ArrayList<Integer>();
        List<Integer> drugsByConceptsIds = new ArrayList<Integer>();
    
        String checkedValueStr[] = null;
        int checkedValue = 0;
    
        String rdBtn = request.getParameter("rdBtn");
        DrugOrderService service = Context.getService(DrugOrderService.class);
    
        if (request.getParameterValues("checkValue") != null) {
            checkedValueStr = request.getParameterValues("checkValue");
            //log.info(">>>>>>>>>>>>>>>>>>checkedValue>>>>>>>>>>>>>>>>>> " + checkedValueStr[0]);
            checkedValue = Integer.parseInt(checkedValueStr[0]);
        }
    
        String gender = request.getParameter("gender"), mnAge = request.getParameter("minAge"),
                mxAge = request.getParameter("maxAge"), mnBirthdate = request.getParameter("minBirthdate"),
                mxBirthdate = request.getParameter("maxBirthdate"), anyOrAll = request.getParameter("anyOrAll"),
                startD = request.getParameter("startdate"), endD = request.getParameter("enddate");
    
        String[] drugs = request.getParameterValues("drugList");
        String[] drugsByConcepts = request.getParameterValues("drugConceptsList");
    
        /**********************************************************************************/
        // get drug by id
        if (drugs != null) {
            for (String drug : drugs) {
                drugIds.add(Integer.parseInt(drug));
            }
        } else {
            for (Drug d : service.getArvDrugs()) {
                drugIds.add(d.getDrugId());
            }
        }
        /**********************************************************************************/
        // get drug by concept id
        if (drugsByConcepts != null) {
            for (String conceptStr : drugsByConcepts) {
                drugsByConceptsIds.add(Integer.parseInt(conceptStr));
            }
        } else {
            for (Object obj[] : service.getArvDrugsByConcepts()) {
                drugsByConceptsIds.add((Integer) obj[0]);
            }
        }
    
        Date minBirthdate = null;
        Date maxBirthdate = null;
        Date minAge = null;
        Date maxAge = null;
        Date startDate = null;
        Date endDate = null;
    
        DrugOrderControllerMessage message = new DrugOrderControllerMessage();
        String arvConceptIds = DrugOrderExportUtil.gpGetARVConceptIds();
        String arvDrugIds = DrugOrderExportUtil.gpGetARVDrugsIds();
        /*
         * Data validation
         */
        SimpleDateFormat df = OpenmrsUtil.getDateFormat();
        if (startD != null && startD.length() != 0) {
            startDate = df.parse(startD);
        }
        if (endD != null && endD.length() != 0) {
            endDate = df.parse(endD);
        }
    
        if (mnBirthdate != null && mnBirthdate.length() != 0) {
            minBirthdate = df.parse(mnBirthdate);
        }
        if (mxBirthdate != null && mxBirthdate.length() != 0) {
            maxBirthdate = df.parse(mxBirthdate);
        }
    
        if (mxAge != null && mxAge.length() != 0) {
            maxAge = service.getDateObjectFormAge(Integer.parseInt(mxAge));
        }
        if (mnAge != null && mnAge.length() != 0) {
            minAge = service.getDateObjectFormAge(Integer.parseInt(mnAge));
        }
    
        if (rdBtn.equals("drugs")) {
            patientIds = service.searchDrugOrderByDrug(anyOrAll, startDate, endDate,
                    service.getListOfDrugsByIds(drugIds), gender, minAge, maxAge, minBirthdate, maxBirthdate);
    
            if (checkedValue == 1) {
                List<Integer> allPatients = service.searchDrugOrderByDrug(anyOrAll, startDate, endDate,
                        service.getListOfDrugsByIds(drugIds), gender, minAge, maxAge, minBirthdate, maxBirthdate);
    
                patientIds = service.getActiveOnDrugsPatients(allPatients, arvDrugIds, endDate);
    
            }
        } else if (rdBtn.equals("concepts")) {
            patientIds = service.searchDrugOrderByDrugsConcepts(anyOrAll, startDate, endDate,
                    service.getListOfDrugsByConceptsIds(drugsByConceptsIds), gender, minAge, maxAge, minBirthdate,
                    maxBirthdate);
    
            if (checkedValue == 1)
                patientIds = service.searchDrugOrderByDrugActive(anyOrAll, startDate, endDate,
                        service.getListOfDrugsByConceptsIds(drugsByConceptsIds), gender, minAge, maxAge,
                        minBirthdate, maxBirthdate);
    
        }
    
        for (Integer patientId : patientIds) {
            Patient patient = new Patient();
    
            patient = Context.getPatientService().getPatient(patientId);
    
            if (!patient.getVoided())
                patients.add(patient);
    
            Date startTreatmentDate = null;
            Date lastEncounterDate = null;
            Date lastVisitDate = null;
            String startTreatmentDateStr = "";
            String lastEncounterDateStr = "";
            String lastVisitDateStr = "";
    
            if (service.getPatientLastVisitDate(patientId) != null) {
                lastVisitDate = service.getPatientLastVisitDate(patientId);
                lastVisitDateStr = lastVisitDate.toString();
            }
            if (service.getWhenPatStartedXRegimen(patientId, DrugOrderExportUtil.gpGetARVDrugsIds()) != null) {
                startTreatmentDate = service.getWhenPatientStarted(patient);
                startTreatmentDateStr = startTreatmentDate.toString();
            }
            if (service.getPatientLastEncounterDate(patientId) != null) {
                lastEncounterDate = service.getPatientLastEncounterDate(patientId);
                lastEncounterDateStr = lastEncounterDate.toString();
            }
    
            List<String> programs = new ArrayList<String>();
            String progAndDate = "";
            Collection<PatientProgram> patientPrograms = Context.getProgramWorkflowService()
                    .getPatientPrograms(patient, null, null, null, null, null, false);
            Date date = null;
            if (endDate == null)
                endDate = new Date();
            for (PatientProgram pg : patientPrograms) {
                date = pg.getDateCompleted();
                if (date == null)
                    progAndDate += pg.getProgram().getName() + "(Still Enrolled),";
                else if (date != null && date.getTime() <= endDate.getTime())
                    progAndDate += pg.getProgram().getName() + " (Completed on " + df.format(pg.getDateCompleted())
                            + "),";
            }
            objectsList.add(new Object[] { Context.getPersonService().getPerson(patientId), startTreatmentDateStr,
                    lastEncounterDateStr, lastVisitDateStr, progAndDate });
        }
    
        Date now = new Date();
    
        List<String> drugNames = new ArrayList<String>();
        String anyARVs = " ARVs";
    
        if (rdBtn.equals("drugs")) {
            for (Integer id : drugIds) {
                drugNames.add(Context.getConceptService().getDrug(id).getName());
            }
        }
    
        if (rdBtn.equals("concepts")) {
    
            for (Integer conceptId : drugsByConceptsIds) {
                //               if(Context.getConceptService().getDrug(conceptId)!=null)
                drugNames.add(Context.getConceptService().getConcept(conceptId).getName().toString());
            }
        }
    
        model.put("anyOrAll", anyOrAll);
        if (drugNames != null && drugNames.size() != 0) {
            model.put("drugList", drugNames.toString().substring(1, drugNames.toString().indexOf(']')));
            message.setDrugIds(drugNames.toString().substring(1, drugNames.toString().indexOf(']')));
        } else {
            model.put("drugList", anyARVs);
            message.setDrugIds(anyARVs);
        }
    
        if (startDate != null) {
            model.put("startdate", df.format(startDate));
            message.setStartDate(df.format(startDate) + "");
        }
    
        if (endDate != null) {
            model.put("enddate", df.format(endDate));
            message.setEndDate(df.format(endDate) + "");
        }
    
        if (gender.equals("f")) {
            model.put("gender", "Female");
            message.setGender("Female");
        } else if (gender.equals("")) {
            model.put("gender", "Any");
            message.setGender("Any");
        } else if (!gender.equals("m")) {
            model.put("gender", "Male");
            message.setGender("Male");
        }
        if (minAge != null) {
            model.put("minAge", now.getYear() - minAge.getYear());
            message.setMinAge(now.getYear() - minAge.getYear() + "");
        }
        if (maxAge != null) {
            model.put("maxAge", now.getYear() - maxAge.getYear());
            message.setMaxAge(now.getYear() - maxAge.getYear() + "");
        }
        if (minBirthdate != null) {
            model.put("minBirthdate", df.format(minBirthdate));
            message.setMinBirthdate(df.format(minBirthdate) + "");
        }
        if (maxBirthdate != null) {
            model.put("maxBirthdate", df.format(maxBirthdate));
            message.setMaxBirthdate(df.format(maxBirthdate) + "");
        }
    
        // for data exportation
        if (request.getParameter("export") != null && !request.getParameter("export").equals("")) {
            if (Context.getAuthenticatedUser().hasPrivilege("Export Collective Patient Data")) {
                if (request.getParameter("export").equals("excel"))
                    DrugOrderExportUtil.exportData(request, response, patients);
                if (request.getParameter("export").equals("pdf"))
                    DrugOrderExportUtil.exportToPDF(request, response, patients);
            } else {
                model.put("msg", "Required Privilege: [Export Collective Patient Data]");
            }
        }
    
        model.put("objectsList", objectsList);
        model.put("drugIdback", drugIds);
        model.put("conceptIdsback", drugsByConceptsIds);
        model.put("listSize", objectsList.size());
        model.put("checkedValueExport", checkedValue);
        model.put("rdBtn", rdBtn);
    
    }
    

    From source file:eu.europeana.uim.sugarcrmclient.plugin.SugarCRMServiceImpl.java

    @Override
    public void addNoteAttachmentToRecord(String recordId, String message) throws FileAttachmentException {
        SetNoteAttachment request = new SetNoteAttachment();
        NoteAttachment note = new NoteAttachment();
    
        note.setId(recordId);/*  w  ww.j  av a  2 s  . co  m*/
        note.setFile(message);
    
        Date date = new Date();
    
        note.setFilename(date.toString() + ".txt");
    
        request.setNote(note);
        request.setSession(sugarwsClient.getSessionID());
        ClientUtils.logMarshalledObject(request);
        SetNoteAttachmentResponse resp = sugarwsClient.setnoteattachment(request);
    
    }