Fóruns

Início » Liferay Portal » English » 3. Development

Visualização combinada Visão plana Exibição em árvore
Tópicos [ Anterior | Próximo ]
James Falkner
Liferay 6.1 jsonws example
16 de Abril de 2012 08:34
Resposta

James Falkner

LIFERAY STAFF

Ranking: Liferay Legend

Mensagens: 1198

Data de entrada: 17 de Setembro de 2010

Mensagens recentes

In my blog post from last June, I gave 3 examples of using Liferay's built-in JSON web services to query and post new content to Liferay. It was based on 6.0, and a couple of you noticed that it doesn't work in 6.1, so I re-did the 3rd example to demonstrate how to achieve the same thing using 6.1's new jsonws services. Below you will find the addArticle() and removeArticle() from the 3rd example of my blog post, re-written to work with Liferay 6.1 GA1.


  1
  2    private static void addArticle() throws Exception {
  3        HttpHost targetHost = new HttpHost("localhost", 8080, "http");
  4        DefaultHttpClient httpclient = new DefaultHttpClient();
  5        httpclient.getCredentialsProvider().setCredentials(
  6            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
  7            new UsernamePasswordCredentials("bruno@7cogs.com", "bruno"));
  8
  9        // Create AuthCache instance
 10        AuthCache authCache = new BasicAuthCache();
 11        // Generate BASIC scheme object and add it to the local
 12        // auth cache
 13        BasicScheme basicAuth = new BasicScheme();
 14        authCache.put(targetHost, basicAuth);
 15
 16        // Add AuthCache to the execution context
 17        BasicHttpContext ctx = new BasicHttpContext();
 18        ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);
 19
 20        HttpPost post = new HttpPost("/api/secure/jsonws/journalarticle/add-article");
 21        Calendar yesterday = Calendar.getInstance();
 22        yesterday.add(Calendar.DAY_OF_YEAR, -1);
 23        Calendar nextWeek = Calendar.getInstance();
 24        nextWeek.add(Calendar.WEEK_OF_YEAR, 1);
 25        List<NameValuePair> params = new ArrayList<NameValuePair>();
 26        params.add(new BasicNameValuePair("groupId", "10180"));
 27        params.add(new BasicNameValuePair("classNameId", "0"));
 28        params.add(new BasicNameValuePair("classPK", "0"));
 29        params.add(new BasicNameValuePair("articleId", "60000"));
 30        params.add(new BasicNameValuePair("autoArticleId", "false"));
 31        params.add(new BasicNameValuePair("titleMap", "{\"en_US\":\"Test JSON Article\"}"));
 32        params.add(new BasicNameValuePair("descriptionMap", "{\"en_US\":\"Test JSON Description\"}"));
 33        params.add(new BasicNameValuePair("content", "<?xml version='1.0' encoding='UTF-8'?><root available-locales=\"en_US\" default-locale=\"en_US\"><static-content language-id=\"en_US\"><![CDATA[<p>\n" +
 34            "\ttest content</p>]]></static-content></root>"));
 35        params.add(new BasicNameValuePair("type", "general"));
 36        params.add(new BasicNameValuePair("structureId", ""));
 37        params.add(new BasicNameValuePair("templateId", ""));
 38        params.add(new BasicNameValuePair("layoutUuid", ""));
 39        params.add(new BasicNameValuePair("displayDateMonth", "" + (1 + yesterday.get(Calendar.MONTH))));
 40        params.add(new BasicNameValuePair("displayDateDay", "" + yesterday.get(Calendar.DAY_OF_MONTH)));
 41        params.add(new BasicNameValuePair("displayDateYear", "" + yesterday.get(Calendar.YEAR)));
 42        params.add(new BasicNameValuePair("displayDateHour", "" + yesterday.get(Calendar.HOUR_OF_DAY)));
 43        params.add(new BasicNameValuePair("displayDateMinute", "" + yesterday.get(Calendar.MINUTE)));
 44        params.add(new BasicNameValuePair("expirationDateMonth", "" + (1 + nextWeek.get(Calendar.MONTH))));
 45        params.add(new BasicNameValuePair("expirationDateDay", "" + nextWeek.get(Calendar.DAY_OF_MONTH)));
 46        params.add(new BasicNameValuePair("expirationDateYear", "" + nextWeek.get(Calendar.YEAR)));
 47        params.add(new BasicNameValuePair("expirationDateHour", "" + nextWeek.get(Calendar.HOUR_OF_DAY)));
 48        params.add(new BasicNameValuePair("expirationDateMinute", "" + nextWeek.get(Calendar.MINUTE)));
 49        params.add(new BasicNameValuePair("neverExpire", "false"));
 50        params.add(new BasicNameValuePair("reviewDateMonth", "" + (1 + nextWeek.get(Calendar.MONTH))));
 51        params.add(new BasicNameValuePair("reviewDateDay", "" + nextWeek.get(Calendar.DAY_OF_MONTH)));
 52        params.add(new BasicNameValuePair("reviewDateYear", "" + nextWeek.get(Calendar.YEAR)));
 53        params.add(new BasicNameValuePair("reviewDateHour", "" + nextWeek.get(Calendar.HOUR_OF_DAY)));
 54        params.add(new BasicNameValuePair("reviewDateMinute", "" + nextWeek.get(Calendar.MINUTE)));
 55        params.add(new BasicNameValuePair("neverReview", "false"));
 56        params.add(new BasicNameValuePair("indexable", "true"));
 57        params.add(new BasicNameValuePair("articleURL", "articleURL"));
 58        params.add(new BasicNameValuePair("serviceContext", "{}"));
 59        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
 60        post.setEntity(entity);
 61        HttpResponse resp = httpclient.execute(targetHost, post, ctx);
 62        System.out.println(resp.getStatusLine());
 63        resp.getEntity().writeTo(System.out);
 64        httpclient.getConnectionManager().shutdown();
 65    }
 66
 67    public static void removeArticle() throws Exception {
 68        HttpHost targetHost = new HttpHost("localhost", 8080, "http");
 69        DefaultHttpClient httpclient = new DefaultHttpClient();
 70        httpclient.getCredentialsProvider().setCredentials(
 71            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
 72            new UsernamePasswordCredentials("bruno@7cogs.com", "bruno"));
 73
 74        // Create AuthCache instance
 75        AuthCache authCache = new BasicAuthCache();
 76        // Generate BASIC scheme object and add it to the local
 77        // auth cache
 78        BasicScheme basicAuth = new BasicScheme();
 79        authCache.put(targetHost, basicAuth);
 80
 81        // Add AuthCache to the execution context
 82        BasicHttpContext ctx = new BasicHttpContext();
 83        ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);
 84
 85        HttpPost post = new HttpPost("/api/secure/jsonws/journalarticle/delete-article");
 86        List<NameValuePair> params = new ArrayList<NameValuePair>();
 87        params.add(new BasicNameValuePair("groupId", "10180"));
 88        params.add(new BasicNameValuePair("articleId", "60000"));
 89        params.add(new BasicNameValuePair("articleURL", "articleURL"));
 90        params.add(new BasicNameValuePair("serviceContext", "{}"));
 91
 92        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
 93        post.setEntity(entity);
 94        HttpResponse resp = httpclient.execute(targetHost, post, ctx);
 95        System.out.println(resp.getStatusLine());
 96        resp.getEntity().writeTo(System.out);
 97        httpclient.getConnectionManager().shutdown();
 98
 99    }


