Thursday, 25 June 2020

CSV read and write using apache common csv

https://www.callicoder.com/java-read-write-csv-file-apache-commons-csv/

Reading a CSV file (Access Values by Names assigned to each column)

In the earlier example, We accessed the values in each record using their column index. If you don’t want to use column indexes to retrieve the values in each record, then you can assign names to each column in the CSV file and retrieve the values using the assigned names.
Check out the following example where we define a manual header and retrieve the values using the header names.
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;

public class CSVReaderWithManualHeader {
    private static final String SAMPLE_CSV_FILE_PATH = "./users.csv";

    public static void main(String[] args) throws IOException {
        try (
            Reader reader = Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH));
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
                    .withHeader("Name", "Email", "Phone", "Country")
                    .withIgnoreHeaderCase()
                    .withTrim());
        ) {
            for (CSVRecord csvRecord : csvParser) {
                // Accessing values by the names assigned to each column
                String name = csvRecord.get("Name");
                String email = csvRecord.get("Email");
                String phone = csvRecord.get("Phone");
                String country = csvRecord.get("Country");

                System.out.println("Record No - " + csvRecord.getRecordNumber());
                System.out.println("---------------");
                System.out.println("Name : " + name);
                System.out.println("Email : " + email);
                System.out.println("Phone : " + phone);
                System.out.println("Country : " + country);
                System.out.println("---------------\n\n");
            }
        }
    }
}




Generating a CSV file

Finally, Let’s see an example of generating a CSV file with Apache Commons CSV.
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class CSVWriter {
    private static final String SAMPLE_CSV_FILE = "./sample.csv";

    public static void main(String[] args) throws IOException {
        try (
            BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE));

            CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
                    .withHeader("ID", "Name", "Designation", "Company"));
        ) {
            csvPrinter.printRecord("1", "Sundar Pichai ♥", "CEO", "Google");
            csvPrinter.printRecord("2", "Satya Nadella", "CEO", "Microsoft");
            csvPrinter.printRecord("3", "Tim cook", "CEO", "Apple");

            csvPrinter.printRecord(Arrays.asList("4", "Mark Zuckerberg", "CEO", "Facebook"));

            csvPrinter.flush();            
        }
    }
}
The above program will generate the following CSV file -
ID,Name,Designation,Company
1,Sundar Pichai ♥,CEO,Google
2,Satya Nadella,CEO,Microsoft
3,Tim cook,CEO,Apple
4,Mark Zuckerberg,CEO,Facebook

Tuesday, 19 May 2020

Access modifier in java

Access modifier in java
1. default
2. private
3. protected
4. public

1.default:-

-If you dont define any access modifier for any method in java then that method will access within same package  classes defined under the package.

- if try to access method outside the package you will get error.
Note:- if class is public but method is default then again you will get error.

Note if class is not public but method is public again you will get error at package import in another package.

2.private :- private access modifier method or variable accessed within the class.If you try to access method out the class the class you will get error .
even the class in same package.
 you can not declare a class private .you will get error.

3.protected  method you cant access outside the package. You will get protected method access within the same package classes .

Note:- If you want to access protected method in another package then 
extends another package class with method class name which contain protected method.
then create the object  of current class and call protected method .

Public :- accessible every where no rstriction.
 

Wednesday, 6 May 2020

interceptor in spring boot

https://medium.com/@dila.gurung/intercepting-incoming-request-using-springs-interceptor-bc1300e03f9


registry.addInterceptor(new LogInterceptor()).addPathPatterns("/secure-code");
//addPathPattern ensure that interceptor is levied to specified pattern. In our case it is applicable to path with this pattern "/admin/login"
Similiary path can be exculded from intercepting using code given below.
" registry.addInterceptor(new LogInterceptor()).addPathPatterns("/secure-code/*").excludePathPatterns("/secure-code/public"); "


https://stackoverflow.com/questions/34970179/exclude-spring-request-handlerinterceptor-by-path-pattern



@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleInterceptor());
        registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");

        // multiple urls (same is possible for `exludePathPatterns`)
        registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*", "/admin/**", "/profile/**");
    }
}

Tuesday, 5 May 2020

download file instead of open in browser

 $s3Client = new S3Client(array(
           'version'     => 'latest',
           'region'      => env('lambda_region'),
           'credentials' => array(
               'key'    => env('s3_accessKey'),
               'secret' => env('s3_secretKey')
           )
       ));
       $result =  $s3Client->putObject(array(
           'Bucket'     => env('s3_bucket'),
           'Key'        => $fileName,
           'SourceFile' => $localfilePath,
           'ContentType' =>'image/png',
           'ContentDisposition' => 'attachment',
           'ACL'          => 'public-read'
       ));
     return $result['ObjectURL'];
   }