import java.io.*;
import java.util.*;

import java.net.*;

import java.security.cert.CertificateException;
import java.security.KeyStoreException;
import java.security.cert.X509Certificate;

import java.security.PrivateKey;
import java.security.PublicKey;


 import java.security.KeyStore.*;
// import java.security.Provider;
// import java.security.SecureRandom;
// import java.security.Security;
import java.security.*;

// import javax.net.ssl.KeyManagerFactory;
// import javax.net.ssl.SSLContext;
// import javax.net.ssl.SSLSocketFactory;
// import javax.net.ssl.TrustManagerFactory;
// import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;


// import javax.mail.internet.MimeUtility;
// import org.apache.commons.codec.binary.Base64;

//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;
//import sun.misc.BASE64Decoder;

//import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
//import java.util.TimeZone;

//import it.sauronsoftware.base64.*;
//import it.sauronsoftware.base64.Base64;


public class Personalizare  
{

   // public String password = "C6AB5-HXCN-NRHX-HUFM";
   // public String user = "19995194_CAS-B";
   // public String eTokenPin = "1234567890";
   // public String getInsuredUrl = "https://www.siui.ro/svapntws/services/SiuiInsuredWS";
   // public String cnp = "1691125441563";

  
//**********************
  public static void  main(String arg[]) throws Exception 
   {
    
	Personalizare ob = new Personalizare();
 //  String cnp = arg[0];
   
   
   //carmen
   // String password = "C6AB5-HXCN-NRHX-HUFM";
   // String user = "19995194_CAS-B";
   // String eTokenPin = "20898190"; 
   
   // PATRICIA POPESCU
   // String password = "D8CF2-MSEK-AISY-LDYC";
   // String user = "20810397_CAS-B";
   // String eTokenPin = "36600451";			//"12200427";
   
   //Otilia
   // String password = "95F22-OHRL-OSKD-YTVL";  //"DB9C9-RGPU-KQEE-BMFD";
   // String user = "20450212_CAS-B";
   // String eTokenPin = "1234567890";
   
  //Dan - DAVA
   // String password = "6443F-BNGS-WAAO-HVCE";
   // String user = "5822606_CAS-B";
   // String eTokenPin = "85987438";
   

  //Calin -digisign
  // String password = "4A128-WPJI-ENMU-YDVC";
  // String user = "20837201_CAS-B";
  // String eTokenPin = "1234567890";
   
  //Minculescu Magdalena
  // String password = "6E128-TWMD-QPMG-EMOD";
  // String user = "15463208_CAS-B";
  // String eTokenPin = "67581082";
  
  
  // Andra Ticarau
								// String password = "92DFC-QWPE-HONN-CNHH";
								// String user = "12433636_CAS-B";
								// String eTokenPin = "bcfe35eb";     
	// String password = "0E14A-NGYX-HSMV-OSHJ";
    // String user = "12433636_CAS-B";
    // String eTokenPin = "1122334455";  
   
  // Alin Negrean
     // String password = "EC3B3-DUMG-PCJJ-CMBS";
     // String user = "20437043_CAS-B";
     // String eTokenPin = "1234567890";  
	 
	 
	 // citire date configurare din fisier
//   /*	 
	
	String fisierConfigurare = "config.conf";
	Properties conf = ob.readFileConfig(fisierConfigurare);
	
	 String accessFile = conf.getProperty("accessFile");
	 String responseFile = conf.getProperty("responseFile");
	 Properties acces = ob.readFileConfig(accessFile);
	 // System.out.println("key = " + conf.getProperty("password") );
	 // System.out.println("user = " + conf.getProperty("user") );
	 // System.out.println("pin = " + conf.getProperty("eTokenPin") );
	 
   String password = acces.getProperty("key");
   String user = acces.getProperty("user");
   String eTokenPin = acces.getProperty("pin");	 
   String tokenFile = acces.getProperty("tokenFile");	 
	 
	 
 //     end citire date din fisier  */
   System.setProperty("java.security.debug","all");
   System.setProperty("javax.net.debug","ssl");
//   System.setProperty("javax.net.ssl.keyStoreType","pkcs11");
   
   
   
   String serviceUrl = "https://www.siui.ro/svapntws/services/SiuiWS";
   String cnp = "";
   // if(arg[0].length() == 13){
		// cnp = arg[0];
	// } else {
		// cnp = "1691125441563";
   // }
    try
       {   
         //Create our certificates from our CAC Card
         String configName = tokenFile ;   // "card.config";
         Provider p = new sun.security.pkcs11.SunPKCS11(configName);
         Security.addProvider(p);
		 
//		 Provider x = new sun.security.mscapi.SunMSCAPI();

		 /*
		 Provider[] providers = Security.getProviders();
		
		 for(int i=0;i<providers.length;i++){
		 Provider pr = providers[i];
		 System.out.println(pr.getName() + "    " + pr.getInfo());
		 }
//		 */
		 
	//	 String gName = p.getName();
		 System.out.println(p.getName());
		 System.out.println(p.getInfo());
//		 System.out.println(p.Service.getAlgorithm());

         //Get the pin from user entered data
         Console c = System.console();
 //        char[] pin = c.readPassword("Enter your PIN: ");
         char[] pin = eTokenPin.toCharArray();
         KeyStore cac = null;

         cac = KeyStore.getInstance("PKCS11",p);
 //        cac = KeyStore.getInstance("Windows-MY",p);
 //          cac = KeyStore.getInstance("JKS");
 //        cac = KeyStore.getInstance("JCEKS");
 //System.out.println(KeyStore.getDefaultType());
 //        cac = KeyStore.getInstance(KeyStore.getDefaultType());
         
//			FileInputStream is = new FileInputStream("test.txt");
			
			cac.load(null, pin);

//         Personalizare ob = new Personalizare();
		 
//		 X509Certificate ccert = (X509Certificate) showInfoAboutCAC(cac);
		String ccert = showInfoAboutCAC(cac);

		
		//////////////////////////////////////////////////////
		/////                                          ///////
		/////   CONNECT TO OSCP AND GET SERVER TOKEN   ///////
		/////                                          ///////
		//////////////////////////////////////////////////////
	
	
//	KeyStore kwr = KeyStore.getInstance("Windows-MY");
//	kwr.load(null,null);
	//	String serverToken = webAccess(cac,user,p);
	//	String[] tokens = ob.webAccess(cac,user,p,cac);
		String[] tokens = ob.webAccess(cac,user,p
//		,kwr
		);
		String serverToken = tokens[0];
		String CookieJar = tokens[1];
		
		System.out.println("Token : " + serverToken);
		System.out.println("Cookiejar : " + CookieJar);
		  

		DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
		dfm.setTimeZone(TimeZone.getTimeZone("Europe/Bucharest"));
        Date now = new Date();
		String df = dfm.format(now);
		
		String method = "getProviderInfo";
		String partnerCategory = "MF";
		String start = "2013-01-01T01:00:00";
		String stop = "2013-01-30T23:59:59";
		String uic = user.split("_")[0];
		String request = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
		request += "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n";
		request += "<SOAP-ENV:Body>\r\n";
		request += "<m:" + method + " xmlns:m=\"http://balsiui/svapntws/services/SiuiWS\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n";
		request += "<partnerCategory xsi:type=\"xsd:string\">" + partnerCategory + "</partnerCategory>\r\n";
		request += "<start xsi:type=\"xsd:dateTime\">" + start + "</start>\r\n";
		request += "<stop xsi:type=\"xsd:dateTime\">" + stop + "</stop>\r\n";
		request += "<uic xsi:type=\"xsd:string\">" + uic + "</uic>\r\n";
		request += "</m:" + method + ">\r\n";
		request += "</SOAP-ENV:Body>\r\n";
		request += "</SOAP-ENV:Envelope>";
   
        String requestUrl = serviceUrl;
        
		String currentDate = df.split("T")[0];
		String asigFile = "last_personalizare.xml"; //currentDate + "_personalizare.xml";
		String fileOut =  "Personalizare_" + uic + "_" + currentDate  + ".zip";
		String destinationDir = "personalizari";
		
		///////////////////////////////////
		/////                       ///////
		/////   STARE DE ASIGURAT   ///////
		/////                       ///////
		///////////////////////////////////
		if(serverToken.length() > 10) {
//		 ob.sendRequest(cac,requestUrl,user,password,serverToken,request,CookieJar); //nu merge
//		 ob.sendRequest(kwr,requestUrl,user,password,serverToken,request,CookieJar);
		 }
		 
//   send report    String sendReport(String fileZip, String reportType, KeyStore ks, String requestUrl, String user, String password, String serverToken
		String fileZip = "arhivat.zip";
		String reportType="MF";
		// String reportType="CLIN";
		String reqUrl = "https://www.siui.ro/svapntws/services/SiuiWS";
//		String reqUrl = "https://www.simbiosis.ro";
		
		
		
		
		//////////////////////////////////////
		/////                          ///////
		/////   Cerere Personalizare   ///////
		/////                          ///////
		//////////////////////////////////////
		if(serverToken.length() > 10) {
//		ob.sendReport(fileZip, reportType, cac, reqUrl, user, password, serverToken, CookieJar);
//		, kwr
		String[] response = ob.sendRequest(cac,requestUrl,user,password,serverToken,request,CookieJar);
		// String fileName = responseFile;	
		String fileName = asigFile;	
		FileWriter fstream = new FileWriter(fileName);
		BufferedWriter wrout = new BufferedWriter(fstream);
		wrout.write(response[0] + "\r\n");
		String respFile = "";
		int responseFileSize = 0;
		
		String tag1 = "<ns1:getProviderInfoReturn xmlns:ns1=\"http://webservices.utils.svapnt.siveco.ro\">";
		String endtag1 = "</ns1:getProviderInfoReturn>";
		
		String tag2 = "<ns2:getProviderInfoReturn xmlns:ns2=\"http://webservices.utils.svapnt.siveco.ro\">";
		String endtag2 = "</ns2:getProviderInfoReturn>";
		
		if( response[1].indexOf(tag1) > 0 && response[1].indexOf(endtag1) > 0 ) {
		
		int startFileName = response[1].indexOf(tag1) + tag1.length();
		
		int stopFileName = response[1].indexOf(endtag1);
		
		respFile = response[1].substring(startFileName, stopFileName);
		}
		
		
		if( response[1].indexOf(tag2) > 0 && response[1].indexOf(endtag2) > 0 ) {
		
		int startFileSize = response[1].indexOf(tag2) + tag2.length();
		
		int stopFileSize = response[1].indexOf(endtag2);
		
		responseFileSize = Integer.parseInt(response[1].substring(startFileSize, stopFileSize));
		}
		
//		int end =response[1].indexOf("</getInsuredReturn>");
		String xmlContent = response[1]; //.substring(start, end);
		// xmlContent = replace(xmlContent, "&lt;", "<");
		// xmlContent = replace(xmlContent, "&gt;", ">");
		// xmlContent = replace(xmlContent, "&quot;", "\"");
		wrout.write(xmlContent );
		wrout.close();
		
	//	
		System.out.println("fisier = " + respFile + " \ncu lungimea = " + Integer.toString(responseFileSize) );
		String GFResp = ob.getFile(respFile, cac, user, password, serverToken, destinationDir, fileOut, responseFileSize);
		
		}

//		String reportedFile = "MF_19995194_20110606_0041.xml";   //carmen
//		String feedbackFilename = "/svapntws/download?fileName=;  //carmen


//		String reportedFile = "MF_5822606_20110606_0035.xml";   //dan
//		String feedbackFilename = "/svapntws/download?fileName=;  //dan



//		String reportedFile = "MF_20450212_20110603_1811.xml";   //otilia
//		String feedbackFilename = "/svapntws/download?fileName=;  //otilia


		// String reportedFile = "MF_20810397_20110601_1341.xml";   //patricia popescu
		// String feedbackFilename = "/svapntws/download?fileName=6ooo5t0djjqct1624h39t0";  //patricia popescu

		
		//feedback raportare
//		ob.getReportFeedback(reportedFile,cac, reqUrl, user, password, serverToken);
		
		//obtinere fisier de feedback
//		ob.getFile(feedbackFilename ,cac,  user, password, serverToken);
		 
      }
      catch(Exception ex)
      {
         //System.out.println("*" + ex.getMessage());
         ex.printStackTrace();
         System.exit(0);
      }
   }



/////////////////////////////////////////////////
//////////                             //////////
//////////       INFO CERTIFICAT       //////////
//////////                             //////////
/////////////////////////////////////////////////
   //  public static X509Certificate showInfoAboutCAC(KeyStore ks) throws KeyStoreException, CertificateException
   public static String showInfoAboutCAC(KeyStore ks) throws KeyStoreException, CertificateException
   {
   
   System.out.println("Read keystore certificates");
   String ccert = new String();
      Enumeration<String> aliases = ks.aliases();

      while (aliases.hasMoreElements()) 
      {
         String alias = aliases.nextElement();
		 System.out.println(alias);
         X509Certificate[] cchain = (X509Certificate[]) ks.getCertificateChain(alias);
		X509Certificate kccert = (X509Certificate) ks.getCertificate(alias);
		ccert = kccert.toString();
		
         System.out.println("Certificate Chain for : " + alias);
         System.out.println("Certificate  : " + ccert.toString() );
         for (int i = 0; i < cchain.length; i ++)
         {
            System.out.println(i + " SubjectDN: " + cchain[i].getSubjectDN());
            System.out.println(i + " IssuerDN:  " + cchain[i].getIssuerDN());
         }
		 
//		 PrivateKey kpriv = (PrivateKey) ks.getPrivateKey(alias);
		
      }
	  return ccert;
   }
   
 
 ///////////////////////////////////////////
 ///////////                      //////////
 //////////      WEB ACCESS      ///////////
 /////////                      ////////////
 ///////////////////////////////////////////
 // public static void webAccess(X509Certificate ccert)  throws KeyStoreException, CertificateException {
  public  String[] webAccess(KeyStore ks, String user, Provider p
//  , KeyStore kwr
  )  throws KeyStoreException, CertificateException {
		//	String uri = "https://www.siui.ro/OCSP/validator?username=19995194_CAS-B";
		// URI uri;
		// try {
		// uri = new URI("https","www.siui.ro","/OCSP/validator/","username=19995194_CAS-B");
		// } catch (MalformedURLException e) {
			// System.out.println(e);
			// uri = new URI("http","www.simbiosis.ro","","");
		// }
			String serverToken = "";
			String cookie = "";
//			String certAlias = "f6fa0537-e488-4e83-a8f4-2c9002963b6b";
			

			


	//get certificate
	 //  KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)  ks.getEntry(certAlias, pin);
    //PrivateKey myPrivateKey = pkEntry.getPrivateKey();

	try{		

/*
			KeyStore kwr = KeyStore.getInstance("Windows-MY");
			
			kwr.load(null,null);
*/			
/*			KeyStore kwrr = KeyStore.getInstance("Windows-ROOT");
			kwrr.load(null,null);
			Enumeration en = kwrr.aliases();
			final X509Certificate[] trustedIssuers = new X509Certificate[300];
			int indx = 0;
			while(en.hasMoreElements()) {
				String aliasKey = (String)en.nextElement();
				System.out.println("-----> alias:  " + aliasKey);
		//		ks.setCertificateEntry(aliasKey, kwr.getCertificate(aliasKey));
				trustedIssuers[indx] = (X509Certificate) kwrr.getCertificate(aliasKey);
				indx++;
			}
*/			
//		final	Map mapa = (System.getSecurityManager() == null) ? (Map)this : new HashMap();
//			mapa.put(ks,kwr);
			
	URL url = new URL("https://www.siui.ro/OCSP/validator?username=" + user);
//	URL url = uri.toURL();

			KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
			kmf.init(ks, null);
			
//			KeyManagerFactory kmfw = KeyManagerFactory.getInstance("SunX509");
//			kmfw.init(kwr, null);
			
			// ArrayList<KeyManager> kms =new ArrayList<KeyManager>(Arrays.asList(kmf.getKeyManagers()));
			// kms.addAll(Arrays.asList(kmfw.getKeyManagers()));
			
			KeyManager[] kms_a = kmf.getKeyManagers();
//			KeyManager[] kms_b = kmfw.getKeyManagers();
//			KeyManager[] kms = new KeyManager[kms_a.length + kms_b.length];
/* 			for(int i = 0; i<kms_a.length; i++) {
				kms[i] = kms_a[i];
			}
			for(int i = 0; i<kms_b.length; i++) {
				kms[i + kms_a.length] = kms_b[i];
			}
			 */
//			kmf.init(kwr, null);

			
			// Create a trust manager that does not validate certificate chains

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { 
    new X509TrustManager() {     
        public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
            return null;
        } 
        public void checkClientTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
            } 
        public void checkServerTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    } 
}; 

			
			
//			SSLContext sslContext = SSLContext.getInstance("TLS",p);
//			SSLContext sslContext = SSLContext.getInstance("SSLv3",p);
			SSLContext sslContext = SSLContext.getInstance("TLS");
			System.out.println(sslContext.getProtocol());
			System.out.println(sslContext.getProvider().getName());
//			sslContext.init(kmf.getKeyManagers(), null, null);
//			sslContext.init(kms_a, null, null);
			sslContext.init(kms_a, trustAllCerts, new java.security.SecureRandom());
			
//			sslContext.init(kmf.getKeyManagers(), trustAllCerts,);
			
