下面列出了org.springframework.core.io.ClassPathResource#getInputStream ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public List<T> parseCsv() throws IOException {
ClassPathResource classPathResource = new ClassPathResource(getClassPathFilePath(), this.getClass().getClassLoader());
InputStreamReader ioReader = new InputStreamReader(classPathResource.getInputStream(), "UTF-8");
CSVReader reader = new CSVReader(ioReader, ';');
ColumnPositionMappingStrategy<T> strat = new ColumnPositionMappingStrategy<>();
strat.setType(getDestinationClass());
strat.setColumnMapping(getColumnMapping());
CsvToBean<T> csv = getParser();
return csv.parse(strat, reader);
}
/**
* 新增灰度配置
*
* @throws Exception
*/
@Test
public void test_quick_start_3_addGrayConfig() throws Exception {
ClassPathResource classPathResource1 = new ClassPathResource("1.yml");
MockMultipartFile multipartFile1 = new MockMultipartFile("file", "1.yml", "application/octet-stream", classPathResource1.getInputStream());
ClassPathResource classPathResource2 = new ClassPathResource("2.yml");
MockMultipartFile multipartFile2 = new MockMultipartFile("file", "2.yml", "application/octet-stream", classPathResource2.getInputStream());
ClassPathResource classPathResource3 = new ClassPathResource("3.yml");
MockMultipartFile multipartFile3 = new MockMultipartFile("file", "3.yml", "application/octet-stream", classPathResource3.getInputStream());
String result = this.mockMvc.perform(MockMvcRequestBuilders.fileUpload("/api/v1/grayConfig/addGrayConfig")
.file(multipartFile1)
.file(multipartFile2)
.file(multipartFile3)
.param("project", "测试项目")
.param("cluster", "测试集群")
.param("service", "测试服务")
.param("version", "测试版本")
.param("versionId", "3776343244166660096")
.param("desc", "测试sdk")
.param("grayId", "3780699522712207360")
.param("name", "test")
.contentType(MediaType.MULTIPART_FORM_DATA)
.session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
.accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
Utils.assertResult(result);
}
public boolean addGitIgnoreFile(String siteId) {
String defaultFileLocation = studioConfiguration.getProperty(REPO_DEFAULT_IGNORE_FILE);
ClassPathResource defaultFile = new ClassPathResource(defaultFileLocation);
if (defaultFile.exists()) {
logger.debug("Adding ignore file for site {0}", siteId);
Path siteSandboxPath = buildRepoPath(GitRepositories.SANDBOX, siteId);
Path ignoreFile = siteSandboxPath.resolve(GitContentRepositoryConstants.IGNORE_FILE);
if (!Files.exists(ignoreFile)) {
try (OutputStream out = Files.newOutputStream(ignoreFile, StandardOpenOption.CREATE);
InputStream in = defaultFile.getInputStream()) {
IOUtils.copy(in, out);
} catch (IOException e) {
logger.error("Error writing ignore file for site {0}", e, siteId);
return false;
}
} else {
logger.debug("Repository already contains an ignore file for site {0}", siteId);
}
} else {
logger.warn("Could not find the default ignore file at {0}", defaultFileLocation);
}
return true;
}
@RequestMapping(value = "/ueditor", method = RequestMethod.GET)
@Timed
public String getConfig(@RequestParam(value = "action") String action) {
log.debug("REST request to get config json string");
Ueditor ueditor = new Ueditor();
if (action.equals("config")) {
try {
ClassPathResource classPathResource = new ClassPathResource("ueditor/config.json");
InputStream stream = classPathResource.getInputStream();
String config = IOUtils.toString(stream, "UTF-8");
stream.close();
return config;
} catch (Exception e) {
ueditor.setState("找不到配置文件!");
return JSONObject.toJSONString(ueditor);
}
} else {
ueditor.setState("不支持操作!");
return JSONObject.toJSONString(ueditor);
}
}
@PostConstruct
public void afterPropertiesSet() {
ClassPathResource classPathResource = new ClassPathResource("api.json");
try (InputStreamReader reader = new InputStreamReader(classPathResource.getInputStream(),"utf-8")) {
StringBuilder api = new StringBuilder();
int tempchar;
while ((tempchar = reader.read()) != -1) {
api.append((char) tempchar);
}
String roleResource = api.toString();
if(!StringUtils.isEmpty(roleResource)){
RBucket<Object> bucket = redissonClient.getBucket(clientId.concat("_").concat("resource"));
bucket.set(roleResource);
logger.info("初始化or更新url资源完成:" + roleResource);
}
} catch (IOException e) {
logger.error("Api抽取上传失败", e);
}
}
private void loadResource(String version) {
InputStream inputStream = null;
try {
ClassPathResource classPathResource = new ClassPathResource("kafka/" + version + "/kafka-clients-" + version + ".jar");
inputStream = classPathResource.getInputStream();
File dir = File.createTempFile("kafka-clients-" + version, ".jar");
FileUtils.copyInputStreamToFile(inputStream, dir);
logger.info("loadResource:{}",dir.getAbsoluteFile());
this.addURL(dir);
}catch (Exception e){
e.printStackTrace();
}finally {
IOUtils.closeQuietly(inputStream);
}
}
@Override
public Boolean testAccess(UploadInfo uploadInfo) {
ClassPathResource classPathResource = new ClassPathResource("static/images/userface1.jpg");
try {
Auth auth = Auth.create(uploadInfo.getQiniuAccessKey(), uploadInfo.getQiniuSecretKey());
String authstr = auth.uploadToken(uploadInfo.getQiniuBucketName());
InputStream inputStream = classPathResource .getInputStream();
Response response = getUploadManager().put(inputStream,"test.jpg",authstr,null,null);
if(response.isOK()){
return true;
}else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static void getHelpItems( OutputStream out, Locale locale )
{
try
{
ClassPathResource classPathResource = resolveHelpFileResource( locale );
Source source = new StreamSource( classPathResource.getInputStream(), ENCODING_UTF8 );
Result result = new StreamResult( out );
getTransformer( "helpitems_stylesheet.xsl" ).transform( source, result );
}
catch ( Exception ex )
{
throw new RuntimeException( "Failed to get help content", ex );
}
}
public DataContainer load(String resourcePath) {
log.debug("Loading data: {}", resourcePath);
ClassPathResource resource = new ClassPathResource(resourcePath);
try (InputStream is = resource.getInputStream()) {
data.putAll(MapUtils.merge(data, yaml.load(is)));
} catch (IOException e) {
throw new KorkTestException(format("Failed reading mimic data: %s", resourcePath), e);
}
return this;
}
/**
* 新增灰度组
*
* @throws Exception
*/
@Test
public void test_gray_group_1_add() throws Exception {
ClassPathResource classPathResource1 = new ClassPathResource("1.yml");
MockMultipartFile multipartFile1 = new MockMultipartFile("file", "1.yml", "application/octet-stream", classPathResource1.getInputStream());
ClassPathResource classPathResource2 = new ClassPathResource("2.yml");
MockMultipartFile multipartFile2 = new MockMultipartFile("file", "2.yml", "application/octet-stream", classPathResource2.getInputStream());
ClassPathResource classPathResource3 = new ClassPathResource("3.yml");
MockMultipartFile multipartFile3 = new MockMultipartFile("file", "3.yml", "application/octet-stream", classPathResource3.getInputStream());
String result = this.mockMvc.perform(MockMvcRequestBuilders.fileUpload("/api/v1/gray/add")
.file(multipartFile1)
.file(multipartFile2)
.file(multipartFile3)
.param("project", "测试项目")
.param("cluster", "测试集群")
.param("service", "测试服务")
.param("version", "测试版本")
.param("versionId", "3776343244166660096")
.param("desc", "测试灰度组")
.param("name", "测试灰度组2")
.contentType(MediaType.MULTIPART_FORM_DATA)
.session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
.accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
Utils.assertResult(result);
}
public static byte[] get(String classpathResource) throws Exception {
ClassPathResource r = new ClassPathResource(classpathResource);
InputStream in = r.getInputStream();
byte[] b = FileCopyUtils.copyToByteArray(in);
in.close();
return b;
}
private MultipartFile getResume() {
ClassPathResource cpr = new ClassPathResource("testdata/" + FILE_NAME + "." + FILE_ENDING);
MultipartFile file = null;
try {
file = new MockMultipartFile(FILE_NAME + "." + FILE_ENDING, cpr.getFilename(), FILE_ENDING, cpr.getInputStream());
} catch (IOException e) {
throw new IllegalStateException("Error getting file.", e);
}
return file;
}
/**
* 导出
*
* @param templatePath
* 模板地址,自定义比较好看 classPath下的路径
* @param colums
* 导出的数据列 反射用
* @param clazz
* @param data
* @param out
* @param startRow
* 从几行开始写数据
* @return
* @throws IOException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static <T> void doExport(String templatePath, String[] columns, Class<T> clazz, List<T> data,
OutputStream out, int startRow) throws IOException, IllegalArgumentException, IllegalAccessException {
ClassPathResource classPathResource = new ClassPathResource(templatePath);
InputStream inputStream = classPathResource.getInputStream();
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int size = data.size() + startRow;
int cellNum = sheet.getRow(0).getPhysicalNumberOfCells();
for (int i = startRow; i < size; i++) {
Row row = sheet.createRow(i);
for (int j = 0; j < cellNum; j++) {
Cell cell = row.createCell(j);
Field field = ReflectionUtils.findField(clazz, columns[j]);
if (null == field) {
throw new ServiceException(columns[j] + " 配置错误");
}
ReflectionUtils.makeAccessible(field);
Object obj = data.get(i - startRow);
if (field.getType().getSimpleName().equalsIgnoreCase("double")) {
cell.setCellValue((Double) field.get(obj));
} else if (field.getType().getSimpleName().equalsIgnoreCase("date")) {
CellStyle style = workbook.createCellStyle();
style.setDataFormat(workbook.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
cell.setCellStyle(style);
cell.setCellValue((Date) field.get(obj));
} else {
cell.setCellValue(field.get(obj) == null ? "" : "" + field.get(obj));
}
}
}
workbook.write(out);
workbook.close();
}
@Override
public Boolean testAccess(UploadInfo uploadInfo) {
ClassPathResource classPathResource = new ClassPathResource("static/images/userface1.jpg");
try {
OSSClient ossClient = new OSSClient(uploadInfo.getOssEndpoint(),uploadInfo.getOssKeyId(), uploadInfo.getOssKeySecret());
InputStream inputStream = classPathResource .getInputStream();
ossClient.putObject(uploadInfo.getOssBucketName(), "test.jpg", inputStream, null);
ossClient.shutdown();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static void initDirectoryServer(final InputStream ldifFile) throws IOException {
final ClassPathResource properties = new ClassPathResource("ldap.properties");
final ClassPathResource schema = new ClassPathResource("schema/standard-ldap.schema");
DIRECTORY = new InMemoryTestLdapDirectoryServer(properties.getInputStream(),
ldifFile,
schema.getInputStream());
}
@Override
public Map<String, String> loadCountryToCurrencyMappings() throws Exception {
ClassPathResource classPathResource = new ClassPathResource("country-currency-mapping.json");
InputStreamReader reader = new InputStreamReader(classPathResource.getInputStream());
try {
Map<String, String> countryCurrencyMap = new ObjectMapper().readValue(classPathResource.getInputStream(), new TypeReference<Map<String, String>>() {});
return countryCurrencyMap;
} finally {
reader.close();
}
}
private static void loadProperties() {
epub2pdfProps = new Properties();
String propsFilename = "epub2pdf.properties";
try {
ClassPathResource classPathResource = new ClassPathResource("epub2pdf.properties");
InputStreamReader reader = new InputStreamReader(classPathResource.getInputStream());
try {
epub2pdfProps.load(reader);
} finally {
reader.close();
}
} catch (IOException e) {
printlnerr("IOException reading properties from " + propsFilename + "; continuing anyway");
}
}
private String base64EncodeImageData(String filename) {
String formattedImageData = null;
ClassPathResource resource = new ClassPathResource(filename);
try (InputStream stream = resource.getInputStream()) {
byte[] imageBytes = StreamUtils.copyToByteArray(stream);
String imageData = Base64Utils.encodeToString(imageBytes);
formattedImageData = String.format(IMAGE_DATA_FORMAT, imageData);
}
catch (IOException e) {
LOG.warn("Error converting image file to byte array", e);
}
return formattedImageData;
}
private FileResource getFileResource(String path,String type){
InputStream inputStream = null;
try {
ClassPathResource resource = new ClassPathResource(path);
inputStream = resource.getInputStream();
File tempFile = File.createTempFile("ds_" + System.currentTimeMillis(), type);
FileUtils.copyInputStreamToFile(inputStream, tempFile);
return new FileResource(tempFile);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
IOUtils.closeQuietly(inputStream);
}
}
/**
* Parse test data from a resources file
* @param resourcePath
* @return
* @throws IOException
*/
private List<Document> parseTestData(String resourcePath) throws IOException {
ClassPathResource resource = new ClassPathResource(resourcePath);
InputStream inputStream = resource.getInputStream();
// first we read the data
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(new InputStreamReader
(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
String jsonData = textBuilder.toString();
// then we convert that data to a json node
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(jsonData);
// we ensure it is an array of documents to insert
if (!jsonNode.isArray()) {
throw new InvalidObjectException(Constants.ERR_TEST_DATA_FORMAT);
}
// we parse and store the elements of the array
Iterator<JsonNode> it = jsonNode.elements();
ArrayList results = new ArrayList<Document>();
while (it.hasNext()) {
JsonNode node = it.next();
Document parsed = Document.parse(node.toString());
results.add(parsed);
}
// return those elements
return results;
}