<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harsh Ghuriani on Medium]]></title>
        <description><![CDATA[Stories by Harsh Ghuriani on Medium]]></description>
        <link>https://medium.com/@harsh.ghuriani?source=rss-7e62d3bebca7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4MNDk4ljD0yAi4g--qW10A.jpeg</url>
            <title>Stories by Harsh Ghuriani on Medium</title>
            <link>https://medium.com/@harsh.ghuriani?source=rss-7e62d3bebca7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:41:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harsh.ghuriani/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Export Functionality via Google Cloud Functions and Java]]></title>
            <link>https://medium.com/globant/export-functionality-via-google-cloud-functions-and-java-12a34df00458?source=rss-7e62d3bebca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/12a34df00458</guid>
            <category><![CDATA[export-data]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[apache-poi]]></category>
            <category><![CDATA[google-cloud-functions]]></category>
            <category><![CDATA[function-as-a-service]]></category>
            <dc:creator><![CDATA[Harsh Ghuriani]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 13:12:48 GMT</pubDate>
            <atom:updated>2022-09-30T13:12:48.953Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Tech Used : Java, Gradle, GCP</blockquote><p>Google Cloud Function (GCF) is a serverless architecture where you can build small cloud services. Services can be written down in different languages including Python, Node.js, Java, PHP, and a few others. GCF is aimed to serve one purpose, hence the service we create should not be quite large functionality. What I feel is that we should break down large functionalities into simpler &amp; smaller services which can be written down into their own GCFs.</p><p>GCFs are triggered by different events. These events can either be HTTP triggers, event based triggers or some additional triggers. I am going to focus on the event based triggers, pub/sub trigger in particular.</p><blockquote><strong>Note</strong> : As of now, the maximum function execution time is 3600 seconds(60 mins) for HTTP-driven functions and 540 seconds(9 mins) for event-driven functions, after which the function times out.</blockquote><p>Other triggers include cloud storage triggers (event based), cloud logging, cloud scheduler, cloud task and gmail.</p><p>Here I take an example of export functionality which we create as a service in our GCF. This GCF will be triggered by subscribing to an event emitted to a GCP topic.</p><h3>Export Functionality</h3><p>The export functionality that I create involves exporting data into an excel file. I then store this excel file to cloud storage.</p><p>This excel file can then be downloaded from storage using a pre-signed url. (I am not going to cover this part here)</p><p>We use Java in our GCF and for the excel generation I use Apache POI dependency.</p><p><strong>Design</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1oeH4cM3B-AQtGGGKkw0LA.png" /><figcaption>End to End Export Functionality</figcaption></figure><p>Once the event is published from the source to the Pub/Sub topic, say <strong>export-topic</strong>, it will be subscribed by our subscription, say <strong>export-to-excel-sub</strong>, provided it passes the filters required (if any). This subscription will be a push subscription. Hence, on subscribing to the event, it will trigger our GCF.</p><p>To deploy the GCF, below command can be used :</p><pre>gcloud functions deploy export-function --entry-point functions.ExportToExcel --runtime java17 --trigger-http --memory 512MB --allow-unauthenticated</pre><p>where ExportToExcel is the name of the GCF’s qualified class name just similar to a SpringBoot Application class name.</p><p>The endpoint for our GCF can be fetched either from the GCF deployment logs or through this command, after deployment, on google cloud console :</p><pre>gcloud functions describe export-function</pre><p>Here, export-function is the name for our GCF which is registered with google cloud.</p><p>This is how an endpoint would like :</p><pre>https://GCP_REGION-PROJECT_ID.cloudfunctions.net/export-function</pre><p>Below is a sample of how my GCP subscription looks like with the push endpoint for GCF:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Um7JzvnLitvuU0PMH_411A.jpeg" /><figcaption>GCP subscription — export-to-excel-sub</figcaption></figure><p>To test the GCF locally, below command can be used to generate the endpoint:</p><pre>gradle runFunction -Prun.functionTarget=functions.ExportToExcel</pre><p>This provides us with a local endpoint, <a href="http://localhost:8080/"><em>http://localhost:8080/</em></a> , which can be used to test the functionality.</p><h3>Defining Dependencies</h3><p>I have been using Gradle, so this is how the dependency part of my build.gradle looks like :</p><pre>dependencies {<br>  // Necessary to have Functions Framework API.<br>  compileOnly &#39;com.google.cloud.functions:functions-framework-api:1.0.4&#39;<br><br>  // Necessary to run function locally<br>  invoker &#39;com.google.cloud.functions.invoker:java-function-invoker:1.1.0&#39; </pre><pre>  // Needed to access Microsoft format files (Excel in our case)<br>  implementation &#39;org.apache.poi:poi-ooxml:5.2.2&#39;</pre><pre>  // Only needed by the tests.<br>  testImplementation &#39;com.google.cloud.functions:functions-framework-api:1.0.4&#39;<br>  testImplementation &#39;junit:junit:4.13.2&#39;<br>  testImplementation &#39;com.google.truth:truth:1.1.3&#39;<br>  testImplementation &#39;org.mockito:mockito-core:4.5.1&#39;<br><br>}</pre><p>To run the GCF locally, the function needs to be registered like below in build.gradle :</p><pre>// Register a &quot;runFunction&quot; task<br>tasks.register(&quot;runFunction&quot;, JavaExec) <strong>{<br>    </strong>main = &#39;com.google.cloud.functions.invoker.runner.Invoker&#39;<br>    classpath(configurations.invoker)<br>    inputs.files(configurations.runtimeClasspath, sourceSets.main.output)<br>    args(<br>            &#39;--target&#39;, project.findProperty(&#39;run.functionTarget&#39;) ?: &#39;functions.<strong>ExportToExcel</strong>&#39;,<br>            &#39;--port&#39;, project.findProperty(&#39;run.port&#39;) ?: 8080<br>    )<br>    doFirst <strong>{<br>        </strong>args(&#39;--classpath&#39;, files(configurations.runtimeClasspath, sourceSets.main.output).asPath)<br>    <strong>}<br>}</strong></pre><h3>Creating the Source File</h3><p>Inside the source directory of our project, I create our source file : ExportToExcel.java .</p><pre>src/main/java/functions/ExportToExcel.java</pre><p>This is how the initial file looks like :</p><pre>package functions;<br><br>import com.google.cloud.functions.HttpFunction;<br>import com.google.cloud.functions.HttpRequest;<br>import com.google.cloud.functions.HttpResponse;<br>import java.io.BufferedWriter;<br>import java.io.IOException;<br><br>public class ExportToExcel implements HttpFunction {<br>  // Cloud function to create an Excel containing some data and upload it onto cloud storage<br>  @Override<br>  public void service(HttpRequest request, HttpResponse response)<br>      throws IOException {<br>    BufferedWriter writer = response.getWriter();<br>    writer.write(&quot;Excel Exporter&quot;);<br>  }<br>}</pre><p>Every Http triggered GCF implements the HttpFunction interface which is a functional interface. Hence an action needs to be provided to the service method. The service method is called to handle the Http request.</p><p>Data is read from the request and after our action is complete, the response should be written into response.</p><p>On reading the input request, I try to make a connection to the database and fetch the required data. The resultset is then processed and stored in the excel file.</p><p>Either <strong>HSSFWorkbook</strong> or <strong>XSSFWorkbook</strong> or <strong>SXSSFWorkbook</strong> class of apache poi library can be used to create an excel file.</p><p>XSSFWorkbook is slower as it keeps the all its cells in-memory till the time the excel is saved. Hence, after a point of time it runs out of the heap memory. On the other hand, SXSSFWorkbook is the streaming extension of XSSFWorkbook.</p><blockquote><strong>Note : </strong>SXSSFWorkbook implements a strategy that allows to write very large files without running out of memory as only a configurable portion of the rows are kept in memory at any one time.</blockquote><p>The number of rows to be kept in-memory for SXSSFWorkbook, until they are flushed out, can be done during its object creation through an integer parameter named ‘<strong>rowAccessWindowSize</strong>’.</p><p>Assuming that I have a large resultSet fetched from the DB , below is my sample code for how to export the data into excel :</p><p><strong>createExportFileForData</strong><em> method is used to populate the Excel file and upload it to GCS bucket. It returns either “EXPORTED” or “FAILED” string message to be passed on to the http response. It is the entry point to our functionality and takes the data to be exported as input.</em></p><pre><em><br>    </em>public String <strong>createExportFileForData</strong>(ResultSet data) {<br>        //Default file status<br>        String file_status = &quot;EXPORTED&quot;;<br>        //Default_Window_Size is 100<br>        try (SXSSFWorkbook workbook = new SXSSFWorkbook(SXSSFWorkbook.<em>DEFAULT_WINDOW_SIZE</em>)) {<br>            //Sheet name as parameter<br>            Sheet sheet = workbook.createSheet(&quot;SHEET_NAME&quot;);<br>            <em>createSheetHeader</em>(workbook, sheet);<br>            <em>createSheetBody</em>(workbook, sheet, data);</pre><pre>            //To upload the file to GCS, we need byte array, hence we write the workbook to ByteArrayOutputStream.<br>            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();<br>            workbook.write(outputStream);<br>            uploadToBucket(outputStream.toByteArray(), &quot;FileName.xlsx&quot;);<br>        }<br>        catch (Exception e) {<br>            <em>LOGGER</em>.info(&quot;Failed to generate and upload file to storage&quot;);<br>            <em>LOGGER</em>.warning(&quot;Error : &quot; + e);<br>            file_status = &quot;FAILED&quot;;<br>        }<br>        return file_status;<br>    }</pre><p><strong>createSheetBody </strong><em>method is used to write data into the Excel Sheet. It is called from createExportFileForData method.</em></p><pre><em>    </em>private void <strong>createSheetBody</strong>(SXSSFWorkbook workbook, Sheet sheet, ResultSet data) throws SQLException {<br><br>        //Row 0 would be the header row<br>        int rowNumber = 1;<br>        while(data.next()) {<br>            Row dataRow = sheet.createRow(rowNumber++);<br>            <em>createSheetCell</em>(dataRow, 0, data.getObject(&quot;name&quot;, String.class));<br>            <em>createSheetCell</em>(dataRow, 1, data.getObject(&quot;address&quot;, String.class));<br>//            .<br>//            .<br>//            .<br>            <em>createSheetCell</em>(dataRow, <em>N</em>, data.getObject(&quot;phone_no&quot;, String.class));<br>        }<br>    }</pre><p><strong>createSheetHeader</strong><em> method creates the header row for the data sheet. It is called from createExportFileForData method.</em></p><pre>private void <strong>createSheetHeader</strong>(SXSSFWorkbook workbook, Sheet sheet) {<br>        //Creating an SXSSFRow for row number 0 (index starts from 0)<br>        Row headerRow = sheet.createRow(0);<br>        Font headerFont = workbook.createFont();<br>        headerFont.setBold(true);<br>        <br>        <em>fillHeaderData</em>(headerRow);<br>    }</pre><p><strong>fillHeaderData</strong><em> method is used to fill the header row (Column Names). It is called from </em>createSheetHeader<em> method.</em></p><pre>private void <strong>fillHeaderData</strong>(Row headerRow) {<br>        //Passing columnNo and value to the createSheetCell method<br>        <em>createSheetCell</em>(headerRow, 0, &quot;Name&quot;);<br>        <em>createSheetCell</em>(headerRow, 1, &quot;Address&quot;);<br>        //Similar n cells<br>//        .<br>//        .<br>//        .<br>        <em>createSheetCell</em>(headerRow, <em>N</em>, &quot;Phone Number&quot;);<br>    }</pre><p><strong>createSheetCell</strong><em> method is used to create each cell of the row. It is called from </em>createSheetHeader<em> method.</em></p><pre>private void <strong>createSheetCell</strong>(Row row, int columnNo, Object value) {<br>    Cell cell = row.createCell(columnNo);<br>    if (value == null) {<br>        cell.setCellValue(&quot;&quot;);<br>    } else if (value instanceof String) {<br>        cell.setCellValue((String) value);<br>    } else if (value instanceof Timestamp) {<br>        cell.setCellValue(((Timestamp) value).toLocalDateTime().format(DateTimeFormatter.<em>ISO_LOCAL_DATE_TIME</em>));<br>    } else if (value instanceof BigInteger) {<br>        cell.setCellValue(((BigInteger) value).doubleValue());<br>    } else if (value instanceof UUID) {<br>        cell.setCellValue(value.toString());<br>    } else if (value instanceof BigDecimal) {<br>        cell.setCellValue(String.<em>valueOf</em>(value));<br>    }<br>}</pre><p><strong><em>uploadToBucket</em></strong><em> method is called from createExportFileForData method and is used to upload my export file to the GCP bucket.</em></p><pre>private void <strong>uploadToBucket</strong>(byte[] bytes, String fileName) {<br>        String bucketName = &quot;BUCKET_NAME&quot;;<br>        //Using the google cloud lib classes to insert the byte data of the file into the blob and upload it to GCS bucket<br>        BlobId blobId = BlobId.<em>of</em>(bucketName, fileName);<br>        //BlobInfo will contain the info about in GCS<br>        BlobInfo blobInfo = BlobInfo.<em>newBuilder</em>(blobId).build();<br>        Storage storage = StorageOptions.<em>newBuilder</em>().setProjectId(&quot;PROJECT_NAME&quot;).build().getService();<br>        storage.create(blobInfo, bytes);<br>    }</pre><h3>Conclusion</h3><p>GCFs, serving Function as a service(FaaS), are helpful when a functionality is to be performed in response to event triggers. GCFs are extremely useful in case of small requests aiming to fulfil single action/ purpose.</p><blockquote>More languages and triggers are being continuously added to Google Cloud Functions.</blockquote><h4>References</h4><p><a href="https://cloud.google.com/functions/docs/"><em>https://cloud.google.com/functions/docs/</em></a></p><p><a href="https://poi.apache.org/apidocs/4.0/org/apache/poi/xssf/"><em>https://poi.apache.org/apidocs/4.0/org/apache/poi/xssf/</em></a></p><p><a href="https://andriymz.github.io/misc/apache-poi-slow-excel-generation/"><em>https://andriymz.github.io/misc/apache-poi-slow-excel-generation/</em></a></p><p>#googlecloudfunction #java # apachepoi #exportdata #excelfilegenerate #faas #gcf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a34df00458" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/export-functionality-via-google-cloud-functions-and-java-12a34df00458">Export Functionality via Google Cloud Functions and Java</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>