			//Set pset = sslContext.getProvider().getServices();
			// Set pset = p.getServices();
			// Iterator piterator = pset.iterator();
			// while (piterator.hasNext()) {
				// System.out.println(piterator.next().toString()) ;
			// }			
			
			//	SSLParameters sslParams = sslContext.getSupportedSSlParameters();
				
			
//			if(true){ String[] reta = {"ert","lor"}; return reta;}
			
	HttpsURLConnection  connection = (HttpsURLConnection)url.openConnection();
	connection.setSSLSocketFactory(sslContext.getSocketFactory());
// Add headers example:
// connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
	
//	connection.setDoOutput(true);

	// OutputStreamWriter out = new OutputStreamWriter(
                              // connection.getOutputStream());
							  
	
	// write certificate						  
//	out.write(ccert);
//	out.close();

//content length
	Integer clen = connection.getContentLength();
	String sclen = Integer.toString(clen);
	System.out.println("Content Length: "+sclen);
	

	
	
	
	
	

	String incomingHeaders = "";
		 Map map = connection.getHeaderFields();
        Set set = map.entrySet();
        
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            incomingHeaders += iterator.next().toString() + "\r\n";
        }

System.out.println("HEADERE: \n"+incomingHeaders);


	
/////////////////////////////////

//write output to file	
String fileName = "test.txt";	
  FileWriter fstream = new FileWriter(fileName);
  BufferedWriter wrout = new BufferedWriter(fstream);
