Skip to content

Instantly share code, notes, and snippets.

@aakash14goplani
Last active July 8, 2018 12:46
Show Gist options
  • Select an option

  • Save aakash14goplani/ea42fc836c4cd06a57c31d5fa0d76202 to your computer and use it in GitHub Desktop.

Select an option

Save aakash14goplani/ea42fc836c4cd06a57c31d5fa0d76202 to your computer and use it in GitHub Desktop.
Automation
<%@ taglib prefix="cs" uri="futuretense_cs/ftcs1_0.tld"
%><%@ taglib prefix="asset" uri="futuretense_cs/asset.tld"
%><%@ taglib prefix="ics" uri="futuretense_cs/ics.tld"
%><%@ taglib prefix="render" uri="futuretense_cs/render.tld"
%><%@ page import="java.text.SimpleDateFormat, org.apache.commons.lang.StringEscapeUtils, java.util.regex.*, java.util.*, COM.FutureTense.Interfaces.*"
%><%
 /******************************************************************************************************************************
   *    Element Name        :  Practice/Automation/WriteAssetDataToCSV
   *    Author              :  Aakash Goplani 
   *    Creation Date       :  (20/06/2018) 
   *    Description         :  This element reads the asset id instance and then makes a call to CreateNestedAssets element
   *						   to fetch csvString and build a CSV file
   *    Input Parameters    :  Asset Id instance (i.e. comma seperated 'asset_type:asset_id')
   *    Output              :  CSV file with Asset Data
 *****************************************************************************************************************************/
