List of usage examples for java.text DateFormat MEDIUM
int MEDIUM
To view the source code for java.text DateFormat MEDIUM.
Click Source Link
From source file:org.sakaiproject.chat2.tool.ChatTool.java
/** * @return the translated message based on the current date settings for this channel *///from www. ja va 2s . c o m public String getDatesMessage() { String msg = null; if (this.currentChannel != null) { DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM); if (this.currentChannel.getStartDate() != null && this.currentChannel.getEndDate() != null) { msg = getMessageFromBundle("custom_date_display", new Object[] { TimeService.newTime(this.currentChannel.getStartDate().getTime()).toStringLocalDate(), TimeService.newTime(this.currentChannel.getEndDate().getTime()).toStringLocalDate() }); } else if (this.currentChannel.getStartDate() != null) { msg = getMessageFromBundle("custom_date_display_start", new Object[] { TimeService.newTime(this.currentChannel.getStartDate().getTime()).toStringLocalDate(), "" }); } else if (this.currentChannel.getEndDate() != null) { msg = getMessageFromBundle("custom_date_display_end", new Object[] { "", TimeService.newTime(this.currentChannel.getEndDate().getTime()).toStringLocalDate() }); } } return msg; }
From source file:org.tinymediamanager.core.tvshow.entities.TvShow.java
/** * Gets the first aired as a string, formatted in the system locale. * /*w w w. j a v a 2 s . co m*/ * @return the first aired as string */ public String getFirstAiredAsString() { if (this.firstAired == null) { return ""; } return SimpleDateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()).format(firstAired); }
From source file:org.pentaho.platform.repository.subscription.SubscriptionHelper.java
/** * This formatter works with a date/time string with this format: May 21, 2008 8:29:21 PM * /* ww w.ja v a 2 s . c o m*/ * NOTE: the formatter cannot be shared across threads (since DateFormat implementations are not guaranteed to be thread safe) or across sessions (since * different sessions may have different locales). So create a new one an each call. * * @return */ public static DateFormat getDateTimeFormatter() { return DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, LocaleHelper.getLocale()); }
From source file:org.pengyou.ooo.PublishAsDialog.java
private String formatList(String[] t) { String res = new String(); if (t[2] == "COLLECTION") { if (t[4].length() > 21) res = t[4].substring(0, 20) + ""; else//from w ww . j a v a2 s . c om res = t[4]; //res = " " + res; res = " " + res; } else { if (t[4].length() > 23) res = t[4].substring(0, 22) + ""; else res = t[4]; } //int l = res.length(); while (res.length() < 25) res += " "; res += t[6]; while (res.length() < 42) res += " "; Locale locale = Locale.FRENCH; Date date = null; String s = null; try { date = DateFormat.getDateTimeInstance().parse(t[5]); s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(date); res += s; while (res.length() < 57) res += " "; } catch (ParseException e) { e.printStackTrace(); log.log(Level.DEBUG, e.getLocalizedMessage()); } date = null; s = null; try { date = DateFormat.getDateTimeInstance().parse(t[3]); s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(date); res += s; while (res.length() < 71) res += " "; } catch (ParseException e) { e.printStackTrace(); log.log(Level.DEBUG, e.getLocalizedMessage()); } return res; }
From source file:org.xwiki.batchimport.internal.DefaultBatchImport.java
public BatchImportLog doImport(BatchImportConfiguration config, boolean withFiles, boolean overwritefile, boolean simulation, String logHint) throws IOException, XWikiException { XWikiContext xcontext = getXWikiContext(); XWiki xwiki = xcontext.getWiki();/* ww w .j a v a 2 s. com*/ // log to report how this import goes BatchImportLog log = getLog(logHint); // the file to import ImportFileIterator metadatafilename = null; try { metadatafilename = getImportFileIterator(config); } catch (ComponentLookupException e) { // IOException directly from the getFileIterator method throw new IOException( "Could not find an import file reader for the configuration: " + config.toString(), e); } // mapping from the class fields to source file columns Map<String, String> mapping = config.getFieldsMapping(); // -------------------- Not transformed to config yet, will not work ---------------------// Document doc = new Document(xcontext.getDoc(), xcontext); // attach files referred in the column _file to the document boolean fileupload = (Integer) doc.getValue("fileupload") == null || ((Integer) doc.getValue("fileupload")).equals(0) ? false : true; // use office importer to import the content from the column _file to the document content boolean fileimport = (Integer) doc.getValue("fileimport") == null || ((Integer) doc.getValue("fileimport")).equals(0) ? false : true; // directory or zip file where the referenced files are stored. Directory on disk. String datadir = (String) doc.getValue("datafilename"); // path of the files inside the zip String datadirprefix = (String) doc.getValue("datafileprefix"); // column in the xls that will turn into tags // TODO: this tags needs to be reimplemented, now it works only with xwiki fields in the list: so you can // add something in the tags only if you import it as well. You should be able to configure it to be a // column in the csv / xls and that column needs to be handled as a list with the list separator. Implement as // doc.tags List<String> fieldsfortags = getAsList((String) doc.getValue("fieldsfortags"), config.getListSeparator()); // -------------------- ----------------------------- ---------------------// // class to map data to (objects of this class will be created) BaseClass defaultClass = xwiki.getXClass( currentDocumentStringResolver.resolve(config.getMappingClassName(), StringUtils.isEmpty(config.getWiki()) ? null : new WikiReference(config.getWiki())), xcontext); // TODO: validate that mapping is correct on top of this class, issue an "Error" if not (more of a warning than // an error): check that fields exist, etc // the locale of the data to read Locale sourceLocale = config.getLocale(); // prepare the default date formatter to process the dates in this row DateFormat defaultDateFormatter = null; String defaultDateFormat = config.getDefaultDateFormat(); if (StringUtils.isEmpty(defaultDateFormat)) { if (sourceLocale != null) { defaultDateFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM, sourceLocale); } // get it from preferences, hoping that it's set defaultDateFormat = xcontext.getWiki().getXWikiPreference("dateformat", xcontext); } defaultDateFormatter = new SimpleDateFormat(defaultDateFormat); // and get a number formatter, we'll use this to process the numbers a bit. NumberFormat numberFormatter = null; if (sourceLocale != null) { numberFormatter = NumberFormat.getInstance(sourceLocale); } // whether this file has header row or not (whether first line needs to be imported or not) boolean hasHeaderRow = config.hasHeaderRow(); // list of document names, used to remember what are the document names that were generated from the // document. Note that for multiple imports from the same document, this list should be identical. List<DocumentReference> docNameList = new ArrayList<DocumentReference>(); // list of documents that were actually saved during this import, to know how to make proper replacements. // Basically it serves to know if a document which is not new was saved before during this import or it was // there before the import started. This prevents "replace" from deleting twice (if multiple rows with the // same name are supposed to update each other) and allows to save multiple rows in the same document if // overwrite is set to skip and the document is created during this import (in which case duplicate rows // should not "skip" but "update"). List<DocumentReference> savedDocuments = new ArrayList<DocumentReference>(); ZipFile zipfile = null; if (!fileupload || StringUtils.isEmpty(datadir)) { withFiles = false; } // check if the files in the datadir can be properly read if (withFiles) { // if it's a zip, try to read the zip if (datadir.endsWith(".zip")) { log.log("checkingzip", datadir); try { zipfile = new ZipFile(new File(datadir), "cp437"); // TODO: what the hell is this, why are we putting it on empty? datadir = ""; } catch (IOException e) { log.logError("cannotopenzip", datadir); return log; } if (debug) { @SuppressWarnings("unchecked") Enumeration<ZipEntry> zipFileEntries = zipfile.getEntries(); while (zipFileEntries.hasMoreElements()) { ZipEntry zipe = zipFileEntries.nextElement(); debug("Found zip entry: " + zipe.getName()); } } } else { // checking it as a directory log.log("checkingdatadir", datadir); File datad = new File(datadir); if (datad == null || !datad.isDirectory()) { log.logError("cannotopendatadir", datadir); return log; } } } // start reading the rows and process them one by one metadatafilename.resetFile(config); List<String> currentLine = null; int rowIndex = 0; List<String> headers = null; // if there is no header row the headers are the numbers of the columns as strings if (hasHeaderRow) { headers = getColumnHeaders(metadatafilename, hasHeaderRow); currentLine = metadatafilename.readNextLine(); rowIndex = 1; } else { currentLine = metadatafilename.readNextLine(); headers = new ArrayList<String>(); for (int i = 0; i < currentLine.size(); i++) { headers.add(Integer.toString(i)); } } debug("Headers are: " + headers); debug("Mapping is: " + mapping); while (currentLine != null) { debug("Processing row " + rowIndex + "."); Map<String, String> data = getData(currentLine, mapping, headers); if (data == null) { break; } debug("Row " + currentLine.toString() + " data is: " + data.toString() + ""); // generate page name DocumentReference generatedDocName = getPageName(data, rowIndex, config, docNameList); // process the row if (generatedDocName != null) { // check if it's duplicated name boolean isDuplicateName = docNameList.contains(generatedDocName); if (!isDuplicateName) { docNameList.add(generatedDocName); } // check that this pageName should be used from the pov of the already generated file names if (!(isDuplicateName && config.getDocNameDeduplication() == Overwrite.SKIP)) { // potentially deduplicate it on the wiki, if needed DocumentReference pageName = maybeDeduplicatePageNameInWiki(generatedDocName, config, savedDocuments, xcontext); // validate the page name (check if it fits in the xwiki db, length of fullName, etc) boolean pageNameValid = validatePageName(pageName, rowIndex, currentLine, mapping, data, simulation, log); if (pageNameValid) { // try catch here, in case a row fails to save because of xwiki issues, we go to next row try { // marshal data to the document objects (this is creating the document and handling // overwrites) Document newDoc = this.marshalDataToDocumentObjects(pageName, data, currentLine, rowIndex, defaultClass, isDuplicateName, savedDocuments.contains(pageName), config, xcontext, fieldsfortags, defaultDateFormatter, numberFormatter, log, simulation); // if a new document was created and filled, valid, with the proper overwrite if (newDoc != null) { // save the document ... if (withFiles) { // ... either with its files. Saving is done in the same function as files saving // there are reasons to do multiple saves when saving attachments and importing // office // documents, so we rely completely on files for saving. // TODO: fix the overwrite parameter, for now pass false if it's set to anything // else // besides skip saveDocumentWithFiles(newDoc, data, currentLine, rowIndex, config, xcontext, config.getOverwrite() != Overwrite.SKIP, simulation, overwritefile, fileimport, datadir, datadirprefix, zipfile, savedDocuments, log); } else { // ... or just save it: no files handling it, we save it here manually String serializedPageName = entityReferenceSerializer.serialize(pageName); if (!simulation) { newDoc.save(); log.logSave("import", rowIndex, currentLine, serializedPageName); } else { // NOTE: when used with overwrite=GENERATE_NEW, this line here can yield results // a // bit different from the actual results during the import, since, if a document // fails to save with an exception, the simulation thinks it actually saved, // while // the actual import knows it didn't. log.logSave("simimport", rowIndex, currentLine, serializedPageName); } savedDocuments.add(newDoc.getDocumentReference()); } } else { // newDoc is null // validation error during page generation, page generation and validation is // responsible to log } } catch (XWikiException xwe) { log.logCritical("importfail", rowIndex, currentLine, pageName, xwe); LOGGER.warn("Failed to import line " + currentLine + " to document " + pageName, xwe); } catch (IOException ioe) { log.logCritical("importfail", rowIndex, currentLine, pageName, ioe); LOGGER.warn("Failed to import line " + currentLine + " to document " + pageName, ioe); } } else { // page name not valid, doesn't fit in the db. If we're simulating, validate the rest as well to // show all errors at once if (simulation) { parseAndValidatePageData(data, rowIndex, currentLine, this.entityReferenceSerializer.serialize(pageName), defaultClass, config, defaultDateFormatter, numberFormatter, simulation, log, false); } // don't log, the validation functions are logging } } else { // pageName exists and the config is set to ignore log.logSkip("ignoreduplicate", rowIndex, currentLine); } } else { // pageName is null log.logSkip("ignoreemptypagename", rowIndex, currentLine); } // go to next line currentLine = metadatafilename.readNextLine(); rowIndex++; } log.log("done"); // set saved documents to the log, if it knows how to accept them if (log instanceof AbstractSavedDocumentsBatchImportLog) { ((AbstractSavedDocumentsBatchImportLog) log).setSavedDocuments(savedDocuments); } return log; }
From source file:org.hoteia.qalingo.core.web.mvc.factory.impl.ViewBeanFactoryImpl.java
/** * //from www .j av a 2 s .c o m */ public RetailerViewBean buildRetailerViewBean(final RequestData requestData, final Retailer retailer) throws Exception { final HttpServletRequest request = requestData.getRequest(); final MarketArea marketArea = requestData.getMarketArea(); final Locale locale = requestData.getLocale(); final RetailerViewBean retailerViewBean = new RetailerViewBean(); retailerViewBean.setCode(retailer.getCode()); retailerViewBean.setName(retailer.getName()); retailerViewBean.setDescription(retailer.getDescription()); retailerViewBean.setOfficialRetailer(retailer.isOfficialRetailer()); retailerViewBean.setBrand(retailer.isBrand()); retailerViewBean.setEcommerce(retailer.isEcommerce()); if (retailer.getAddresses() != null) { RetailerAddress defaultAddress = retailer.getDefaultAddress(); if (defaultAddress != null) { retailerViewBean.getDefaultAddress().setAddress1(defaultAddress.getAddress1()); retailerViewBean.getDefaultAddress().setAddress2(defaultAddress.getAddress2()); retailerViewBean.getDefaultAddress() .setAddressAdditionalInformation(defaultAddress.getAddressAdditionalInformation()); retailerViewBean.getDefaultAddress().setPostalCode(defaultAddress.getPostalCode()); retailerViewBean.getDefaultAddress().setCity(defaultAddress.getCity()); retailerViewBean.getDefaultAddress().setStateCode(defaultAddress.getStateCode()); retailerViewBean.getDefaultAddress().setStateLabel(defaultAddress.getStateCode()); retailerViewBean.getDefaultAddress().setAreaCode(defaultAddress.getAreaCode()); retailerViewBean.getDefaultAddress().setAreaLabel(defaultAddress.getAreaCode()); retailerViewBean.getDefaultAddress().setCountryCode(defaultAddress.getCountryCode()); String countryLabel = referentialDataService.getCountryByLocale(defaultAddress.getCountryCode(), locale); retailerViewBean.getDefaultAddress().setCountryLabel(countryLabel); retailerViewBean.getDefaultAddress().setLongitude(defaultAddress.getLongitude()); retailerViewBean.getDefaultAddress().setLatitude(defaultAddress.getLatitude()); retailerViewBean.getDefaultAddress().setPhone(defaultAddress.getPhone()); retailerViewBean.getDefaultAddress().setMobile(defaultAddress.getMobile()); retailerViewBean.getDefaultAddress().setFax(defaultAddress.getFax()); retailerViewBean.getDefaultAddress().setEmail(defaultAddress.getEmail()); String websiteUrl = defaultAddress.getWebsite(); if (StringUtils.isNotEmpty(websiteUrl) && !websiteUrl.contains("http")) { websiteUrl = "http://" + websiteUrl; } retailerViewBean.getDefaultAddress().setWebsite(websiteUrl); } } // CLONE THE CURRENT REQUEST DATE TO BUILD THE CHANGE CONTEXT URL (MENU) RequestData requestDataChangecontext = new RequestData(); BeanUtils.copyProperties(requestData, requestDataChangecontext); requestDataChangecontext.setMarketAreaRetailer(retailer); retailerViewBean.setChangeContextUrl(urlService.buildChangeContextUrl(requestDataChangecontext)); retailerViewBean.setHomeUrl(urlService.generateUrl(FoUrls.HOME, requestDataChangecontext)); retailerViewBean.setDetailsUrl(urlService.generateUrl(FoUrls.RETAILER_DETAILS, requestData, retailer)); retailerViewBean.setQualityOfService(retailer.getQualityOfService()); retailerViewBean.setPriceScore(retailer.getPriceScore()); retailerViewBean.setRatioQualityPrice(retailer.getRatioQualityPrice()); int reviewCount = retailerViewBean.getComments().size(); retailerViewBean.setReviewCount(reviewCount); Object[] reviewCountLabelParams = { reviewCount }; retailerViewBean.setReviewCountLabel( getSpecificMessage(ScopeWebMessage.SOCIAL, "review_count_label", reviewCountLabelParams, locale)); Set<RetailerCustomerComment> customerComments = retailer.getCustomerComments(); if (customerComments != null) { for (Iterator<RetailerCustomerComment> iterator = customerComments.iterator(); iterator.hasNext();) { RetailerCustomerComment retailerCustomerComment = (RetailerCustomerComment) iterator.next(); RetailerCustomerCommentViewBean retailerCustomerCommentViewBean = new RetailerCustomerCommentViewBean(); retailerCustomerCommentViewBean .setCustomerDisplayName(retailerCustomerComment.getCustomer().getScreenName()); retailerCustomerCommentViewBean.setCustomerUrl(urlService.buildCustomerDetailsUrl(requestData, retailerCustomerComment.getCustomer().getPermalink())); retailerCustomerCommentViewBean.setCustomerAvatarImg(requestUtil .getCustomerAvatar(requestData.getRequest(), retailerCustomerComment.getCustomer())); DateFormat dateFormat = requestUtil.getFormatDate(requestData, DateFormat.MEDIUM, DateFormat.MEDIUM); if (retailerCustomerComment.getDateCreate() != null) { retailerCustomerCommentViewBean .setDateCreate(dateFormat.format(retailerCustomerComment.getDateCreate())); } else { retailerCustomerCommentViewBean.setDateCreate(Constants.NOT_AVAILABLE); } retailerCustomerCommentViewBean.setComment(retailerCustomerComment.getComment()); ReviewDataVocabularyPojo reviewDataVocabulary = new ReviewDataVocabularyPojo(); reviewDataVocabulary.setItemreviewed(retailer.getName()); reviewDataVocabulary.setReviewer(retailerCustomerComment.getCustomer().getScreenName()); DateFormat dateFormatDataVocabulary = requestUtil.getDataVocabularyFormatDate(requestData); reviewDataVocabulary.setDtreviewed(dateFormat.format(retailerCustomerComment.getDateCreate())); // reviewDataVocabulary.setSummary(summary); reviewDataVocabulary.setDescription(retailerCustomerComment.getComment()); // reviewDataVocabulary.setRating(rating); retailerCustomerCommentViewBean.setReviewDataVocabulary(reviewDataVocabulary); retailerViewBean.getComments().add(retailerCustomerCommentViewBean); } } Set<RetailerTag> tags = retailer.getRetailerTags(); if (tags != null) { for (Iterator<RetailerTag> iterator = tags.iterator(); iterator.hasNext();) { RetailerTag retailerTag = (RetailerTag) iterator.next(); RetailerTagViewBean retailerTagViewBean = new RetailerTagViewBean(); retailerTagViewBean.setCode(retailerTag.getCode()); retailerTagViewBean.setName(retailerTag.getName()); retailerTagViewBean.setDescription(retailerTag.getDescription()); retailerViewBean.getTags().add(retailerTagViewBean); } } Set<Store> stores = retailer.getStores(); if (stores != null) { for (Iterator<Store> iterator = stores.iterator(); iterator.hasNext();) { Store store = (Store) iterator.next(); StoreViewBean storeViewBean = buildStoreViewBean(requestData, store); retailerViewBean.getStores().add(storeViewBean); } } final String contextNameValue = requestUtil.getCurrentContextNameValue(request); List<String> shareOptions = marketArea.getShareOptions(contextNameValue); if (shareOptions != null) { for (Iterator<String> iterator = shareOptions.iterator(); iterator.hasNext();) { String shareOption = (String) iterator.next(); String relativeUrl = urlService.generateUrl(FoUrls.RETAILER_DETAILS, requestData, retailer); ShareOptionViewBean shareOptionViewBean = buildShareOptionViewBean(requestData, shareOption, relativeUrl); retailerViewBean.getShareOptions().add(shareOptionViewBean); } } return retailerViewBean; }
From source file:com.intuit.tank.harness.APITestHarness.java
/** * Run concurrent test plans at the same time * /*from w w w. j ava 2 s. com*/ * @param parser */ public void runConcurrentTestPlans() { if (started) { LOG.warn("Agent already started. Ignoring start command"); return; } tpsMonitor = new TPSMonitor(tankConfig.getAgentConfig().getTPSPeriod()); StringBuilder info = new StringBuilder().append(" RAMP_TIME=").append(agentRunData.getRampTime()) .append("; agentRunData.getNumUsers()=").append(agentRunData.getNumUsers()) .append("; NUM_START_THREADS=").append(agentRunData.getNumStartUsers()).append("; simulationTime=") .append(agentRunData.getSimulationTime()); LOG.info(LogUtil.getLogMessage("starting test with " + info.toString())); started = true; if (agentRunData.getJobId() == null) { String jobId = AmazonUtil.getJobId(); agentRunData.setJobId(jobId); } TestPlanRunner[] sessions = new TestPlanRunner[agentRunData.getNumUsers()]; sessionThreads = new Thread[agentRunData.getNumUsers()]; Thread monitorThread = null; doneSignal = new CountDownLatch(agentRunData.getNumUsers()); try { HDWorkload hdWorkload = TestPlanSingleton.getInstance().getTestPlans().get(0); if (StringUtils.isBlank(tankHttpClientClass)) { tankHttpClientClass = hdWorkload.getTankHttpClientClass(); } agentRunData.setProjectName(hdWorkload.getName()); agentRunData.setTankhttpClientClass(tankHttpClientClass); List<TestPlanStarter> testPlans = new ArrayList<TestPlanStarter>(); int total = 0; for (HDTestPlan plan : hdWorkload.getPlans()) { if (plan.getUserPercentage() > 0) { plan.setVariables(hdWorkload.getVariables()); TestPlanStarter starter = new TestPlanStarter(plan, agentRunData.getNumUsers()); total += starter.getNumThreads(); testPlans.add(starter); LOG.info(LogUtil.getLogMessage("Users for Test Plan " + plan.getTestPlanName() + " at " + plan.getUserPercentage() + "% = " + starter.getNumThreads())); } } LOG.info(LogUtil.getLogMessage("Total Users calculated for all test Plans = " + total)); if (total != agentRunData.getNumUsers()) { int numToAdd = agentRunData.getNumUsers() - total; TestPlanStarter starter = testPlans.get(testPlans.size() - 1); LOG.info(LogUtil.getLogMessage( "adding " + numToAdd + " threads to testPlan " + starter.getPlan().getTestPlanName())); starter.setNumThreads(starter.getNumThreads() + numToAdd); } // create threads int tp = 0; for (TestPlanStarter starter : testPlans) { for (int i = 0; i < starter.getNumThreads(); i++) { sessions[tp] = new TestPlanRunner(starter.getPlan(), tp); sessionThreads[tp] = new Thread(threadGroup, sessions[tp], "AGENT"); sessionThreads[tp].setDaemon(true);// system won't shut down normally until all user threads stop starter.addThread(sessionThreads[tp]); sessions[tp].setUniqueName( sessionThreads[tp].getThreadGroup().getName() + "-" + sessionThreads[tp].getId()); tp++; } } LOG.info(LogUtil.getLogMessage("Have all testPlan runners configured")); // start status thread first only if (!isLocal && !isDebug() && NumberUtils.isDigits(agentRunData.getJobId())) { LOG.info(LogUtil.getLogMessage("Starting monitor thread...")); CloudVmStatus status = getInitialStatus(); monitorThread = new Thread(new APIMonitor(status)); monitorThread.setDaemon(true); monitorThread.setPriority(Thread.NORM_PRIORITY - 2); monitorThread.start(); } LOG.info(LogUtil.getLogMessage("Starting threads...")); // start initial users startTime = System.currentTimeMillis(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); LOG.info(LogUtil.getLogMessage("Simulation start: " + df.format(new Date(getStartTime())))); if (agentRunData.getSimulationTime() != 0) { LOG.info(LogUtil.getLogMessage( "Scheduled Simulation End : " + df.format(new Date(getSimulationEndTimeMillis())))); LOG.info(LogUtil.getLogMessage( "Max Simulation End : " + df.format(new Date(getMaxSimulationEndTimeMillis())))); } else { LOG.info(LogUtil.getLogMessage("Ends at script loops completed with no Max Simulation Time.")); } currentNumThreads = 0; if (agentRunData.getNumUsers() > 0) { for (TestPlanStarter starter : testPlans) { if (isDebug()) { starter.run(); } else { Thread t = new Thread(starter); t.setDaemon(true); t.start(); } } boolean ramping = true; while (ramping) { boolean done = true; for (TestPlanStarter starter : testPlans) { done = done && starter.isDone(); } ramping = !done; if (ramping) { Thread.sleep(5000); } } // if we broke early, fix our countdown latch int numToCount = 0; for (TestPlanStarter starter : testPlans) { numToCount += starter.getThreadsStarted(); } while (numToCount < agentRunData.getNumUsers()) { doneSignal.countDown(); numToCount++; } // wait for them to finish LOG.info(LogUtil.getLogMessage("Ramp Complete...")); doneSignal.await(); } } catch (Throwable t) { LOG.error("error executing..." + t, t); } finally { LOG.info(LogUtil.getLogMessage("Test Complete...")); if (!isDebug() && NumberUtils.isDigits(agentRunData.getJobId())) { if (null != monitorThread) { APIMonitor.setJobStatus(JobStatus.Completed); APIMonitor.setDoMonitor(false); } sendBatchToDB(false); // sleep for 60 seconds to let wily agent clear any data try { Thread.sleep(60000); } catch (InterruptedException e) { // nothing to do } } } flowControllerTemplate.endTest(); // System.exit(0); }
From source file:org.madsonic.ajax.PlayQueueService.java
public String savePlaylist() { HttpServletRequest request = WebContextFactory.get().getHttpServletRequest(); HttpServletResponse response = WebContextFactory.get().getHttpServletResponse(); Player player = getCurrentPlayer(request, response); Locale locale = settingsService.getLocale(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, locale); Date now = new Date(); Playlist playlist = new Playlist(); playlist.setUsername(securityService.getCurrentUsername(request)); playlist.setCreated(now);//from ww w . j av a 2 s .c om playlist.setChanged(now); playlist.setPublic(false); playlist.setName(dateFormat.format(now)); playlistService.createPlaylist(playlist); playlistService.setFilesInPlaylist(playlist.getId(), player.getPlayQueue().getFiles()); return playlist.getName(); }
From source file:org.opencms.ade.galleries.CmsGalleryService.java
/** * @see org.opencms.ade.galleries.shared.rpc.I_CmsGalleryService#getInfoForResource(java.lang.String, java.lang.String) *///from ww w . ja va 2 s . c o m public CmsResultItemBean getInfoForResource(String linkPath, String locale) throws CmsRpcException { CmsResultItemBean result = null; CmsObject cms = getCmsObject(); CmsMessages messageBundle = Messages.get().getBundle(getWorkplaceLocale()); try { if (new CmsUriSplitter(linkPath).getProtocol() != null) { result = new CmsResultItemBean(); result.setTitle(messageBundle.key(Messages.GUI_EXTERNAL_LINK_0)); result.setSubTitle(""); result.setType(CmsResourceTypePointer.getStaticTypeName()); } else if (CmsStaticResourceHandler.isStaticResourceUri(linkPath)) { result = new CmsResultItemBean(); result.setTitle(messageBundle.key(Messages.GUI_STATIC_RESOURCE_0)); result.setSubTitle(CmsStaticResourceHandler.removeStaticResourcePrefix(linkPath)); result.setType(CmsResourceTypeBinary.getStaticTypeName()); } else { boolean notFound = false; String path = linkPath; String siteRoot = OpenCms.getSiteManager().getSiteRoot(linkPath); String oldSite = cms.getRequestContext().getSiteRoot(); try { if (siteRoot != null) { // only switch the site if needed cms.getRequestContext().setSiteRoot(siteRoot); // remove the site root, because the link manager call will append it anyway path = cms.getRequestContext().removeSiteRoot(linkPath); } // remove parameters, if not the link manager call might fail int pos = path.indexOf(CmsRequestUtil.URL_DELIMITER); int anchorPos = path.indexOf('#'); if ((pos == -1) || ((anchorPos > -1) && (pos > anchorPos))) { pos = anchorPos; } if (pos > -1) { path = path.substring(0, pos); } // get the root path path = OpenCms.getLinkManager().getRootPath(cms, path); } catch (Exception e) { notFound = true; } finally { if (siteRoot != null) { cms.getRequestContext().setSiteRoot(oldSite); } } notFound = notFound || (path == null); boolean isInTimeRange = true; if (!notFound) { CmsObject rootCms = OpenCms.initCmsObject(cms); rootCms.getRequestContext().setSiteRoot(""); try { CmsResource selectedResource = rootCms.readResource(path, CmsResourceFilter.IGNORE_EXPIRATION); long currentTime = System.currentTimeMillis(); isInTimeRange = selectedResource.isReleasedAndNotExpired(currentTime); if (selectedResource.isFolder()) { result = new CmsResultItemBean(); CmsJspNavElement folderNav = new CmsJspNavBuilder(rootCms).getNavigationForResource( selectedResource.getRootPath(), CmsResourceFilter.IGNORE_EXPIRATION); CmsResource defaultFileResource = null; if (folderNav.isInNavigation() && !folderNav.isNavigationLevel()) { try { defaultFileResource = rootCms.readDefaultFile(selectedResource, CmsResourceFilter.ONLY_VISIBLE); } catch (Exception e) { log(e.getMessage(), e); } } CmsResource resourceForType = defaultFileResource != null ? defaultFileResource : selectedResource; result.setType( OpenCms.getResourceManager().getResourceType(resourceForType).getTypeName()); String title = folderNav.getProperty(CmsPropertyDefinition.PROPERTY_NAVTEXT); if (CmsStringUtil.isEmptyOrWhitespaceOnly(title)) { title = folderNav.getTitle(); } else if (CmsStringUtil.isEmptyOrWhitespaceOnly(title)) { title = CmsResource.getName(path); if (title.contains("/")) { title = title.substring(0, title.indexOf("/")); } } result.setTitle(title); try { String userName = cms.readUser(selectedResource.getUserLastModified()) .getFullName(); result.setUserLastModified(userName); } catch (CmsException e) { log(e.getMessage(), e); } Date date = new Date(selectedResource.getDateLastModified()); String formattedDate = CmsDateUtil.getDateTime(date, DateFormat.MEDIUM, getWorkplaceLocale()); result.setDateLastModified(formattedDate); } else { CmsGallerySearchResult resultItem = null; try { resultItem = CmsGallerySearch.searchByPath(cms, path, CmsLocaleManager.getLocale(locale)); } catch (CmsVfsResourceNotFoundException ex) { // ignore } notFound = resultItem == null; if (!notFound) { result = buildSingleSearchResultItem(getCmsObject(), resultItem, null); } } } catch (CmsException ex) { notFound = true; } } if (notFound) { result = new CmsResultItemBean(); result.setTitle(messageBundle.key(Messages.GUI_RESOURCE_NOT_FOUND_0)); result.setSubTitle(""); result.setType(CmsIconUtil.TYPE_RESOURCE_NOT_FOUND); } else if (!isInTimeRange && (result != null)) { result.setType(CmsIconUtil.TYPE_RESOURCE_NOT_FOUND); result.setTitle( messageBundle.key(Messages.GUI_RESOURCE_OUT_OF_TIME_RANGE_1, result.getTitle())); } } } catch (Throwable t) { error(t); } return result; }
From source file:mitm.common.security.certificate.GenerateTestCertificates.java
private void generateCertificateKeyUsageOnlyNonRepudiation() throws Exception { X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder(); String encodedPrivateKey = "30820277020100300d06092a864886f70d0101010500048202613082025d" + "02010002818100b342cf47e9e631e987a91cd281303c79be1ee94355e439" + "4a11606b740e30752eedd3a4d4c476963be7a329d7c92ed1f818f862389b" + "2c6bbec1b3f37e83a19aa05444d89c0d3bf7e567368320d1c1f4f1ef53c0" + "cb939f1c5cd01d4a8f4f637f0c4b16ff8e6ee4ba3beb4beddfc588ae1490" + "414dcaf1277f9c3287c9ea77897219020301000102818059a6a813c71ea1" + "07b21919990d931a2ba8b1bce7382593a13f5f815de15acac055a0eb669d" + "7ad157d458fdac35a97cc91f73d96b85ef8953357cd1e20be2de79470d67" + "841c79736d3938cf751816e214c176932d1ba26158d80da6f3f5ba61ac54" + "c1c9446435b2a0ef12b5cf25a03eabd931995175d40fe6aaef17b7b46bb8" + "01024100ff909d5f9ae1d2d3317137c9a9d775c0bdbf66b88b4a5d4893a4" + "ad9c7be321b78f00e76525e4269f0c1529750e87a4d4d6e5ac20e86a7095" + "c3441663ccb5f5f9024100b390f04e1944969dc3c05a4a699e6f9ae3e28b" + "e88d5d749271c849f4ca044648bff99de49257d07bcde0900a46294e233b" + "689bd447ce1280c1f3034416b5e521024100acb70c54677504a92c39eacd" + "045693c30db983ef665b7c8da7125d2e6b5f8612eab75eaab21feda60161" + "6fe2274eaeac150ba4f79c7b0ad97bdcd110e37179e9024100a17326ed41" + "80cedf68bad133e8c50059c69dd1e7b4fb1b2df4c9fddcefaa6a3b4d08b5" + "b366f537c9a8f148f143e62d9036013762e570de68107a5c2c633306a102" + "400cb68f16900107b2d2db6175807a05261caa05cf5bb14bcbafd9202cc4" + "5f75922185187c30f95d4ce5f44481d59174548e5bddd7bfe2896e6401a8" + "ed79797fed"; String encodedPublicKey = "30819f300d06092a864886f70d010101050003818d0030818902818100b3" + "42cf47e9e631e987a91cd281303c79be1ee94355e4394a11606b740e3075" + "2eedd3a4d4c476963be7a329d7c92ed1f818f862389b2c6bbec1b3f37e83" + "a19aa05444d89c0d3bf7e567368320d1c1f4f1ef53c0cb939f1c5cd01d4a" + "8f4f637f0c4b16ff8e6ee4ba3beb4beddfc588ae1490414dcaf1277f9c32" + "87c9ea778972190203010001"; PrivateKey privateKey = decodePrivateKey(encodedPrivateKey); PublicKey publicKey = decodePublicKey(encodedPublicKey); X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder(); String email = "test@example.com"; subjectBuilder.setCommonName("Valid certificate"); subjectBuilder.setEmail(email);// ww w .j av a2 s .c o m subjectBuilder.setCountryCode("NL"); subjectBuilder.setLocality("Amsterdam"); subjectBuilder.setState("NH"); AltNamesBuilder altNamesBuider = new AltNamesBuilder(); altNamesBuider.setRFC822Names(email); X500Principal subject = subjectBuilder.buildPrincipal(); GeneralNames altNames = altNamesBuider.buildAltNames(); // use TreeSet because we want a deterministic certificate (ie. hash should not change) Set<KeyUsageType> keyUsage = new TreeSet<KeyUsageType>(); keyUsage.add(KeyUsageType.NONREPUDIATION); Set<ExtendedKeyUsageType> extendedKeyUsage = new TreeSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); BigInteger serialNumber = new BigInteger("1178c3b653829e895acb7100eb1f627", 16); Date now = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.UK) .parse("21-Nov-2007 10:38:35"); certificateBuilder.setSubject(subject); certificateBuilder.setAltNames(altNames, true); certificateBuilder.setKeyUsage(keyUsage, true); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true /* critical */); certificateBuilder.setNotBefore(DateUtils.addDays(now, -20)); certificateBuilder.setNotAfter(DateUtils.addYears(now, 20)); certificateBuilder.setPublicKey(publicKey); certificateBuilder.setSerialNumber(serialNumber); certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption"); certificateBuilder.addSubjectKeyIdentifier(true); X509Certificate certificate = certificateBuilder.generateCertificate(caPrivateKey, caCertificate); assertNotNull(certificate); certificates.add(certificate); Certificate[] chain = new Certificate[] { certificate, caCertificate, rootCertificate }; keyStore.setKeyEntry("KeyUsageOnlyNonRepudiation", privateKey, null, chain); }