//  wrout.write("Hello Java");
  //Close the output stream
//  wrout.close();
//////////////////////////////  
	
//	int fkey = connection.getHeaderFieldInt("OSCP_RESPONSE",4);
	serverToken = connection.getHeaderField("OSCP_RESPONSE");
	cookie = connection.getHeaderField("Set-Cookie");
//	System.out.println(fkey);
	 System.out.println("SERVER_TOKEN:" + serverToken);
	// System.out.println("SERVER_COOKIE:" + cookie);
	wrout.write("SERVER_TOKEN:" + serverToken);
	wrout.write("\r\nSERVER_COOKIE:" + cookie);
	

/* 	String incomingHeaders = "";
		 Map map = connection.getHeaderFields();
        Set set = map.entrySet();
        
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next()); 
        } */

	BufferedReader in = new BufferedReader(
				new InputStreamReader(
				connection.getInputStream()));
				
	String bufferRead;
	String result = "";
		// get result, get headers
	while ((bufferRead = in.readLine()) != null) {
	    result += bufferRead + "\r\n";
	}
//	System.out.println("REZULTAT OBTINUT\n"+result);
	wrout.write("\r\nRASPUNS:"+result);
	in.close();
	wrout.close();
	} catch (Exception e){
		System.err.println("Error: " + e.getMessage());
		e.printStackTrace();
		
	}
	String[] retStr = {serverToken,cookie};
	 return retStr;
	// return serverToken;
   }
 
 
 
 //*************************
	 public static String B64encode(String s) throws Exception {
		// byte[] b = s.getBytes();
        // ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // OutputStream b64os = MimeUtility.encode(baos, "base64");
        // b64os.write(b);
        // b64os.close();
        // return baos.toString();
		
/* 		InputStream inputStream = new ByteArrayInputStream(s.getBytes());
			//	InputStream inputStream = new FileInputStream("inputFile.txt");
	
					// byte[] xxx = s.getBytes();
		 System.out.println(inputStream.toString());
		
				// while(inputStream.read(xxx,
		// inputStream.read(xxx);
		System.out.println("aici");
	//	OutputStream outputStream = new FileOutputStream("encoded.b64");
		OutputStream outputStream = null;
		Base64.encode(inputStream, outputStream);
		outputStream.close();
		inputStream.close();
		String ret = outputStream.toString();
		
		 */
		
		
		String ret = Base64.encodeBytes( s.getBytes() );
//		byte[] myByteArray = Base64.decode( ret );
		// BASE64Encoder encoder = new BASE64Encoder();
		// byte[] b = s.getBytes();
		// String ret = encoder.encode(b);
		
		return ret;
     }

	 public static String B64decode(String s) throws Exception {
		// byte[] b = s.getBytes();
        // ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // OutputStream b64os = MimeUtility.encode(baos, "base64");
        // b64os.write(b);
        // b64os.close();
        // return baos.toString();
/* 		BASE64Decoder decoder = new BASE64Decoder();
		byte[] b = decoder.decodeBuffer(s);
		String file = "decodat.zip";
		ByteBuffer bb = ByteBuffer.wrap(b);
		try {
//		FileChannel fc = (FileChannel.open(fileOut, READ, WRITE));
			FileOutputStream fo	= new FileOutputStream(file);
	 
			FileChannel fc = fo.getChannel(); 
			fc.position(0);
			while (bb.hasRemaining())
					fc.write(bb);
			bb.rewind();

		} catch (IOException x) {
			System.out.println("exception thrown: " + x);
		} */
		
		byte[] ret = Base64.decode( s.getBytes() );
		
	//	InputStream inputStream = null;
	//	inputStream.read(s.getBytes());
	//	inputStream.read(ret);
		OutputStream outputStream = new FileOutputStream("decodat.zip");
		outputStream.write(ret,0,ret.length);
		
	//	Base64.decode(inputStream, outputStream);
		outputStream.close();
	//	inputStream.close();
		
		return "";
     }

	 
	 
	 