You will notice a couple of changes:

  • The path to the jsonws resource has changed (no longer need tunnel-web). It is now /api/secure/jsonws/<service>/<method>. You can read more about these services in the official development documentation.
  • There are a couple of new parameters needed for addArticle(), and they are of type java.util.Map - these can be passed by forming a serialized representation of the map using json notation. e.g. {"en_US":"Some Title in US English"}
  • There are also new parameters for classNameID, classPK, and layoutId - all can be set to 0 when creating a new article. These new parameters are used for storing default values for content (see LPS-16960) and for setting the default display page (see LPS-15035).

Similar changes are needed to make the other 2 examples work, but they should be straightforward based on the example above.

Enjoy!
Mohammad Islam
RE: Liferay 6.1 jsonws example
21 de Junho de 2012 06:13
Resposta

Mohammad Islam

Ranking: New Member

Mensagens: 10

Data de entrada: 18 de Abril de 2012

Mensagens recentes

Hi James:
I have JSON services working in 6.1 but it's not secured. I can access my test service using url http://localhost:8080/DataSourceTest-portlet/api/secure/jsonws/training/get-my-training/myparam/myparamvalue

Only problem is I can not secure access using user id and pass. What does this mean when we have api/secure/jsonws in the url?

Thanks.
Mohammad
Hitoshi Ozawa
RE: Liferay 6.1 jsonws example
10 de Agosto de 2012 08:04
Resposta

Hitoshi Ozawa

Ranking: Liferay Legend

Mensagens: 7990

Data de entrada: 23 de Março de 2010

