четверг, 19 июня 2014 г.

How to call web service from java code example (How to generate proxy java class)

How to call web service from java code from standalone application, from Java Bean or from Servlet.

We have two ways:
  • For Java Bean or Servlet we use Eclipse (NWDS) to generate Java Class Client - Proxy Class.
  • For standalone (desktop) we use SAAJ - SOAP with Attachments API for Java.
Generate web-service client (Proxy Class) in Eclipse:
  1. Create EJB Module project in Eclipse (NWDS)
  2. Create Enterprise Application project in Eclipse (NWDS)
  3. Import here web-service WSDL
  4. Right click on WSDL -> Web Services -> Generate Client
  5. In pop-up window move slider to "Develop client" level. Check that "client project" and "EAR project" is yours. Go to next and then push finish.
  6. Eclipse has created package which contains your Proxy Class for your web-service. It's name looks like "<NameOfYourWebService> + Service" - remember that class.
  7. If you want to call web-service from Java Bean go to 8 step, if from servlet go to 9 step. 
  8. Create Session Java Bean. In your Java Bean create parameter "webService" with type of your proxy class ( it's name "<NameOfYourWebService> + Service" - remember? ). Over that parameter specify "@WebServiceRef" annotation and set: "name=<NameOfYourWebService> + Service".
  9. Create Servlet. In your Servlet create parameter "webService" with type of your proxy class ( it's name "<NameOfYourWebService> + Service" - remember? ). Over that parameter specify "@WebServiceRef" annotation and set "name=<NameOfYourWebService> + Service".
  10. Now if you want call web-service from Servlet, J2EE engine will initialize our parameter "webService" with proxy class when it will be initialized. If you want call web-service from another Java Bean, you can use JNDI to get initialized proxy class. Do that like this: javax.naming.InitialContext.doLookup("<Java Bean JNDI Name of your Java Bean>");
  11. In Java Bean or Servlet create method where you want to call web-service.
  12. In parameter "webService" you have method "get + <NameOfYourWebService> + Port". Call that and you will get your web-service object. This object contains all operations of your web-service. Use it!

Call web-service from standalone application (desktop) using SAAJ:

We will create SOAP message, using SAAJ, and then we will call web service.

1. Create SOAP message:

If you have web service operation getName and this operation has input structure like this:

<user>
  <userId>1</userId>
</user>

Then we will create SOAPMessage like this:

MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();

SOAPPart soapPart = msg.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody body = envelope.getBody();

//create structure like our web service operation input
SOAPElement bodyElement = body.addBodyElement(envelope.createName(
"<web service operation name - getName>", "<prefix, I use 'ns1'>", "<uri, it is property 'targetNamespace' in annotation '@WebService' in your web service java class>"));
SOAPElement nodeUser = bodyElement.addChild("user");
SOAPElement nextNode = nodeUser.addChildElement("userId").addTextNode("1");

//if you should make authorization do this
MimeHeaders headers = msg.getMimeHeaders();
String upas = "login" + ":" + "password";
String auth = "Basic " + new String(javax.xml.bind.DatatypeConverter.printBase64Binary(upas.getBytes()));
headers.addHeaders("Authorization", new String(auth.getBytes()));

2. Now we can call web service with our SOAPMessage

URL url = new URL("<url to web service wsdl without '?wsdl', or url in web service wsdl in node 'address' in property 'location'>");

SOAPConnectionFactory cf = SOAPConnectionFactory.newInstance();
SOAPConnection conn = cf.createConnection();
//here we call web service by java code
SOAPMessage replay = conn.call(msg, url);// replay contains web service response
conn.close();


понедельник, 16 июня 2014 г.

Automated testing in SAP Portal

If you want to test you web application or web-service, you can use JUnitEE to make automated testing.

- create you application, and java classes in there

- create WebModule Project and EAR project for that

- create External Library project and add there junit.jar and junitee.jar

- add dependency from WebModule and EAR project to external library project. After that you can use JUnit API in your WebModule project

- create Java Class in WebModule project and extend it from abstract class junit.framework.TestCase

- create methods in that class to make tests and write everything like it is simple JUnit test

- in WebModule project in folder WEB-INF edit or create if not exist web.xml file

- in that file write this:

  <servlet>
      <servlet-name>UnitTestServlet</servlet-name>
      <servlet-class>org.junitee.servlet.JUnitEEServlet</servlet-class>
  </servlet>

  <servlet-mapping>
      <servlet-name>UnitTestServlet</servlet-name>
      <url-pattern>/UnitTestServlet/*</url-pattern>
  </servlet-mapping>

- in folder WEB-INF create file with name "testCase.txt" and write in that file full class name which contains your tests (which extended from junit.framework.TestCase)

- deploy EAR and external library project on your AS 

- use link  <host>:<port>/<vendor>~<WebModule project name>/UnitTestServlet to see your tests. For example if vendor name is demo.sap.com and WebModule project name is junit/frmw than url will be:  <host>:<port>/demo.sap.com~junit~frmw/UnitTestServlet

среда, 21 мая 2014 г.

Использование Destination API на SAP Portal

Что бы использовать Destination API необходимо:

Подключить из компонента ENGFACADE следующие библиотеки:
tc/bl/exception/lib
tc/bl/security/destination/api
tc/bl/security/lib

вторник, 20 мая 2014 г.

Переменные и методы в Eclipse не подсвечиваются / Variables and methods do not highlight

Если в Eclips не выделяются переменные, методы, классы, константы и т.д., то необходимо:


Window -> Preferences -> Java -> Editor -> Mark Occurrences - поставить галочку напротив Mark Occurences
---------------------------------------------------------------------------------------------------------------------
If variables, methods do not highlight in Eclipse do this:
Window -> Preferences -> Java -> Editor -> Mark Occurrences

пятница, 14 марта 2014 г.

Regexp for checking email string


To check your email with regular expression do that:

String pattern = "[a-zA-Z0-9-_.]+@[a-zA-Z0-9-_.]+\\.[a-zA-Z]{2,4};
System.out.println(Pattern.matches(pattern, "ваша email");

Регулярное выражения для проверки почтового адреса - email

Для того что бы проврить корректность почтового адреса - email сделайте следующее:

String pattern = "[a-zA-Z0-9-_.]+@[a-zA-Z0-9-_.]+\\.[a-zA-Z]{2,4};
System.out.println(Pattern.matches(pattern, "ваша email");

Данное выражение проверяет, что строка содержит перед собакой буквы латиницы большие и маленькие, цифры от 0 до 9, тире, нижнее подчеркивание и точку. Далее проверяется наличие собаки в строке. Далее делаются теже проверки что и вначале. Далее проверяется что строка оканчивается на точку и после очки могут быть латинские буквы большие и маленьки в количестве от 2 до 4.

понедельник, 10 марта 2014 г.

Java concole вывод русских букв

Для того что бы вывести русские буквы в консоль при выполнении java программы в Windows нужно:
- Зайти в консоль(cmd);
- В самом верху на синей полоске правой кнопкой мыши и выбрать свойства;
- На вкладке шрифт выбрать Lucida Console;
- Выполнить команду 'chcp 1251' в консоли;
- Готово;

четверг, 27 февраля 2014 г.

пятница, 15 ноября 2013 г.

Базовые запросы по SQL

В таблице А выбрать определенную последнюю запись:

SELECT *
FROM А
WHERE field1 = '<value>' ORDER BY <field_date> DESC LIMIT 1;

Идея данного запроса в том, что мы берем записи с определенным значением в поле field1, упорядочиваем их по полю field2_date и выводим только первую запись. Условие "последняя запись" достигается тем, что мы упорядочиванием по убыванию по полю field_date, в котором хранится дата записи, и берем только первую оператором LIMIT из результирующей выборки.