Zimbra SOAP API authenticate using zm_auth_token in java - java

I want to authenticate a user using the zm_auth_token that I dispose :
For the moment, I'm doing this :
LmcAuthRequest auth = new LmcAuthRequest();
auth.setUsername(userName);
auth.setPassword(password);
LmcAuthResponse authResp = (LmcAuthResponse) auth.invoke(serverURL);
LmcSession session = authResp.getSession();
But I want to use the zm_auth_token that I have. How to do this ???
Thnx

The zimbra Lmc methods are deprecated now ...
If you want to use SOAP they prefer doing it using ZMailBox (It doesn't work for me), I used this method :
// Create the connection where we're going to send the file.
URL url = new URL(SOAPUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
String postContent = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">"+
"<soap:Header>" +
"<context xmlns=\"urn:zimbra\">" +
"<format type=\"js\"/>" +
"<authToken>" + authToken + "</authToken>" +
"</context>" +
"</soap:Header>" +
"<soap:Body>" +
"<GetFolderRequest xmlns=\"urn:zimbraMail\" />" +
"</soap:Body>" +
"</soap:Envelope>";
// insert your SOAP XML!!!
byte[] b = postContent.getBytes();
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty( "Content-Length", String.valueOf( b.length ) );
httpConn.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
httpConn.setRequestMethod( "POST" );
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Everything's set up; send the XML that was read in to b.
OutputStream out = httpConn.getOutputStream();
out.write( b );
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
// read & do something with input stream...
String s = null;
String response = "";
while((s=in.readLine()) != null){
response += s;
}
in.close();

SOAPConnectionFactory soapfactory=SOAPConnectionFactory.newInstance();
SOAPConnection soapconnection=soapfactory.createConnection();
MessageFactory messagefactory=MessageFactory.newInstance();
SOAPMessage messege=messagefactory.createMessage();
SOAPEnvelope envelop=messege.getSOAPPart().getEnvelope();
SOAPHeader header=messege.getSOAPHeader();
SOAPBody body=messege.getSOAPBody();
Name header_context=envelop.createName("context", null,"urn:zimbra");
Name auth_request=envelop.createName("AuthRequest",null,"urn:zimbraAccount");
Name account=envelop.createName("account");
Name password=envelop.createName("password");
header.addHeaderElement(header_context);
SOAPBodyElement auth_body=body.addBodyElement(auth_request);
auth_body.addChildElement(account).addAttribute(envelop.createName("by"),"name").addTextNode("abc");//(abc==your username)
auth_body.addChildElement(password).addTextNode("1234");//(1234=your password)
URL url=new URL("http://192.168.1.67/service/soap/AuthRequest");
SOAPMessage response=soapconnection.call(messege, url);

You can use Zimbra libraries for calling SOAP API. Please check this answer.

Related

OData Bad Request 400 with Java Client

I have an issue regarding OData querying with an Java Client.
If I use Postman, everything works as expected and I'm receiving a response from the web service with the metadata. But in my Java Client, which runs not on the SCP / HCP I'm receiving "400-Bad Request". I used the original Olingo libary.
I only used the $metadata Parameter, so there is no filter value or something else.
public void sendGet(String user, String password, String url) throws IOException, URISyntaxException {
// String userPassword = user + ":" + password;
// String encoding = Base64.encodeBase64String(userPassword.getBytes("UTF-8"));
URL obj = new URL(url);
URL urlToEncode = new URL(url);
URI uri = new URI(urlToEncode.getProtocol(), urlToEncode.getUserInfo(), urlToEncode.getHost(), urlToEncode.getPort(), urlToEncode.getPath(), urlToEncode.getQuery(), urlToEncode.getRef());
// open Connection
HttpURLConnection con = (HttpURLConnection) uri.toURL().openConnection();
// Basis Authentifizierung
con.setRequestProperty("Authorization", "Basic " + user);
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("Content-Type", "application/xml");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
response.append("\n");
}
in.close();
// print result
System.out.println(response.toString());
// Schließt eine Vorhandene Verbindung
con.disconnect();
in User is already the encoded value. by manipulating this one, i'm receiving an authorization error, so already tested.
May somebody can help me in that case :)
Thanks in advance.
Tim
So I solved it by myself.
i added the statement con.setRequestProperty("Accept", "application/xml"); and it works fo me.
Maybe it could help somebody else.

How to get response as XML from webService response?

I have to create a method for getting webService response as xml. I know how to create with Java class but problem is getting response as xml from webService.
These webServices are soap based.
Thanks in advance.
I have just solve my problem. HttpURLConnection helps me.
The following code block show how I make poster for getting xml response in java like Mozilla Poster.
public static void main(String[] args) {
try {
String uri = "http://test.com/IntegratedServices/IntegratedServices.asmx?op=GetUserInfo";
String postData = new XmlTest().xmlRequest("QWERTY10");
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true); // This is important. If you not set doOutput it is default value is false and throws java.net.ProtocolException: cannot write to a URLConnection exception
connection.setRequestMethod("POST"); // This is method type. If you are using GET method you can pass by url. If method post you must write
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); // it is important if you post utf-8 characters
DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); // This three lines is importy for POST method. I wrote preceding comment.
wr.write(postData.getBytes());
wr.close();
InputStream xml = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(xml));
String line = "";
String xmlResponse = "";
while ((line = reader.readLine()) != null) {
xmlResponse += line;
}
File file = new File("D://test.xml"); // If you want to write as file to local.
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(xmlResponse);
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String xmlRequest(String pin) {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
+ " <soap:Body>\n"
+ " <GetUserInfo xmlns=\"http://tempuri.org/\">\n"
+ " <pin>" + pin + "</pin>\n"
+ " </GetUserInfo>\n"
+ " </soap:Body>\n"
+ "</soap:Envelope>";
}
I hope this helps who want to get xml as response. Also I wrote detailed comment to my code.
For soap type webservice :
Parsing SOAP Response in Java
For rest look at this link:
http://duckranger.com/2011/06/jaxb-without-a-schema/