////////////////////////////////////////////
////////                              //////
////////   SEND REQUEST - ASIGURAT?   //////
////////                              //////
////////////////////////////////////////////

	public  static String[] sendRequest(KeyStore ks, String requestUrl, String user, String password, String serverToken, String request, String CookieJar) throws Exception {

	String result = "";
	String incomingHeaders = "";
	
System.out.println("Send Request");

		try{		
		URL url = new URL(requestUrl);
	//	URL url = uri.toURL();

				KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
				kmf.init(ks, null);

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { 
    new X509TrustManager() {     
        public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
            return null;
        } 
        public void checkClientTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
            } 
        public void checkServerTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    } 
}; 
				
				
				SSLContext sslContext = SSLContext.getInstance("TLS");
				sslContext.init(kmf.getKeyManagers(), trustAllCerts, new java.security.SecureRandom());

		HttpsURLConnection  connection = (HttpsURLConnection)url.openConnection();
		connection.setSSLSocketFactory(sslContext.getSocketFactory());
	// Add headers example:
//	 connection.setRequestProperty(null, "POST /svapntws/services/SiuiInsuredWS HTTP/1.1");
	 connection.setRequestProperty("OSCP_RESPONSE", serverToken);
	 System.out.println(serverToken);
//	 connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
	connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
	 connection.setRequestProperty("Authorization", "Basic " + B64encode(user + ":" + password));
	 	System.out.println("Basic " + B64encode(user + ":" + password));
	 connection.setRequestProperty("SOAPAction", "");	
	 connection.setRequestProperty("Cookie", CookieJar);	
	 
	 connection.setRequestProperty("Cache-Control", "no-store,no-cache");	
	 connection.setRequestProperty("Pragma", "no-cache");	
	 int ln = request.length();
	 String lns = Integer.toString(ln);
	 connection.setRequestProperty("Content-Length", lns);	
		connection.setDoOutput(true);

		OutputStreamWriter out = new OutputStreamWriter(
								  connection.getOutputStream());
								  
		
		// write request						  
		out.write(request);
		System.out.println(request);
		out.close();
		
