Download and Upload Images In Google Cloud Storage

Hey guys, recently I was working on a application where I need to upload the images in google Cloud storage, I searched a lot and started banging my head on the wall because there was so many tutorial out there and none was fitting into my use case.
My usecase was, my client application (which is mobile developed in react-native) sending me image base64 string and json data together, when I searched on stackoverflow and GCS docs all were using either multipart or some other annotation, but those were not useful for me as my usecase was..( as mentioned above).
So after spending a day I wrote some code which is working for me.
I am posting here a sample code for uploading and download Images (basically base64) from and to Google Cloud storage,
I have a SpringBoot Application deployed on Google App Engine.
My Client Side application is written in React-Native
Client is sending me some Data and Image base64 string in one single json object like below

{
    "code":"BA001",
    "date":"24-04-1992",
    "mobile":"9202209519",
    "remarks":"remarks",
    "reminderDate":"12-04-2016",
    "amount":"5000",
    "document":"base64 Image"
}
 In My document element I am getting an Image (which is base64 String) which is coming in string format.

Here is my controller

@RequestMapping(value="/saveLeadDetails",method=RequestMethod.POST)
    public @ResponseBody ResponseSchema saveDetails(@RequestBody RequestSchema request) {
        ResponseSchema response = service.saveDetails(request);
        return response;
    }
In my pojo class the document element is declared as String

@JsonProperty("document")
private String document;


@JsonProperty("document")
public String getDocument() {
return document;
}

@JsonProperty("document")
public void setDocument(String document) {
this.document = document;
}

Now here comes the main part

@Override
    public ResponseSchema saveLeadDetails(RequestSchema request) {
        ResponseSchema response = new ResponseSchema();
        try {
            String id= UploadDocuments(request);
            String data = downloadObject();
            Generationdb req = new Generationdb();
            req.setAmount(request.getAmount());
            req.setBranchCode(request.getBranchCode());
            req.setInterestedIn(request.getInterestedIn());
            req.setMobile(request.getMobile());
            req.setName(request.getName());
            req.setProduct(request.getProduct());
            req.setRemarks(request.getRemarks());
            req.setReminderDate(request.getReminderDate());
            req.setDocument(id);
            leadGenerationRepository.save(req);
            response.setStatus(data);
            response.setResponseCode(ApplicationConstant.SUCCESS_CODE);
            response.setResponseMessage(ApplicationConstant.SUCCESS_MESSAGE);
          
        }catch(Exception e){
            response.setResponseCode(ApplicationConstant.ERROR_CODE);
            response.setResponseMessage(ApplicationConstant.FAILURE_MESSAGE);
            response.setErrorMessage("ERROR001-"+e.getMessage());
        }
        return response;
    }