Mensagens recentes

I have JSON services working in 6.1 but it's not secured. I can access my test service using url http://localhost:8080/DataSourceTest-portlet/api/secure/jsonws/training/get-my-training/myparam/myparamvalue

Only problem is I can not secure access using user id and pass. What does this mean when we have api/secure/jsonws in the url?


Check the following security patch.

http://www.liferay.com/community/security-team/known-vulnerabilities/-/asset_publisher/T8Ei/content/cst-sa-lps-26935-all-json-web-services-are-accessible-without-authentication-?redirect=http%3A%2F%2Fwww.liferay.com%2Fcommunity%2Fsecurity-team%2Fknown-vulnerabilities%3Fp_p_id%3D101_INSTANCE_T8Ei%26p_p_lifecycle%3D0%26p_p_state%3Dnormal%26p_p_mode%3Dview%26p_p_col_id%3Dcolumn-5%26p_p_col_count%3D1
KARTHIK VENKATARAMAN
RE: Liferay 6.1 jsonws example
26 de Setembro de 2012 18:15
Resposta

KARTHIK VENKATARAMAN

Ranking: New Member

Mensagens: 3

Data de entrada: 26 de Setembro de 2012

Mensagens recentes

Doesn't work with 6.1 EE

Pass value 0 to classNameId parameter.
I get the following exception
com.liferay.portal.NoSuchGroupException: No Group exists with the primary key 0
So I changed classNameId to a positive value.
The article gets added but is not being displayed in the liferay webcontent list.
I had to manually update the classNameId to 0 in JournalArticle table in the DB for the newly added article to appear in the web content list

Please reply
J W
RE: Liferay 6.1 jsonws example
8 de Outubro de 2012 06:49
Resposta

J W

Ranking: New Member

Mensagens: 5

Data de entrada: 7 de Junho de 2011

Mensagens recentes

KARTHIK VENKATARAMAN:
Doesn't work with 6.1 EE

Pass value 0 to classNameId parameter.
I get the following exception
com.liferay.portal.NoSuchGroupException: No Group exists with the primary key 0
So I changed classNameId to a positive value.
The article gets added but is not being displayed in the liferay webcontent list.
I had to manually update the classNameId to 0 in JournalArticle table in the DB for the newly added article to appear in the web content list

Please reply



I'm getting the same Error with LR 6.1.1 CE GA2. I already tried to submit a serviceContext with the scopeGroupId, but it's still the same error. Is there no possible solution?
Harish Kumar
RE: Liferay 6.1 jsonws example
8 de Outubro de 2012 22:56
Resposta

Harish Kumar

Ranking: Expert

Mensagens: 327

Data de entrada: 31 de Julho de 2010

Mensagens recentes

Hi Karthik, J W

I have debugged the code and following are my findings -

1com.liferay.portal.NoSuchGroupException: No Group exists with the primary key 0


Above exception has nothing to do with classNameId parameter; Its because of following code in the JournalArticleWorkflowHandler class

1
2ServiceContext serviceContext = (ServiceContext)workflowContext.get(
3            "serviceContext");
4
5        String articleURL = PortalUtil.getControlPanelFullURL(
6            serviceContext.getScopeGroupId(), PortletKeys.JOURNAL, null);


Here serviceContext.getScopeGroupId() returns 0 that results in com.liferay.portal.NoSuchGroupException exception in PortalImpl class