%><cs:ftcs>
	<ics:if condition='<%=ics.GetVar("seid") != null%>'>
		<ics:then>
			<render:logdep cid='<%=ics.GetVar("seid")%>' c="SiteEntry" />
		</ics:then>
	</ics:if>
	<ics:if condition='<%=ics.GetVar("eid") != null%>'>
		<ics:then>
			<render:logdep cid='<%=ics.GetVar("eid")%>' c="CSElement" />
		</ics:then>
	</ics:if>
	<html>
		<head>
			<title>Generate CSV File</title>
			<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
			<style type="text/css">
				.error {
					color: red;
					font-weight: bold;
				}
			</style>
		</head>
		<body>
			<div class="container-fluid">
				<div class="row">
					<div class="col-xs-12 col-md-12">
						<form>
							<div class="form-group">
								<label for="AssetIdInstance">Asset Id instance:</label>
			    				<textarea class="form-control" name="assetInstance" rows="5" cols="50" placeholder="accepted format:- comma seperated 'asset_type:asset_id'" required="required"></textarea>
			  				</div>			   	
						    <input type="hidden" name="writeData" value="true" />
						    <input type="hidden" name="pagename" value="Practice/Automation/WriteAssetDataToCSV" />
						    <button type="submit" class="btn btn-light">Submit</button>
						</form>
					</div>
				</div>
				<div class="row"><% 
							
					if( Utilities.goodString(ics.GetVar("writeData")) ) {
					
						%><div class="col-xs-6 col-md-6">
							<h1 align="center">Progress Log</h1>
						</div>
						<div class="col-xs-6 col-md-6" style="margin-top:20px">
							<button class="btn btn-success" id="initiateDownload">Download CSV file</button>
						</div>
						<div class="col-xs-12 col-md-12"><% 
						
							StringBuffer sb = new StringBuffer();
							String date = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format(Calendar.getInstance().getTime());
							String fileName = "Report_" + date + ".csv";
							double totalTimeTaken = 0, startTime = 0, endTime = 0;
							startTime = System.nanoTime();
							for(String assetIdInstance : ics.GetVar("assetInstance").split(",")) {
								try {
									String assetType = assetIdInstance.split(":")[0];
									String assetId = assetIdInstance.split(":")[1];
									if( Utilities.goodString(assetType) && Utilities.goodString(assetId)) {
										boolean flag = true;
										/* make a check to see if valid c cid combination is passed and change status of flag */
										ics.ClearErrno();
										String sql = "select * from AssetPublication where assettype='"+assetType+"' and assetid="+assetId;
										
										%><ics:sql sql="<%=sql %>" table='<%="AssetPublication"%>' listname="validationList"/><%
												
										if(ics.GetList("validationList") != null && ics.GetList("validationList").numRows() < 1)
											flag = false;
										
										if(flag) {
											
											%><ics:clearerrno/>
											<asset:getsubtype objectid="<%=assetId %>" type="<%=assetType %>" output="assetDefinition" /><%
											
											sb.append("_NEW_ASSET_CONTENT_");sb.append("\n");
											sb.append(assetType + ":" + assetId);sb.append(",");
											sb.append(ics.GetVar("assetDefinition"));sb.append("\n");
											
											%><ics:logmsg msg='<%="Calling CreateNestedAssets with " + assetType + " : " + assetId + " from WriteAssetDataToCSV" %>' severity="INFO" />
											<ics:callelement element="Practice/Automation/CreateNestedAssets">
								    			<ics:argument name="cid" value='<%=assetId %>'/>
								    			<ics:argument name="c" value='<%=assetType %>' />
								    		</ics:callelement><%
								    		
								    		if(Utilities.goodString(ics.GetVar("csvString"))) {
								    			StringBuffer innerBuffer = new StringBuffer(ics.GetVar("csvString"));
								    			sb.append(innerBuffer);
								    		}
											ics.RemoveVar("assetDefinition");
										} else {
											out.println("<div class=\"error\">Invalid combination of AssetId: " + assetId + " Asset Type: " + assetType + "</div>");
										}
									} else {
										out.println("<div class=\"error\">Invalid combination of AssetId: " + assetId + " Asset Type: " + assetType + "</div>");
									}
								} catch(ArrayIndexOutOfBoundsException e) {
									out.println("<div class=\"error\">Invalid combination of Asset Id Instance: " + assetIdInstance + "</div>");
								} catch(Exception e) {
									out.println("<div class=\"error\">Exception Occured in WriteAPI element: " + e.getMessage() + "</div><br/>");
								}
							}
							String csvFileContents = StringEscapeUtils.escapeJavaScript(sb.toString().replaceAll("[^\\x00-\\x7F]", " "));
							
							%><%-- script to download csv file --%>
							<ics:if condition='<%=ics.GetErrno() == 0 && csvFileContents.length() > 0 %>'>
								<ics:then>
									<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
									<script>
										$(document).ready(function() {
											$("#initiateDownload").on("click", function(event) {
										    	var ua = window.navigator.userAgent;
										        var msie = ua.indexOf("MSIE ");
										        var csv = '<%=csvFileContents %>';				
										        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
										            var blob = new Blob([decodeURIComponent(csv)], {type: "text/csv;charset=utf-8"});
										           	window.navigator.msSaveBlob(blob, "<%=fileName %>");
										        } else {
										            var link = document.createElement("a");
													var blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
										            var url = URL.createObjectURL(blob);
										            link.href = url;
										            link.setAttribute("download", ("<%=fileName %>"));
										            document.body.appendChild(link);
										            link.click(); 
										        }
											});
										});
									</script><%
									
									endTime = System.nanoTime();
									totalTimeTaken = (endTime - startTime) / 1000000;
									if(totalTimeTaken < 1000)
										out.println("<hr><b>Total time taken : " + totalTimeTaken + " milliseconds</b>");
									else
										out.println("<hr><b>Total time taken : " + (totalTimeTaken / 1000) + " seconds</b>");
										
								%></ics:then>
								<ics:else><% 
									out.println("<div class=\"error\">Error Occured: " + ics.GetErrno() + "</div>");
									
									%><script>
										document.getElementById("initiateDownload").style.display = 'none';
									</script>
								</ics:else>
							</ics:if><%
						}
					%></div>
				</div>
			</div>
		</body>
	</html>
</cs:ftcs>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment