List of usage examples for java.text DateFormat getInstance
public static final DateFormat getInstance()
From source file:org.craftercms.social.util.support.security.CrafterProfileFilter.java
/** * Generate an encrypted token from the user profile details. * * @param cipher//from w w w . jav a2 s . c om * @param profileToken * @param userProfile * @return */ private String generateEncryptedToken(SimpleDesCipher cipher, String profileToken, Profile userProfile) throws org.craftercms.social.exceptions.AuthenticationException { // create new cookie byte[] encrypted = null; try { // increment the expires time Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.SECOND, cipherTokenExpires); encrypted = cipher .encrypt(new StringBuilder(profileToken).append(TOKEN_SEPARATOR).append(userProfile.getId()) .append(TOKEN_SEPARATOR).append(DateFormat.getInstance().format(cal.getTime())) .append(TOKEN_SEPARATOR).append(StringUtils.join(userProfile.getRoles().toArray(), ',')) .append(TOKEN_SEPARATOR).append(userProfile.getTenantName()).append(TOKEN_SEPARATOR) .append(UUID.randomUUID().toString()).toString().getBytes()); } catch (InvalidKeyException e) { log.error(ERROR_ENCRYPTED_TOKEN, e); throw new org.craftercms.social.exceptions.AuthenticationException(ERROR_ENCRYPTED_TOKEN, e); } catch (IllegalBlockSizeException e) { log.error(ERROR_ENCRYPTED_TOKEN, e); throw new org.craftercms.social.exceptions.AuthenticationException(ERROR_ENCRYPTED_TOKEN, e); } catch (BadPaddingException e) { log.error(ERROR_ENCRYPTED_TOKEN, e); throw new org.craftercms.social.exceptions.AuthenticationException(ERROR_ENCRYPTED_TOKEN, e); } return new String(Base64.encodeBase64(encrypted)); }
From source file:org.apache.flex.swf.io.SWFDump.java
public void dumpProductInfo(ProductInfoTag productInfo) { open(productInfo);/* w ww .j a v a2 s.c om*/ out.print(" product=\"" + productInfo.getProduct() + "\""); out.print(" edition=\"" + productInfo.getEdition() + "\""); out.print(" version=\"" + productInfo.getMajorVersion() + "." + productInfo.getMinorVersion() + "\""); out.print(" build=\"" + productInfo.getBuild() + "\""); out.print( " compileDate=\"" + DateFormat.getInstance().format(new Date(productInfo.getCompileDate())) + "\""); close(); }
From source file:org.nuxeo.ecm.csv.CSVImporterWork.java
protected void sendMail() throws Exception { UserManager userManager = Framework.getLocalService(UserManager.class); NuxeoPrincipal principal = userManager.getPrincipal(username); String email = principal.getEmail(); if (email == null) { log.info(String.format("Not sending import result email to '%s', no email configured", username)); return;// w ww .j ava 2 s . co m } OperationContext ctx = new OperationContext(session); ctx.setInput(session.getRootDocument()); CSVImporter csvImporter = Framework.getLocalService(CSVImporter.class); List<CSVImportLog> importLogs = csvImporter.getImportLogs(getId()); CSVImportResult importResult = CSVImportResult.fromImportLogs(importLogs); List<CSVImportLog> skippedAndErrorImportLogs = csvImporter.getImportLogs(getId(), Status.SKIPPED, Status.ERROR); ctx.put("importResult", importResult); ctx.put("skippedAndErrorImportLogs", skippedAndErrorImportLogs); ctx.put("csvFilename", csvFileName); ctx.put("startDate", DateFormat.getInstance().format(startDate)); ctx.put("username", username); DocumentModel importFolder = session.getDocument(new PathRef(parentPath)); String importFolderUrl = getDocumentUrl(importFolder); ctx.put("importFolderTitle", importFolder.getTitle()); ctx.put("importFolderUrl", importFolderUrl); ctx.put("userUrl", getUserUrl(principal.getName())); StringList to = buildRecipientsList(email); Expression from = Scripting.newExpression("Env[\"mail.from\"]"); String subject = "CSV Import result of " + csvFileName; String message = loadTemplate(TEMPLATE_IMPORT_RESULT); try { OperationChain chain = new OperationChain("SendMail"); chain.add(SendMail.ID).set("from", from).set("to", to).set("HTML", true).set("subject", subject) .set("message", message); Framework.getLocalService(AutomationService.class).run(ctx, chain); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", e); } catch (Exception e) { log.error(String.format("Unable to notify user '%s' for import result of '%s': %s", username, csvFileName, e.getMessage())); log.debug(e, e); throw e; } }
From source file:edu.ku.brc.specify.config.init.DataBuilder.java
public static CollectionObject createCollectionObject(final String catalogNumber, final String fieldNumber, final Agent cataloger, final Collection collection, final int count, final CollectingEvent collectingEvent, final Calendar catalogedDate, final UIFieldFormatterIFace.PartialDateEnum dateType, @SuppressWarnings("unused") final String lastEditedBy) { // Create Collection Object CollectionObject colObj = new CollectionObject(); colObj.initialize();/*from ww w . j a v a 2s .c o m*/ colObj.setCataloger(cataloger); colObj.setCatalogedDate(catalogedDate); colObj.setCatalogedDateVerbatim(DateFormat.getInstance().format(catalogedDate.getTime())); colObj.setCatalogNumber(catalogNumber); colObj.setCatalogedDatePrecision((byte) dateType.ordinal()); colObj.setCollection(collection); colObj.setCollectingEvent(collectingEvent); colObj.setCountAmt(count); colObj.setFieldNumber(fieldNumber); colObj.setModifiedByAgent(cataloger); Timestamp now = new Timestamp(System.currentTimeMillis()); colObj.setTimestampCreated(now); if (collectingEvent != null) { collectingEvent.getCollectionObjects().add(colObj); } persist(colObj); if (collectingEvent != null) { persist(collectingEvent); } return colObj; }
From source file:com.atlassian.jira.startup.JiraSystemInfo.java
private void printServiceInfo(JiraServiceContainer service) { logMsg.outputProperty(service.getName(), service.getServiceClass()); logMsg.outputProperty("Service Delay", String.valueOf(service.getDelay()) + "ms", 2); try {/* w w w . j av a 2 s. co m*/ final long lastRun = service.getLastRun(); if (lastRun > 0) { final DateFormat df = DateFormat.getInstance(); final Date dt = new Date(lastRun); logMsg.outputProperty("Last Run", df.format(dt)); } final Map<String, String> properties = ConfigurableObjectUtil.getPropertyMap(service); for (final Map.Entry<String, String> entry : properties.entrySet()) { logMsg.outputProperty(entry.getKey(), entry.getValue(), 2); } } catch (final Exception e) { logMsg.outputProperty("Exception getting Service information", e.toString()); } }
From source file:org.cimmyt.dnast.service.imp.FileRepositoryServiceClientImp.java
/** * Adds information to an item about a shipment. * <br/>//www .j a va2s.com * @param item The item to be sent to the Knowledge base * @param study The study from which the information is taken; * @param samples List of samples contained in the shipment to register */ private void addMetadata(DsItem item, LabStudy study, Shipment shipment, List<SampleDetail> samples) { List<DsSchema> schemas = this.getSchemaList(); DsSchema schema = null; DsSchema schemaDC = null; for (DsSchema s : schemas) { if (s.getShortName().equals(SIU_SCHEMA)) {//schema cimmyt schema = s; } else if (s.getShortName().equals(DUBLIN_CORE_SCHEMA)) { schemaDC = s; } } schema.setMetadatas(this.getMetadataListBySchema(schema.getId())); schemaDC.setMetadatas(this.getMetadataListBySchema(schemaDC.getId())); StringBuilder gids = new StringBuilder(); StringBuilder species = new StringBuilder(); StringBuilder sampleIds = new StringBuilder(); for (int i = 0; i < samples.size(); i++) { sampleIds.append(samples.get(i).getLabstudyid().getPrefix() + samples.get(i).getStudysampleid()); if (i + 1 < samples.size()) { sampleIds.append(","); } if (samples.get(i).getBreedergid() != null) { gids.append(samples.get(i).getBreedergid().toString()); if (i + 1 < samples.size()) { gids.append(","); } } if (samples.get(i).getSpecie() != null) { species.append(samples.get(i).getSpecie().toString()); if (i + 1 < samples.size()) { species.append(","); } } } for (DsMetadataElement metadata : schema.getMetadatas()) { if (metadata.getElement().equals(META.PROJ_NAME.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.PROJ_NAME.qualif)) { metadata.setValue(study.getProject().getProjectname()); } else if (metadata.getElement().equals(META.PROJ_SRC.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.PROJ_SRC.qualif)) { metadata.setValue(study.getProject().getPurposename()); } else if (metadata.getElement().equals(META.AUTH_PRINC.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.AUTH_PRINC.qualif)) { metadata.setValue(study.getInvestigatorid().getInvest_name()); } else if (metadata.getElement().equals(META.AUTH_INTERN.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.AUTH_INTERN.qualif)) { metadata.setValue("Not Available"); } else if (metadata.getElement().equals(META.INV_GID.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.INV_GID.qualif)) { metadata.setValue(gids.toString()); } else if (metadata.getElement().equals(META.STDY_DESC.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDY_DESC.qualif)) { metadata.setValue(study.getObjective()); } else if (metadata.getElement().equals(META.STDY_OBJ.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDY_OBJ.qualif)) { metadata.setValue(study.getObjective()); } else if (metadata.getElement().equals(META.STDY_LOCA.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDY_LOCA.qualif)) { metadata.setValue(study.getLocation().toString()); } else if (metadata.getElement().equals(META.STDY_SESN.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDY_SESN.qualif)) { metadata.setValue(study.getSeason().toString()); } else if (metadata.getElement().equals(META.STDY_NAME.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDY_NAME.qualif)) { metadata.setValue(study.getTitle()); } else if (metadata.getElement().equals(META.INV_POPNAME.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.INV_POPNAME.qualif)) { metadata.setValue("NA"); } else if (metadata.getElement().equals(META.INV_SAMPID.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.INV_SAMPID.qualif)) { metadata.setValue(sampleIds.toString()); } else if (metadata.getElement().equals(META.INV_PEDIGREE.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.INV_PEDIGREE.qualif)) { metadata.setValue("NA"); } else if (metadata.getElement().equals(META.IP_DTUSES.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.IP_DTUSES.qualif)) { metadata.setValue("NA"); } else if (metadata.getElement().equals(META.STDYDOC_LANG.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDYDOC_LANG.qualif)) { metadata.setValue("english");//take from session?? } else if (metadata.getElement().equals(META.METHD_OTHR.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.METHD_OTHR.qualif)) { metadata.setValue(shipment.getStCompany().getName()); } else if (metadata.getElement().equals(META.STDY_RESAR.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDY_RESAR.qualif)) { metadata.setValue("NA"); } else if (metadata.getElement().equals(META.STDY_GERM.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDY_GERM.qualif)) { metadata.setValue("NA"); } else if (metadata.getElement().equals(META.STDY_CROP.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDY_CROP.qualif)) { metadata.setValue("maize");//make dynamic } else if (metadata.getElement().equals(META.STDY_CTRY.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDY_CTRY.qualif)) { metadata.setValue("Mexico");//make dynamic } else if (metadata.getElement().equals(META.STDY_YEAR.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.STDY_YEAR.qualif)) { metadata.setValue(String.valueOf(Calendar.getInstance().get(Calendar.YEAR))); Calendar myCal = Calendar.getInstance(); myCal.setTime(study.getStartdate()); metadata.setValue(String.valueOf(myCal.get(Calendar.YEAR))); } else if (metadata.getElement().equals(META.AUTH_EXTERN.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.AUTH_EXTERN.qualif)) { metadata.setValue("Not Available"); } else if (metadata.getElement().equals(META.AUTH_PROGM.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.AUTH_PROGM.qualif)) { metadata.setValue("Not Available"); } else if (metadata.getElement().equals(META.AUTH_SUBPROG.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.AUTH_SUBPROG.qualif)) { metadata.setValue("Not Available"); } else if (metadata.getElement().equals(META.DATA_SETNAME.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.DATA_SETNAME.qualif)) { metadata.setValue(shipment.getComment()); } else if (metadata.getElement().equals(META.DATA_SETUPL.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.DATA_SETUPL.qualif)) { metadata.setValue("true"); } else if (metadata.getElement().equals(META.DATA_TYP.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.DATA_TYP.qualif)) { metadata.setValue("Genotypic data"); } } for (DsMetadataElement metadata : schemaDC.getMetadatas()) { if (metadata.getElement().equals(META.DC_DAT_ACCCNED.key) && metadata.getQualifier() != null && metadata.getQualifier().equals(META.DC_DAT_ACCCNED.qualif)) { metadata.setValue(DateFormat.getInstance().format(GregorianCalendar.getInstance().getTime())); } } List<DsMetadataElement> tmpMedatada = new ArrayList<DsMetadataElement>(); for (DsMetadataElement metadata : schema.getMetadatas()) { if (metadata.getValue() != null && !metadata.getValue().isEmpty()) { tmpMedatada.add(metadata); } } schema.setMetadatas(tmpMedatada); schema.setName(schema.getShortName()); schema.setShortName(null); schema.setId(null); schema.setNameSpace(null); tmpMedatada = new ArrayList<DsMetadataElement>(); for (DsMetadataElement metadata : schemaDC.getMetadatas()) { if (metadata.getValue() != null && !metadata.getValue().isEmpty()) { tmpMedatada.add(metadata); } } schemaDC.setMetadatas(tmpMedatada); schemaDC.setName(schemaDC.getShortName()); schemaDC.setShortName(null); schemaDC.setId(null); schemaDC.setNameSpace(null); schemas.clear(); schemas.add(schema); schemas.add(schemaDC); item.setSchemas(schemas); }
From source file:org.nebulaframework.ui.swing.cluster.ClusterMainUI.java
/** * Creates a tab pane for the given GridJob. * /*from w w w. java2s . c o m*/ * @param jobId JobId */ protected void createJobTab(final String jobId) { // Request Job Profile final InternalClusterJobService jobService = ClusterManager.getInstance().getJobService(); final GridJobProfile profile = jobService.getProfile(jobId); // Job Start Time final long startTime = System.currentTimeMillis(); final JPanel jobPanel = new JPanel(); jobPanel.setLayout(new BorderLayout(10, 10)); // Progess Panel JPanel progressPanel = new JPanel(); progressPanel.setLayout(new BorderLayout(10, 10)); progressPanel.setBorder(BorderFactory.createTitledBorder("Progress")); jobPanel.add(progressPanel, BorderLayout.NORTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setStringPainted(true); progressPanel.add(progressBar, BorderLayout.CENTER); addUIElement("jobs." + jobId + ".progress", progressBar); // Add to components map // Buttons Panel JPanel buttonsPanel = new JPanel(); jobPanel.add(buttonsPanel, BorderLayout.SOUTH); buttonsPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); // Terminate Button JButton terminateButton = new JButton("Terminate"); terminateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Thread(new Runnable() { public void run() { // Job Name = Class Name String name = profile.getJob().getClass().getSimpleName(); // Request user confirmation int option = JOptionPane.showConfirmDialog(ClusterMainUI.this, "Are you sure to terminate GridJob " + name + "?", "Nebula - Terminate GridJob", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.NO_OPTION) return; // Attempt Cancel boolean result = profile.getFuture().cancel(); // Notify results if (result) { JOptionPane.showMessageDialog(ClusterMainUI.this, "Grid Job '" + name + "terminated successfully.", "Nebula - Job Terminated", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(ClusterMainUI.this, "Failed to terminate Grid Job '" + name, "Nebula - Job Termination Failed", JOptionPane.WARNING_MESSAGE); } } }).start(); } }); buttonsPanel.add(terminateButton); addUIElement("jobs." + jobId + ".terminate", terminateButton); // Add to components map // Close Tab Button JButton closeButton = new JButton("Close Tab"); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { removeJobTab(jobId); } }); } }); closeButton.setEnabled(false); buttonsPanel.add(closeButton); addUIElement("jobs." + jobId + ".closetab", closeButton); // Add to components map JPanel centerPanel = new JPanel(); centerPanel.setLayout(new GridBagLayout()); jobPanel.add(centerPanel, BorderLayout.CENTER); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weightx = 1.0; /* -- Job Information -- */ JPanel jobInfoPanel = new JPanel(); jobInfoPanel.setBorder(BorderFactory.createTitledBorder("Job Information")); jobInfoPanel.setLayout(new GridBagLayout()); c.gridy = 0; c.ipady = 30; centerPanel.add(jobInfoPanel, c); GridBagConstraints c1 = new GridBagConstraints(); c1.fill = GridBagConstraints.BOTH; c1.weightx = 1; c1.weighty = 1; // Name jobInfoPanel.add(new JLabel("Name :"), c1); JLabel jobNameLabel = new JLabel(); jobInfoPanel.add(jobNameLabel, c1); jobNameLabel.setText(profile.getJob().getClass().getSimpleName()); addUIElement("jobs." + jobId + ".job.name", jobNameLabel); // Add to components map // Gap jobInfoPanel.add(new JLabel(), c1); // Type jobInfoPanel.add(new JLabel("Type :"), c1); JLabel jobType = new JLabel(); jobType.setText(getJobType(profile.getJob())); jobInfoPanel.add(jobType, c1); addUIElement("jobs." + jobId + ".job.type", jobType); // Add to components map // Job Class Name c1.gridy = 1; c1.gridwidth = 1; jobInfoPanel.add(new JLabel("GridJob Class :"), c1); c1.gridwidth = GridBagConstraints.REMAINDER; JLabel jobClassLabel = new JLabel(); jobClassLabel.setText(profile.getJob().getClass().getName()); jobInfoPanel.add(jobClassLabel, c1); addUIElement("jobs." + jobId + ".job.class", jobClassLabel); // Add to components map /* -- Execution Information -- */ JPanel executionInfoPanel = new JPanel(); executionInfoPanel.setBorder(BorderFactory.createTitledBorder("Execution Statistics")); executionInfoPanel.setLayout(new GridBagLayout()); c.gridy = 1; c.ipady = 30; centerPanel.add(executionInfoPanel, c); GridBagConstraints c3 = new GridBagConstraints(); c3.weightx = 1; c3.weighty = 1; c3.fill = GridBagConstraints.BOTH; // Start Time executionInfoPanel.add(new JLabel("Job Status :"), c3); final JLabel statusLabel = new JLabel("Initializing"); executionInfoPanel.add(statusLabel, c3); addUIElement("jobs." + jobId + ".execution.status", statusLabel); // Add to components map // Status Update Listener profile.getFuture().addGridJobStateListener(new GridJobStateListener() { public void stateChanged(final GridJobState newState) { SwingUtilities.invokeLater(new Runnable() { public void run() { statusLabel.setText(StringUtils.capitalize(newState.toString().toLowerCase())); } }); } }); executionInfoPanel.add(new JLabel(), c3); // Space Holder // Percent Complete executionInfoPanel.add(new JLabel("Completed % :"), c3); final JLabel percentLabel = new JLabel("-N/A-"); executionInfoPanel.add(percentLabel, c3); addUIElement("jobs." + jobId + ".execution.percentage", percentLabel); // Add to components map c3.gridy = 1; // Start Time executionInfoPanel.add(new JLabel("Start Time :"), c3); JLabel startTimeLabel = new JLabel(DateFormat.getInstance().format(new Date(startTime))); executionInfoPanel.add(startTimeLabel, c3); addUIElement("jobs." + jobId + ".execution.starttime", startTimeLabel); // Add to components map executionInfoPanel.add(new JLabel(), c3); // Space Holder // Elapsed Time executionInfoPanel.add(new JLabel("Elapsed Time :"), c3); JLabel elapsedTimeLabel = new JLabel("-N/A-"); executionInfoPanel.add(elapsedTimeLabel, c3); addUIElement("jobs." + jobId + ".execution.elapsedtime", elapsedTimeLabel); // Add to components map c3.gridy = 2; // Tasks Deployed (Count) executionInfoPanel.add(new JLabel("Tasks Deployed :"), c3); JLabel tasksDeployedLabel = new JLabel("-N/A-"); executionInfoPanel.add(tasksDeployedLabel, c3); addUIElement("jobs." + jobId + ".execution.tasks", tasksDeployedLabel); // Add to components map executionInfoPanel.add(new JLabel(), c3); // Space Holder // Results Collected (Count) executionInfoPanel.add(new JLabel("Results Collected :"), c3); JLabel resultsCollectedLabel = new JLabel("-N/A-"); executionInfoPanel.add(resultsCollectedLabel, c3); addUIElement("jobs." + jobId + ".execution.results", resultsCollectedLabel); // Add to components map c3.gridy = 3; // Remaining Tasks (Count) executionInfoPanel.add(new JLabel("Remaining Tasks :"), c3); JLabel remainingTasksLabel = new JLabel("-N/A-"); executionInfoPanel.add(remainingTasksLabel, c3); addUIElement("jobs." + jobId + ".execution.remaining", remainingTasksLabel); // Add to components map executionInfoPanel.add(new JLabel(), c3); // Space Holder // Failed Tasks (Count) executionInfoPanel.add(new JLabel("Failed Tasks :"), c3); JLabel failedTasksLabel = new JLabel("-N/A-"); executionInfoPanel.add(failedTasksLabel, c3); addUIElement("jobs." + jobId + ".execution.failed", failedTasksLabel); // Add to components map /* -- Submitter Information -- */ UUID ownerId = profile.getOwner(); GridNodeDelegate owner = ClusterManager.getInstance().getClusterRegistrationService() .getGridNodeDelegate(ownerId); JPanel ownerInfoPanel = new JPanel(); ownerInfoPanel.setBorder(BorderFactory.createTitledBorder("Owner Information")); ownerInfoPanel.setLayout(new GridBagLayout()); c.gridy = 2; c.ipady = 10; centerPanel.add(ownerInfoPanel, c); GridBagConstraints c2 = new GridBagConstraints(); c2.fill = GridBagConstraints.BOTH; c2.weightx = 1; c2.weighty = 1; // Host Name ownerInfoPanel.add(new JLabel("Host Name :"), c2); JLabel hostNameLabel = new JLabel(owner.getProfile().getName()); ownerInfoPanel.add(hostNameLabel, c2); addUIElement("jobs." + jobId + ".owner.hostname", hostNameLabel); // Add to components map // Gap ownerInfoPanel.add(new JLabel(), c2); // Host IP Address ownerInfoPanel.add(new JLabel("Host IP :"), c2); JLabel hostIPLabel = new JLabel(owner.getProfile().getIpAddress()); ownerInfoPanel.add(hostIPLabel, c2); addUIElement("jobs." + jobId + ".owner.hostip", hostIPLabel); // Add to components map // Owner UUID c2.gridy = 1; c2.gridx = 0; ownerInfoPanel.add(new JLabel("Owner ID :"), c2); JLabel ownerIdLabel = new JLabel(profile.getOwner().toString()); c2.gridx = 1; c2.gridwidth = 4; ownerInfoPanel.add(ownerIdLabel, c2); addUIElement("jobs." + jobId + ".owner.id", ownerIdLabel); // Add to components map SwingUtilities.invokeLater(new Runnable() { public void run() { // Create Tab addUIElement("jobs." + jobId, jobPanel); JTabbedPane tabs = getUIElement("tabs"); tabs.addTab(profile.getJob().getClass().getSimpleName(), jobPanel); tabs.revalidate(); } }); // Execution Information Updater Thread new Thread(new Runnable() { boolean initialized = false; boolean unbounded = false; public void run() { // Unbounded, No Progress Supported if ((!initialized) && profile.getJob() instanceof UnboundedGridJob<?>) { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setIndeterminate(true); progressBar.setStringPainted(false); // Infinity Symbol percentLabel.setText(String.valueOf('\u221e')); } }); initialized = true; unbounded = true; } // Update Job Info while (true) { try { // 500ms Interval Thread.sleep(500); } catch (InterruptedException e) { log.warn("Interrupted Progress Updater Thread", e); } final int totalCount = profile.getTotalTasks(); final int tasksRem = profile.getTaskCount(); final int resCount = profile.getResultCount(); final int failCount = profile.getFailedCount(); showBusyIcon(); // Task Information JLabel totalTaskLabel = getUIElement("jobs." + jobId + ".execution.tasks"); totalTaskLabel.setText(String.valueOf(totalCount)); // Result Count JLabel resCountLabel = getUIElement("jobs." + jobId + ".execution.results"); resCountLabel.setText(String.valueOf(resCount)); // Remaining Task Count JLabel remLabel = getUIElement("jobs." + jobId + ".execution.remaining"); remLabel.setText(String.valueOf(tasksRem)); // Failed Task Count JLabel failedLabel = getUIElement("jobs." + jobId + ".execution.failed"); failedLabel.setText(String.valueOf(failCount)); // Elapsed Time JLabel elapsedLabel = getUIElement("jobs." + jobId + ".execution.elapsedtime"); elapsedLabel.setText(TimeUtils.timeDifference(startTime)); // Job State final JLabel statusLabel = getUIElement("jobs." + jobId + ".execution.status"); // If not in Executing Mode if ((!profile.getFuture().isJobFinished()) && profile.getFuture().getState() != GridJobState.EXECUTING) { SwingUtilities.invokeLater(new Runnable() { public void run() { // Progress Bar progressBar.setIndeterminate(true); progressBar.setStringPainted(false); // Status Text String state = profile.getFuture().getState().toString(); statusLabel.setText(StringUtils.capitalize(state.toLowerCase())); // Percentage Label percentLabel.setText(String.valueOf('\u221e')); } }); } else { // Executing Mode : Progress Information // Job Finished, Stop if (profile.getFuture().isJobFinished()) { showIdleIcon(); return; } // Double check for status label if (!statusLabel.getText().equalsIgnoreCase("executing")) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String newstate = profile.getFuture().getState().toString(); statusLabel.setText(StringUtils.capitalize(newstate.toLowerCase())); } }); } if (!unbounded) { final int percentage = (int) (profile.percentage() * 100); //final int failCount = profile.get SwingUtilities.invokeLater(new Runnable() { public void run() { // If finished at this point, do not update if (progressBar.getValue() == 100) { return; } // If ProgressBar is in indeterminate if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); progressBar.setStringPainted(true); } // Update Progress Bar / Percent Label progressBar.setValue(percentage); percentLabel.setText(percentage + " %"); } }); } } } } }).start(); // Job End Hook to Execute Job End Actions ServiceEventsSupport.addServiceHook(new ServiceHookCallback() { public void onServiceEvent(final ServiceMessage event) { SwingUtilities.invokeLater(new Runnable() { public void run() { JButton close = getUIElement("jobs." + jobId + ".closetab"); JButton terminate = getUIElement("jobs." + jobId + ".terminate"); terminate.setEnabled(false); close.setEnabled(true); JProgressBar progress = getUIElement("jobs." + jobId + ".progress"); JLabel percentage = getUIElement("jobs." + jobId + ".execution.percentage"); progress.setEnabled(false); // If Successfully Finished if (event.getType() == ServiceMessageType.JOB_END) { if (profile.getFuture().getState() != GridJobState.FAILED) { // If Not Job Failed progress.setValue(100); percentage.setText("100 %"); } else { // If Failed percentage.setText("N/A"); } // Stop (if) Indeterminate Progress Bar if (progress.isIndeterminate()) { progress.setIndeterminate(false); progress.setStringPainted(true); } } else if (event.getType() == ServiceMessageType.JOB_CANCEL) { if (progress.isIndeterminate()) { progress.setIndeterminate(false); progress.setStringPainted(false); percentage.setText("N/A"); } } showIdleIcon(); } }); } }, jobId, ServiceMessageType.JOB_CANCEL, ServiceMessageType.JOB_END); }
From source file:xc.mst.manager.record.DefaultRecordService.java
@Override public long getCount(Date fromDate, Date untilDate, Set set, int formatId, int serviceId) throws IndexException { Date from; // fromDate, or the minimum value for a Date if fromDate is null Date until; // toDate, or now if toDate is null // If from is null, set it to the minimum possible value // Otherwise set it to the same value as fromDate if (fromDate == null) { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date(0)); c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) - ((c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)) / (60 * 60 * 1000))); from = c.getTime();//from w ww . j a v a 2 s.co m } else { from = fromDate; } // If to is null, set it to now // Otherwise set it to the same value as toDate if (untilDate == null) { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date()); c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) - ((c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)) / (60 * 60 * 1000))); until = c.getTime(); } else { until = untilDate; } // True if we're getting the count for a specific set, false if we're getting it for all records boolean useSet = (set != null); // True if we're getting the count for a specific metadataPrefix, false if we're getting it for all records boolean useMetadataPrefix = (formatId > 0); DateFormat format = DateFormat.getInstance(); if (log.isDebugEnabled()) log.debug("Counting the records updated later than " + format.format(from) + " and earlier than " + format.format(until) + (useSet ? " with set ID " + set.getSetSpec() : "") + (useMetadataPrefix ? " with format ID " + formatId : "")); // Create a query to get the Documents for unprocessed records SolrQuery query = new SolrQuery(); StringBuffer queryBuffer = new StringBuffer(); queryBuffer.append(FIELD_SERVICE_ID).append(":").append(Integer.toString(serviceId)); if (useSet) queryBuffer.append(" AND ").append(FIELD_SET_SPEC).append(":").append(set.getSetSpec()); if (useMetadataPrefix) queryBuffer.append(" AND ").append(FIELD_FORMAT_ID).append(":").append(Integer.toString(formatId)); queryBuffer.append(" AND ").append(FIELD_DELETED).append(":").append("false"); query.setQuery(queryBuffer.toString()); if (from != null && until != null) query.addFilterQuery( FIELD_UPDATED_AT + ":[" + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(from)) + " TO " + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(until)) + "]"); // Get the result of the query RecordList records = new RecordList(query, 0); if (log.isDebugEnabled()) log.debug("Found " + records.size() + " records updated later than " + format.format(from) + " and earlier than " + format.format(until) + (useSet ? " with set ID " + set.getSetSpec() : "") + (useMetadataPrefix ? " with format ID " + formatId : "")); // Return the list of results return records.size(); }
From source file:org.nuxeo.ecm.csv.core.CSVImporterWork.java
protected void sendMail() { UserManager userManager = Framework.getService(UserManager.class); NuxeoPrincipal principal = userManager.getPrincipal(username); String email = principal.getEmail(); if (email == null) { log.info(String.format("Not sending import result email to '%s', no email configured", username)); return;/*from w w w. j ava2s . co m*/ } try (OperationContext ctx = new OperationContext(session)) { ctx.setInput(session.getRootDocument()); CSVImporter csvImporter = Framework.getService(CSVImporter.class); List<CSVImportLog> importerLogs = csvImporter.getImportLogs(getId()); CSVImportResult importResult = CSVImportResult.fromImportLogs(importerLogs); List<CSVImportLog> skippedAndErrorImportLogs = csvImporter.getImportLogs(getId(), Status.SKIPPED, Status.ERROR); ctx.put("importResult", importResult); ctx.put("skippedAndErrorImportLogs", skippedAndErrorImportLogs); ctx.put("csvFilename", getBlob().getFilename()); ctx.put("startDate", DateFormat.getInstance().format(startDate)); ctx.put("username", username); DocumentModel importFolder = session.getDocument(new PathRef(parentPath)); String importFolderUrl = getDocumentUrl(importFolder); ctx.put("importFolderTitle", importFolder.getTitle()); ctx.put("importFolderUrl", importFolderUrl); ctx.put("userUrl", getUserUrl()); StringList to = buildRecipientsList(email); Expression from = Scripting.newExpression("Env[\"mail.from\"]"); String subject = "CSV Import result of " + getBlob().getFilename(); String message = loadTemplate(TEMPLATE_IMPORT_RESULT); OperationChain chain = new OperationChain("SendMail"); chain.add(SendMail.ID).set("from", from).set("to", to).set("HTML", true).set("subject", subject) .set("message", message); Framework.getService(AutomationService.class).run(ctx, chain); } catch (Exception e) { ExceptionUtils.checkInterrupt(e); log.error(String.format("Unable to notify user '%s' for import result of '%s': %s", username, getBlob().getFilename(), e.getMessage())); log.debug(e, e); throw ExceptionUtils.runtimeException(e); } }
From source file:edu.utah.further.i2b2.query.criteria.service.impl.I2b2SearchCriterionBuilder.java
/** * Converts a {@link List} of {@link String}'s to a {@link List} of {@link Integer}'s * //from ww w .ja v a2 s.co m * @param strings * @return */ private List<Date> toDateList(final List<String> strings) { final List<Date> dates = newList(); for (final String date : domain) { try { dates.add(DateFormat.getInstance().parse(date)); } catch (final ParseException e) { log.error("Unsupported date format"); } } return dates; }