Java - SOAP - TrinityCore

Hi everyone,

I try to learn java and I want to make a ‘account panel’ where you can manage your wow account, like change password, teleport characters etc.

I need SOAP connection, may be somebody can explain or show how to pass those parameters in java:

‘uri’ => ‘urn:’. $soap_uri .‘’,
‘user_agent’ => ‘aframework’,
‘style’ => SOAP_RPC,
‘login’ => $soapUser,
‘password’ => $soapPass,
‘trace’ => 1,
‘exceptions’ => 0

with PHP it is very easy

final class SOAP {
private $conn = null;
function __construct($user, $pass, $host, $port, $uri) {
if(!$this->connect($user, $pass, $host, $port, $uri))
die(‘SOAP UNABLE CONNECT’);
}
private function connect($soapUser, $soapPass, $soapHost, $soapPort, $soap_uri) {
$this->conn = new SoapClient(null, array(

            'uri'           => 'urn:'. $soap_uri .'',
            'user_agent'    => 'aframework',
            'style'         => SOAP_RPC,
            'login'         => $soapUser,
            'password'      => $soapPass,
            'trace'         => 1,
            'exceptions'    => 0
        )
    );
    if(is_soap_fault($this->conn)) {
        $client = $this->conn;
        throw new Exception('SOAP Error | Faultcode: '. $client->faultcode .' | Faultstring: '. $client->faultstring);
    }
    return true;
}
function disconnect() {
    if($this->conn != null)
        $this->conn = null;
    else
        return false;
    return true;
}
function fetch($command) {
    $client     = $this->conn;
    if($client == null)
        return false;
    $params     = func_get_args();
    array_shift($params);
    $command    = vsprintf($command, $params);
    $client->executeCommand(new SoapParam($command, 'command'));
    if(is_soap_fault($client))
        throw new Exception('SOAP Error | Faultcode: '. $client->faultcode .' | Faultstring: '. $client->faultstring);
    return $this->getResult($client->__getLastResponse());
}
private function getResult($XMLResponse) {
    // echo 'SOAP:' . $XMLResponse;
    $start      = strpos($XMLResponse, '<?xml');
    $end        = strrpos($XMLResponse, '>');
    $soapdata   = substr($XMLResponse, $start, $end - $start + 1);
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $soapdata, $vals, $index);
    xml_parser_free($xml_parser);
    $result     = array_key_exists('RESULT', $index) ? $vals[$index['RESULT'][0]]['value'] : null;
    if(empty($result))
        return 'SOAP DO NOT RESPOND!';
    return $result;
}

}
Java code:

[CODE]
package com.example.newapp.framework.soap;

import javax.xml.soap.;
import javax.xml.transform.
;
import javax.xml.transform.stream.*;

public class SOAP {
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// soapConnection.

// Send SOAP Message to SOAP Server
// String url = “http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx”;
String url = “http://localhost:7878”;

// ‘uri’ => ‘urn:’. $soap_uri .‘’,
// ‘user_agent’ => ‘aframework’,
// ‘style’ => SOAP_RPC,
// ‘login’ => $soapUser,
// ‘password’ => $soapPass,
// ‘trace’ => 1,
// ‘exceptions’ => 0
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

// <?xml version="1.0" encoding="UTF-8"?>
// <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/1999/XMLSchema-instance
// xmlns:xsd=“http://www.w3.org/1999/XMLSchema
// xmlns:ns1=“urn:TC”>
// <SOAP-ENV:Body SOAP-ENV:encodingStyle=“http://schemas.xmlsoap.org/soap/encoding/”>
// SOAP-ENV:Fault
// SOAP-ENV:Client
// Method ‘example:VerifyEmail’ not implemented: method name or namespace not recognized
// </SOAP-ENV:Fault>
// </SOAP-ENV:Body>
// </SOAP-ENV:Envelope>

        // Process the SOAP Response
        printSOAPResponse(soapResponse);


        soapConnection.close();
    } catch (Exception e) {
        System.err.println("Error occurred while sending SOAP Request to Server");
        e.printStackTrace();
    }
}


private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();


    String serverURI = "http://ws.cdyne.com/";


    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);


    /*
    Constructed SOAP Request Message:
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
        <SOAP-ENV:Header/>
        <SOAP-ENV:Body>
            <example:VerifyEmail>
                <example:email>[email protected]</example:email>
                <example:LicenseKey>123</example:LicenseKey>
            </example:VerifyEmail>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */


    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("[email protected]");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");


    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");


    soapMessage.saveChanges();


    /* Print the request message */
    System.out.print("Request SOAP Message = ");
    soapMessage.writeTo(System.out);
    System.out.println();


    return soapMessage;
}
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    Source sourceContent = soapResponse.getSOAPPart().getContent();
    System.out.print("nResponse SOAP Message = ");
    StreamResult result = new StreamResult(System.out);
    transformer.transform(sourceContent, result);
}

}[/CODE]

Would a perl script to execute console commands be helpful? If so, here’s what I slapped together (almost certainly could be improved):

#!/usr/bin/perl -w

use SOAP::Lite;

site variables (edit these)

my $server = ‘:’;
my $username = ‘admin’;
my $password = ‘password’;

