/** * Resolve metadata from resource. * * @param service the service * @param metadataResolvers the metadata resolvers * @throws Exception the io exception */ protected void resolveMetadataFromResource(final SamlRegisteredService service, final List<MetadataResolver> metadataResolvers) throws Exception { final String metadataLocation = service.getMetadataLocation(); LOGGER.info("Loading SAML metadata from [{}]", metadataLocation); final AbstractResource metadataResource = ResourceUtils.getResourceFrom(metadataLocation); if (metadataResource instanceof FileSystemResource) { resolveFileSystemBasedMetadataResource(service, metadataResolvers, metadataResource); } if (metadataResource instanceof UrlResource) { resolveUrlBasedMetadataResource(service, metadataResolvers, metadataResource); } if (metadataResource instanceof ClassPathResource) { resolveClasspathBasedMetadataResource(service, metadataResolvers, metadataLocation, metadataResource); } }
@Bean public MetadataResolver casSamlIdPMetadataResolver() { try { final SamlIdPProperties idp = casProperties.getAuthn().getSamlIdp(); final ResourceBackedMetadataResolver resolver = new ResourceBackedMetadataResolver( ResourceHelper.of(new FileSystemResource(idp.getMetadata().getMetadataFile()))); resolver.setParserPool(this.openSamlConfigBean.getParserPool()); resolver.setFailFastInitialization(idp.getMetadata().isFailFast()); resolver.setRequireValidMetadata(idp.getMetadata().isRequireValidMetadata()); resolver.setId(idp.getEntityId()); resolver.initialize(); return resolver; } catch (final Exception e) { throw new BeanCreationException(e.getMessage(), e); } }
/** * Create the public key. * * @throws Exception if key creation ran into an error */ protected void createGoogleAppsPublicKey() throws Exception { if (!isValidConfiguration()) { LOGGER.debug("Google Apps public key bean will not be created, because it's not configured"); return; } final PublicKeyFactoryBean bean = new PublicKeyFactoryBean(); if (this.publicKeyLocation.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { bean.setLocation(new ClassPathResource(StringUtils.removeStart(this.publicKeyLocation, ResourceUtils.CLASSPATH_URL_PREFIX))); } else if (this.publicKeyLocation.startsWith(ResourceUtils.FILE_URL_PREFIX)) { bean.setLocation(new FileSystemResource(StringUtils.removeStart(this.publicKeyLocation, ResourceUtils.FILE_URL_PREFIX))); } else { bean.setLocation(new FileSystemResource(this.publicKeyLocation)); } bean.setAlgorithm(this.keyAlgorithm); LOGGER.debug("Loading Google Apps public key from [{}] with key algorithm [{}]", bean.getResource(), bean.getAlgorithm()); bean.afterPropertiesSet(); LOGGER.debug("Creating Google Apps public key instance via [{}]", this.publicKeyLocation); this.publicKey = bean.getObject(); }
/** * Creates a new test instance with given parameters. * * @param checker Revocation checker instance. * @param expiredCRLPolicy Policy instance for handling expired CRL data. * @param certFiles File names of certificates to check. * @param crlFile File name of CRL file to serve out. * @param expected Expected result of check; null to indicate expected success. */ public CRLDistributionPointRevocationCheckerTests( final CRLDistributionPointRevocationChecker checker, final RevocationPolicy<X509CRL> expiredCRLPolicy, final String[] certFiles, final String crlFile, final GeneralSecurityException expected) throws Exception { super(certFiles, expected); final File file = new File(System.getProperty("java.io.tmpdir"), "ca.crl"); if (file.exists()) { file.delete(); } final OutputStream out = new FileOutputStream(file); IOUtils.copy(new ClassPathResource(crlFile).getInputStream(), out); this.checker = checker; this.checker.setExpiredCRLPolicy(expiredCRLPolicy); this.webServer = new MockWebServer(8085, new FileSystemResource(file), "text/plain"); logger.debug("Web server listening on port 8085 serving file {}", crlFile); }
/** * Create the private key. * * @throws Exception if key creation ran into an error */ protected void createGoogleAppsPrivateKey() throws Exception { if (!isValidConfiguration()) { LOGGER.debug("Google Apps private key bean will not be created, because it's not configured"); return; } final PrivateKeyFactoryBean bean = new PrivateKeyFactoryBean(); if (this.privateKeyLocation.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { bean.setLocation(new ClassPathResource(StringUtils.removeStart(this.privateKeyLocation, ResourceUtils.CLASSPATH_URL_PREFIX))); } else if (this.privateKeyLocation.startsWith(ResourceUtils.FILE_URL_PREFIX)) { bean.setLocation(new FileSystemResource(StringUtils.removeStart(this.privateKeyLocation, ResourceUtils.FILE_URL_PREFIX))); } else { bean.setLocation(new FileSystemResource(this.privateKeyLocation)); } bean.setAlgorithm(this.keyAlgorithm); LOGGER.debug("Loading Google Apps private key from [{}] with key algorithm [{}]", bean.getLocation(), bean.getAlgorithm()); bean.afterPropertiesSet(); LOGGER.debug("Creating Google Apps private key instance via [{}]", this.privateKeyLocation); this.privateKey = bean.getObject(); }
@Before public void setUp() { applicationContext = new XmlWebApplicationContext(); applicationContext.setConfigLocations( "file:src/main/webapp/WEB-INF/cas-management-servlet.xml", "file:src/main/webapp/WEB-INF/managementConfigContext.xml", "file:src/main/webapp/WEB-INF/spring-configuration/*.xml"); applicationContext.setServletContext(new MockServletContext(new ResourceLoader() { @Override public Resource getResource(final String location) { return new FileSystemResource("src/main/webapp" + location); } @Override public ClassLoader getClassLoader() { return getClassLoader(); } })); applicationContext.refresh(); }
@Bean @StepScope @Qualifier(STEP_NAME) public FlatFileItemReader<InnofactorImportFileLine> innofactorReader( @Value("#{jobParameters['inputFile']}") String inputFile) { FlatFileItemReader<InnofactorImportFileLine> reader = new FlatFileItemReader<>(); reader.setEncoding(StandardCharsets.UTF_8.name()); reader.setLineMapper(innofactorImportLineMapper()); reader.setStrict(true); reader.setResource(new FileSystemResource(inputFile)); reader.setLinesToSkip(0); reader.setBufferedReaderFactory(bufferedReaderFactory); return reader; }
@Test public void ableToUploadFile() throws IOException { String file1Content = "hello world"; String file2Content = "bonjour"; String username = "mike"; MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); map.add("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath())); map.add("someFile", new FileSystemResource(newFile(file2Content).getAbsolutePath())); map.add("name", username); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); String result = restTemplate.postForObject( codeFirstUrl + "upload", new HttpEntity<>(map, headers), String.class); assertThat(result, is(file1Content + file2Content + username)); }
@Test public void ableToUploadFileFromConsumer() throws IOException { String file1Content = "hello world"; String file2Content = "bonjour"; String username = "mike"; Map<String, Object> map = new HashMap<>(); map.put("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath())); map.put("someFile", new FileSystemResource(newFile(file2Content).getAbsolutePath())); map.put("name", username); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); String result = RestTemplateBuilder.create().postForObject( "cse://springmvc-tests/codeFirstSpringmvc/upload", new HttpEntity<>(map, headers), String.class); assertThat(result, is(file1Content + file2Content + username)); }
@Test public void ableToUploadFileWithoutAnnotation() throws IOException { String file1Content = "hello world"; String file2Content = "bonjour"; String username = "mike"; MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); map.add("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath())); map.add("file2", new FileSystemResource(newFile(file2Content).getAbsolutePath())); map.add("name", username); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); String result = restTemplate.postForObject( codeFirstUrl + "uploadWithoutAnnotation", new HttpEntity<>(map, headers), String.class); assertThat(result, is(file1Content + file2Content + username)); }
@Test public void blowsUpWhenFileNameDoesNotMatch() throws IOException { String file1Content = "hello world"; String file2Content = "bonjour"; MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); map.add("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath())); map.add("unmatched name", new FileSystemResource(newFile(file2Content).getAbsolutePath())); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); try { restTemplate.postForObject( codeFirstUrl + "uploadWithoutAnnotation", new HttpEntity<>(map, headers), String.class); expectFailing(UnknownHttpStatusCodeException.class); } catch (RestClientException ignored) { } }
@Before public void setUp() { applicationContext = new XmlWebApplicationContext(); applicationContext.setConfigLocations( "classpath:/webappContext.xml", "file:src/main/webapp/WEB-INF/cas-servlet.xml", "file:src/main/webapp/WEB-INF/deployerConfigContext.xml", "file:src/main/webapp/WEB-INF/spring-configuration/*.xml"); applicationContext.setServletContext(new MockServletContext(new ResourceLoader() { @Override public Resource getResource(final String location) { return new FileSystemResource("src/main/webapp" + location); } @Override public ClassLoader getClassLoader() { return getClassLoader(); } })); applicationContext.refresh(); }
@Before public void setUp() { applicationContext = new XmlWebApplicationContext(); applicationContext.setConfigLocations( "classpath:/cas-management-servlet.xml", "classpath:/managementConfigContext.xml", "classpath:/spring-configuration/*.xml"); applicationContext.setServletContext(new MockServletContext(new ResourceLoader() { @Override public Resource getResource(final String location) { return new FileSystemResource("src/main/webapp" + location); } @Override public ClassLoader getClassLoader() { return WiringTests.class.getClassLoader(); } })); applicationContext.refresh(); }
@Override public PublicKey createInstance() throws Exception { try { final PublicKeyFactoryBean factory = publicKeyFactoryBeanClass.newInstance(); if (this.location.startsWith("classpath:")) { factory.setLocation(new ClassPathResource(StringUtils.removeStart(this.location, "classpath:"))); } else { factory.setLocation(new FileSystemResource(this.location)); } factory.setAlgorithm(this.algorithm); factory.setSingleton(false); return factory.getObject(); } catch (final Exception e) { LOGGER.warn(e.getMessage(), e); throw new RuntimeException(e); } }
/** * Creates a new test instance with given parameters. * * @param checker Revocation checker instance. * @param expiredCRLPolicy Policy instance for handling expired CRL data. * @param certFiles File names of certificates to check. * @param crlFile File name of CRL file to serve out. * @param expected Expected result of check; null to indicate expected success. */ public CRLDistributionPointRevocationCheckerTests( final CRLDistributionPointRevocationChecker checker, final RevocationPolicy<X509CRL> expiredCRLPolicy, final String[] certFiles, final String crlFile, final GeneralSecurityException expected) throws Exception { super(certFiles, expected); final File file = new File(System.getProperty("java.io.tmpdir"), "ca.crl"); if (file.exists()) { file.delete(); } final OutputStream out = new FileOutputStream(file); IOUtils.copy(new ClassPathResource(crlFile).getInputStream(), out); this.checker = checker; this.checker.setExpiredCRLPolicy(expiredCRLPolicy); this.checker.init(); this.webServer = new MockWebServer(8085, new FileSystemResource(file), "text/plain"); logger.debug("Web server listening on port 8085 serving file {}", crlFile); }
@Before public void setUp() { applicationContext = new XmlWebApplicationContext(); applicationContext.setConfigLocations( "file:src/main/webapp/WEB-INF/cas-servlet.xml", "file:src/main/webapp/WEB-INF/deployerConfigContext.xml", "file:src/main/webapp/WEB-INF/spring-configuration/*.xml"); applicationContext.setServletContext(new MockServletContext(new ResourceLoader() { @Override public Resource getResource(final String location) { return new FileSystemResource("src/main/webapp" + location); } @Override public ClassLoader getClassLoader() { return getClassLoader(); } })); applicationContext.refresh(); }
@Override public PublicKey createInstance() throws Exception { try { final PublicKeyFactoryBean factory = publicKeyFactoryBeanClass.newInstance(); if (this.location.startsWith("classpath:")) { factory.setLocation(new ClassPathResource(StringUtils.removeStart(this.location, "classpath:"))); } else { factory.setLocation(new FileSystemResource(this.location)); } factory.setAlgorithm(this.algorithm); factory.setSingleton(false); return factory.getObject(); } catch (final Exception e) { logger.warn(e.getMessage(), e); throw new RuntimeException(e); } }
@Override public PublicKey createInstance() throws Exception { try { final PublicKeyFactoryBean factory = this.publicKeyFactoryBeanClass.newInstance(); if (this.location.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { factory.setLocation(new ClassPathResource(StringUtils.removeStart(this.location, ResourceUtils.CLASSPATH_URL_PREFIX))); } else { factory.setLocation(new FileSystemResource(this.location)); } factory.setAlgorithm(this.algorithm); factory.setSingleton(false); return factory.getObject(); } catch (final Exception e) { LOGGER.warn(e.getMessage(), e); throw Throwables.propagate(e); } }
/** * Get Resources to load for CloudUnit Context. * * @param profileProperties The filename of the profile properties. * @return An array of Resource. * The array will have at least the profileProperties given by parameter, and eventually a custom * configuration file if found in the {@code $HOME/.cloudunit/} repertory. */ private static Resource[] getResources(String profileProperties) { final File customFile = new File(System.getProperty("user.home") + "/.cloudunit/configuration.properties"); Resource[] resources = null; if (customFile.exists()) { logger.warn("Custom file configuration found ! : {}", customFile.getAbsolutePath()); resources = new Resource[] { new ClassPathResource(profileProperties), new FileSystemResource(customFile) }; } else { logger.warn(customFile.getAbsolutePath() + " is missing. Needed for production !"); resources = new Resource[] { new ClassPathResource(profileProperties), }; } return resources; }
public String uploadFile(File path) { checkConnectedAndInFileExplorer(); File file = path; try { FileInputStream fileInputStream = new FileInputStream(file); fileInputStream.available(); fileInputStream.close(); FileSystemResource resource = new FileSystemResource(file); Map<String, Object> params = new HashMap<>(); params.put("file", resource); params.putAll(authentificationUtils.getMap()); restUtils.sendPostForUpload(authentificationUtils.finalHost + "/file/container/" + currentContainerId + "/application/" + applicationUtils.getCurrentApplication().getName() + "?path=" + currentPath, params); } catch (IOException e) { log.log(Level.SEVERE, "File not found! Check the path file"); statusCommand.setExitStatut(1); } return "File uploaded"; }
public String runScript(String moduleName, File file) { applicationUtils.checkConnectedAndApplicationSelected(); Module module = findModule(moduleName); Map<String, Object> parameters = new HashMap<>(); parameters.put("file", new FileSystemResource(file)); parameters.putAll(authenticationUtils.getMap()); String url = String.format("%s%s%s/run-script", authenticationUtils.finalHost, urlLoader.modulePrefix, module.getName()); log.info("Running script..."); restUtils.sendPostForUpload(url, parameters); return "Done"; }
private Mono<ServerResponse> renderInternal(CompiledResponse compiledResponse, ResponseContext responseContext) { val headers = new HttpHeaders(); headers.setAll(compiledResponse.evaluateHeaders(responseContext)); val responseBuilder = ServerResponse .status(compiledResponse.getHttpStatus()) .headers(httpHeaders -> httpHeaders.putAll(headers)); val evaluatedBody = compiledResponse.getBody().evaluate(responseContext); if (evaluatedBody == null) { return responseBuilder.build() .doOnSuccess(response -> requestResponseLogger.logResponse(response, null)); } else if (evaluatedBody instanceof File) { val resource = new FileSystemResource((File) evaluatedBody); return responseBuilder .body(BodyInserters.fromResource(resource)) .doOnSuccess(response -> requestResponseLogger.logResponse(response, resource.toString())); } else { val serializedBody = serialize(evaluatedBody, headers.getContentType()); return responseBuilder .syncBody(serializedBody) .doOnSuccess(response -> requestResponseLogger.logResponse(response, serializedBody)); } }
@Before public void setUp() { applicationContext = new XmlWebApplicationContext(); applicationContext.setConfigLocations(new String[]{ "file:src/main/webapp/WEB-INF/cas-servlet.xml", "file:src/main/webapp/WEB-INF/deployerConfigContext.xml", "file:src/main/webapp/WEB-INF/spring-configuration/*.xml"}); applicationContext.setServletContext(new MockServletContext(new ResourceLoader() { @Override public Resource getResource(final String location) { return new FileSystemResource("src/main/webapp" + location); } @Override public ClassLoader getClassLoader() { return getClassLoader(); } })); applicationContext.refresh(); }
@Before public void setUp() { applicationContext = new XmlWebApplicationContext(); applicationContext.setConfigLocations(new String[]{ "file:src/main/webapp/WEB-INF/cas-management-servlet.xml", "file:src/main/webapp/WEB-INF/managementConfigContext.xml", "file:src/main/webapp/WEB-INF/spring-configuration/*.xml"}); applicationContext.setServletContext(new MockServletContext(new ResourceLoader() { @Override public Resource getResource(final String location) { return new FileSystemResource("src/main/webapp" + location); } @Override public ClassLoader getClassLoader() { return getClassLoader(); } })); applicationContext.refresh(); }
/** * 获取文件的绝对路径,class查找和系统路径查找 */ public static String getClassOrSystemPath(String path) { ClassPathResource rs = new ClassPathResource(path); FileSystemResource fr = new FileSystemResource(path); if (rs.exists()) return FileUtils.class.getClassLoader().getResource(path).getFile(); if (fr.exists()) return fr.getPath(); return null; }
/** * 下载 * @param file 文件 * @param fileName 生成的文件名 * @return {ResponseEntity} */ protected ResponseEntity<Resource> download(File file, String fileName) { Resource resource = new FileSystemResource(file); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); String header = request.getHeader("User-Agent"); // 避免空指针 header = header == null ? "" : header.toUpperCase(); HttpStatus status; if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) { fileName = URLUtils.encodeURL(fileName, Charsets.UTF_8); status = HttpStatus.OK; } else { fileName = new String(fileName.getBytes(Charsets.UTF_8), Charsets.ISO_8859_1); status = HttpStatus.CREATED; } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", fileName); return new ResponseEntity<Resource>(resource, headers, status); }
@BeforeClass public static void setUp() throws Exception { layoutMapper = new LayoutMapper(); YamlMapFactoryBean yamlMapFactoryBean = new YamlMapFactoryBean(); yamlMapFactoryBean.setResources(new FileSystemResource(LayoutMapperTest.class.getResource("layout.yml").getPath())); // String layout = "" + // "category:\n" + // " _default_: \"category/_layout\"\n" + // "food:\n" + // " detail: \"food/_layout\"\n" + // "boo:\n" + // " _default_: \"boo/_layout\"\n" + // " index: \"_boo\"\n" + // " foo:\n" + // " detail: \"boo/_detail\"" + // ""; // yamlMapFactoryBean.setResources(new ByteArrayResource(layout.getBytes("UTF-8"))); yamlMapFactoryBean.afterPropertiesSet(); ReflectionTestUtils.setField(layoutMapper, "layout", yamlMapFactoryBean.getObject()); ReflectionTestUtils.invokeMethod(layoutMapper, "init"); }
/** * 发送带附件的邮件 */ @Async("mailAsync") public void sendAttachmentsMail(String to, String subject, String content, String filePath) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); helper.setSentDate(new Date()); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); mailSender.send(message); logger.info("带附件的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送带附件的邮件时发生异常!", e); } }
/** * 发送正文中有静态资源(图片)的邮件 */ @Async("mailAsync") public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); helper.setSentDate(new Date()); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); logger.info("嵌入静态资源的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送嵌入静态资源的邮件时发生异常!", e); } }
/** * Get zipped log file by cmd id */ @GetMapping(path = "/log/download", produces = "application/zip") public Resource downloadFullLog(@RequestParam String cmdId, @RequestParam Integer index, HttpServletResponse httpResponse) { Cmd cmd = cmdService.find(cmdId); if (cmd == null) { throw new IllegalParameterException("Cmd not found"); } try { Path filePath = Paths.get(cmd.getLogPath()); FileSystemResource resource = new FileSystemResource(filePath.toFile()); httpResponse.setHeader("Content-Disposition", String.format("attachment; filename=%s", filePath.getFileName().toString())); return resource; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalStatusException("Log not found"); } }
@Test public void should_find_property_by_sequence() { // should find property from test resource Resource resource = propertyResourceLoader.find(); Assert.assertEquals(ClassPathResource.class, resource.getClass()); // should find property from system property when(System.getProperty("flow.cc.config.path")).thenReturn("/"); resource = propertyResourceLoader.find(); Assert.assertEquals(FileSystemResource.class, resource.getClass()); Assert.assertEquals(Paths.get("/").toString(), ((FileSystemResource) resource).getPath()); // should find property from env when(System.getenv("FLOW_CC_CONFIG_PATH")).thenReturn("/bin"); resource = propertyResourceLoader.find(); Assert.assertEquals(FileSystemResource.class, resource.getClass()); Assert.assertEquals(Paths.get("/bin").toString(), ((FileSystemResource) resource).getPath()); }
/** * Get properties for serviceId * * @param serviceId * @return * @throws SysException */ Properties getProperties(String serviceId) throws SysException { Properties result = new Properties(); try { List<File> fileList = this.findAll(); if (!(fileList != null && fileList.size() > 0)) { return result; } for (File file : fileList) { String name = file.getName(); int length = name.substring(name.lastIndexOf(".")).length(); if (serviceId.equals(name.substring(0, file.getName().length() - length))) { Resource resource = new FileSystemResource(file.getPath()); result.load(resource.getInputStream()); } } } catch (Exception e) { throw new SysException(e); } return result; }
@Override public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); log.info("邮件发送成功!"); } catch (MessagingException e) { log.error("邮件发送失败!"); log.error("失败原因:{}", e); } }
@Bean public KerberosTicketValidator kerberosTicketValidator() throws Exception { if (kerberosTicketValidator == null && properties.isKerberosSpnegoSupportEnabled()) { // Configure SunJaasKerberos (global) final File krb5ConfigFile = properties.getKerberosConfigurationFile(); if (krb5ConfigFile != null) { final GlobalSunJaasKerberosConfig krb5Config = new GlobalSunJaasKerberosConfig(); krb5Config.setKrbConfLocation(krb5ConfigFile.getAbsolutePath()); krb5Config.afterPropertiesSet(); } // Create ticket validator to inject into KerberosServiceAuthenticationProvider SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator(); ticketValidator.setServicePrincipal(properties.getKerberosSpnegoPrincipal()); ticketValidator.setKeyTabLocation(new FileSystemResource(properties.getKerberosSpnegoKeytabLocation())); ticketValidator.afterPropertiesSet(); kerberosTicketValidator = ticketValidator; } return kerberosTicketValidator; }
/** * 保存Resource到持久化,这个实现中是文件 * * @param mediaEntity * @return File */ @Override public Resource storeResource(MediaEntity mediaEntity) throws IOException { if (!(mediaEntity.getResource() instanceof WxMediaResource)) { return null; } WxMediaResource wxMediaResource = (WxMediaResource) mediaEntity.getResource(); if (wxMediaResource.isUrlMedia()) { return null; } String fileName = wxMediaResource.getFilename(); if (fileName == null) { fileName = mediaEntity.getMediaId(); } File file = new File(StringUtils.applyRelativePath(Type.TEMP.equals(mediaEntity.getStoreType()) ? defaultTempFilePath : defaultFilePath, fileName)); if (file.exists()) { return new FileSystemResource(file); } file.createNewFile(); file.setLastModified(System.currentTimeMillis()); FileCopyUtils.copy(mediaEntity.getResource().getInputStream(), new FileOutputStream(file)); mediaEntity.setResourcePath(file.getAbsolutePath()); store(mediaEntity); return new FileSystemResource(file); }