List of usage examples for org.springframework.core.io FileSystemResource FileSystemResource
public FileSystemResource(Path filePath)
From source file:com.wavemaker.tools.ant.NewCopyRuntimeJarsTask.java
public void setProjectRoot(File projectRoot) { this.wmProject = new Project(new FileSystemResource(projectRoot), new LocalStudioFileSystem()); }
From source file:fr.acxio.tools.agia.tasks.ZipFilesTaskletTest.java
@Test public void testZipDirectories() throws Exception { FileUtils.forceMkdir(new File("target/Z-testfiles/source/subdir")); FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/CP0-input.csv")); FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/subdir/CP1-input.csv")); String aTargetFilename = "target/Z3-input.zip"; ZipFilesTasklet aTasklet = new ZipFilesTasklet(); aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/")); FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory(); aSourceFactory.setPattern("file:target/Z-testfiles/source/"); aTasklet.setSourceFactory(aSourceFactory); ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory(); aDestinationFactory.setExpression(aTargetFilename); aTasklet.setDestinationFactory(aDestinationFactory); assertFalse(new File(aTargetFilename).exists()); StepContribution aStepContribution = mock(StepContribution.class); assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null)); verify(aStepContribution, times(4)).incrementReadCount(); verify(aStepContribution, times(4)).incrementWriteCount(1); assertTrue(new File(aTargetFilename).exists()); ZipFile aZipFile = new ZipFile(new File(aTargetFilename)); Enumeration<ZipArchiveEntry> aEntries = aZipFile.getEntries(); assertTrue(aEntries.hasMoreElements()); assertEquals("source", aEntries.nextElement().getName()); assertTrue(aEntries.hasMoreElements()); assertEquals("source/CP0-input.csv", aEntries.nextElement().getName()); assertTrue(aEntries.hasMoreElements()); assertEquals("source/subdir", aEntries.nextElement().getName()); assertTrue(aEntries.hasMoreElements()); assertEquals("source/subdir/CP1-input.csv", aEntries.nextElement().getName()); assertFalse(aEntries.hasMoreElements()); aZipFile.close();/*from w w w . java 2 s . co m*/ }
From source file:uk.ac.gda.dls.client.feedback.FeedbackDialog.java
@Override protected void createButtonsForButtonBar(Composite parent) { GridData data = new GridData(SWT.FILL, SWT.FILL, false, true, 4, 1); GridLayout layout = new GridLayout(5, false); parent.setLayoutData(data);/*from w w w . ja v a 2s. c o m*/ parent.setLayout(layout); Button attachButton = new Button(parent, SWT.TOGGLE); attachButton.setText("Attach File(s)"); attachButton.setToolTipText("Add files to feedback"); final Button screenGrabButton = new Button(parent, SWT.CHECK); screenGrabButton.setText("Include Screenshot"); screenGrabButton.setToolTipText("Send screenshot with feedback"); Label space = new Label(parent, SWT.NONE); space.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true)); Button sendButton = new Button(parent, SWT.PUSH); sendButton.setText("Send"); Button cancelButton = new Button(parent, SWT.PUSH); cancelButton.setText("Cancel"); sendButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final String name = nameText.getText(); final String email = emailText.getText(); final String subject = subjectText.getText(); final String description = descriptionText.getText(); fileList = attachedFileList.getItems(); Job job = new Job("Send feedback email") { @Override protected IStatus run(IProgressMonitor monitor) { try { final String recipientsProperty = LocalProperties.get("gda.feedback.recipients", "dag-group@diamond.ac.uk"); final String[] recipients = recipientsProperty.split(" "); for (int i = 0; i < recipients.length; i++) { recipients[i] = recipients[i].trim(); } final String from = String.format("%s <%s>", name, email); final String beamlineName = LocalProperties.get("gda.beamline.name", "Beamline Unknown"); final String mailSubject = String.format("[GDA feedback - %s] %s", beamlineName.toUpperCase(), subject); final String smtpHost = LocalProperties.get("gda.feedback.smtp.host", "localhost"); JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(smtpHost); MimeMessage message = mailSender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message, (FeedbackDialog.this.hasFiles && fileList.length > 0) || FeedbackDialog.this.screenshot); helper.setFrom(from); helper.setTo(recipients); helper.setSubject(mailSubject); helper.setText(description); if (FeedbackDialog.this.screenshot) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { String fileName = "/tmp/feedbackScreenshot.png"; try { captureScreen(fileName); FileSystemResource file = new FileSystemResource(new File(fileName)); helper.addAttachment(file.getFilename(), file); } catch (Exception e) { logger.error("Could not attach screenshot to feedback", e); } } }); } if (FeedbackDialog.this.hasFiles) { for (String fileName : fileList) { FileSystemResource file = new FileSystemResource(new File(fileName)); helper.addAttachment(file.getFilename(), file); } } {//required to workaround class loader issue with "no object DCH..." error MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap( "text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap( "multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); CommandMap.setDefaultCommandMap(mc); } mailSender.send(message); return Status.OK_STATUS; } catch (Exception ex) { logger.error("Could not send feedback", ex); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, 1, "Error sending email", ex); } } }; job.schedule(); setReturnCode(OK); close(); } }); cancelButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setReturnCode(CANCEL); close(); } }); attachButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { hasFiles = !hasFiles; GridData data = ((GridData) attachments.getLayoutData()); data.exclude = !hasFiles; attachments.setVisible(hasFiles); topParent.layout(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); screenGrabButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { screenshot = ((Button) e.widget).getSelection(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); }
From source file:org.craftercms.search.service.impl.RestClientSearchService.java
@Override public String updateDocument(String site, String id, File document, Map<String, String> additionalFields) throws SearchException { FileSystemResource fsrDoc = new FileSystemResource(document); MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>(); form.add(REQUEST_PARAM_SITE, site);//from w w w . j a v a 2s . c om form.add(REQUEST_PARAM_ID, id); form.add(REQUEST_PARAM_DOCUMENT, fsrDoc); if (MapUtils.isNotEmpty(additionalFields)) { for (Map.Entry<String, String> additionalField : additionalFields.entrySet()) { String fieldName = additionalField.getKey(); if (fieldName.equals(REQUEST_PARAM_SITE) || fieldName.equals(REQUEST_PARAM_ID) || fieldName.equals(REQUEST_PARAM_DOCUMENT)) { throw new SearchException( String.format("An additional field shouldn't have the following names: %s, %s, %s", REQUEST_PARAM_SITE, REQUEST_PARAM_ID, REQUEST_PARAM_DOCUMENT)); } form.add(fieldName, additionalField.getValue()); } } String updateDocumentUrl = serverUrl + URL_ROOT + URL_UPDATE_DOCUMENT; try { return restTemplate.postForObject(new URI(updateDocumentUrl), form, String.class); } catch (URISyntaxException e) { throw new SearchException("Invalid URI: " + updateDocumentUrl, e); } catch (HttpStatusCodeException e) { throw new SearchException("Update for document '" + id + "' failed: [" + e.getStatusText() + "] " + e.getResponseBodyAsString()); } catch (Exception e) { throw new SearchException("Update for document '" + id + "' failed: " + e.getMessage(), e); } }
From source file:org.apigw.commons.crypto.ApigwCrypto.java
/** * * @param keyStoreFile/*w w w .j a v a2 s. c o m*/ * @param keyStorePassword * @param keyStoreType * @return a new KeyStore corresponding to provided values * @throws IOException * @throws KeyStoreException * @throws CertificateException * @throws NoSuchAlgorithmException */ private KeyStore initKeyStore(String keyStoreFile, String keyStorePassword, String keyStoreType) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { InputStream inputStream; KeyStore keyStore; try { inputStream = new ClassPathResource(keyStoreFile).getInputStream(); } catch (FileNotFoundException e) { log.warn("unable to load {} from classpath, will try filesystem", keyStoreFile); inputStream = new FileSystemResource(keyStoreFile).getInputStream(); } keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(inputStream, keyStorePassword.toCharArray()); inputStream.close(); return keyStore; }
From source file:com.wavemaker.tools.project.LocalStudioConfiguration.java
@Override public Resource getTomcatHome() { String tomcatHome = System.getProperty("catalina.home"); tomcatHome = tomcatHome.endsWith("/") ? tomcatHome : tomcatHome + "/"; return new FileSystemResource(tomcatHome); }
From source file:aiai.ai.launchpad.server.ServerController.java
private HttpEntity<AbstractResource> deliverResource(HttpServletResponse response, String typeAsStr, String code) throws IOException { Enums.BinaryDataType binaryDataType = Enums.BinaryDataType.valueOf(typeAsStr.toUpperCase()); AssetFile assetFile = StationResourceUtils.prepareResourceFile(globals.launchpadResourcesDir, binaryDataType, code, null); if (assetFile == null) { return returnEmptyAsGone(response); }/* ww w .ja v a2s . c o m*/ try { binaryDataService.storeToFile(code, assetFile.file); } catch (BinaryDataNotFoundException e) { return returnEmptyAsGone(response); } return new HttpEntity<>(new FileSystemResource(assetFile.file.toPath()), getHeader(assetFile.file.length())); }
From source file:com.glaf.mail.MailSenderImpl.java
public void send(JavaMailSender javaMailSender, MailMessage mailMessage) throws Exception { if (StringUtils.isEmpty(mailMessage.getMessageId())) { mailMessage.setMessageId(UUID32.getUUID()); }// w w w .j av a 2 s. c om mailHelper = new MxMailHelper(); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true); if (StringUtils.isNotEmpty(mailMessage.getFrom())) { messageHelper.setFrom(mailMessage.getFrom()); mailFrom = mailMessage.getFrom(); } else { if (StringUtils.isEmpty(mailFrom)) { mailFrom = MailProperties.getString("mail.mailFrom"); } messageHelper.setFrom(mailFrom); } logger.debug("mailFrom:" + mailFrom); if (mailMessage.getTo() != null) { messageHelper.setTo(mailMessage.getTo()); } if (mailMessage.getCc() != null) { messageHelper.setCc(mailMessage.getCc()); } if (mailMessage.getBcc() != null) { messageHelper.setBcc(mailMessage.getBcc()); } if (mailMessage.getReplyTo() != null) { messageHelper.setReplyTo(mailMessage.getReplyTo()); } String mailSubject = mailMessage.getSubject(); if (mailSubject == null) { mailSubject = ""; } if (mailSubject != null) { // mailSubject = MimeUtility.encodeText(new // String(mailSubject.getBytes(), encoding), encoding, "B"); mailSubject = MimeUtility.encodeWord(mailSubject); } mimeMessage.setSubject(mailSubject); Map<String, Object> dataMap = mailMessage.getDataMap(); if (dataMap == null) { dataMap = new java.util.HashMap<String, Object>(); } String serviceUrl = SystemConfig.getServiceUrl(); logger.debug("mailSubject:" + mailSubject); logger.debug("serviceUrl:" + serviceUrl); if (serviceUrl != null) { String loginUrl = serviceUrl + "/mx/login"; String mainUrl = serviceUrl + "/mx/main"; logger.debug("loginUrl:" + loginUrl); dataMap.put("loginUrl", loginUrl); dataMap.put("mainUrl", mainUrl); } mailMessage.setDataMap(dataMap); if (StringUtils.isEmpty(mailMessage.getContent())) { Template template = TemplateContainer.getContainer().getTemplate(mailMessage.getTemplateId()); if (template != null) { String templateType = template.getTemplateType(); logger.debug("templateType:" + templateType); // logger.debug("content:" + template.getContent()); if (StringUtils.equals(templateType, "eml")) { if (template.getContent() != null) { Mail m = mailHelper.getMail(template.getContent().getBytes()); String content = m.getContent(); if (StringUtils.isNotEmpty(content)) { template.setContent(content); try { Writer writer = new StringWriter(); TemplateUtils.evaluate(mailMessage.getTemplateId(), dataMap, writer); String text = writer.toString(); writer.close(); writer = null; mailMessage.setContent(text); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } } } else { try { String text = TemplateUtils.process(dataMap, template.getContent()); mailMessage.setContent(text); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } } } if (StringUtils.isNotEmpty(mailMessage.getContent())) { String text = mailMessage.getContent(); if (StringUtils.isNotEmpty(callbackUrl)) { String href = callbackUrl + "?messageId=" + mailMessage.getMessageId(); text = mailHelper.embedCallbackScript(text, href); mailMessage.setContent(text); logger.debug(text); messageHelper.setText(text, true); } messageHelper.setText(text, true); } logger.debug("mail body:" + mailMessage.getContent()); Collection<Object> files = mailMessage.getFiles(); if (files != null && !files.isEmpty()) { Iterator<Object> iterator = files.iterator(); while (iterator.hasNext()) { Object object = iterator.next(); if (object instanceof java.io.File) { java.io.File file = (java.io.File) object; FileSystemResource resource = new FileSystemResource(file); String name = file.getName(); name = MailTools.chineseStringToAscii(name); messageHelper.addAttachment(name, resource); logger.debug("add attachment:" + name); } else if (object instanceof DataSource) { DataSource dataSource = (DataSource) object; String name = dataSource.getName(); name = MailTools.chineseStringToAscii(name); messageHelper.addAttachment(name, dataSource); logger.debug("add attachment:" + name); } else if (object instanceof DataFile) { DataFile dataFile = (DataFile) object; if (StringUtils.isNotEmpty(dataFile.getFilename())) { String name = dataFile.getFilename(); name = MailTools.chineseStringToAscii(name); InputStreamSource inputStreamSource = new MxMailInputSource(dataFile); messageHelper.addAttachment(name, inputStreamSource); logger.debug("add attachment:" + name); } } } } mimeMessage.setSentDate(new java.util.Date()); javaMailSender.send(mimeMessage); logger.info("-----------------------------------------"); logger.info("????"); logger.info("-----------------------------------------"); }
From source file:annis.administration.DefaultAdministrationDao.java
protected void populateSchema() { log.info("populating the schemas with default values"); bulkloadTableFromResource("resolver_vis_map", new FileSystemResource(new File(scriptPath, FILE_RESOLVER_VIS_MAP + REL_ANNIS_FILE_SUFFIX))); // update the sequence executeSqlFromScript("update_resolver_sequence.sql"); }
From source file:net.frontlinesms.FrontlineSMS.java
/** Initialise {@link #applicationContext}. */ public void initApplicationContext() throws DataAccessResourceFailureException { // Load the data mode from the app.properties file AppProperties appProperties = AppProperties.getInstance(); LOG.info("Load Spring/Hibernate application context to initialise DAOs"); // Create a base ApplicationContext defining the hibernate config file we need to import StaticApplicationContext baseApplicationContext = new StaticApplicationContext(); baseApplicationContext.registerBeanDefinition("hibernateConfigLocations", createHibernateConfigLocationsBeanDefinition()); // Get the spring config locations String databaseExternalConfigPath = ResourceUtils.getConfigDirectoryPath() + ResourceUtils.PROPERTIES_DIRECTORY_NAME + File.separatorChar + appProperties.getDatabaseConfigPath(); String[] configLocations = getSpringConfigLocations(databaseExternalConfigPath); baseApplicationContext.refresh();// www. java 2 s. co m FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext(configLocations, false, baseApplicationContext); this.applicationContext = applicationContext; // Add post-processor to handle substituted database properties PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer(); String databasePropertiesPath = ResourceUtils.getConfigDirectoryPath() + ResourceUtils.PROPERTIES_DIRECTORY_NAME + File.separatorChar + appProperties.getDatabaseConfigPath() + ".properties"; propertyPlaceholderConfigurer.setLocation(new FileSystemResource(new File(databasePropertiesPath))); propertyPlaceholderConfigurer.setIgnoreResourceNotFound(true); applicationContext.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer); applicationContext.refresh(); LOG.info("Context loaded successfully."); this.pluginManager = new PluginManager(this, applicationContext); LOG.info("Getting DAOs from application context..."); groupDao = (GroupDao) applicationContext.getBean("groupDao"); groupMembershipDao = (GroupMembershipDao) applicationContext.getBean("groupMembershipDao"); contactDao = (ContactDao) applicationContext.getBean("contactDao"); keywordDao = (KeywordDao) applicationContext.getBean("keywordDao"); keywordActionDao = (KeywordActionDao) applicationContext.getBean("keywordActionDao"); messageDao = (MessageDao) applicationContext.getBean("messageDao"); emailDao = (EmailDao) applicationContext.getBean("emailDao"); emailAccountDao = (EmailAccountDao) applicationContext.getBean("emailAccountDao"); smsInternetServiceSettingsDao = (SmsInternetServiceSettingsDao) applicationContext .getBean("smsInternetServiceSettingsDao"); smsModemSettingsDao = (SmsModemSettingsDao) applicationContext.getBean("smsModemSettingsDao"); eventBus = (EventBus) applicationContext.getBean("eventBus"); }