java - How to return a file with Google Cloud Endpoints? -
i have method generate csv file db records
public static void generatecsvforattendees( list<attendee> attendeelist ) throws filenotfoundexception { printwriter pw = new printwriter(new file("test.csv")); stringbuilder sb = new stringbuilder(); //header sb.append( "id" ); sb.append( ',' ); sb.append( "name" ); sb.append( ',' ); sb.append( "lastname" ); sb.append('\n'); //content for( attendee attendee: attendeelist ) { sb.append( attendee.getid() ); sb.append( ',' ); sb.append( attendee.getuser().getname() ); sb.append( ',' ); sb.append( attendee.getuser().getlastname() ); sb.append( '\n' ); } pw.write(sb.tostring()); pw.close(); }
i method endpoint in order invoke kind of client (web or mobile) download it. in google cloud endpoint documentation there isn't file valid return type. how create , endpoint return file?
here how save file endpoint cloud storage , return url downloading it.
1/ activate google cloud storage in project console
2/ create bucket in cloud storage instance, name bucketname. optional: can set access rights on bucket.
3/ in endpoint class, create gcsservice folllow:
private final gcsservice gcsservice = gcsservicefactory.creategcsservice(new retryparams.builder() .initialretrydelaymillis(10) .retrymaxattempts(10) .totalretryperiodmillis(15000) .build());
4/ in method, create bytearrayoutputstream:
bytearrayoutputstream os = new bytearrayoutputstream();
5/ create printer bytearrayoutputstream
6/ following:
bytebuffer buf = bytebuffer.wrap(os.tobytearray()); gcsfilename gcsfilename = new gcsfilename(bucketname, bucketfilename); //bucketfilename = file name gcsfileoptions options = new gcsfileoptions.builder().mimetype("text/plain").build(); gcsoutputchannel outputchannel = gcsservice.createorreplace(gcsfilename, options); outputchannel.write(buf); outputchannel.close();
7/ file should saved cloud storage: have return in string wrapper url open it. following documentation decide url use (depending on whether user shall authenticated or not, see section "a user granted read access object") https://cloud.google.com/storage/docs/cloud-console#_accessing