// read receiving data		
		
	
	// String incomingHeaders = "";
		 Map map = connection.getHeaderFields();
        Set set = map.entrySet();
        
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            incomingHeaders += iterator.next() + "\r\n";
        }

	BufferedReader in = new BufferedReader(
				new InputStreamReader(
				connection.getInputStream()));
				
	String bufferRead;
	// String result = "";
		// get result, get headers
	while ((bufferRead = in.readLine()) != null) {
	    result += bufferRead + "\r\n";
	}
	
	System.out.println("HEADERE\n"+incomingHeaders);
	System.out.println("REZULTAT OBTINUT\n"+result);

	in.close();
	
		
		} catch (Exception e) {
			System.out.println(e);
			System.out.println(e.getMessage());
		}
		
		String[] returns = {incomingHeaders,result};
		return returns;
	} 
  
  
  
 ///////////////////////////////////////////////
 /////                            //////////////
 /////     SEND REPORT            //////////////
 /////                            //////////////
 ///////////////////////////////////////////////
 
	public String sendReport(String fileZip, String reportType, KeyStore ks, String requestUrl, String user, String password, String serverToken, String CookieJar
//	, KeyStore kwr
	) throws Exception {
	
		System.out.println("Send Report");
		String log = new String();
		
		DateFormat dfm = new SimpleDateFormat("yyyyMMddHHmm");
		dfm.setTimeZone(TimeZone.getTimeZone("Europe/Bucharest"));
        Date now = new Date();
		String df = dfm.format(now);		
		String fileOut = "Rap"+df+".txt";		
		try{	

//		Build the request string

		
		
//		Request and response will output into a file		

//		FileWriter fstream = new FileWriter(fileOut);
//		BufferedWriter wrout = new BufferedWriter(fstream);
		
		
		File reqFile = new File(fileZip);
		//read file. ......

	    DataInputStream dis = new DataInputStream ( new FileInputStream (fileZip));
 
		 byte[] datainBytes = new byte[dis.available()];
		 dis.readFully(datainBytes);
		 dis.close();
 
		 String content = new String(datainBytes, 0, datainBytes.length);
		
//		String encodedRequest = B64encode(content);
		String encodedRequest = Base64.encodeFromFile(fileZip);
		
		
		String request = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
		request += "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservices.utils.svapnt.siveco.ro\">\r\n";
		request += "<soapenv:Header/>\r\n";
		request += "<soapenv:Body>\r\n";
		request += "<web:sendReport>\r\n";
		request += "<web:reportType>" + reportType + "</web:reportType>\r\n";
		request += "<web:reportXML>" + encodedRequest + "</web:reportXML>\r\n";
		request += "</web:sendReport>\r\n";
		request += "</soapenv:Body>\r\n";
		request += "</soapenv:Envelope>";

		//String nimic = B64decode(encodedRequest);
		Base64.decodeToFile(encodedRequest, "decodat1.zip");
		
		log += "Request: \r\n";
		log += request;
		log += "\r\n\r\n\r\n Response:\r\n";
//		System.out.println(request);
//		System.exit(1);

		
		URL url = new URL(requestUrl);
//		KeyStore kwr = KeyStore.getInstance("Windows-MY");
//		kwr.load(null,null);


		Enumeration ensc = ks.aliases();
		while(ensc.hasMoreElements()){
		String aliass = (String)ensc.nextElement();
//		kwr.setCertificateEntry(aliass, (X509Certificate) ks.getCertificate(aliass));
		// kwr.setKeyEntry(aliass,ks.getKey(aliass,null).getEncoded(),ks.getCertificateChain(aliass));
//		kwr.setEntry(aliass,ks.getEntry(aliass,"N12A56A"),new KeyStore.PasswordProtection("N12A56A".toCharArray()));
		System.out.println(">>>>>> alias:  " + aliass);
//		kwr.setKeyEntry(aliass,ks.getKey(aliass,null).getEncoded(),ks.getCertificateChain(aliass));
		
		}
		
//		kwr.setCertificateEntry("skcert",certificatDinSmartcard);
/* 
			KeyStore kwrr = KeyStore.getInstance("Windows-ROOT");
			kwrr.load(null,null);
			Enumeration en = kwrr.aliases();
			final X509Certificate[] trustedIssuers = new X509Certificate[300];
			int indx = 0;
			while(en.hasMoreElements()) {
				String aliasKey = (String)en.nextElement();
				System.out.println("=====> alias:  " + aliasKey);
		//		ks.setCertificateEntry(aliasKey, kwr.getCertificate(aliasKey));
				trustedIssuers[indx] = (X509Certificate) kwrr.getCertificate(aliasKey);
				indx++;
			}
 */

/* 	final		TrustManager[] trustAllCerts = new TrustManager[]{
				new X509TrustManager() {
					// public java.security.cert.X509Certificate[] getAcceptedIssuers() {
						// return null;
					// }
			public X509Certificate[] getAcceptedIssuers() {
			// X509Certificate[] issuers = trustAllCerts.getAcceptedIssuers();
			// issuers = trustedIssuers;
			// return issuers;
			return trustedIssuers;
			}					
					
					public void checkClientTrusted(
						java.security.cert.X509Certificate[] certs, String authType) {
					}
					public void checkServerTrusted(
						java.security.cert.X509Certificate[] certs, String authType) {
					}
				}
			};

	 */		
		// KeyManagerFactory kmi = KeyManagerFactory.getInstance("SunX509");
		// kmi.init(ks, null);		
		
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
//		kmf.init(kwr, null);
		kmf.init(ks, null);

		KeyManager[] kms_b = kmf.getKeyManagers();

		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(kms_b, null, null);
		
		
		System.out.println(sslContext.getProtocol());
		System.out.println(sslContext.getProvider().getName());
		
		HttpsURLConnection  connection = (HttpsURLConnection)url.openConnection();
		connection.setSSLSocketFactory(sslContext.getSocketFactory());
		
// 		Add headers example:
//	 	connection.setRequestProperty(null, "POST /svapntws/services/SiuiInsuredWS HTTP/1.1");
		connection.setRequestProperty("OSCP_RESPONSE", serverToken);
		System.out.println(serverToken);
//	 	connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
		connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		connection.setRequestProperty("Authorization", "Basic " + B64encode(user + ":" + password));
	 	System.out.println("Basic " + B64encode(user + ":" + password));
		connection.setRequestProperty("SOAPAction", "");	
		//connection.setRequestProperty("Cookie", "CookieJar");
		connection.setRequestProperty("Cookie", CookieJar);	
	 
//		connection.setRequestProperty("Cache-Control", "no-store,no-cache");	
//		connection.setRequestProperty("Pragma", "no-cache");
		
		int ln = request.length();
		String lns = Integer.toString(ln);
		connection.setRequestProperty("Content-Length", lns);	
		connection.setDoOutput(true);

		OutputStreamWriter out = new OutputStreamWriter(
								  connection.getOutputStream());
								  
		
		// write request						  
		out.write(request);
//		System.out.println(request);
		out.close();
		
// read receiving data		
		
	
		String incomingHeaders = "";
		 Map map = connection.getHeaderFields();
        Set set = map.entrySet();
        
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            incomingHeaders += iterator.next() + "\r\n";
        }
		log += "Headers:\r\n " + incomingHeaders + "\r\n\r\n Content:\r\n";
		BufferedReader in = new BufferedReader(
				new InputStreamReader(
				connection.getInputStream()));
				
		String bufferRead;
		String result = "";
		// get result, get headers
		while ((bufferRead = in.readLine()) != null) {
			result += bufferRead + "\r\n";
		}
		
		System.out.println("HEADERE\n"+incomingHeaders);
		System.out.println("REZULTAT OBTINUT\n"+result);

		in.close();
		
		log += result;
		
 //////////////////////////////////////////////     
		byte data[] = log.getBytes();
		ByteBuffer bb = ByteBuffer.wrap(data);

		

	try {
//		FileChannel fc = (FileChannel.open(fileOut, READ, WRITE));
		FileOutputStream fo	= new FileOutputStream(fileOut);
 
		FileChannel fc = fo.getChannel(); 
		fc.position(0);
		while (bb.hasRemaining())
				fc.write(bb);
		bb.rewind();

		} catch (IOException x) {
			System.out.println("exception thrown: " + x);
		}

 
 
 //////////////////////////////////////////////		

		
		System.out.println("HEADERE\n"+incomingHeaders);
		System.out.println("REZULTAT OBTINUT\n"+result);

		in.close();

	
		
		} catch (Exception e) {
			System.out.println(e);
			e.printStackTrace();
			log += e.getMessage();
					byte data[] = log.getBytes();
			ByteBuffer bb = ByteBuffer.wrap(data);
			
		

			try {
		//		FileChannel fc = (FileChannel.open(fileOut, READ, WRITE));
				FileOutputStream fo	= new FileOutputStream(fileOut);
		 
				FileChannel fc = fo.getChannel(); 
				fc.position(0);
				while (bb.hasRemaining())
						fc.write(bb);
				bb.rewind();

				} catch (IOException x) {
					System.out.println("exception thrown: " + x);
				}

			
		}
		return "";	
	

	}