1
2    public String getControlPanelFullURL(
3            long scopeGroupId, String ppid, Map<String, String[]> params)
4        throws PortalException, SystemException {
5
6        StringBundler sb = new StringBundler(6);
7
8        Group group = GroupLocalServiceUtil.getGroup(scopeGroupId); // at this line


When we pass classNameId parameter a value >0 then this flow is bypassed so we do not get this exceprion.

 1
 2if (classNameId == 0) {
 3            WorkflowHandlerRegistryUtil.startWorkflowInstance(
 4                user.getCompanyId(), groupId, userId,
 5                JournalArticle.class.getName(), article.getId(), article,
 6                serviceContext);
 7
 8            if (serviceContext.getWorkflowAction() !=
 9                    WorkflowConstants.ACTION_PUBLISH) {
10
11                // Indexer
12
13                Indexer indexer = IndexerRegistryUtil.getIndexer(
14                    JournalArticle.class);
15
16                indexer.reindex(article);
17            }
18        }
19        else {
20            updateStatus(
21                userId, article, WorkflowConstants.STATUS_APPROVED, null,
22                serviceContext);
23        }


HTH
Regards
Harish Kumar
RE: Liferay 6.1 jsonws example
15 de Outubro de 2012 23:31
Resposta

Harish Kumar

Ranking: Expert

Mensagens: 327

Data de entrada: 31 de Julho de 2010

Mensagens recentes

To get this fixed pass scopeGroupId within serviceContext -

1 params.add(new BasicNameValuePair("serviceContext.scopeGroupId", "10180"));
Alessandro Nizzo
RE: Liferay 6.1 jsonws example
28 de Agosto de 2014 23:36
Resposta

Alessandro Nizzo

Ranking: Junior Member

Mensagens: 26

Data de entrada: 13 de Fevereiro de 2014

Mensagens recentes

Harish Kumar:
To get this fixed pass scopeGroupId within serviceContext -

1 params.add(new BasicNameValuePair("serviceContext.scopeGroupId", "10180"));


Hi Haris,
where can I find scopeGroupId in lportal database?

I have the same problem with Liferay 6.2.

Thanks in advance
Cesar Quinteiro
RE: Liferay 6.1 jsonws example
8 de Fevereiro de 2013 03:03
Resposta

Cesar Quinteiro

Ranking: Junior Member

Mensagens: 29

Data de entrada: 18 de Outubro de 2011

Mensagens recentes

Hi

first of all thanks for your post,
I was try your sample 1) and after adapting is working fine. But I want to invoke a service (DLFileEntry or DLApp) and in both cases i get the same error:

1java.lang.RuntimeException: No JSON web service action associated with path /dlapp/add-file-entry and method POST for /


the last code I test (for DLApp):

.
 1......
 2
 3         String sTRgroupId = groupId+"";
 4        String sTRfolderId = folderId+"";
 5        String sTRfileEntryTypeId = fileEntryTypeId+"";
 6        String sTRfieldsMap = JsonWriter.objectToJson(fieldsMap);
 7        String sTRfile = JsonWriter.objectToJson(file);;
 8        String sTRis = JsonWriter.objectToJson(is);;
 9        String sTRsize =size+"";
