package engine;
import java.net.*;
import java.io.*;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class XmlManager {
String path = "";
private final MyLog myLog;
public XmlManager(MyLog myLog, String path){
this.path = path;
this.myLog = myLog;
}
public static void main(String[] args){
String path = "S:\\Fatturazione Apple\\WS\\";
MyLog myLog = new MyLog(path + "/Log/", "LOG_AppleWS.txt");
XmlManager xmlManager = new XmlManager(myLog, path);
//Usare i due link sotto è la stessa cosa
String url = "https://gsxwsit.apple.com/gsx-ws/services/emea/asp";
//String url = "https://gsxwsit.apple.com/gsx-ws/services/emea/asp?wsdl";
String content = xmlManager.authenticate();
//myLog.info(content);
xmlManager.postData(content, url);
myLog.info(xmlManager.postRespOnString(url, content));
xmlManager.postRespOnStream_sam(content);
}
private String sendCommandHTTPS(String urlS, String content){
this.myLog.info("Send Command");
URL url;
String ret = "";
try
{
url = new URL (urlS);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("POST");
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches (false);
con.setDefaultUseCaches (false);
// tell the web server what we are sending
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Telis");
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
//this.myLog.debug(content);
writer.write( content );
writer.flush();
writer.close();
BufferedReader bufline = new BufferedReader(new InputStreamReader(con.getInputStream()));
String str;
while (null != ((str = bufline.readLine()))) {
//this.myLog.debug(str);
ret+=str+"\n";
}
bufline.close ();
}
catch( IOException t )
{
t.printStackTrace();
this.myLog.errorException(t);
}
return ret;
}
/**
* * invia i dati XML e inserisce la risposta su un stringa
* @param xmldata
* @return
*/
public String postRespOnString(String hostname, String xmldata){
String result = "";
try
{
URL url = new URL( hostname );
//HttpURLConnection con = (HttpURLConnection) url.openConnection();
URLConnection con = (URLConnection) url.openConnection();
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches (false);
con.setDefaultUseCaches (false);
// tell the web server what we are sending
//con.setRequestMethod("POST");
//con.setRequestProperty("Accept-Encoding", "gzip,deflate"); //
con.setRequestProperty("Content-Type", "text/xml;charset=\"UTF-8\"" );
con.setRequestProperty("SOAPAction", "\"urn:authenticate\"" );
con.setRequestProperty("Content-Length", xmldata.length()+"");
con.setRequestProperty("Host", "gsxwsit.apple.com");
con.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
OutputStream os = con.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os);
writer.write( xmldata );
writer.flush();
// reading the response
InputStream is=null;
//if (con.getResponseCode() != 200)
// is = con.getErrorStream();
//else
is = con.getInputStream();
//result = isToString_alt(is, writer);
isToString(is, 200);
}
catch( Throwable t )
{
t.printStackTrace( System.out );
}
return result;
}
/**
* * invia i dati XML e inserisce la risposta su un stringa
* @param xmldata
* @param hostname the url
* @return
*/
public String postData(String xmldata, String hostname){
String result = "";
try
{
URL url = new URL(hostname );
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches (false);
con.setDefaultUseCaches (false);
con.setRequestMethod("POST");
//La stringa seguente può creare problemi
//con.setRequestProperty("Accept-Encoding", "gzip,deflate"); //
con.setRequestProperty("Content-Type", "text/xml;charset=\"UTF-8\"" );
con.setRequestProperty("SOAPAction", "\"urn:authenticate\"" );
con.setRequestProperty("Content-Length", xmldata.length()+"");
con.setRequestProperty("Host", "gsxwsit.apple.com");
con.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
writer.write( xmldata );
writer.flush();
writer.close();
// reading the response
InputStream is=null;
if (con.getResponseCode() != 200)
is = con.getErrorStream();
else
is = con.getInputStream();
InputStreamReader reader = new InputStreamReader( is );
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf )))
{
buf.append( cbuf, 0, num );
}
result = buf.toString();
reader.close();
if (con.getResponseCode() != 200)
this.myLog.error(result);
else
this.myLog.info(result);
}
catch( Exception e )
{
e.printStackTrace();
this.myLog.errorException(e);
}
return result;
}
private String isToString_alt(InputStream is, OutputStreamWriter writer) throws IOException{
String ret ="";
if (is != null) {
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
ret = buffer.toString();
} else {
ret= "Null";
}
return ret;
}
void isToString(InputStream is, int respCode){
String result="";
try {
InputStreamReader reader = new InputStreamReader( is );
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf ))){
buf.append( cbuf, 0, num );
}
result = buf.toString();
reader.close();
if (respCode != 200)
this.myLog.error(result);
else
this.myLog.info(result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
public static String encode (String source) {
BASE64Encoder enc = new sun.misc.BASE64Encoder();
return(enc.encode(source.getBytes()));
}
*/
/**
* Invia il file XML al WEB Service
* @param xmlData
* @return
*/
public String post_1(String xmlData, String host) {
String resp = "";
try {
//Create socket
//host = host.replace("https", "http");
//int port = 443;
int port = 80;
InetAddress addr = InetAddress.getByName(host);
Socket sock = new Socket(addr, port);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
xmlData = this.header(xmlData.length(), host) + xmlData;
//Send data
wr.write(xmlData);
wr.flush();
// Response
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
while((line = rd.readLine()) != null)
resp +=line;
} catch (Exception e) {
e.printStackTrace();
}
return resp;
}
String header(int dataLenght, String url){
String xml="";
// You can use "UTF8" for compatibility with the Microsoft virtual machine.
xml+="POST " + url + " HTTP/1.1\r\n";
xml+="Accept-Encoding: gzip,deflate\r\n";
xml+="Content-Type: text/xml; charset=\"UTF-8\"\r\n";
xml+="SOAPAction: \"urn:authenticate\"\r\n";
xml+="Content-Length: " + dataLenght + "\r\n";
xml+="Host: gsxwsit.apple.com\r\n";
xml+="Connection: Keep-Alive\r\n";
//wr.write("SOAPAction: \"transfer\"\r\n");
xml+="User-Agent: Apache-HttpClient/4.1.1 (java 1.5)";
xml+="\r\n";
return xml;
}
String authenticate(){
String user = "m.gimondo@celltel.it";
String pw = "Apple@344";
String account = "636264";
String xml = "" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n " +
"xmlns:glob=\"http://gsxws.apple.com/elements/global\">\n" +
"<soapenv:Header/>\n" +
"<soapenv:Body>\n" +
"<glob:Authenticate>\n" +
"<AuthenticateRequest>\n" +
"<userId>" + user + "</userId>\n" +
"<password>" + pw + "</password>\n" +
"<languageCode>IT</languageCode>\n" +
"<userTimeZone>CEST</userTimeZone>\n" +
"<serviceAccountNo>" + account + "</serviceAccountNo>\n" +
"</AuthenticateRequest>\n" +
"</glob:Authenticate>\n" +
"</soapenv:Body>\n" +
"</soapenv:Envelope>\n";
//xml = xml.replace("\n", "");
return xml;
}
/**
* invia i dati XML e inserisce la risposta su un InputStream
* @param xmldata
* @return
*/
public InputStream postRespOnStream(String xmldata, String hostname){
InputStream is = null;
try
{
URL url = new URL( hostname);
//URLConnection con = url.openConnection();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches (false);
con.setDefaultUseCaches (false);
// tell the web server what we are sending
con.setRequestProperty ( "Content-Type", "text/xml" );
con.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
writer.write( xmldata );
writer.flush();
writer.close();
if (con.getResponseCode() != 200)
is = con.getErrorStream();
else
is = con.getInputStream();
is = con.getInputStream();
}
catch( Throwable t )
{
t.printStackTrace( System.out );
}
return is;
}
void sendCommand(String command, String xmldata){
InputStream responseIS = null;
//UTILIZZA STREAM
responseIS = this.postRespOnStream(xmldata, "");
if (responseIS == null){
this.myLog.error("" +
"Impossibile comunicare i dati." +
"Controllare il file " + command + "_post");
//this.writeOnFile(command + "_post", xmldata);
}
this.writeOnFile(command + "_post", xmldata);
//if(responseIS.markSupported())
// responseIS.mark(64);
//this.xmlReader.parse(false, false, "", responseIS, myLog);
//this.isToFile(command + "_resp", responseIS);
//Utilizza i file
/*String response ="";
//Invia i dati a Samsung
response = this.postRespOnFile(xmldata);
if(response==null || response.equalsIgnoreCase("")){
this.myLog.error("" +
"Impossibile comunicare i dati." +
"Controllare il file " + command + "_post");
this.writeOnFile(command + "_post", xmldata);
}
//Scrive la risposta su file
this.writeOnFile(command + "_risposta", response);
//Parse il file ricevuto da file e aggiorna i dati esistenti
this.xmlReader.parse(true, false, command + "_risposta.xml", null, myLog);
//this.myLog.debug("\nResponse from server after POST:\n" + response );
*
*/
}
private void isToFile(String fileName, InputStream is){
OutputStream out = null;
try {
is.reset();
out = new FileOutputStream(new File(fileName));
byte buf[]=new byte[1024];
int len;
while((len=is.read(buf))>0)
out.write(buf,0,len);
out.close();
is.close();
} catch (IOException ex) {
this.myLog.errorException(ex);
Logger.getLogger(XmlManager.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
out.close();
} catch (IOException ex) {
this.myLog.errorException(ex);
Logger.getLogger(XmlManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* invia i dati XML e inserisce la risposta su un InputStream
* @param xmldata
* @return
*/
public InputStream postRespOnStream_sam(String xmldata){
InputStream is = null;
//Create socket
//String hostname_3 = "http://test-fsv2.samsung.it:8080/operations/FutureService?wsdl";
//String hostname_3 = "http://test-fsv2.samsung.it:8888/operations/FutureService?wsdl";
//String hostname_3 = "http://futureservice.samsung.it:8888/operations/FutureService?wsdl";
String hostname_3 = "https://gsxwsit.apple.com/gsx-ws/services/emea/asp?wsdl";
try
{
URL url = new URL( hostname_3 );
URLConnection con = url.openConnection();
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches (false);
con.setDefaultUseCaches (false);
// tell the web server what we are sending
con.setRequestProperty ( "Content-Type", "text/xml" );
con.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
writer.write( xmldata );
writer.flush();
writer.close();
is = con.getInputStream();
isToString(is, 200);
}
catch( Throwable t )
{
t.printStackTrace( System.out );
}
return is;
}
/**
* Legge un file di testo e lo mette in una stringa
* @param fileName
* @return
*/
String readFile(String fileName){
String xmldata = "";
String file = path + fileName;
try {
Scanner scanner = new Scanner(new File(file));
while(scanner.hasNext()){
xmldata+=scanner.nextLine();
}
}
catch(Exception e){
e.printStackTrace();
}
return xmldata;
}
/**
* Scrive su un file il contenuto di data
* @param fileName
* @param data
*/
void writeOnFile(String fileName, String data){
FileWriter fw;
PrintWriter pw;
String pathFile = "";
try {
pathFile = path + fileName + ".xml";
fw = new FileWriter(pathFile, false);
pw = new PrintWriter(fw);
pw.write(data);
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();}
}
}