//////////////////////////////////////////////////
/////////      GET REPORT FEEDBACK     ///////////
//////////////////////////////////////////////////  
	
	public String getReportFeedback(String filename, KeyStore ks, String requestUrl, String user, String password, String serverToken) throws Exception {
	
		System.out.println("Get Report Feedback");
		String log = new String();
		
		DateFormat dfm = new SimpleDateFormat("yyyyMMddHHmm");
		dfm.setTimeZone(TimeZone.getTimeZone("Europe/Bucharest"));
        Date now = new Date();
		String df = dfm.format(now);		
		String fileOut = "Rap"+df+".txt";

	//construim cererea	
	String req = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservices.utils.svapnt.siveco.ro\">\n";
	req += "<soapenv:Header/>\n";
	req += "<soapenv:Body>\n";
	req += "<web:getReportFeedback>\n";
    req += "    <web:fileName>" + filename + "</web:fileName>\n";
    req += "  </web:getReportFeedback>\n";
	req += "</soapenv:Body>\n";
	req += "</soapenv:Envelope>";
	log += req + "\n\n";
	try {
		URL url = new URL(requestUrl);

		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		kmf.init(ks, null);

		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(kmf.getKeyManagers(), null, null);

		HttpsURLConnection  connection = (HttpsURLConnection)url.openConnection();
		connection.setSSLSocketFactory(sslContext.getSocketFactory());
		
// 		Add headers example:
//	 	connection.setRequestProperty(null, "POST /svapntws/services/SiuiInsuredWS HTTP/1.1");
		connection.setRequestProperty("OSCP_RESPONSE", serverToken);
		System.out.println(serverToken);
//	 	connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
		connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		connection.setRequestProperty("Authorization", "Basic " + B64encode(user + ":" + password));
	 	System.out.println("Basic " + B64encode(user + ":" + password));
		connection.setRequestProperty("SOAPAction", "");	
		connection.setRequestProperty("Cookie", "CookieJar");	
		int ln = req.length();
		String lns = Integer.toString(ln);
		connection.setRequestProperty("Content-Length", lns);	
		connection.setDoOutput(true);

		OutputStreamWriter out = new OutputStreamWriter(
								  connection.getOutputStream());
								  
		
		// write request						  
		out.write(req);
//		System.out.println(request);
		out.close();
		
// read receiving data		
		
	
		String incomingHeaders = "";
		 Map map = connection.getHeaderFields();
        Set set = map.entrySet();
        
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            incomingHeaders += iterator.next() + "\r\n";
        }
		log += "Headers:\r\n " + incomingHeaders + "\r\n\r\n Content:\r\n";
		BufferedReader in = new BufferedReader(
				new InputStreamReader(
				connection.getInputStream()));
				
		String bufferRead;
		String result = "";
		// get result, get headers
		while ((bufferRead = in.readLine()) != null) {
			result += bufferRead + "\r\n";
		}
		
		System.out.println("HEADERE\n"+incomingHeaders);
		System.out.println("REZULTAT OBTINUT\n"+result);

		in.close();
		
		log += result;
		
 //////////////////////////////////////////////     
		byte data[] = log.getBytes();
		ByteBuffer bb = ByteBuffer.wrap(data);

		

	try {
//		FileChannel fc = (FileChannel.open(fileOut, READ, WRITE));
		FileOutputStream fo	= new FileOutputStream(fileOut);
 
		FileChannel fc = fo.getChannel(); 
		fc.position(0);
		while (bb.hasRemaining())
				fc.write(bb);
		bb.rewind();

		} catch (IOException x) {
			System.out.println("exception thrown: " + x);
		}

 
 
 //////////////////////////////////////////////		

		
		// System.out.println("HEADERE\n"+incomingHeaders);
		// System.out.println("REZULTAT OBTINUT\n"+result);

		in.close();

	
		
		} catch (Exception e) {
			System.out.println(e);
			log += e.getMessage();
					byte data[] = log.getBytes();
			ByteBuffer bb = ByteBuffer.wrap(data);

		

			try {
		//		FileChannel fc = (FileChannel.open(fileOut, READ, WRITE));
				FileOutputStream fo	= new FileOutputStream(fileOut);
		 
				FileChannel fc = fo.getChannel(); 
				fc.position(0);
				while (bb.hasRemaining())
						fc.write(bb);
				bb.rewind();

				} catch (IOException x) {
					System.out.println("exception thrown: " + x);
				}

			
		}
		return "";	

	}  // end getFeedback
	
