couldn't find method readString(Path) while loading BulkApi - spring-boot

I'm going to load the bulk of data using BulkApi but while compiling the code it shows me the error.
private static final Logger log = LoggerFactory.getLogger(BulkApiService.class);
#Autowired
public ElasticSearchConfig elasticSearchConfig;
private static String FOLDER_PATH = "src/main/resources/allFiles";
public void loadAllDataUsingBulkApi() {
Client client = elasticSearchConfig.client();
AtomicReference<BulkRequestBuilder> request = new AtomicReference<>(client.prepareBulk());
AtomicInteger counter = new AtomicInteger();
try (Stream<Path> filePathStream = Files.walk(Paths.get(FOLDER_PATH))) {
filePathStream.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
counter.getAndIncrement();
try {
String content = Files.readString(filePath);
JSONObject contentJson = new JSONObject(content);
HashMap contentMap = new Gson().fromJson(contentJson.toString(), HashMap.class);
request.get().add(client.prepareIndex("indexName", "default").setSource(contentMap));
} catch (IOException ignore) {
log.error(ignore.toString());
}
}
});
BulkResponse bulkResponse = request.get().execute().actionGet();
} catch (Exception e) {
log.error(e.toString());
}
}
}
Expected Output : it should load all the data on specified path to ES.
Actual output :
Error on "String content = Files.readString(filePath);" that couldn't find symbol.
symbol: method readString(Path)
location: class Files

Related

AWS S3 uploaded file was not shown on cyberduck