end of site variables

my $link = SOAP::Lite
→ uri(‘urn:TC’)
→ proxy(“http://$username:$password@$server/”);

if ($#ARGV == -1) {
print “worldserver command not providednn”;
exit;
}

if ($#ARGV == 0) {
$command = $ARGV[0];
} else {
for (my $l=0; $l <= $#ARGV; $l++) {
$command .= $ARGV[$l];
if ($l != $#ARGV) {
$command .= " ";
}
}
}

my $results = $link->executeCommand(SOAP::Data->name(‘command’)->value(“$command”));
print $results->result, “n”;
As for the passing of commands, it’s the “executeCommand” function, with the parameter name set as “command” and the value set as whatever console command you wish to execute. Surely, there should be a java equivalent to “$link->executeCommand()”.

yes , thank you, but I just want do that on pure java, I can execute php script from console as well, but … http://www.trinitycore.org/f/topic/10002-cnet-trinitycore-soap-client/ i try to get something like this, but only for java

It looks like you have found everything you need in order to make your java app. You’ve cloned a working SOAP client for java and linked a thread that shows you a template for your desired output (the requestBody string variable). I’m a little confused as to what else you need.

SOAP response now:

Bad Response; Unauthorized
Code:

package com.example.newapp.framework.soap;

/**

  • Created by Sun on 30/01/2015.
    */

import javax.xml.bind.DatatypeConverter;
import javax.xml.soap.;
import javax.xml.transform.
;
import javax.xml.transform.stream.*;

public class NEWSOAP {
public static void main(String args[]) {
try {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        String url = "http://localhost:7878";
        SOAPMessage soapResponse = soapConnection.call(createSOAPRequest("admin", "admin", ".server info"), url);
        printSOAPResponse(soapResponse);
        soapConnection.close();
    } catch (Exception e) {
        System.err.println("Error occurred while sending SOAP Request to Server");
        e.printStackTrace();
    }
}
private static SOAPMessage createSOAPRequest(String _username, String _password, String _command) throws Exception {
    MessageFactory messageFactory   = MessageFactory.newInstance();
    SOAPMessage soapMessage         = messageFactory.createMessage();
    SOAPPart soapPart               = soapMessage.getSOAPPart();

    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
    envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");
    envelope.addNamespaceDeclaration("ns1", "urn:TC");

// “<?xml version="1.0" encoding="UTF-8"?>” +
// “<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”" +
// " xmlns:ns1=“urn:TC”>" +
// “SOAP-ENV:Body” +
// “ns1:executeCommand” +
// “” + _command + “” +
// “</ns1:executeCommand>” +
// “</SOAP-ENV:Body>” +
// “</SOAP-ENV:Envelope>”;
// <SOAP-ENV:Envelope xmlns:SOAP-ENV=“http://schemas.xmlsoap.org/soap/envelope/
// xmlns:SOAP-ENC=“http://schemas.xmlsoap.org/soap/encoding/
// xmlns:ns1=“urn:TC”
// xmlns:xsd=“http://www.w3.org/2001/XMLSchema
// xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”>
// SOAP-ENV:Header/
// SOAP-ENV:Body
// ns1:executeCommand
// .server info
// </ns1:executeCommand>
// </SOAP-ENV:Body>
// </SOAP-ENV:Envelope>

    SOAPBody soapBody           = envelope.getBody();
    SOAPElement soapBodyElem0   = soapBody.addChildElement("executeCommand", "ns1");
    SOAPElement soapBodyElem1   = soapBodyElem0.addChildElement("command");
    soapBodyElem1.addTextNode(_command);

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", "executeCommand");
    headers.addHeader("Authorization", "Basic " + DatatypeConverter.parseBase64Binary(_username + ":" + _password));
    soapMessage.saveChanges();

    /* Print the request message */
    System.out.println("Request SOAP Message");
    soapMessage.writeTo(System.out);
    System.out.println();

    return soapMessage;
}
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
    TransformerFactory transformerFactory   = TransformerFactory.newInstance();
    Transformer transformer                 = transformerFactory.newTransformer();
    Source sourceContent                    = soapResponse.getSOAPPart().getContent();
    System.out.println("Response SOAP Message:");
    StreamResult result                     = new StreamResult(System.out);
    transformer.transform(sourceContent, result);
}

}

may be someone understand what is wrong?

I had the same errors until I put “user:password@” on my URL. The issue seems to come in with how the authentication is performed by the various SOAP libraries. When I saw that the standard URI scheme worked, I was able to simplify my script. Maybe that will work for you, too?

Also, does “[COLOR=rgb(102,0,102)]DatatypeConverter[COLOR=rgb(102,102,0)].parseBase64Binary” convert the “name:password” string to its base64 encoded version? If not, that could be the issue you have.

Update: That does seem to be your issue. That “parseBase64Binary” is expecting a base64 encoded string to convert. You want to encode the string to base64. A web search will reveal methods for such a conversion (in java).

Kylroi,
thank you.

finally I got it work, not without your help, thanks. I gonna write few unit tests later, and I’ll publish final version here

— Canned message start —

This thread is not related to the official Trinity codebase and was moved to the Custom Code section.

Please read the stickies next time.

— Canned message end —