get JSON response while performing POST request with HttpURLConnection

I am using the following code to perform POST requests on a REST API. It is all working fine. What I am being unable to do is after POST is successful the API returns response JSON in body with headers, this JSON has information which I require. I am unable to get the JSON response.
I need this response as this response includes the ID generated by DB. I can see the response while using REST Client plugin of firefox. Need to do implement the same in Java.
String json = "{\"name\": \"Test by JSON 1\",\"description\": \"Test by JSON 1\",\"fields\": {\"field\": []},\"typeDefinitionId\": \"23\",\"primaryParentId\": \"26982\"}";
String url = "http://serv23/api/contents";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//Setting the Request Method header as POST
con.setRequestMethod("POST");
//Prepairing credentials
String cred= "user123:p#ssw0rd";
byte[] encoded = Base64.encodeBase64(cred.getBytes());
String credentials = new String(encoded);
//Setting the Authorization Header as 'Basic' with the given credentials
con.setRequestProperty ("Authorization", "Basic " + credentials);
//Setting the Content Type Header as application/json
con.setRequestProperty("Content-Type", "application/json");
//Overriding the HTTP method as as mentioned in documentation
con.setRequestProperty("X-HTTP-Method-Override", "POST");
con.setDoOutput(true);
JSONObject jsonObject = (JSONObject)new JSONParser().parse(json);
OutputStream os = con.getOutputStream();
os.write(jsonObject.toJSONString().getBytes());
os.flush();
WriteLine( con.getResponseMessage() );
int responseCode = con.getResponseCode();
Get the input stream and read it.
String json_response = "";
InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(in);
String text = "";
while ((text = br.readLine()) != null) {
json_response += text;
}

HTTP response code 400 sending GET Request to HTTPS Query API

