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:ome.formats.importer.gui.HistoryTableStore.java

    /**
     * Return an array of ids based on query and date
     * @param uid/*from  w  w  w .  j  a  va  2  s.  c  o  m*/
     * @param queryString
     * @param from
     * @param to
     * @return
     */
    public long[] getItemTableIDsByQuery(Long baseId, String queryString, Date start, Date end) {
        try {
            String searchString = "";
            if (start == null || end == null) {
                if (queryString.trim().length() > 0) {
                    searchString = "(BaseUid==" + baseId + ")"; // & (" + queryString + "in Filename)";
                } else {
                    // Search by id
                    searchString = "(BaseUid==" + baseId + ")";
                }
    
            } else {
                // Search by date
                searchString = "(DateTime>=" + start.getTime() + ") & (DateTime<=" + end.getTime() + ")";
            }
            long[] ids = itemTable.getWhereList(searchString, null, 0, itemTable.getNumberOfRows(), 1);
    
            return ids;
        } catch (Exception e) {
            String s = String.format("Error retrieving import list from %s to %s.", start.toString(),
                    end.toString());
            log.error(s, e);
        }
        return null;
    }
    

    From source file:fr.gouv.culture.vitam.eml.PstExtract.java

    private Element extractInfoAppointment(PSTAppointment appointment) {
        Element root = XmlDom.factory.createElement("appointment");
    
        String value = null;//from  w  w w .j av a 2 s .  c o  m
    
        value = appointment.getLocation();
        if (value != null && !value.isEmpty()) {
            root.add(XmlDom.factory.createElement("Location").addText(value));
        }
        Date date = appointment.getStartTime();
        if (date != null) {
            root.add(XmlDom.factory.createElement("StartTime").addText(date.toString()));
        }
        PSTTimeZone zone = appointment.getStartTimeZone();
        if (zone != null) {
            root.add(XmlDom.factory.createElement("StartTimeZone").addText(TZString(zone)));
        }
        date = appointment.getEndTime();
        if (date != null) {
            root.add(XmlDom.factory.createElement("EndTime").addText(date.toString()));
        }
        zone = appointment.getEndTimeZone();
        if (zone != null) {
            root.add(XmlDom.factory.createElement("EndTimeZone").addText(TZString(zone)));
        }
        zone = appointment.getRecurrenceTimeZone();
        if (zone != null) {
            root.add(XmlDom.factory.createElement("RecurrenceTimeZone").addText(TZString(zone)));
        }
        Integer ival = appointment.getDuration();
        root.add(XmlDom.factory.createElement("Duration").addText(ival.toString()));
        ival = appointment.getMeetingStatus();
        root.add(XmlDom.factory.createElement("MeetingStatus").addText(ival.toString()));
        ival = appointment.getResponseStatus();
        root.add(XmlDom.factory.createElement("ResponseStatus").addText(ival.toString()));
        Boolean bval = appointment.isRecurring();
        root.add(XmlDom.factory.createElement("isRecurring").addText(bval.toString()));
        date = appointment.getRecurrenceBase();
        if (date != null) {
            root.add(XmlDom.factory.createElement("RecurrenceBase").addText(date.toString()));
        }
        ival = appointment.getRecurrenceType();
        root.add(XmlDom.factory.createElement("RecurrenceType").addText(ival.toString()));
        value = appointment.getRecurrencePattern();
        if (value != null && !value.isEmpty()) {
            root.add(XmlDom.factory.createElement("RecurrencePattern").addText(value));
        }
        value = appointment.getAllAttendees();
        if (value != null && !value.isEmpty()) {
            root.add(XmlDom.factory.createElement("AllAttendees").addText(value));
        }
        value = appointment.getToAttendees();
        if (value != null && !value.isEmpty()) {
            root.add(XmlDom.factory.createElement("ToAttendees").addText(value));
        }
        value = appointment.getCCAttendees();
        if (value != null && !value.isEmpty()) {
            root.add(XmlDom.factory.createElement("CCAttendees").addText(value));
        }
        ival = appointment.getAppointmentSequence();
        root.add(XmlDom.factory.createElement("AppointmentSequence").addText(ival.toString()));
    
        // online meeting properties
        bval = appointment.isOnlineMeeting();
        if (bval) {
            root.add(XmlDom.factory.createElement("isOnlineMeeting").addText(bval.toString()));
            ival = appointment.getNetMeetingType();
            root.add(XmlDom.factory.createElement("NetMeetingType").addText(ival.toString()));
            value = appointment.getNetMeetingServer();
            if (value != null && !value.isEmpty()) {
                root.add(XmlDom.factory.createElement("NetMeetingServer").addText(value));
            }
            value = appointment.getNetMeetingOrganizerAlias();
            if (value != null && !value.isEmpty()) {
                root.add(XmlDom.factory.createElement("NetMeetingOrganizerAlias").addText(value));
            }
            bval = appointment.getNetMeetingAutostart();
            root.add(XmlDom.factory.createElement("NetMeetingAutostart").addText(bval.toString()));
            bval = appointment.getConferenceServerAllowExternal();
            root.add(XmlDom.factory.createElement("ConferenceServerAllowExternal").addText(bval.toString()));
            value = appointment.getNetMeetingDocumentPathName();
            if (value != null && !value.isEmpty()) {
                root.add(XmlDom.factory.createElement("NetMeetingDocumentPathName").addText(value));
            }
            value = appointment.getNetShowURL();
            if (value != null && !value.isEmpty()) {
                root.add(XmlDom.factory.createElement("NetShowURL").addText(value));
            }
            date = appointment.getAttendeeCriticalChange();
            if (date != null) {
                root.add(XmlDom.factory.createElement("AttendeeCriticalChange").addText(date.toString()));
            }
            date = appointment.getOwnerCriticalChange();
            if (date != null) {
                root.add(XmlDom.factory.createElement("OwnerCriticalChange").addText(date.toString()));
            }
            value = appointment.getConferenceServerPassword();
            if (value != null && !value.isEmpty()) {
                root.add(XmlDom.factory.createElement("ConferenceServerPassword").addText(value));
            }
            bval = appointment.getAppointmentCounterProposal();
            root.add(XmlDom.factory.createElement("AppointmentCounterProposal").addText(bval.toString()));
            bval = appointment.isSilent();
            root.add(XmlDom.factory.createElement("isSilent").addText(bval.toString()));
            value = appointment.getRequiredAttendees();
            if (value != null && !value.isEmpty()) {
                root.add(XmlDom.factory.createElement("RequiredAttendees").addText(value));
            }
        }
        return root;
    }
    

    From source file:com.cloud.network.security.SecurityGroupManagerImpl.java

    public void cleanupFinishedWork() {
        Date before = new Date(System.currentTimeMillis() - 6 * 3600 * 1000l);
        int numDeleted = _workDao.deleteFinishedWork(before);
        if (numDeleted > 0) {
            s_logger.info("Network Group Work cleanup deleted " + numDeleted + " finished work items older than "
                    + before.toString());
        }/*from   www . j a  v  a 2  s .c o  m*/
    
    }
    

    From source file:org.gbif.ipt.service.manage.impl.ResourceManagerImplTest.java

    @Test
    public void testPublishNonRegisteredMetadataOnlyResource() throws ParserConfigurationException, SAXException,
            IOException, AlreadyExistingException, ImportException, InvalidFilenameException {
        // create instance of manager
        ResourceManagerImpl resourceManager = getResourceManagerImpl();
        // prepare resource
        Resource resource = getNonRegisteredMetadataOnlyResource();
        // configure turning auto-publishing daily
        resource.setUpdateFrequency("daily");
        resource.setPublicationMode(PublicationMode.AUTO_PUBLISH_ON);
    
        // make a few pre-publication assertions
        assertEquals(3, resource.getEml().getEmlVersion());
        Date created = resource.getCreated();
        assertNotNull(created);//  w  w  w. j  a  v a  2  s  .  com
        Date pubDate = resource.getEml().getPubDate();
        assertNotNull(pubDate);
        Date lastPublished = resource.getLastPublished();
        assertNull(lastPublished);
        assertNull(resource.getNextPublished());
        assertEquals(Constants.DATASET_TYPE_METADATA_IDENTIFIER, resource.getCoreType());
    
        // publish
        resourceManager.publish(resource, 4, baseAction);
    
        // make some post-publication assertions
        assertEquals(4, resource.getEml().getEmlVersion());
        assertNotNull(resource.getNextPublished());
        assertEquals(created.toString(), resource.getCreated().toString());
        assertNotEquals(pubDate.toString(), resource.getEml().getPubDate());
        assertNotNull(resource.getLastPublished().toString());
        assertTrue(new File(resourceDir, DataDir.EML_XML_FILENAME).exists());
        assertTrue(new File(resourceDir, "eml-4.xml").exists());
        assertTrue(new File(resourceDir, "rtf-res2.rtf").exists());
        assertTrue(new File(resourceDir, "rtf-res2-4.rtf").exists());
    }
    

    From source file:com.cloud.network.security.SecurityGroupManagerImpl.java

    private void cleanupUnfinishedWork() {
        Date before = new Date(System.currentTimeMillis() - 2 * _timeBetweenCleanups * 1000l);
        List<SecurityGroupWorkVO> unfinished = _workDao.findUnfinishedWork(before);
        if (unfinished.size() > 0) {
            s_logger.info("Network Group Work cleanup found " + unfinished.size()
                    + " unfinished work items older than " + before.toString());
            ArrayList<Long> affectedVms = new ArrayList<Long>();
            for (SecurityGroupWorkVO work : unfinished) {
                affectedVms.add(work.getInstanceId());
                work.setStep(Step.Error);
                _workDao.update(work.getId(), work);
            }//  w w  w  . j a  v a2  s. c  o m
            scheduleRulesetUpdateToHosts(affectedVms, false, null);
        } else {
            s_logger.debug(
                    "Network Group Work cleanup found no unfinished work items older than " + before.toString());
        }
    }
    

    From source file:org.jini.commands.files.List.java

    /**
     * Print the results/*from w  ww . ja v  a  2  s. c om*/
     *
     * @param withDetails
     * @param fileList
     * @return
     */
    private boolean printResults(boolean withDetails, ArrayList<File> fileList) {
    
        if (this.getJcError() == false) {
            if (withDetails == true) {
                TablePrinter tableF = new TablePrinter("Name", "Type", "Readable", "Writable", "Executable",
                        "Size KB", "Size MB", "Last Modified");
                for (File v : fileList) {
    
                    java.util.Date lastModified = new java.util.Date(v.lastModified());
                    long filesizeInKB = v.length() / 1024;
                    double bytes = v.length();
                    double kilobytes = (bytes / 1024);
                    double megabytes = (kilobytes / 1024);
    
                    String type = "";
    
                    DecimalFormat df = new DecimalFormat("####.####");
    
                    if (v.isDirectory()) {
                        type = "Dir";
                    }
                    if (v.isFile()) {
                        type = "File";
                    }
    
                    if (v.isFile() && v.isHidden()) {
                        type = "File (Hidden)";
                    }
                    if (v.isDirectory() && (v.isHidden())) {
                        type = "Dir (Hidden)";
                    }
    
                    String canExec = "" + v.canExecute();
                    String canRead = "" + v.canRead();
                    String canWrite = "" + v.canWrite();
                    String filesizeInKBStr = Long.toString(filesizeInKB);
                    String filesizeInMBStr = df.format(megabytes);
    
                    tableF.addRow(v.getName(), type, canRead, canWrite, canExec, filesizeInKBStr, filesizeInMBStr,
                            lastModified.toString());
                }
    
                tableF.print();
            } else {
                for (File v : fileList) {
                    System.out.println(v.getName());
                }
            }
        }
    
        return true;
    }
    

    From source file:fr.gouv.culture.vitam.eml.PstExtract.java

    private String extractInfoAttachment(PSTAttachment attachment, Element identification) {
        Element newElt = XmlDom.factory.createElement(EMAIL_FIELDS.subidentity.name);
        String filename = null;//w  w  w .  j  av  a2s  . com
        String result = "";
        Date creationTime = attachment.getCreationTime();
        if (creationTime != null) {
            Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.creationTime.name);
            elt.setText(creationTime.toString());
            newElt.add(elt);
        }
        boolean isMsg = false;
        try {
            PSTMessage msg = attachment.getEmbeddedPSTMessage();
            if (msg != null) {
                Element cur = currentRoot;
                currentRoot = newElt;
                if (argument.extractKeyword) {
                    result = extractInfoMessage(msg);
                } else {
                    extractInfoMessage(msg);
                }
                currentRoot = cur;
                isMsg = true;
            }
        } catch (IOException e) {
        } catch (PSTException e) {
        }
        if (!isMsg) {
            // Check file
            filename = attachment.getLongFilename();
            if (filename.isEmpty()) {
                filename = attachment.getFilename();
            }
            filename = StringUtils.toFileName(filename);
            long size = 0;
            if (true) {
                InputStream attachmentStream = null;
                FileOutputStream out = null;
                File filetemp = null;
                try {
                    attachmentStream = attachment.getFileInputStream();
                    String tempfilename = filename.isEmpty() ? (config.nbDoc.get() + 1) + "_unknownAttachment.eml"
                            : filename;
                    // Force out as eml
                    if (config.extractFile) {
                        filetemp = new File(curPath, tempfilename);
                    } else {
                        filetemp = File.createTempFile(StaticValues.PREFIX_TEMPFILE, tempfilename);
                    }
                    out = new FileOutputStream(filetemp);
                    // 8176 is the block size used internally and should give the best performance
                    int bufferSize = 8176;
                    byte[] buffer = new byte[bufferSize];
                    int count;
                    do {
                        count = attachmentStream.read(buffer);
                        if (count >= 0) {
                            out.write(buffer, 0, count);
                            size += count;
                        }
                    } while (count == bufferSize);
                    out.close();
                    attachmentStream.close();
                    // Now check file against Droid or more
                    try {
                        Commands.addFormatIdentification(newElt, filename, filetemp, config, argument);
                        if (argument.extractKeyword) {
                            // get back keyword in the main list
                            Element keyw = (Element) newElt.selectSingleNode(EMAIL_FIELDS.keywords.name);
                            if (keyw != null) {
                                StringBuilder builder = new StringBuilder();
                                @SuppressWarnings("unchecked")
                                List<Element> elts = (List<Element>) keyw
                                        .selectNodes(EMAIL_FIELDS.keywordRank.name);
                                for (Element elt : elts) {
                                    String value = elt.attributeValue(EMAIL_FIELDS.keywordOccur.name);
                                    int occur = Integer.parseInt(value) / 2 + 1;
                                    @SuppressWarnings("unchecked")
                                    List<Element> words = (List<Element>) elt
                                            .selectNodes(EMAIL_FIELDS.keywordWord.name);
                                    for (Element eword : words) {
                                        String word = eword.attributeValue(EMAIL_FIELDS.keywordValue.name) + " ";
                                        for (int i = 0; i < occur; i++) {
                                            builder.append(word);
                                        }
                                    }
                                }
                                result = builder.toString().trim();
                            }
                        }
    
                    } catch (Exception e) {
                        config.addRankId(newElt);
                        //String id = Long.toString(config.nbDoc.incrementAndGet());
                        //newElt.addAttribute(EMAIL_FIELDS.rankId.name, id);
                        String status = "Error during identification";
                        e.printStackTrace();
                        newElt.addAttribute(EMAIL_FIELDS.status.name, status);
                        return "";
                    }
                    // then clear
                    if (!config.extractFile) {
                        filetemp.delete();
                    }
                } catch (IOException e) {
                    config.addRankId(newElt);
                    //String id = Long.toString(config.nbDoc.incrementAndGet());
                    //newElt.addAttribute(EMAIL_FIELDS.rankId.name, id);
                    e.printStackTrace();
                    String status = "Error during access to attachment";
                    newElt.addAttribute(EMAIL_FIELDS.status.name, status);
                    identification.add(newElt);
                    return "";
                } catch (PSTException e) {
                    config.addRankId(newElt);
                    //String id = Long.toString(config.nbDoc.incrementAndGet());
                    //newElt.addAttribute(EMAIL_FIELDS.rankId.name, id);
                    e.printStackTrace();
                    String status = "Error during access to attachment";
                    newElt.addAttribute(EMAIL_FIELDS.status.name, status);
                    identification.add(newElt);
                    return "";
                } finally {
                    if (filetemp != null && !config.extractFile) {
                        filetemp.delete();
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e2) {
                        }
                    }
                    if (attachmentStream != null) {
                        try {
                            attachmentStream.close();
                        } catch (IOException e2) {
                        }
                    }
                }
            }
            if (filename != null) {
                Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.filename.name);
                elt.setText(filename);
                newElt.add(elt);
            }
            if (size == 0) {
                size = attachment.getAttachSize();
            }
            if (size > 0) {
                Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.attSize.name);
                elt.setText(Long.toString(size));
                newElt.add(elt);
            }
        }
        identification.add(newElt);
        return result;
    }
    

    From source file:logdruid.util.DataMiner.java

    public static FileMineResult fileMine(FileRecord fileRecord, Repository repo, Source source, boolean stats,
            boolean timings) {
        ExtendedTimeSeries ts = null;/*from   ww  w  .jav  a 2  s. c o  m*/
        PatternCache patternCache = new PatternCache();
        Date startDate = null;
        Date endDate = null;
    
        DecimalFormat decimalFormat = new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.US));
    
        FastDateFormat fastDateFormat = null;
        FileReader flstr = null;
        BufferedReader buf1st;
        Matcher matcher;
        Matcher matcher2;
        FixedMillisecond fMS = null;
        Boolean successMatch = false;
        DateFormat df = null;
        int statHit = 0;
        int statMatch = 0;
        int eventHit = 0;
        int eventMatch = 0;
        long[] arrayBefore;
        Map<Recording, String> recMatch = new HashMap<Recording, String>();
        Map<String, ExtendedTimeSeries> statMap = new HashMap<String, ExtendedTimeSeries>();
        Map<String, ExtendedTimeSeries> eventMap = new HashMap<String, ExtendedTimeSeries>();
        Map<String, Map<Date, FileLine>> RIFileLineDateMap = new HashMap<String, Map<Date, FileLine>>();
        Map<String, long[]> matchTimings = new HashMap<String, long[]>();
    
        long recordingMatchStart = 0;
        long recordingMatchEnd = 0;
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("++file: " + repo.getBaseSourcePath() + " + "
                        + (String) fileRecord.getCompletePath().toString());
            }
            flstr = new FileReader(fileRecord.getCompletePath());
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        buf1st = new BufferedReader(flstr);
        String line;
        try {
            recMatch = getRegexp(repo, source);
            int lineCount = 1;
            while ((line = buf1st.readLine()) != null) {
                // check against one Recording pattern at a tim
                // if (logger.isDebugEnabled()) {
                // logger.debug("line " + line);
                // }
                Iterator recMatchIte = recMatch.entrySet().iterator();
                while (recMatchIte.hasNext()) {
                    if (timings) {
                        recordingMatchStart = ManagementFactory.getThreadMXBean()
                                .getThreadCpuTime(Thread.currentThread().getId());
                    }
                    Map.Entry me = (Map.Entry) recMatchIte.next();
                    Recording rec = (Recording) me.getKey();
                    matcher = patternCache.getPattern((String) (rec.getRegexp())).matcher(line);
                    if (matcher.find()) {
                        Boolean isStatRecording = rec.getClass().equals(StatRecording.class);
                        if (stats) {
                            if (isStatRecording) {
                                statMatch++;
                            } else {
                                eventMatch++;
                            }
                        }
                        // logger.info("1**** matched: " + line);
                        ArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();
                        int cnt = 0;
                        matcher2 = patternCache.getPattern((String) me.getValue()).matcher(line);
                        successMatch = false;
                        if (matcher2.find()) {
                            if (stats) {
                                if (isStatRecording) {
                                    statHit++;
                                } else {
                                    eventHit++;
                                }
                            }
                            int count = 1;
                            Date date1 = null;
    
                            // handling capture for each recording item
                            Iterator<RecordingItem> recItemIte2 = recordingItem.iterator();
                            while (recItemIte2.hasNext()) {
                                RecordingItem recItem2 = recItemIte2.next();
                                // logger.info("3A**** " +
                                // recItem2.getType());
                                if (recItem2.getType().equals("date")) {
                                    try {
                                        df = repo.getDateFormat(rec.getDateFormatID());
                                        if (logger.isDebugEnabled())
                                            logger.debug("4**** rec name" + rec.getName() + " df: " + df.getId());
                                        fastDateFormat = FastDateFormat.getInstance(df.getDateFormat());
                                        date1 = fastDateFormat.parse(matcher2.group(count));
                                        if (logger.isDebugEnabled())
                                            logger.debug(
                                                    "4b**** " + df.getDateFormat() + " date: " + date1.toString());
                                        // logger.info("4**** " +
                                        // date1.toString());
                                    } catch (ParseException e) {
                                        // TODO Auto-generated catch
                                        // block
                                        e.printStackTrace();
                                    }
                                } else if (date1 != null) {
                                    if (recItem2.isSelected()) {
                                        if (logger.isDebugEnabled()) {
                                            logger.debug("FileRecord: " + fileRecord.getFile().getName()
                                                    + ", Source: " + source.getSourceName() + ", "
                                                    + recItem2.getName() + ", " + fileRecord.getFile().getName()
                                                    + ", " + lineCount);
                                        }
                                        // recording line of match in file in map RIFileLineDateMap - note the FileLine object use an int to identify the files to save memory 
                                        Map<Date, FileLine> dateFileLineMap = null;
                                        if (RIFileLineDateMap.containsKey(recItem2.getName())) {
                                            dateFileLineMap = RIFileLineDateMap.get(recItem2.getName());
                                        } else {
                                            dateFileLineMap = new HashMap<Date, FileLine>();
                                        }
                                        dateFileLineMap.put(date1, new FileLine(fileRecord.getId(), lineCount));
                                        if (logger.isDebugEnabled()) {
                                            logger.debug(fileRecord.getFile().getName() + " dateFileLineMap put: "
                                                    + date1 + "fileLine: "
                                                    + new FileLine(fileRecord.getId(), lineCount));
                                            logger.debug(fileRecord.getFile().getName() + " FileRecord: "
                                                    + fileRecord.getFile().getName() + ", RIFileLineDateMap.put: "
                                                    + recItem2.getName() + ", line: " + lineCount
                                                    + " RIFileLineDateMap size: " + RIFileLineDateMap.size()
                                                    + " dateFileLineMap size: " + dateFileLineMap.size());
                                        }
                                        RIFileLineDateMap.put(recItem2.getName(), dateFileLineMap);
    
                                        if (startDate == null) {
                                            startDate = date1;
                                        }
                                        if (endDate == null) {
                                            endDate = date1;
                                        }
                                        if (date1.after(startDate)) {
                                            endDate = date1;
                                        } else if (date1.before(startDate)) {
                                            startDate = date1;
                                        }
    
                                        if (isStatRecording) {
                                            if (statMap.containsKey(recItem2.getName())) {
                                                ts = statMap.get(recItem2.getName());
                                            } else {
                                                ts = new ExtendedTimeSeries(recItem2.getName(),
                                                        FixedMillisecond.class);
                                                if (logger.isDebugEnabled())
                                                    logger.debug(
                                                            "5**** Adding record to Map: " + recItem2.getName());
                                            }
                                            fMS = new FixedMillisecond(date1);
                                            if (matcher2.group(count) == null) {
                                                logger.info("null in match on " + recItem2.getName() + " at "
                                                        + fileRecord.getFile().getName() + " line cnt:"
                                                        + lineCount);
                                                logger.info("line : " + line);
                                            }
                                            try {
    
                                                if (recItem2.getType().equals("long")) {
                                                    ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS,
                                                            Long.valueOf((String) matcher2.group(count)))));
                                                } else {
                                                    ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS,
                                                            Double.parseDouble(String.valueOf(decimalFormat
                                                                    .parse((String) matcher2.group(count)))))));
                                                }
                                            } catch (ParseException e) {
                                                // TODO Auto-generated catch
                                                // block
                                                e.printStackTrace();
                                            }
                                            if (stats) {
                                                //int[] array = { statMatch, statHit };
                                                int[] array = ts.getStat();
                                                array[1] = array[1] + 1;
                                                array[0] = array[0] + 1;
                                                ts.setStat(array);
                                                if (logger.isDebugEnabled())
                                                    logger.debug("stats " + array[0] + " " + array[1]);
                                            }
    
                                            statMap.put(recItem2.getName(), ts);
                                            // performance: add the
                                            // TmeSeriesDataItem to the
                                            // TimeSeries instead of updating
                                            // the TimeSeries in the Map
    
                                        } else { // rec.getClass().equals(EventRecording.class)
                                            if (eventMap.containsKey(recItem2.getName())) {
                                                ts = eventMap.get(recItem2.getName());
                                            } else {
                                                ts = new ExtendedTimeSeries(recItem2.getName(),
                                                        FixedMillisecond.class);
                                                if (logger.isDebugEnabled())
                                                    logger.debug(
                                                            "5**** Adding record to Map: " + recItem2.getName());
                                            }
                                            fMS = new FixedMillisecond(date1);
    
                                            if (((RecordingItem) recItem2).getProcessingType()
                                                    .equals("occurrences")) {
                                                TimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);
                                                if (t != null) {
                                                    ts.getTimeSeries()
                                                            .addOrUpdate((new TimeSeriesDataItem(fMS, 101))); // +
                                                    // (double)t.getValue()
                                                    // need some way to show several occurrences
                                                } else {
                                                    ts.getTimeSeries().add((new TimeSeriesDataItem(fMS, 100)));
                                                }
    
                                            } else if (((RecordingItem) recItem2).getProcessingType()
                                                    .equals("sum")) {
                                                TimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);
                                                if (t != null) {
                                                    if (!recItem2.getType().equals("date")) {
                                                        try {
                                                            ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(
                                                                    fMS,
                                                                    Double.parseDouble(String
                                                                            .valueOf(decimalFormat
                                                                                    .parse(matcher2.group(count)))
                                                                            + ts.getTimeSeries().getDataItem(fMS)
                                                                                    .getValue()))));
                                                            logger.info(
                                                                    ts.getTimeSeries().getDataItem(fMS).getValue());
                                                        } catch (ParseException e) {
                                                            // TODO
                                                            // Auto-generated
                                                            // catch block
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                } else {
                                                    try {
                                                        ts.getTimeSeries()
                                                                .add((new TimeSeriesDataItem(fMS, Double
                                                                        .parseDouble(String.valueOf(decimalFormat
                                                                                .parse(matcher2.group(count)))))));
                                                    } catch (ParseException e) {
                                                        // TODO Auto-generated
                                                        // catch block
                                                        e.printStackTrace();
                                                    }
                                                }
    
                                            } else if (((RecordingItem) recItem2).getProcessingType()
                                                    .equals("capture")) {
    
                                            } else {
                                                if (!recItem2.getType().equals("date")) {
                                                    try {
                                                        ts.getTimeSeries()
                                                                .addOrUpdate((new TimeSeriesDataItem(fMS, Double
                                                                        .parseDouble(String.valueOf(decimalFormat
                                                                                .parse(matcher2.group(count)))))));
                                                    } catch (ParseException e) {
                                                        // TODO Auto-generated
                                                        // catch block
                                                        e.printStackTrace();
                                                    }
                                                }
                                                // ts.addOrUpdate((new
                                                // TimeSeriesDataItem(fMS,
                                                // 100)));
                                            }
                                            // logger.debug(recItem2.getName() +
                                            // " " +
                                            // Double.parseDouble((matcher2.group(count))));
                                            if (stats) {
                                                int[] array = ts.getStat();
                                                array[1] = array[1] + 1;
                                                array[0] = array[0] + 1;
                                                ts.setStat(array);
                                                if (logger.isDebugEnabled())
                                                    logger.debug("stats " + array[0] + " " + array[1]);
                                            }
                                            eventMap.put(recItem2.getName(), ts);
    
                                        }
                                    }
                                }
                                count++;
                                // logger.info("event statistics: "+eventMatch +
                                // " and " +eventHit +
                                // " ; stat statistics: "+statMatch + " and "
                                // +statHit);
                            }
                        }
                        if (timings) {
                            recordingMatchEnd = ManagementFactory.getThreadMXBean()
                                    .getThreadCpuTime(Thread.currentThread().getId());
                            if (matchTimings.containsKey(rec.getName())) {
                                arrayBefore = matchTimings.get(rec.getName());
                                // logger.info(file.getName() + " contains " +
                                // arrayBefore);
                                // 0-> sum of time for success matching of given
                                // recording ; 1-> sum of time for failed
                                // matching ; 2-> count of match attempts,
                                // 3->count of success attempts
    
                                long[] array = { arrayBefore[0] + recordingMatchEnd - recordingMatchStart,
                                        arrayBefore[1], arrayBefore[2] + 1, arrayBefore[3] + 1 };
                                // logger.info(file.getName() +
                                // " add success to" + rec.getName() + " 0: "+
                                // array[0] + " 1: "+ array[1]+ " 2: "+ array[2]
                                // +" 3: "+ array[3]);
                                matchTimings.put(rec.getName(), array);
                            } else {
                                long[] array = { recordingMatchEnd - recordingMatchStart, 0, 1, 1 };
                                matchTimings.put(rec.getName(), array);
                                // logger.info(file.getName() + " first success"
                                // + rec.getName() + " 0: "+ array[0] + " 1: "+
                                // array[1]+ " 2: "+ array[2] +" 3: "+
                                // array[3]);
                            }
                        }
                    } else {
                        if (timings) {
                            recordingMatchEnd = ManagementFactory.getThreadMXBean()
                                    .getThreadCpuTime(Thread.currentThread().getId());
                            if (matchTimings.containsKey(rec.getName())) {
                                arrayBefore = matchTimings.get(rec.getName());
                                // 0-> sum of time for success matching of given
                                // recording ; 1-> sum of time for failed
                                // matching ; 2-> count of match attempts,
                                // 3->count of success attempts
                                long[] array = { arrayBefore[0],
                                        arrayBefore[1] + recordingMatchEnd - recordingMatchStart,
                                        arrayBefore[2] + 1, arrayBefore[3] };
                                matchTimings.put(rec.getName(), array);
                            } else {
                                long[] array = { 0, recordingMatchEnd - recordingMatchStart, 1, 0 };
                                matchTimings.put(rec.getName(), array);
                            }
                        }
                    }
    
                }
                lineCount++;
    
                // timing
            }
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                buf1st.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
        /*
         * if (logger.isInfoEnabled()) { Iterator Ite =
         * matchTimings.entrySet().iterator(); long successTotalTime=0; long
         * failedTotalTime=0; // 0-> sum of time for success matching of given
         * // recording ; 1-> sum of time for failed // matching ; 2-> count of
         * match attempts, // 3->count of success attempts // long[] array;
         * while (Ite.hasNext()) { Map.Entry pairs = (Map.Entry) Ite.next();
         * long[] array = (long[]) pairs.getValue(); logger.info(file.getName()
         * + " - "+ pairs.getKey() + " / success all time: " + array[0] +
         * " failed all time: " + array[1] + " attempt count: " + array[2] +
         * " success count: " + array[3] + " failed count:"
         * +(array[2]-array[3])); successTotalTime=successTotalTime+array[0];
         * failedTotalTime=failedTotalTime+array[1]; } logger.info("success: "
         * +successTotalTime + " failed: " + failedTotalTime); Ite =
         * matchTimings.entrySet().iterator(); while (Ite.hasNext()) { Map.Entry
         * pairs = (Map.Entry) Ite.next(); long[] array = (long[])
         * pairs.getValue(); logger.info(file.getName() + " percents - "+
         * pairs.getKey() + " / % success time: " + (( successTotalTime!=0) ?
         * ((double)((double)array[0] / successTotalTime)*100) : 0 ) +
         * " % failed time: " + (( failedTotalTime!=0) ?((double)array[1]/
         * failedTotalTime)*100 :0) + " attempt cost: " + ((array[2]!=0) ?
         * ((double)successTotalTime + failedTotalTime ) /array[2]:0 )+
         * " success cost: " + ((array[3]!=0) ? ((double)successTotalTime )
         * /array[3] : 0) + " failed cost:" + ((array[2]-array[3]!=0) ?
         * ((double)failedTotalTime/(array[2]-array[3])) : 0) ); } }
         */
        return new FileMineResult(fileRecord, statMap, eventMap, matchTimings, RIFileLineDateMap, startDate,
                endDate);
    }
    

    From source file:com.jaspersoft.jasperserver.test.ReportSchedulingTestTestNG.java

    /**
     *  Sanity Test that exercises getJobsByNextFireTime filtered by Trigger State
     *     choose the state that we can have set most reliably:  STATE_NORMAL
     *
     *  For the test://from   w w  w.  java2 s  . c  om
     *     0.  Define a time window that we will search within
     *     1.  Schedule jobs that will fire outside of our window
     *     2.  Query to find jobs within our window and verify that we fetch the expected one.
     *
     */
    @Test()
    public void doBasicFindByNextFireTimeTriggerStatesPersistenceSanityTest() {
        m_logger.info(
                "\n\nReportSchedulingTestTestNG => doBasicFindByNextFireTimeTriggerStatesPersistenceSanityTest() called");
    
        // REPORT JOB 1  The Job that we want out query to find
    
        Date now = new Date();
        long nowMillis = now.getTime();
        long windowIntervalMillis = 1000 * 60 * 6; //  size of the query time window 6 minutes
        long queryWindowStart = nowMillis - 10; //  wind clock back just to be sure
        long queryWindowEnd = nowMillis + windowIntervalMillis;
        Date report01StartDate = new Date(queryWindowStart + (1000 * 60 * 4)); // start in 4 minutes
        Date report02StartDate = new Date(queryWindowStart + (1000 * 60 * 10)); // start in 10 minutes
        Date startDate = new Date(queryWindowStart);
        Date endDate = new Date(queryWindowEnd);
    
        ReportJobSource source = new ReportJobSource();
        // validator requires a REAL report
        source.setReportUnitURI("/reports/samples/AllAccounts");
        Map params = new HashMap();
        source.setParametersMap(params);
    
        ReportJobSimpleTrigger trigger = new ReportJobSimpleTrigger();
        trigger.setStartDate(report01StartDate);
        trigger.setOccurrenceCount(5);
        trigger.setRecurrenceInterval(1);
        trigger.setRecurrenceIntervalUnit(ReportJobSimpleTrigger.INTERVAL_MINUTE);
    
        ReportJobRepositoryDestination repositoryDestination = new ReportJobRepositoryDestination();
        // validator requires a REAL folder
        repositoryDestination.setFolderURI("/reports/samples");
        repositoryDestination.setOutputDescription("report output");
        repositoryDestination.setSequentialFilenames(true);
        repositoryDestination.setTimestampPattern("yyyyMMdd");
        repositoryDestination.setDefaultReportOutputFolderURI("/default/report_output/folder");
        repositoryDestination.setUsingDefaultReportOutputFolderURI(true);
    
        ReportJobMailNotification mailNotification = new ReportJobMailNotification();
        mailNotification.addTo("john@smith.com");
        mailNotification.setSubject("Scheduled report");
        mailNotification.setMessageText("Executed report");
    
        ReportJob job_01 = new ReportJob();
        job_01.setLabel("foo");
        job_01.setDescription("bar");
        job_01.setSource(source);
        job_01.setTrigger(trigger);
        job_01.setBaseOutputFilename("foo_" + (new Date().getTime()));
        job_01.addOutputFormat(ReportJob.OUTPUT_FORMAT_PDF);
        job_01.addOutputFormat(ReportJob.OUTPUT_FORMAT_RTF);
        job_01.setContentRepositoryDestination(repositoryDestination);
        job_01.setMailNotification(mailNotification);
    
        job_01 = m_reportSchedulingService.scheduleJob(m_executionContext, job_01);
        m_logger.info("scheduled Job 01 id='" + job_01.getId() + "' label='" + job_01.getLabel() + " for "
                + report01StartDate);
    
        assertNotNull(job_01);
        long jobId_01 = job_01.getId();
    
        boolean deleted = false;
        Byte triggerStateNormal = ReportJobRuntimeInformation.STATE_NORMAL;
        m_logger.info("search for Triggers in ReportJobRuntimeInformation.STATE_NORMAL="
                + ReportJobRuntimeInformation.STATE_NORMAL);
        List<Byte> triggerStateArray = new ArrayList<Byte>();
        triggerStateArray.add(triggerStateNormal);
        try {
            List<ReportJobSummary> summaryList = m_reportSchedulingService.getJobsByNextFireTime(m_executionContext,
                    null, startDate, endDate, triggerStateArray);
    
            StringBuilder sb = new StringBuilder();
            int count = 0;
            for (ReportJobSummary js : summaryList) {
                ReportJobRuntimeInformation ri = js.getRuntimeInformation();
                Date nextFireTime = (ri == null ? null : ri.getNextFireTime());
                String time = (nextFireTime == null ? "NULL" : nextFireTime.toString());
                sb.append((count++) + " job " + js.getId() + " " + nextFireTime + " = " + time + "\n");
            }
            m_logger.info(sb.toString());
    
            m_logger.info("expecting query to return 1 report, got " + summaryList.size());
            int expectedNumberOfReports = 1;
            assertEquals("Error ! expected to get back 1 Report in window but instead we got " + summaryList.size(),
                    expectedNumberOfReports, summaryList.size());
    
            ReportJobSummary rjs = summaryList.get(0);
            long id1 = rjs.getId();
            m_logger.info("Expected to get back jobId='" + jobId_01 + "', got '" + id1 + "'");
            assertEquals(
                    "Error ! expected to get back job01 id = '" + jobId_01 + "', but instead we got back " + id1,
                    id1, jobId_01);
    
            try {
                m_reportJobsPersistenceService.deleteJob(m_executionContext, new ReportJobIdHolder(jobId_01));
                deleted = true;
            } catch (Throwable th) {
                m_logger.info("Error !  Throwable while attempting to delete job '" + th.getMessage() + "'");
            }
    
            job_01 = m_reportJobsPersistenceService.loadJob(m_executionContext, new ReportJobIdHolder(jobId_01));
            assertNull(job_01);
        } finally {
            if (!deleted) {
                try {
                    m_reportJobsPersistenceService.deleteJob(m_executionContext, new ReportJobIdHolder(jobId_01));
                } catch (Throwable th) {
                }
            }
        }
    }
    

    From source file:com.hzq.car.CarTest.java

    /**
     * ???//from  w  w  w. ja v a 2s  .co m
     */
    private Map getData(String token, Date date, String url, Integer pageIndex) throws ParseException, IOException {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("access_token", token));
        params.add(new BasicNameValuePair("timestamp", formatIso8601Date(new Date())));
        params.add(new BasicNameValuePair("signNonce", new Random().nextInt(1000000) + ""));
        String format = new SimpleDateFormat("yyyy-MM-dd").format(date);
        String str = format + " 00:00:00";
        String str2 = format + " 23:59:59";
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = fmt.parse(str);
        Date date2 = fmt.parse(str2);
        params.add(new BasicNameValuePair("startQueryTime", formatIso8601Date(date1)));
        params.add(new BasicNameValuePair("endQueryTime", formatIso8601Date(date2)));
        params.add(new BasicNameValuePair("pageIndex", pageIndex.toString()));
        params.add(new BasicNameValuePair("pageSize", "20"));
        params.add(new BasicNameValuePair("carDealerType", "all"));
        params.add(new BasicNameValuePair("province", ""));
        params.add(new BasicNameValuePair("city", "?"));
        String s = sendAndGetResponse(url, params);
        Map map = JSON.parseObject(s, Map.class);
        if (!"10000".equals(map.get("code")))
            throw new RuntimeException(
                    "?? " + url + "  " + date.toString() + " pageIndex" + pageIndex);
        return map;
    }