I am trying to write an API for uploading and downloading files. After I uploaded a test file, it was not shown on cyberduck, but I can download the test file that I just uploaded.
Then I try to download the file that exist on cyberduck, but it shows
com.emc.object.s3.S3Exception: The specified key does not exist.
API code:
StorageImpl.java
#Service
public class StorageImpl implements Storage {
private static Logger logger = LoggerFactory.getLogger(Storage.class);
#Value("${storage.file.repository}")
private String fileRepository;
#Value("${object.storage.user}")
private String oUser;
#Value("${object.storage.endpoint}")
private String endpoint;
#Value("${object.storage.bucket}")
private String nBucket;
#Value("${object.storage.key.secret}")
private String nSecret;
#Value("${object.storage.region.name}")
private String nRegion;
private S3Client s3client;
public StorageImpl() {
}
#Inject
void init() {
try {
s3client = this.getS3Client();
} catch (Exception e) {
e.printStackTrace();
}
}
private S3Client getS3Client() {
if (s3client == null) {
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(new PreferredCipherSuiteSSLSocketFactory(sc.getSocketFactory()));
String hostname = "";
URI uri = null;
try {
uri = new URI(endpoint);
hostname = uri.getHost();
} catch (URISyntaxException e) {
logger.error("URL " + endpoint + " is a malformed URL");
e.printStackTrace();
}
S3Config config = null;
config = new S3Config(new URI(endpoint)).withUseVHost(false);
logger.debug("oUser=" + oUser + ", secret=" + nSecret + ", endpoint=" + endpoint);
config.withIdentity(oUser).withSecretKey(nSecret);
logger.debug("");
config.setSignMetadataSearch(true);
s3client = new S3JerseyClient(config, new URLConnectionClientHandler());
logger.debug("s3client initiated. endpoint: " + endpoint);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
return s3client;
}
private File convertMultiPartFileToFile(final MultipartFile multipartFile) {
final File file = new File(multipartFile.getOriginalFilename());
try (final FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(multipartFile.getBytes());
} catch (IOException e) {
logger.error("Error {} occurred while converting the multipart file", e.getLocalizedMessage());
}
return file;
}
#Override
public void save(final MultipartFile multipartFile) {
try {
final File file = convertMultiPartFileToFile(multipartFile);
logger.info("Uploading file with name {}", file.getName());
final PutObjectRequest putObjectRequest = new PutObjectRequest(nBucket, file.getName(), file);
s3client.putObject(putObjectRequest);
Files.delete(file.toPath()); // Remove the file locally created in the project folder
} catch (AmazonServiceException e) {
logger.error("Error {} occurred while uploading file", e.getLocalizedMessage());
} catch (IOException ex) {
logger.error("Error {} occurred while deleting temporary file", ex.getLocalizedMessage());
}catch(S3Exception ae){
ae.printStackTrace();
logger.error("", ae);
}
}
#Override
public InputStream retrieve(String fileName) {
return s3client.getObject(nBucket, fileName).getObject();
}
}
FileController.java
#RestController
#RequestMapping("/files")
#CrossOrigin(origins = "*", maxAge = 3600)
public class FileController {
private static final String MESSAGE_1 = "Uploaded the file successfully";
private static final String FILE_NAME = "fileName";
#Autowired
protected StorageImpl storageImpl;
#Autowired
protected FileService fileService;
#GetMapping
public ResponseEntity<Object> findByName(#RequestParam("fileName") String fileName) {
return ResponseEntity
.ok()
.cacheControl(CacheControl.noCache())
.header("Content-type", "application/octet-stream")
.header("Content-disposition", "attachment; filename=\"" + fileName + "\"")
.body(new InputStreamResource(storageImpl.retrieve(fileName)));
}
#PostMapping
public ResponseEntity<Object> save(#RequestParam("file") MultipartFile multipartFile) {
storageImpl.save(multipartFile);
return new ResponseEntity<>(MESSAGE_1, HttpStatus.OK);
}
}
What are the possible reasons causing this bug?

Loading value from json upon start up application

I want to load the values from json file upon the Spring Boot Application is started.
My code for the Configuration File is like the below:
#Configuration
#Getter
public class FedexAPIConfig {
private final static String JSON_FILE = "/static/config/fedex-api-credentials.json";
private final boolean IS_PRODUCTION = false;
private FedexAPICred apiCredentials;
public FedexAPIConfig() {
try (InputStream in = getClass().getResourceAsStream(JSON_FILE);
BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
JSONObject json = new JSONObject();
// this.apiCredentials = new JSONObject(new JSONTokener(reader));
if (IS_PRODUCTION) {
json = new JSONObject(new JSONTokener(reader)).getJSONObject("production");
} else {
json = new JSONObject(new JSONTokener(reader)).getJSONObject("test");
}
System.out.println(json.toString());
this.apiCredentials = FedexAPICred.builder()
.url(json.optString("url"))
.apiKey(json.optString("api_key"))
.secretKey(json.optString("secret_key"))
.build();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and with this, when the application is in progress of startup, values are successfully printed on the console.Startup console log
When I tried to call this value from other ordinary class, like the below:, it brings nothing but just throws NullPointerException... What are my faults and what shall I do?
public class FedexOAuthTokenManager extends OAuthToken {
private static final String VALIDATE_TOKEN_URL = "/oauth/token";
private static final String GRANT_TYPE_CLIENT = "client_credentials";
private static final String GRANT_TYPE_CSP = "csp_credentials";
#Autowired
private FedexAPIConfig fedexApiConfig;
#Autowired
private Token token;
#Override
public void validateToken() {
// This is the part where "fedexApiConfig" is null.
FedexAPICred fedexApiCred = fedexApiConfig.getApiCredentials();
Response response = null;
try {
RequestBody body = new FormBody.Builder()
.add("grant_type", GRANT_TYPE_CLIENT)
.add("client_id", fedexApiCred.getApiKey())
.add("client_secret", fedexApiCred.getSecretKey())
.build();
response = new HttpClient().post(fedexApiCred.getUrl() + VALIDATE_TOKEN_URL, body);
if (response.code() == 200) {
JSONObject json = new JSONObject(response.body().string());
token.setAccessToken(json.optString("access_token"));
token.setTokenType(json.optString("token_type"));
token.setExpiredIn(json.optInt("expires_in"));
token.setExpiredDateTime(LocalDateTime.now().plusSeconds(json.optInt("expires_in")));
token.setScope(json.optString("scope"));
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
fedexApiConfg is null even though I autowired it in prior to call.
And this FedexOAuthTokenManager is called from other #Component class by new FedexOAuthTokenManager()
Did you try like below?
Step 1: Create one Configuration class like below
public class DemoConfig implements ApplicationListener<ApplicationPreparedEvent> {
#Override
public void onApplicationEvent(ApplicationPreparedEvent event) {
//Load the values from the JSON file and populate the application
//properties dynamically
ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
Properties props = new Properties();
props.put("spring.datasource.url", "<my value>");
//Add more properties
environment.getPropertySources().addFirst(new PropertiesPropertySource("myProps", props));
}
To listen to a context event, a bean should implement the ApplicationListener interface which has just one method onApplicationEvent().The ApplicationPreparedEvent is invoked very early in the lifecycle of the application
Step 2: Customize in src/main/resources/META-INF/spring.factories
org.springframework.context.ApplicationListener=com.example.demo.DemoConfig
Step 3: #Value in spring boot is commonly used to inject the configuration values into the spring boot application. Access the properties as per your wish.
#Value("${spring.datasource.url}")
private String valueFromJSon;
Try this sample first in your local machine and then modify your changes accordingly.
Refer - https://www.baeldung.com/spring-value-annotation
Refer - https://www.knowledgefactory.net/2021/02/aws-secret-manager-service-as.html

How to change targetSdkVersion

I am having an issue with target targetSdkVersion.I want to move from 27 to 29 but when change to sdk 29 the app runs but does not display videos.But it displays the videos when it is sdk 27 or less.
Please can someone help me fix this.
/**
* A simple {#link Fragment} subclass.
*/
public class ChannelFragment extends Fragment {
private static String GOOGLE_YOUTUBE_API_KEY = "AIzaSyBJQYpQRTzM5wuuhMUxmP7rvP3lbMGtUZ8";//here you should use your api key for testing purpose you can use this api also
private static String CHANNEL_ID = "UCB_ZwuWCAuB7y0B93qvnkWw"; //here you should use your channel id for testing purpose you can use this api also
private static String CHANNLE_GET_URL = "https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&channelId=" + CHANNEL_ID + "&maxResults=50&key=" + GOOGLE_YOUTUBE_API_KEY + "";
private RecyclerView mList_videos = null;
private VideoPostAdapter adapter = null;
private ArrayList<YoutubeDataModel> mListData = new ArrayList<>();
public ChannelFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_channel, container, false);
mList_videos = (RecyclerView) view.findViewById(R.id.mList_videos);
initList(mListData);
new RequestYoutubeAPI().execute();
return view;
}
private void initList(ArrayList<YoutubeDataModel> mListData) {
mList_videos.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new VideoPostAdapter(getActivity(), mListData, new OnItemClickListener() {
#Override
public void onItemClick(YoutubeDataModel item) {
YoutubeDataModel youtubeDataModel = item;
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra(YoutubeDataModel.class.toString(), youtubeDataModel);
startActivity(intent);
}
});
mList_videos.setAdapter(adapter);
}
//create an asynctask to get all the data from youtube
private class RequestYoutubeAPI extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(CHANNLE_GET_URL);
Log.e("URL", CHANNLE_GET_URL);
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity httpEntity = response.getEntity();
String json = EntityUtils.toString(httpEntity);
return json;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (response != null) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<YoutubeDataModel> parseVideoListFromResponse(JSONObject jsonObject) {
ArrayList<YoutubeDataModel> mList = new ArrayList<>();
if (jsonObject.has("items")) {
try {
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
if (json.has("id")) {
JSONObject jsonID = json.getJSONObject("id");
String video_id = "";
if (jsonID.has("videoId")) {
video_id = jsonID.getString("videoId");
}
if (jsonID.has("kind")) {
if (jsonID.getString("kind").equals("youtube#video")) {
YoutubeDataModel youtubeObject = new YoutubeDataModel();
JSONObject jsonSnippet = json.getJSONObject("snippet");
String title = jsonSnippet.getString("title");
String description = jsonSnippet.getString("description");
String publishedAt = jsonSnippet.getString("publishedAt");
String thumbnail = jsonSnippet.getJSONObject("thumbnails").getJSONObject("high").getString("url");
youtubeObject.setTitle(title);
youtubeObject.setDescription(description);
youtubeObject.setPublishedAt(publishedAt);
youtubeObject.setThumbnail(thumbnail);
youtubeObject.setVideo_id(video_id);
mList.add(youtubeObject);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mList;
}
}

How to fix this method renaming problem with Java 8 ASM

Recently I coded an Obfuscator with ASM in Java and wanted to rename classes, methods, and fields. But the problem is, that the code doesn't work it should too, and I have no clue how to fix that. The problem is, that if I obfuscate a jar every method in the class gets renamed, but sometimes (not every time) a bit of code is not getting renamed, so the jar can't be executed. E.g.
public abstract class ColorThread implements Runnable
{
#Getter
private final String name;
#Getter
private Thread thread;
public ColorThread(final String name) {
this.name = name;
Runtime.getRuntime().addShutdownHook(new Thread(this::close));
}
#Override
public void run() {
throw new NotOverriddenException("The Thread \"" + getName() + "\" is not overwritten.");
}
/**
* This method interrupts the running thread.
*/
public void close() {
this.getThread().interrupt();
}
public void start() { //<- Method gets renamed e.g "⢍⢖⣕⠟⡨⠣"
this.thread = new Thread(this, this.getName());
thread.start();
}
}
So this class got obfuscated but later in other code which calls:
final ConnectThread connectThread = new ConnectThread();
connectThread.start(); // <- this line
the line with connectThread.start(); isn't renamed to "connectThread.⢍⢖⣕⠟⡨⠣();". If I use another class which extends ColorThread e.g. ReceiveThread, the start method gets renamed in this bit of code.
I struggled every time with this problem if I made an Obfuscator and because of it I ended the project. But now I want to ask here if someone can help me. Sorry for this long post, but I wanted to give everything needed to see the problem.
The Project is running on Java 1.8.0_161 with ASM-All as a dependency.
To read a jar i use this method. It will store all classes in an ArrayList:
try (final JarFile jarFile = new JarFile(inputFile)) {
final Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
while (jarEntryEnumeration.hasMoreElements()) {
final JarEntry jarEntry = jarEntryEnumeration.nextElement();
if (jarEntry.isDirectory())
continue;
final byte[] bytes = this.readInputStream(jarFile.getInputStream(jarEntry));
if (jarEntry.getName().endsWith(".class")) {
if (jarEntry.getName().endsWith("module-info.class"))
continue;
final ClassNode classNode = new ClassNode();
// new ClassReader(bytes).accept(classNode, ClassReader.EXPAND_FRAMES | ClassReader.SKIP_DEBUG);
new ClassReader(bytes).accept(classNode, ClassReader.EXPAND_FRAMES);
this.classes.add(classNode);
} else {
if (jarEntry.getName().contains("MANIFEST.MF"))
continue;
this.files.put(jarEntry.getName(), bytes);
}
}
this.manifest = jarFile.getManifest();
} catch (final Exception ex) {
ex.printStackTrace();
}
After this i use my transformation system to rename the methods:
#Override
public void transform(final ArrayList<ClassNode> classes, final HashMap<String, byte[]> files) {
final String mainClass = this.getJarResources().getManifest().getMainAttributes().getValue("Main-Class").replace(".", "/");
final HashMap<String, String> methodNames = new HashMap<>();
for (final ClassNode classNode : classes) {
for (final Object methodObj : classNode.methods) {
if (!(methodObj instanceof MethodNode))
continue;
final MethodNode methodNode = (MethodNode) methodObj;
if (methodNode.name.equals("<init>"))
continue;
if (methodNode.name.equals(mainClass) || methodNode.name.equals("main"))
continue;
methodNames.put(classNode.name + "." + methodNode.name + methodNode.desc, this.generateString(6));
}
}
this.remapClasses(classes, methodNames);
}
The remap method looks like this:
public void remapClasses(final ArrayList<ClassNode> classes, final HashMap<String, String> remappedNames) {
final SimpleRemapper simpleRemapper = new SimpleRemapper(remappedNames);
for (int index = 0; index < classes.size(); index++) {
final ClassNode realNode = classes.get(index);
final ClassNode copyNode = new ClassNode();
final ClassRemapper classRemapper = new ClassRemapper(copyNode, simpleRemapper);
realNode.accept(classRemapper);
classes.set(index, copyNode);
}
}
At the end i write the file:
public void writeFile() {
try (final JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(this.outputFile), this.manifest)) {
for (final ClassNode classNode : this.classes) {
final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
jarOutputStream.putNextEntry(new JarEntry(classNode.name + ".class"));
jarOutputStream.write(writer.toByteArray());
jarOutputStream.closeEntry();
}
for (final Map.Entry<String, byte[]> file : this.files.entrySet()) {
final String filePath = file.getKey();
if(filePath.endsWith(".kotlin_module") || filePath.contains("maven") || filePath.contains("3rd-party-licenses"))
continue;
jarOutputStream.putNextEntry(new JarEntry(filePath));
jarOutputStream.write(file.getValue());
jarOutputStream.closeEntry();
}
} catch (final Exception ex) {
ex.printStackTrace();
}
}

Upload File data into database using spring mvc and hibernate

I need to upload data into 2 database tables(factory and factoryType) using the below form but it isnt working can somebody take a look :
Factory table:factoryId,factoryname
FactoryType table: factoryType,factoryTypeId
FactoryConf table: factoryID,factoryTypeId
We are using hibernate for the database operations.
Model:
#Entity
#Table(name = "FactoryConf", uniqueConstraints = {
#UniqueConstraint(columnNames = { "factoryId" } )
})
public class FactoryConf {
#Id
long factoryId;
#OneToOne
#JoinColumn(name = "factoryId", insertable = false, updatable = false)
Factory factory;
#ManyToOne(optional = false)
#JoinColumn(name = "factoryTypeId")
FactoryType factoryType;
public FactoryConf() {
super();
}
public FactoryConf(long factoryId, FactoryType factoryType) {
super();
this.factoryType = factoryType;
this.factoryId = factoryId;
}
public Factory getFactory() {
return factory;
}
public void setFactory(Factory factory) {
this.factory = factory;
}
public FactoryType getFactoryType() {
return factoryType;
}
public void setFactoryType(FactoryType factoryType) {
this.factoryType = factoryType;
}
public long getFactoryId() {
return factoryId;
}
public void setFactoryId(long factoryId) {
this.factoryId = factoryId;
}
public FactoryType getFactoryTypeByFactoryID(long factoryId){
return factoryType;
}
}
Bean class:
/**
* This bean is defined to parse each record from the CSV file.
* All records are mapped to instances of this bean class.
*
*/
public class FactoryCSVFileInputBean {
private String upload_id;
private String file_name;
private byte file_data;
private long Id;
private String Name;
private String Type;
//getter setters
}
CSV parsing:
/**
* This class is defined for following actions
* 1. Validate the input CSV file format, header columns.
* 2. Parse the CSV file into a list of beans.
* 3. Validate input records with missing data and prepare a valid factory list to be processed. *
*/
public class FactoryCSVUtil {
private static Log log = LogFactory.getLog(FactoryCSVUtil.class);
private static final List<String> fileHeaderFields = new ArrayList<String>();
private static final String UTF8CHARSET = "UTF-8";
static{
for (Field f : FactoryCSVFileInputBean.class.getDeclaredFields()) {
fileHeaderFields.add(f.getName());
}
}
public static List<FactoryCSVFileInputBean> getCSVInputList(InputStream inputStream){
CSVReader reader = null;
List<FactoryCSVFileInputBean> csvList = null;
FactoryCSVFileInputBean inputRecord = null;
String[] header = null;
String[] row = null;
try {
reader = new CSVReader(new InputStreamReader(inputStream,UTF8CHARSET));
csvList = new ArrayList<FactoryCSVFileInputBean>();
header = reader.readNext();
boolean isEmptyLine = true;
while ((row = reader.readNext()) != null) {
isEmptyLine = true;
if(!(row.length==1 && StringUtils.isBlank(row[0]))){//not an empty line, not even containing ','
inputRecord = new FactoryCSVFileInputBean();
isEmptyLine = populateFields(inputRecord, header, row);
if(row.length != header.length)
//inputRecord.setUploadStatus("Not Loaded - Missing or invalid Data");
if(!isEmptyLine)
csvList.add(inputRecord);
}
}
} catch (IOException e) {
log.debug("IOException while accessing FactoryCSVFileInputBean: " + e);
return null;
} catch (IllegalAccessException e) {
log.debug("IllegalAccessException while accessing FactoryCSVFileInputBean: " + e);
return null;
} catch (InvocationTargetException e) {
log.debug("InvocationTargetException while copying FactoryCSVFileInputBean properties: " + e);
return null;
} catch (Exception e) {
log.debug("Exception while parsing CSV file: " + e);
return null;
}finally{
try{
if(reader!=null)
reader.close();
}catch(IOException ioe){}
}
return csvList;
}
protected static boolean populateFields(FactoryCSVFileInputBean inputRecord,String[] header, String[] row) throws IllegalAccessException, InvocationTargetException {
boolean isEmptyLine = true;
for (int i = 0; i < row.length; i++) {
String val = row[i];
if(!StringUtils.isBlank(val)){
BeanUtilsBean.getInstance().copyProperty(inputRecord, header[i], val);
isEmptyLine = false;
} else {
//inputRecord.setUploadStatus(String.format("Not Loaded - Missing or invalid Data for:%s",header[i]));
}
}
return isEmptyLine;
}
public static void validateInputFile(CommonsMultipartFile csvFile, Model model){
InputStream inputStream = null;
CSVReader reader = null;
String fileName = csvFile.getOriginalFilename();
String fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
if(fileExtension.toUpperCase().equals("CSV")){
try{
inputStream = csvFile.getInputStream();
reader = new CSVReader(new InputStreamReader(inputStream,UTF8CHARSET));
String[] header = reader.readNext();
if(header!=null){
for (int i = 0; i < header.length; i++) {
if(!header[i].equals("") && !fileHeaderFields.contains(header[i])){
log.debug("Invalid Column found in upload file: " + header[i]);
model.addAttribute("failureMsg", "Invalid Column found in upload file: " + header[i]);
break;
}
}
for(csvHeaderFieldsEnum field : csvHeaderFieldsEnum.values()){
if(!Arrays.asList(header).contains(field.getValue())){
log.debug("Missing column in upload file: " + field.getValue());
model.addAttribute("failureMsg", "Missing column in upload file: " + field.getValue());
break;
}
}
}else{
model.addAttribute("failureMsg", "File is Empty - Please select a valid file");
}
String[] data = reader.readNext();
if(data==null){
log.debug("Empty file with header - No data found");
model.addAttribute("failureMsg", "Empty file with header - No data found");
}
}catch(IOException e){
log.debug("IOException in reading the CSV file: " + e);
model.addAttribute("failureMsg", "Exception in reading the CSV file");
}finally{
if(reader!=null)
try{
reader.close();
}catch(IOException e){ log.debug("IOException in closing reader of CSV file: " + e);}
}
}
else{
model.addAttribute("failureMsg", "Invalid file format - Please select a CSV file");
}
}
}
Model
public class FactoryUploadForm {
private CommonsMultipartFile fileData;
private String uploadComment;
/**
* #return the fileData
*/
public CommonsMultipartFile getFileData() {
return fileData;
}
/**
* #param fileData the fileData to set
*/
public void setFileData(CommonsMultipartFile fileData) {
this.fileData = fileData;
}
/**
* #return the uploadComment
*/
public String getUploadComment() {
return uploadComment;
}
/**
* #param uploadComment the uploadComment to set
*/
public void setUploadComment(String uploadComment) {
this.uploadComment = uploadComment;
}
public String toString(){
return " CSVFileName: " + getFileData().getOriginalFilename() + "; Upload Comment: " + uploadComment;
}
}
Controller
#Controller
public class FactoryUploadDownloadController {
private static final Log logger = LogFactory.getLog(FactoryUploadDownloadController.class);
#Resource
Service Service;
#Resource
FactoryUploadRepository repository;
#RequestMapping(value = "/submitUploadFactoryForm")
public String uploadFactory(FactoryUploadForm uploadform,
HttpServletRequest request, Model model, BindingResult result) {
logger.debug("====================================================================");
List<FactoryCSVFileInputBean> csvList = null;
List<FactoryType> factoryTypes = Service.getFactoryTypes();
try {
CommonsMultipartFile file = uploadform.getFileData();
// parse csv file to list
csvList = FactoryCSVUtil.getCSVInputList(file.getInputStream());
if (csvList == null) {
model.addAttribute("failureMsg","Error in file parsing - Please verify the file");
logger.debug("---------------------------------------------------------");
return "sucess";
}
} catch (Exception e) {
logger.debug("sorry this isn't working for you");
}
try {
CommonsMultipartFile file = uploadform.getFileData();
for (FactoryCSVFileInputBean inputRecord : csvList) {
Factory factoryentity = new Factory();
factoryentity.setId(inputRecord.getId());
factoryentity.setName(inputRecord.getName());
factoryentity = this.Service.saveFactory(factoryentity);
FactoryConf factoryconf = new FactoryConf();
factoryconf.setFactory(factoryentity);
factoryconf.setFactoryType(pickFactoryType(factoryTypes,inputRecord.getType()));
model.addAttribute("factoryconf", factoryconf);
this.Service.savefactoryCfg(factoryconf);
}
} catch (Exception e) {
logger.debug("sorry this isnt working for you");
}
return "success";
}
private FactoryType pickFactoryType(List<FactoryType> types, String typeName) {
for (FactoryType type : types) {
if (type.getFactoryType().equalsIgnoreCase(typeName))
return type;
}
throw new RuntimeException(String.format("Factory Type Invalid :%s", typeName));
}
}
From your question, I understand that you are not able to parse data from a CSV file. Here is sample code for similar task. I think it should help.

Resources