I'm trying to send email using the SES HTTPS Query API. I have a java method that sends a GET request to an Amazon SES endpoint, I'm trying to send an email with SES and capture the result.
Code:
public static String SendElasticEmail(String timeConv,String action,String source, String destinationAddr, String subject, String body) {
try {
System.out.println("date : "+timeConv);
System.out.println("In Sending Mail Method......!!!!!");
//Construct the data
String data = "Action=" + URLEncoder.encode(action, "UTF-8");
data += "&Source=" + URLEncoder.encode(source, "UTF-8");
data += "&Destination.ToAddresses.member.1=" + URLEncoder.encode(destinationAddr, "UTF-8");
data += "&Message.Subject.Data=" + URLEncoder.encode(subject, "UTF-8");
data += "&Message.Body.Text.Data=" + URLEncoder.encode(body, "UTF-8");
//Send data
System.out.println("https://email.us-east-1.amazonaws.com?"+data);
URL url = new URL("https://email.us-east-1.amazonaws.com?"+data);
//URLConnection conn = url.openConnection();
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("x-amz-date" , timeConv);
con.setRequestProperty("Content-Length", ""+data.toString().length());
con.setRequestProperty("X-Amzn-Authorization" , authHeader);
int responseCode = ((HttpsURLConnection) con).getResponseCode();
String responseMessage = ((HttpsURLConnection) con).getResponseMessage();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
//System.out.println("Response Message : " + responseMessage);
InputStream stream = con.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream );
System.out.println("hgfhfhfhgfgfghfgh");
BufferedReader br = new BufferedReader(isReader);
String result = "";
String line;
while ((line = br.readLine()) != null) {
result+= line;
}
System.out.println(result);
br.close();
con.disconnect();
}
catch(Exception e) {
e.printStackTrace();
}
return subject;
}
I have calculated the signature correctly, because on hitting from postman client getting 200 response.
URL url = new URL("https://email.us-east-1.amazonaws.com?"+data);
You missed a '/' before the question mark. It should be
URL url = new URL("https://email.us-east-1.amazonaws.com/?"+data);

Stream Error in Soap Connection

I develop android application in java. And, this application connects .net soap application. It is ok, it works (i use http post method).
My actual problem is web service returns big and huge (especially contains html --cdata source code) data.
So, when i request (such as, getReports methods) to web service, it returns about 3 - 5 mb stream data, causes outofmemory. Because of this, i couldn't parse it. I know my connection method cannot be true.
How can i implement truely if i make a mistake?
Thanks in advance.
String NAMESPACE = "http://tempuri.org/lorem";
String SURL = "http://www.test.com/lorem/test.asmx";
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
xml += "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://tempuri.org/\">"
+ "<soapenv:Header/><soapenv:Body>"
+ "<web:getReport><web:strLang>strLang</web:strLang></web:getReport>"
+ "</soapenv:Body></soapenv:Envelope>";
URLConnection connection = url.openConnection();
HttpURLConnection httpconn = (HttpURLConnection) connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
bout.write(xml.getBytes());
byte[] b = bout.toByteArray();
httpconn.setRequestProperty("SOAPAction", Namespace+ "/" + "getReport");
httpconn.setRequestProperty("Accept-Encoding","gzip,deflate");
httpconn.setRequestProperty("Host","www.test.com");
httpconn.setRequestMethod("POST");
httpconn.setDoInput(true);
httpconn.setDoOutput(true);
httpconn.connect();
OutputStream out = httpconn.getOutputStream();
out.write(b);
InputStreamReader isr = new InputStreamReader(httpconn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine = "";
StringBuffer parsingData = new StringBuffer();
while (null != (inputLine = in.readLine())) {
// OutOfMemory Error
parsingData.append(inputLine);
}
/*
* parsingMethods (parsingData);
*/
Ksoap does support headers here is how
Element AuthHeader = new Element();
AuthHeader.setName("Auth");
AuthHeader.setNamespace(namespace);
Element element = new Element();
element.setName("Username");
element.setNamespace(namespace);
element.addChild(Element.TEXT, username);
AuthHeader.addChild(Element.ELEMENT, element);
element = new Element();
element.setName("Password");
element.setNamespace(namespace);
element.addChild(Element.TEXT, password);
AuthHeader.addChild(Element.ELEMENT, element);
headers[0] = AuthHeader;
envelope.headerOut = headers;

Categories

Resources