This code is used to upload the Image in google Cloud Storage which will take base64 String and it will decode the Base64 string and will upload it into your bucket.
private String UploadDocuments(RequestSchema request) {
       final String fileName = "myImage"; 
try {
        String bucketName = "documents";
        Date date= new Date();
        long time = date.getTime();
       // InputStream ipstream = convertMultiPartToFile( request.getDocument() );
        Credentials credentials = GoogleCredentials.fromStream(MyClass.class.getClassLoader().getResourceAsStream("gcs-ba943a4c3871.json")); // use this if .json file is in your project resource folder
       // Credentials credentials = GoogleCredentials.fromStream(new FileInputStream("/Users/username/Desktop/gcs-ba943a4c3871.json")); // use this if .json file is outside project (In my case its desktop)
        Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
        BlobId blobId = BlobId.of(bucketName, fileName);
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
        Blob blob = storage.create(blobInfo, Base64.decodeBase64(request.getDocument().getBytes()));
        }catch(Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }
    This code us used te get the base64 string from your gcs bucket, it will get the content in byte[] and encode it in base64
    private String downloadObject() {
        String PROJECT_ID = "project-id";
        String BUCKET_NAME = "documents";
        String OBJECT_NAME = "myImage";
        StorageOptions options = null;
        try {
            options = StorageOptions.newBuilder()
                    .setProjectId(PROJECT_ID)              .setCredentials(GoogleCredentials.fromStream(FinomaticServiceImpl.class.getClassLoader().getResourceAsStream("gcs-ba943a4c3871.json"))).build();ba943a4c3871.json"))).build();
        } catch (IOException e) {
            e.printStackTrace();
        }

    Storage storage = options.getService();
    Blob blob = storage.get(BUCKET_NAME, OBJECT_NAME);
    byte[] content = blob.getContent(BlobSourceOption.generationMatch());
    String s = new String(content);
    byte[] encodedBytes = Base64.encodeBase64(content);
    return new String(encodedBytes);
    }

so now everything is done,
feel free to contact in case of any issue.

email - behappiest1992@gmail.com

Happy Coding 🙏



Apple and Orange Solution

public class Test
{
    public static void main(String[] args) throws ParseException
    {
        int[] apple = {-2,2,1};
        int[] orange = {5,-6};
        countApplesAndOranges(7,11,5,15,apple,orange);
       
    }

    private static void countApplesAndOranges(int s, int t, int a, int b, int[] apple, int[] orange) {
       
        int apple_length = apple.length;
        int orange_lrngth = orange.length;
        List<Integer> lstApple = new ArrayList<>();
        List<Integer> lstOrange = new ArrayList<>();
        for (int i = 0; i < apple_length; i++) {
            int length = a + (apple[i]);
            lstApple.add(length);
        }
        for (int i = 0; i < orange_lrngth; i++) {
            int length = b + (orange[i]);
            lstOrange.add(length);
        }
       
        //System.out.println(lstApple);
        //System.out.println(lstOrange);
       
        int countApple=0;
        int countOrange=0;
        for (Iterator iterator = lstApple.iterator(); iterator.hasNext();) {
            Integer integer = (Integer) iterator.next();
            if(integer>=s && integer<=t) {
                countApple++;
            }
        }
        for (Iterator iterator = lstOrange.iterator(); iterator.hasNext();) {
            Integer integer = (Integer) iterator.next();
            if(integer>=s && integer<=t) {
                countOrange++;
            }
        }
        System.out.println(countApple);
        System.out.println(countOrange);
       
    }       
}

Yadon ka daman

yadon k daman se kuch tasvirein chupa rakhi hai,
tasviron k saye me khud ko chupa rakha hai,
Nikle the ghar se duniya ko badalne,
Jab dekhe alag alag se log, to khud hi badal gae,
Na thi apne ki samjh, na paaraye ki pahchaan,
Jo bhi mila, jisse bhi mila, dil me basa k chal diya,
Waqt ki karwat ne sab kuch dikha diya,
kaun hai apna, kaun hai paraya, sabne bata diya,
chale the akele, aj bhi hai akele,
logo ne khub hame ache se sikhaya,
na chalna unrahon pe jinme pade ho kante,
badh chalna un rahon pe jo tumko hai kuch sikhate


Written By Suraj Shukla

Happy B'day sisi

A piece of poetry written on my sister's birthday.

Happy birthday betu........luv u a lot. god bless u sisi 

I met u at the age of 1
from the starting of our life
we are having fun.

U are the first one, who tried to copy
the way I ate, the way I learn
from the chapati roll, silly games , and
to the ever continuing urge.

U are my first friend on dis earth
I have never been an enigma for u
with whom there's no need to share my fervid emotions
as u can easily know them with my evil gestures.

U have got a golden heart
which is lucid as color of sky
as there's us as ur lovely mates .


~~ Prachi Gupta

Code for making gallery in C# for android in xamarin

Hey folks

Here is the great relax for those who want to make a gallery in xamarin for android.I am sharing its code which you can use anywhere.
To run this code, xamarin  must be installed in your PC.

Note :- Xamarin wont work on Windows Xp, it runs on Windows 7 and advance.

Here is the Screenshot of that running code.

Language Used :- c#
FrameWork :- xamarin


 Download Code

 If you have any problem then please let me know.

Thank you

Happy Coding :-)