//////////////////////////////////////////////////
/////////      GET (FEEDBACK) FILE     ///////////
//////////////////////////////////////////////////  
	
	public String getFile(String filename, KeyStore ks, String user, String password, String serverToken, String destinationDir, String fileOut, int filesize) throws Exception {
	
		System.out.println("Get File");
		String log = new String();
		
		DateFormat dfm = new SimpleDateFormat("yyyyMMddHHmm");
		dfm.setTimeZone(TimeZone.getTimeZone("Europe/Bucharest"));
        Date now = new Date();
		String df = dfm.format(now);		
//		String fileOut = "Nom"+df+".zip";
//		String destinationDir = ".";
		String localFileName = fileOut;

	// //construim cererea	
	// String req = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservices.utils.svapnt.siveco.ro\">\n";
	// req += "<soapenv:Header/>\n";
	// req += "<soapenv:Body>\n";
	// req += "<web:getReportFeedback>\n";
    // req += "    <web:fileName>" + filename + "</web:fileName>\n";
    // req += "  </web:getReportFeedback>\n";
	// req += "</soapenv:Body>\n";
	// req += "</soapenv:Envelope>";
	// log += req + "\n\n";
	String requestUrl = "https://www.siui.ro" + filename;
	
	log += requestUrl + "\n";
	
	try {
		URL url = new URL(requestUrl);

		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		kmf.init(ks, null);

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { 
    new X509TrustManager() {     
        public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
            return null;
        } 
        public void checkClientTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
            } 
        public void checkServerTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    } 
};		
		
		
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(kmf.getKeyManagers(), trustAllCerts, new java.security.SecureRandom());

		HttpsURLConnection  connection = (HttpsURLConnection)url.openConnection();
		connection.setSSLSocketFactory(sslContext.getSocketFactory());
		
// 		Add headers example:
//	 	connection.setRequestProperty(null, "POST /svapntws/services/SiuiInsuredWS HTTP/1.1");
		connection.setRequestProperty("OSCP_RESPONSE", serverToken);
		System.out.println(serverToken);
//	 	connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
		connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		connection.setRequestProperty("Authorization", "Basic " + B64encode(user + ":" + password));
	 	System.out.println("Basic " + B64encode(user + ":" + password));
//		connection.setRequestProperty("SOAPAction", "");	
		connection.setRequestProperty("Cookie", "CookieJar");	
//		int ln = req.length();
//		String lns = Integer.toString(ln);
//		connection.setRequestProperty("Content-Length", lns);	
//		connection.setDoOutput(true);

		// OutputStreamWriter out = new OutputStreamWriter(
								  // connection.getOutputStream());
								  
		
		// write request						  
		//out.write(req);
//		System.out.println(request);
		//out.close();
		
// read receiving data		
		InputStream is = connection.getInputStream();
		OutputStream outStream = new BufferedOutputStream(new
			FileOutputStream(destinationDir+"\\"+localFileName));
