# Aggregator upload test v1 by JP
from java.lang import System
from java.util import Properties
from java.util import UUID
from javax.naming import Context, InitialContext
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
from net.grinder.plugin.http import HTTPPluginConnection
from net.grinder.plugin.http import HTTPPluginControl
from HTTPClient import Codecs, NVPair, AuthorizationInfo
from threading import Condition
from jarray import zeros
import HTTPClient

import re
import random
from java.util import Date
from java.util.regex import *
from java.lang import *

#from uuid.py import *

# Put regular expressions outside of class due to jython threading bug
regex_dcIdentifier = re.compile("<DC.Identifier.*?>(.*?)</DC.Identifier>")

# Enable HTTPClient's authorisation module.
httpUtilities = HTTPPluginControl.getHTTPUtilities()
grinder.statistics.registerSummaryExpression("Failed Sends", "userLong0");
grinder.statistics.registerSummaryExpression("MB sent", "(/ userLong1 1024000.0)")
grinder.statistics.registerSummaryExpression("Time", "(/ userLong2 1000)")
grinder.statistics.registerSummaryExpression("Records Uploaded", "userLong3")

class TestRunner:
    def __call__(self):

		test1 = Test(1, "Aggregator Upload Throughput Test")

		#---------------------------------------------------------------------------------------------------------------------------------------------------------------
		# Alter settings here
		
		# serverName="http://office.k-int.com:8080/"
		serverName="http://192.168.1.8:8080/"
		userName="admin"
		password="admin"
		owner="test"		
		
		#---------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		regex_dcIdentifier = re.compile("<DC.Identifier.*?>(.*?)</DC.Identifier>")

		request1 = test1.wrap(HTTPRequest(url=serverName, ))

		filename=random.randrange(2001,4000,1)
		# Have to change path here
		filename="./import_%d.xml" % filename
		files = ( NVPair("upload", filename), )

		parameters = ( #NVPair("Authorization", "Basic " + Codecs.base64Encode(userID + ":" + password)),
					   NVPair("owner", owner), 
					   NVPair("authoritative","true"),
					   NVPair("Connection","Keep-Alive"),
					   NVPair("filename",filename),
					   NVPair('Accept', 'text/xml'),
					   httpUtilities.basicAuthorizationHeader(userName, password),
		)

		# This is the Jython way of creating an NVPair[] Java array
		# with one element.
		headers = zeros(2, NVPair)
		headers[1]= httpUtilities.basicAuthorizationHeader(userName, password)

		# Create a multi-part form encoded byte array.
		data = Codecs.mpFormDataEncode(parameters, files, headers)

		# Generate new id for record
		output=data.tostring()
		#grinder.getStatistics().getForCurrentTest().setLong("userLong0", 1)
		#p=Pattern.compile("<DC.Identifier.*?>(.*?)</DC.Identifier>");
		#m=p.matcher(output)
		#b=m.matches()
		#print b

		currentId=str(regex_dcIdentifier.findall(output))

		# Get UUID in java
		a = UUID.randomUUID().toString();
		
		# Get current data in java
		d=Date()
		newId=str(a)

		# Replace string
		currentId=currentId[2:-2]
		output=output.replace(currentId, newId)

		# Write to file		
		#newId=newId.replace(':','_')
		#newId=newId.replace(' ','_')
		#f=open('C:\\Temp\\aggregatortestfile\\'+newId,'w')
		#f.write(output)
		#f.close()
		
		grinder.statistics.delayReports = 1

		# Post modified record
		result = request1.POST(serverName+"dpp/provider/upload", output, headers)
		grinder.statistics.forLastTest.addLong("userLong1", len(output))
		grinder.statistics.forLastTest.addLong("userLong2",grinder.statistics.forLastTest.time)
		grinder.statistics.forLastTest.addLong("userLong3",1)
							  
		resulttext=result.getText()
		statusCode=result.getStatusCode()
		if statusCode>=200 and statusCode<=299:
			# Test passed
			grinder.statistics.forLastTest.addLong("userLong0",0)
			testok=True
		else:
			# Test failed;
			grinder.statistics.forLastTest.addLong("userLong0",1)
			testok=False
			
		grinder.statistics.report()
