<%@ jet 
	imports="
		org.talend.core.model.process.INode 
		org.talend.core.model.metadata.IMetadataTable 
		org.talend.core.model.process.ElementParameterParser
		org.talend.designer.codegen.config.CodeGeneratorArgument
		java.util.List
        java.util.Map
	"
%>

<%
	CodeGeneratorArgument codeGenArgument = (CodeGeneratorArgument) argument;
	INode node = (INode)codeGenArgument.getArgument();
	String cid = node.getUniqueName();
	
	String accessKey = ElementParameterParser.getValue(node, "__ACCESSKEY__");
	String secretKey = ElementParameterParser.getValue(node, "__SECRETKEY__");
	
	
	String bucketName = ElementParameterParser.getValue(node, "__BUCKET__");
	
	String subDirectory = ElementParameterParser.getValue(node, "__SUBDIRECTORY_OBJECT__");
	
	String objectName = ElementParameterParser.getValue(node, "__OBJECT__");
	
%>
		
	com.amazon.s3.AWSAuthConnection AWSAuthConnection<%=cid %> =null;
	
	<%
	String useExistingConn = ElementParameterParser.getValue(node, "__USE_EXISTING_CONNECTION__");
	
	if(useExistingConn.equals("true")){
		String connection = ElementParameterParser.getValue(node, "__CONNECTION__");
		String conn= "conn_" + connection;
	%>
	
	AWSAuthConnection<%=cid %> = (com.amazon.s3.AWSAuthConnection)globalMap.get("<%=conn %>");
	
	<%}else{%>		
	AWSAuthConnection<%=cid %> = new com.amazon.s3.AWSAuthConnection(<%=accessKey%>,<%=secretKey%>);
	<%} %>	    
	
	java.util.Map<String, List<String>> lHeaders<%=cid %> = new java.util.TreeMap<String, List<String>>();
    lHeaders<%=cid %>.put("Content-Type", java.util.Arrays.asList(new String[] { "text/plain" }));

	boolean lObjectExist<%=cid %> = false;
	
	String fichierToSearch<%=cid %> = ("".equals(<%=subDirectory%>)?"":<%=subDirectory%>+"/")+<%=objectName %>;
	
    try {
    	com.amazon.s3.ListBucketResponse lLBR = AWSAuthConnection<%=cid %>.listBucket(<%=bucketName%>, <%=subDirectory%>, null, null, lHeaders<%=cid %>);

    	if (lLBR==null || lLBR.entries==null)
    		throw new com.ysance.s3.exception.S3ObjectBucketEmptyException("Bucket "+<%=bucketName%>+" is empty");

    	java.util.List<String> lObjectList_<%=cid %> = com.ysance.s3.UtilsS3.convertListListEntryToListString(lLBR.entries);
    	
    	lObjectExist<%=cid %> = (lObjectList_<%=cid %>!=null && lObjectList_<%=cid %>.size()>0 && lObjectList_<%=cid %>.contains(fichierToSearch<%=cid %>));
    } catch (IOException ioe) {
    	if ("Connection refused: connect".equals(ioe.getMessage()))
    		throw new com.ysance.s3.exception.S3ConnectionException(ioe.getMessage());
    		else throw new com.ysance.s3.exception.S3ObjectListException(ioe.getMessage());
    }
    
    
	
	globalMap.put("<%=cid %>_EXISTS", lObjectExist<%=cid %>);    	
    globalMap.put("<%=cid %>_BUCKET", <%=bucketName %>);
    globalMap.put("<%=cid %>_OBJECT", fichierToSearch<%=cid %>);