10        String sTRscopeGroupId = scopeGroupId+"";
11        addFileEntry(sTRgroupId, sTRfolderId , title, description, sTRfileEntryTypeId , sTRfieldsMap, sTRfile, sTRis , sTRsize, sTRscopeGroupId );
12
13    public static void addFileEntry(String groupId, String folderId, String title, String description, String fileEntryTypeId, String fieldsMap, String file, String is, String size, String scopeGroupId) throws Exception {
14       
15       
16        HttpHost targetHost = new HttpHost("localhost",8080,"http");
17        DefaultHttpClient httpclient = new DefaultHttpClient();
18        httpclient.getCredentialsProvider().setCredentials(
19                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
20                new UsernamePasswordCredentials("test@liferay.com", “****"));
21
22        // Create AuthCache instance
23        AuthCache authCache = new BasicAuthCache();
24        // Generate BASIC scheme object and add it to the local
25        // auth cache
26        BasicScheme basicAuth = new BasicScheme();
27        authCache.put(targetHost, basicAuth);
28
29        // Add AuthCache to the execution context
30        BasicHttpContext ctx = new BasicHttpContext();
31        ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);
32
33    //    HttpPost post = new HttpPost("/api/secure/jsonws/dlfileentry/add-file-entry");
34        HttpPost post = new HttpPost("/api/secure/jsonws/dlapp/add-file-entry");
35
36        List<NameValuePair> params = new ArrayList<NameValuePair>();
37//        params.add(new BasicNameValuePair("serviceClassName", "com.liferay.portlet.documentlibrary.service.DLFileEntryServiceUtil"));
38        params.add(new BasicNameValuePair("serviceClassName", "com.liferay.portlet.documentlibrary.service.DLAppServiceUtil"));
39        params.add(new BasicNameValuePair("serviceMethodName", "addFileEntry"));
40// dlapp       params.add(new BasicNameValuePair("serviceParameters", "[groupId,repositoryId,folderId,sourceFileName,mimeType,title,description,changeLog,is,size,serviceContext]"));
41// dlapp       params.add(new BasicNameValuePair("serviceParameterTypes", "[long,long,long,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.io.InputStream,long,com.liferay.portal.service.ServiceContext]"));
42//        params.add(new BasicNameValuePair("serviceParameters", "[groupId,repositoryId,folderId,sourceFileName,mimeType,title,description,changeLog,fileEntryTypeId,fieldsMap,file,is,size,serviceContext]"));
43//        params.add(new BasicNameValuePair("serviceParameterTypes", "[long,long,long,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,long,java.util.Map,java.io.File,java.io.InputStream,long,com.liferay.portal.service.ServiceContext]"));
44
45        params.add(new BasicNameValuePair("groupId", groupId));
46        params.add(new BasicNameValuePair("repositoryId", "0"));
47        params.add(new BasicNameValuePair("folderId", folderId));
48        params.add(new BasicNameValuePair("title",title));
49        params.add(new BasicNameValuePair("description", description));
50        params.add(new BasicNameValuePair("changeLog", ""));
51//        params.add(new BasicNameValuePair("fileEntryTypeId", fileEntryTypeId));
52//        params.add(new BasicNameValuePair("fieldsMap", fieldsMap));
53//        params.add(new BasicNameValuePair("file", file));
54        params.add(new BasicNameValuePair("is", is));
55        params.add(new BasicNameValuePair("size", size));
56        params.add(new BasicNameValuePair("serviceContext", "{}"));
57//        params.add(new BasicNameValuePair("serviceContext.scopeGroupId", scopeGroupId));
58        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
59        post.setEntity(entity);
60        HttpResponse resp = httpclient.execute(targetHost, post, ctx);
61        System.out.println(resp.getStatusLine());
62        resp.getEntity().writeTo(System.out);
63        httpclient.getConnectionManager().shutdown();
64
65    }
Cesar Quinteiro
RE: Liferay 6.1 jsonws example
9 de Fevereiro de 2013 10:00
Resposta

Cesar Quinteiro

Ranking: Junior Member

Mensagens: 29

Data de entrada: 18 de Outubro de 2011

Mensagens recentes

I was able to create a DlFileEntry , with the following code: But it works only with empty “bytes” you get a record create but with a cero bytes, I try many diferents ways to convert the bytes into Json string, but any works I always get the error:

{"exception":"Unable to convert to type: [B\njodd.typeconverter.TypeConversionException: Unable to convert value: JVBERi0xLjQKJeLjz9MKNSAwIG9iago8


what is the correct way to fill up that param “bytes” in a /dlapp/add-file-entry

Here is the code I was trying :

 1    public static void main(String[] args) throws Exception {
 2        long folderId =  13713;
 3        long groupId = 10179;
 4        String scopeGroupId ="10179";
 5        String mimeType =  "application/pdf";
 6        long fileEntryTypeId = 0;
 7
 8
 9        File file = new File("temp"+"sourceFileName");
10        String url = "http://localhost:8080/pdfs/ACTANum126.pdf";
11        System.err.println("URL A conectar" +  url);
12        URLConnection conn;
13        try {
14            conn = new URL(url).openConnection();
15
16        conn.connect();
17        InputStream is = conn.getInputStream();
18        byte[] bytes = IOUtils.toByteArray(is);
19
20
21        Base64 base64 = new Base64();
22        byte[] buffer = new byte[(int) file.length() + 100];
23        int length = is.read(buffer);
24        String sTRBytes = Base64.encodeBase64URLSafeString(bytes);
25//        String sTRBytes = JsonWriter.objectToJson(bytes);
26//        String sTRBytes = JsonWriter.toJson(bytes);
27
28        is.close();
29        addDLFileEntry(sTRgroupId, sTRfolderId , "titlessaasss", "description", sTRfileEntryTypeId , sTRfile, sTRis , sTRsize, sTRscopeGroupId, mimeType,sTRBytes );
30
31public static void addDLFileEntry(String groupId, String folderId, String title, String description, String fileEntryTypeId, String file, String is, String size, String scopeGroupId, String mimeType,String sTRBytes) throws Exception {
32   
33   
34    HttpHost targetHost = new HttpHost("localhost",8080,"http");
35    DefaultHttpClient httpclient = new DefaultHttpClient();
36    httpclient.getCredentialsProvider().setCredentials(
37            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
38            new UsernamePasswordCredentials("test@liferay.com", "brasin"));
39
40    // Create AuthCache instance
41    AuthCache authCache = new BasicAuthCache();
42    // Generate BASIC scheme object and add it to the local
43    // auth cache
44    BasicScheme basicAuth = new BasicScheme();
45    authCache.put(targetHost, basicAuth);
46
47    // Add AuthCache to the execution context
48    BasicHttpContext ctx = new BasicHttpContext();
49    ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);
50    HttpPost post = new HttpPost("/api/secure/jsonws/dlapp/add-file-entry");
51    List<NameValuePair> params = new ArrayList<NameValuePair>();
52
53    params.add(new BasicNameValuePair("repositoryId", "10179"));
54    params.add(new BasicNameValuePair("folderId",folderId));
55    params.add(new BasicNameValuePair("sourceFileName", "/Applications/Liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/webapps/pdfs/ACTANum126.pdf"));
56    params.add(new BasicNameValuePair("mimeType", mimeType));
57   
58    params.add(new BasicNameValuePair("title", title));
59    params.add(new BasicNameValuePair("description", "description"));
60    params.add(new BasicNameValuePair("changeLog", "file"));
61    params.add(new BasicNameValuePair("bytes", sTRBytes));
62    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
63    post.setEntity(entity);
64    HttpResponse resp = httpclient.execute(targetHost, post, ctx);
65    System.out.println(resp.getStatusLine());
66    resp.getEntity().writeTo(System.out);
67    httpclient.getConnectionManager().shutdown();
68
69}
Cesar Quinteiro
RE: Liferay 6.1 jsonws example
9 de Fevereiro de 2013 12:08
Resposta

Cesar Quinteiro

Ranking: Junior Member

Mensagens: 29

Data de entrada: 18 de Outubro de 2011

Mensagens recentes

Finally I found the solution:

what the param need is just a list of values that represents the data by example : 23,34,35,12….
as String sTRBytes = JsonWriter.objectToJson(bytes); returns

{"@type":"B","@items”:[23,34,35,12…..]}

you just have to take off what is not need

sTRBytes = sTRBytes.substring(24,sTRBytes.length()-2);

(or any other way to get the content of a Byte[] as a string of a list of numbers)

then with :
params.add(new BasicNameValuePair("bytes", sTRBytes));
you will your data upload a attached to the DLFileEntry Row
Moisés Belda
RE: Liferay 6.1 jsonws example
12 de Fevereiro de 2013 11:31
Resposta

Moisés Belda

Ranking: Junior Member

Mensagens: 61

Data de entrada: 25 de Janeiro de 2011

Mensagens recentes

Hi

I created a JSON Webservice in liferay without authentication.

I build a simple java client that access with that GET call:


 1
 2
 3    URLConnection conn = null;
 4   try {
 5      conn = url.openConnection ();
 6   } catch (IOException e) {
 7        e.printStackTrace();
 8   }
 9   BufferedReader rd = null;
10   try {
11    rd = new BufferedReader(new InputStreamReader(conn.getInputStream(),Charset.forName("UTF-8")));
12   } catch (IOException e) {
13    e.printStackTrace();
14  }
15
16    StringBuffer sb = new StringBuffer();
17    String line;
18     try {
19        while ((line = rd.readLine()) != null) {sb.append(line);    }
20    } catch (IOException e) {
21               e.printStackTrace();
22    }


Then I mount JSONObject with response obtained. It's a simple http get call.

My problem is encoding. By default I received with ISO-8859-1. I changed the InputStreamReader call , with charset UTF-8 but does not works. The special chars are broken by thuis way.

Any help please?
Ram G
RE: Liferay 6.1 jsonws example
20 de Fevereiro de 2013 04:20
Resposta

Ram G

Ranking: New Member

Mensagens: 8

Data de entrada: 27 de Abril de 2010

Mensagens recentes

Hi James,

We are trying to create announcement through json service using httpClient in Liferay 6.1.

JSON URL: http://localhost:8080/api/secure/jsonws/announcements/add-entry We got below exception

ERROR [JSONWebServiceServiceAction:84] java.lang.RuntimeException: No JSON web service action associated with path /announcements/add-entry and method POST for /
java.lang.RuntimeException: No JSON web service action associated with path /announcements/add-entry and method POST for /
at com.liferay.portal.jsonwebservice.JSONWebServiceActionsManagerImpl.getJSONWebServiceAction(JSONWebServiceActionsManagerImpl.java:100)
at com.liferay.portal.kernel.jsonwebservice.JSONWebServiceActionsManagerUtil.getJSONWebServiceAction(JSONWebServiceActionsManagerUtil.java:31)
at com.liferay.portal.jsonwebservice.JSONWebServiceServiceAction.getJSON(JSONWebServiceServiceAction.java:71)
at com.liferay.portal.struts.JSONAction.execute(JSONAction.java:60)
at com.liferay.portal.servlet.JSONServlet.service(JSONServlet.java:64)


Then I have tried with http://localhost:8080/api/secure/json and passing serviceclassname and method as parameter. we got below exception

ERROR [JSONServiceAction:465] No method found for class class com.liferay.portlet.announcements.service.AnnouncementsEntryServiceUtil, method addEntry, and parameters

Thanks,
Ram
Cesar Quinteiro
RE: Liferay 6.1 jsonws example
20 de Fevereiro de 2013 07:33
Resposta

Cesar Quinteiro

Ranking: Junior Member

Mensagens: 29

Data de entrada: 18 de Outubro de 2011

Mensagens recentes

has you send all the params that the JSON Service needs?

you can see in http://localhost:8080/api/jsonws?signature=/announcementsentry/add-entry-19-plid-classNameId-classPK-title-content-url-type-displayDateMonth-displayDateDay-displayDateYear-displayDateHour-displayDateMinute-expirationDateMonth-expirationDateDay-expirationDateYear-expirationDateHour-expirationDateMinute-priority-alert

If you don’t fill that params, then you get the error :
No JSON web service action associated with path /announcements/add-entry and method POST for /
Ram G
RE: Liferay 6.1 jsonws example
20 de Fevereiro de 2013 10:45
Resposta

Ram G

Ranking: New Member

Mensagens: 8

Data de entrada: 27 de Abril de 2010

Mensagens recentes

Cesar Quinteiro:
has you send all the params that the JSON Service needs?

you can see in http://localhost:8080/api/jsonws?signature=/announcementsentry/add-entry-19-plid-classNameId-classPK-title-content-url-type-displayDateMonth-displayDateDay-displayDateYear-displayDateHour-displayDateMinute-expirationDateMonth-expirationDateDay-expirationDateYear-expirationDateHour-expirationDateMinute-priority-alert

If you don’t fill that params, then you get the error :
No JSON web service action associated with path /announcements/add-entry and method POST for /


Thank you for the suggestion. But I have filled all the params. Please find below.

List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();

params.add(new BasicNameValuePair("plid", PropertiesUtil.getProperty("announce_plid")));
params.add(new BasicNameValuePair("classNameId", PropertiesUtil.getProperty("announce_classNameId")));
params.add(new BasicNameValuePair("classPK", PropertiesUtil.getProperty("announce_classPK")));
params.add(new BasicNameValuePair("title", subject));
params.add(new BasicNameValuePair("content", content));
params.add(new BasicNameValuePair("url", PropertiesUtil.getProperty("announce_URL")));
params.add(new BasicNameValuePair("type", PropertiesUtil.getProperty("announce_Type")));
params.add(new BasicNameValuePair("displayDateMonth", ""+(displayStart.get(Calendar.MONTH))));
params.add(new BasicNameValuePair("displayDateDay", ""+(displayStart.get(Calendar.DAY_OF_MONTH))));
params.add(new BasicNameValuePair("displayDateYear", ""+(displayStart.get(Calendar.YEAR))));
params.add(new BasicNameValuePair("displayDateHour", ""+(displayStart.get(Calendar.HOUR_OF_DAY))));
params.add(new BasicNameValuePair("displayDateMinute", ""+(displayStart.get(Calendar.MINUTE))));
params.add(new BasicNameValuePair("expirationDateMonth", ""+(displayEnd.get(Calendar.MONTH))));
params.add(new BasicNameValuePair("expirationDateDay", ""+(displayEnd.get(Calendar.DAY_OF_MONTH))));
params.add(new BasicNameValuePair("expirationDateYear", ""+(displayEnd.get(Calendar.YEAR))));
params.add(new BasicNameValuePair("expirationDateHour", ""+(displayEnd.get(Calendar.HOUR_OF_DAY))));
params.add(new BasicNameValuePair("expirationDateMinute", ""+(displayEnd.get(Calendar.MINUTE))));
params.add(new BasicNameValuePair("priority", PropertiesUtil.getProperty("announce_Priority")));
params.add(new BasicNameValuePair("alert", PropertiesUtil.getProperty("announce_alert")));
Cesar Quinteiro
RE: Liferay 6.1 jsonws example
20 de Fevereiro de 2013 13:52
Resposta

Cesar Quinteiro

Ranking: Junior Member

Mensagens: 29

Data de entrada: 18 de Outubro de 2011

Mensagens recentes

I have similar problem with /api/secure/jsonws/dlfileentry/add-file-entry and wasn’t able to resolve it even I was sending all the params, I was getting the same error:
finally I used /api/secure/jsonws/dlapp/add-file-entry and then it works,
I don’t know If exists equivalent for announcementsentry, I didn’t found,

Any way I don’t see any mistake in your code and after my case where I was double checking my params, and I was getting always the error , my conclusion is that the JSON service is wrong documented, in your case and also in my case, I hope that somebody from Liferay develoment team clarify this point.

Please If you finally found the solution post it here.
Zenobia L
RE: Liferay 6.1 jsonws example
7 de Abril de 2014 10:48
Resposta

Zenobia L

Ranking: Junior Member

Mensagens: 27

Data de entrada: 8 de Abril de 2011

Mensagens recentes

I had similar error messages and it was solved by using hints on the JSON calls, that helps the web-server to match the correct method
Zenobia L
RE: Liferay 6.1 jsonws example
7 de Abril de 2014 12:42
Resposta

Zenobia L

Ranking: Junior Member

Mensagens: 27

Data de entrada: 8 de Abril de 2011

Mensagens recentes

for example, the below JSON call is working,
using a hint = 10
(I am using "api/secure/jsonws/invoke ", Liferay 6.1 GA2)

 1
 2
 3    JSONObject _command = new JSONObject();
 4        JSONObject serviceContext = new JSONObject();
 5JSONArray files = new JSONArray();
 6
 7        try {
 8
 9            JSONObject _params = new JSONObject();
10            _params.put("groupId", GROUP_ID);
11            _params.put("categoryId", CATEGORY_ID);
12            _params.put("subject", "test 15");
13            _params.put("body", "test 15");
14            _params.put("format", "bbcode");
15            _params.put("inputStreamOvPs", files);
16            _params.put("anonymous", false);
17            _params.put("priority", 0);
18            _params.put("allowPingbacks", false);
19            _params.put("serviceContext", serviceContext);
20            _params.put("serviceContext.addGroupPermissions", true);
21            _params.put("serviceContext.assetTagNames", "vegetables, water");
22            _command.put("/mbmessage/add-message.10", _params);
Jon Hatch
RE: Liferay 6.1 jsonws example
21 de Maio de 2014 07:34
Resposta

Jon Hatch

Ranking: New Member

Mensagens: 3

Data de entrada: 18 de Outubro de 2013

Mensagens recentes

Hello, and thank you for the great informative post!!

I am having trouble executing via JSONWS at http://localhost:8080/api/jsonws

Specifically the add-article method. I am receiving the following message when I invoke: "com.liferay.portlet.journal.ArticleTitleException"

Here is the parameter/value list. Any thoughts?

 1Liferay.Service(
 2  '/journalarticle/add-article',
 3  {
 4    groupId: 10184,
 5    folderId: 12211,
 6    classNameId: 0,
 7    classPK: 0,
 8    articleId: '60000',
 9    autoArticleId: false,
10    titleMap: {"en_us":"Some Title in US English"},
11    descriptionMap: {"en_us":"Some desc in US English"},
12    content: 'This is my test content.',
13    type: 'general',
14    ddmStructureKey: '0',
15    ddmTemplateKey: '0',
16    layoutUuid: '0',
17    displayDateMonth: 02,
18    displayDateDay: 25,
19    displayDateYear: 2014,
20    displayDateHour: 12,
21    displayDateMinute: 12,
22    expirationDateMonth: 12,
23    expirationDateDay: 12,
24    expirationDateYear: 2015,
25    expirationDateHour: 12,
26    expirationDateMinute: 12,
27    neverExpire: true,
28    reviewDateMonth: 12,
29    reviewDateDay: 12,
30    reviewDateYear: 2014,
31    reviewDateHour: 12,
32    reviewDateMinute: 12,
33    neverReview: true,
34    indexable: true,
35    articleURL: 'testURL'
36  },
37  function(obj) {
38    console.log(obj);
39  }
40);
Jon Hatch
RE: Liferay 6.1 jsonws example
21 de Maio de 2014 13:21
Resposta

Jon Hatch

Ranking: New Member

Mensagens: 3

Data de entrada: 18 de Outubro de 2013

Mensagens recentes

Well, I figured out that exception. I didn't have my content wrapped in XML.

Now I am getting the following...any thoughts?

"No DDMStructure exists with the key {groupId=10197, classNameId=10109, structureKey=0}"
Vijay Aravind Rajagopalan
RE: Liferay 6.1 jsonws example
25 de Agosto de 2014 07:57
Resposta

Vijay Aravind Rajagopalan

Ranking: New Member

Mensagens: 1

Data de entrada: 21 de Agosto de 2014

Mensagens recentes

I am getting the same error. I am using the /api/jsonws/invoke

"No DDMStructure exists with the key {groupId=10197, classNameId=10109, structureKey=11680}"

Any help and pointers is greatly appreciated.