//		outStream = new BufferedOutputStream(new FileOutputStream(destinationDir+"\\"+localFileName));
		
	try {
	//URL Url;
	byte[] buf;
	int size=1024;
	int ByteRead,ByteWritten=0;
	//Url= new URL(fAddress);
	

	//uCon = Url.openConnection();
	is = connection.getInputStream();
	buf = new byte[size];
	while ((ByteRead = is.read(buf)) != -1) {
	outStream.write(buf, 0, ByteRead);
	ByteWritten += ByteRead;
	}
	System.out.println("Downloaded Successfully.");
	System.out.println
	("File name:\""+localFileName+ "\"\nNo ofbytes :" + ByteWritten );
	if(ByteWritten == filesize) { System.out.println("Fisier descarcat cu succes!!!"); }
	}
	catch (Exception e) {
	e.printStackTrace();
	}
	finally {
	try {
	is.close();
	outStream.close();
	}
	catch (IOException e) {
	e.printStackTrace();
	}}		
// ==================================================================		
/* 		int len = connection.getContentLength();
		String lns = Integer.toString(len);
		System.out.println("\n Lungime continut: "+lns+ "\n\n");
		
		String incomingHeaders = "";
		 Map map = connection.getHeaderFields();
        Set set = map.entrySet();
        
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            incomingHeaders += iterator.next() + "\r\n";
        }
		log += "Headers:\r\n " + incomingHeaders + "\r\n\r\n Content:\r\n";
		BufferedReader in = new BufferedReader(
				new InputStreamReader(
				connection.getInputStream()));
				
		String bufferRead;
		String result = "";
		System.out.println(connection.getContentEncoding());
		String fileOutZip = "raspuns"+df+".zip";
		FileOutputStream out = new FileOutputStream(fileOutZip);
		// out.write(in);
		// get result, get headers
		while ((bufferRead = in.readLine()) != null) {
			out.write(bufferRead.getBytes());
			result += bufferRead + "\r\n";
		}
		out.close();
		System.out.println("HEADERE\n"+incomingHeaders);
		System.out.println("REZULTAT OBTINUT\nvezi fisier..\n");

		in.close();
		
		log += " lungime: " + result.length() + "\n\n"+result + "\n";
		 */
 //////////////////////////////////////////////     
/* 		byte dataz[] = result.getBytes();
		ByteBuffer bbz = ByteBuffer.wrap(dataz);

		
// scriem raspunsul in arhiva zil
	try {
//		FileChannel fc = (FileChannel.open(fileOut, READ, WRITE));
		FileOutputStream foz	= new FileOutputStream(fileOutZip);
 
		FileChannel fcz = foz.getChannel(); 
		fcz.position(0);
		while (bbz.hasRemaining())
				fcz.write(bbz);
		bbz.rewind();

		} catch (IOException x) {
			System.out.println("exceptie scriere arhiva raspuns: " + x);
		}
 
 

		byte data[] = log.getBytes();
		ByteBuffer bb = ByteBuffer.wrap(data);
// scriem log-ul
	try {
//		FileChannel fc = (FileChannel.open(fileOut, READ, WRITE));
		FileOutputStream fo	= new FileOutputStream(fileOut);
 
		FileChannel fc = fo.getChannel(); 
		fc.position(0);
		while (bb.hasRemaining())
				fc.write(bb);
		bb.rewind();

		} catch (IOException x) {
			System.out.println("exceptie scriere log: " + x);
		}

 
 
 //////////////////////////////////////////////		

		
		// System.out.println("HEADERE\n"+incomingHeaders);
		// System.out.println("REZULTAT OBTINUT\n"+result);

		in.close();

	*/
		
		} catch (Exception e) {
			System.out.println(e);
			log += e.getMessage();
					byte data[] = log.getBytes();
			ByteBuffer bb = ByteBuffer.wrap(data);

		
/* 
			try {
		//		FileChannel fc = (FileChannel.open(fileOut, READ, WRITE));
				FileOutputStream fo	= new FileOutputStream(fileOut);
		 
				FileChannel fc = fo.getChannel(); 
				fc.position(0);
				while (bb.hasRemaining())
						fc.write(bb);
				bb.rewind();

				} catch (IOException x) {
					System.out.println("exception thrown: " + x);
				}
 */
			
		}
		
		
		return "";	

	}  // end getFile
	
/////////////////////////////////////////////////////////////////////////////	
/////////////////////////  FILE  READER        //////////////////////////////
/////////////////////////////////////////////////////////////////////////////
	private String readFile(String pathname) throws IOException {

		File file = new File(pathname);
		StringBuilder fileContents = new StringBuilder((int)file.length());
		Scanner scanner = new Scanner(file);
		String lineSeparator = System.getProperty("line.separator");

		try {
			while(scanner.hasNextLine()) {        
				fileContents.append(scanner.nextLine() + lineSeparator);
			}
			return fileContents.toString();
		} finally {
			scanner.close();
		}
	}
	
////////////////////////////////////////////////////////////////////////////////////////
///////////////////   Functie de citire a valorilor dintr-un fisier   //////////////////
////////////////////////////////////////////////////////////////////////////////////////	
		private Properties readFileConfig(String pathname) throws IOException {
		
		String commentDelimiter = ";";
		String contentDelimiter = "=";
		Properties prop = new java.util.Properties();
		File file = new File(pathname);
		StringBuilder fileContents = new StringBuilder((int)file.length());
		Scanner scanner = new Scanner(file);
		String lineSeparator = System.getProperty("line.separator");
		
		try {
			while(scanner.hasNextLine()) {    
				String[] content = scanner.nextLine().split(commentDelimiter);
				String[] p = content[0].split(contentDelimiter);
				if(p.length == 2){
				prop.setProperty(p[0].trim(), p[1].trim());
				}
				
//				fileContents.append(scanner.nextLine() + lineSeparator);
			}
			// return fileContents.toString();
			return prop;
		} finally {
			scanner.close();
		}
	}
	
	static String replace(String str, String pattern, String replace) {
		int s = 0;
		int e = 0;
		StringBuffer result = new StringBuffer();

		while ((e = str.indexOf(pattern, s)) >= 0) {
			result.append(str.substring(s, e));
			result.append(replace);
			s = e+pattern.length();
		}
		result.append(str.substring(s));
		return result.toString();
	}	
	
	static void getUrlFile () {
	
	}
}
