How to unassign/delete usergroup from role progmatically in Liferay 6.2 - liferay

Im trying to remove usergroup from role using the following method. But it doesn't work. Can some one help me to identify the problem?
public static boolean deleteUserGroupFromRole( String groupName, String roleName )
{
try
{
company = CompanyLocalServiceUtil.getCompanyByMx( PropsUtil.get( PropsKeys.COMPANY_DEFAULT_WEB_ID ) );
long companyId = company.getCompanyId();
UserGroup lportalUserGroup= SoasLportalGroupHelper.getLportalUserGroup( groupName);
Role role= getRole( companyId, roleName );
GroupLocalServiceUtil.deleteRoleGroup(role.getRoleId(), lportalUserGroup.getGroupId() );
logger.debug( "Role : "+roleName +" has been deleted from groupName "+groupName);
return true;
}
catch ( PortalException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch ( SystemException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}

Related

How to copy content of generic object for specific object

I need a support in this code, I have a method that I get generic object and a String, so according to the String I get I want to copy the contents of the generic object to
specific object, one observation that Object TypeA don't have same fields that TypeB. for example:
Thanks in advance
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Authorize("Receiving")
#Path("/Print")
public Response LabelPrint(#Context HttpServletRequest request,
final Object generic
,#QueryParam("Type") final String Type) {
if ( Typex.compareTo("X")) {
TypeA typeA = generic;
...
} else {
TypeB typeB = generic;
...
}
return buildResponse(OK);
}
I tried that away, but unsuccessfully
if (labelType.compareTo("X")) {
TypeA x = new TypeA();
BeanUtils.copyProperties(x, generic);
}
else {
TypeA y = new TypeA();
BeanUtils.copyProperties(y, generic);
}
I managed to do it that away, receiving how String
public Response LabelPrint(#Context HttpServletRequest request,
final String objetcForImpression
,#QueryParam("Type") final String Type) {
if ( Typex.compareTo("X")) {
try {
ObjectMapper objetcForImpression = new ObjectMapper();
TypeA typeA = objetcForImpression.readValue(objetcForImpression, TypeA.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
...
} else {
try {
ObjectMapper objetcForImpression = new ObjectMapper();
TypeB typeB = objetcForImpression.readValue(objetcForImpression, TypeA.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return buildResponse(OK);
}

send a JSON request with JSONObject as parameter?

I want to make an android-json request to a webservice with httpClient.
The method which i try to call is "authenticate"
The request should have the following structure:
{"id":"ID","method":"authenticate","params":{"user":"ANDROID",
"password":"PASSWORD", "client":"CLIENT"},"jsonrpc":"2.0"}
mandatory parameter: ?school=SCHOOLNAME
This is what i have tried:
class MyAsnycTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... params) {
String apiUrl = "https://arche.webuntis.com/WebUntis/jsonrpc.do";
JSONObject jsonParams = new JSONObject();
JSONObject params1 = new JSONObject();
HttpClient client = new DefaultHttpClient();
// Prepare a request object
HttpPost post = new HttpPost(apiUrl);
post.setHeader("Content-type", "application/json");
try {
params1.put("?school","litec");
params1.put("user", "40146720133271");
params1.put("password", "1234567");
jsonParams.put("id", "ID");
jsonParams.put("method", "authenticate");
jsonParams.put("params", params1);
jsonParams.put("jsonrpc", "2.0");
StringEntity se = new StringEntity(jsonParams.toString());
post.setEntity(se);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute the request
try {
HttpResponse response = client.execute(post);
Log.d("log_response: ", response.getStatusLine().toString());
// Get hold the response entity
HttpEntity entity = response.getEntity();
// if the response does not enclose the entity, there is no need
// to worry about it
if(entity != null){
// a simple JSON Response read
InputStream instream = entity.getContent();
String result;
// convert content of response to bufferedreader
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
instream.close();
}catch(IOException exp){
exp.printStackTrace();
}
}
result = sb.toString();
Log.d("Result of the Request: ", result);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "OK";
}
protected String doInBackground(String result) {
return result;
// TODO Auto-generated method stub
}
}
After executing this, i get the request:
{"jsonrpc":"2.0","id":"error","error":{"message":"invalid schoolname","code":-8500}}
So its telling me that our schoolname is false.
So what can i do, is my way to pass parameters wrong ?
I saw your question some time ago, but I was not able to answer. I'm working with the WebUntis API as well, and I dont know if you solved the error, but it is a simple error in the url. As mentionend in the API, the mandatory paramter for the method 'authenthicate' is ?school=SCHULNAME. Your Url in the code is 'https://arche.webuntis.com/WebUntis/jsonrpc.do', but the mandatory parameter SCHULNAME is not given. Your Url should look like this: https://arche.webuntis.com/WebUntis/jsonrpc.do?school=SCHULNAME. Maybe you have to add the length of your request. E.g. if you use the method authenthicate: {"id":"ID","method":"authenticate","params":{"user":"USR", "password":"PW", "client":"MyApp"},"jsonrpc":"2.0"}
In this case length would be 109. I hope this helped, even if the question is over a month old. For other Googlers: If you are not using an AsyncTask, you have to return true, not ok.
EDIT:
The code looks like this (I haven't tested this yet, I hope it works):
class MyAsnycTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... params) {
String apiUrl = "https://arche.webuntis.com/WebUntis/jsonrpc.do?school=SCHULNAME"; //Changes here
JSONObject jsonParams = new JSONObject();
JSONObject params1 = new JSONObject();
HttpClient client = new DefaultHttpClient();
// Prepare a request object
HttpPost post = new HttpPost(apiUrl);
post.setHeader("Content-type", "application/json");
try {
params1.put("user", "40146720133271");
params1.put("password", "1234567");
params1.put("client", "seriouslysAndroidApp"); //You can change the name
jsonParams.put("id", "ID");
jsonParams.put("method", "authenticate");
jsonParams.put("params", params1);
jsonParams.put("jsonrpc", "2.0");
StringEntity se = new StringEntity(jsonParams.toString());
post.setHeader("Content-length",""+se.getContentLength()); //header has to be set after jsonparams are complete
post.setEntity(se);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute the request
try {
HttpResponse response = client.execute(post);
Log.d("log_response: ", response.getStatusLine().toString());
// Get hold the response entity
HttpEntity entity = response.getEntity();
// if the response does not enclose the entity, there is no need
// to worry about it
if(entity != null){
// a simple JSON Response read
InputStream instream = entity.getContent();
String result;
// convert content of response to bufferedreader
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
instream.close();
}catch(IOException exp){
exp.printStackTrace();
}
}
result = sb.toString();
Log.d("Result of the Request: ", result);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "OK";
}
protected String doInBackground(String result) {
return result;
// TODO Auto-generated method stub
}

Liferay Document Management System Workflow

I am creating a DMS in Liferay. So far I could upload documents in Liferay in document library. And also I can see documents in document and media portlet. The problem is though status for the document is in pending state, the workflow is not started. Below is my code.
Folder folder = null;
// getting folder
try {
folder = DLAppLocalServiceUtil.getFolder(10181, 0, folderName);
System.out.println("getting folder");
} catch(NoSuchFolderException e)
{
// creating folder
System.out.println("creating folder");
try {
folder = DLAppLocalServiceUtil.addFolder(userId, 10181, 0, folderName, description, serviceContext);
} catch (PortalException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
} catch (SystemException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
}
catch (PortalException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
} catch (SystemException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
// adding file
try {
System.out.println("New File");
fileEntry = DLAppLocalServiceUtil.addFileEntry(userId,
10181, folder.getFolderId(), sourceFileName,
mimeType, title, "testing description",
"changeLog", sampleChapter, serviceContext);
Map<String, Serializable> workflowContext = new HashMap<String, Serializable>();
workflowContext.put("event",DLSyncConstants.EVENT_CHECK_IN);
DLFileEntryLocalServiceUtil.updateStatus(userId, fileEntry.getFileVersion().getFileVersionId(), WorkflowConstants.ACTION_PUBLISH, workflowContext, serviceContext);
System.out.println("after entry"+ fileEntry.getFileEntryId());
} catch (DuplicateFileException e) {
} catch (PortalException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SystemException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return fileEntry.getFileEntryId();
}
I have even used WorkflowHandlerRegistryUtil.startWorkflowInstance(companyId, userId, fileEntry.getClass().getName(), fileEntry.getClassPK, fileEntry, serviceContext);
But still i have the same problem
If you are working on DMS service for upload document and media in Liferay Dxp.
By default status of the document will be draft.You can use below code,
DLFileEntry dlFileEntry = null;
String fileName = null;
long PARENT_FOLDER_ID = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
DLFolder folder = DLFolderLocalServiceUtil.getFolder(group.getGroupId(), PARENT_FOLDER_ID,
"SirswaPartnerDocuments");
long groupId = folder.getGroupId();
long repositoryId = folder.getRepositoryId();
long folderId = folder.getFolderId();
String sourceFileName = "dummy";
String mimeType = MimeTypesUtil.getContentType(file);
String title = file.getName();
String extension = "Caption";
fileName = file.getName();
String uniqueTitle = DLFileEntryLocalServiceUtil.getUniqueTitle(groupId, folderId,
folder.getDefaultFileEntryTypeId(), title, extension);
String changeLog = "SirswaChangeLog";
String description = folder.getDescription();
long defaultFileEntryTypeId = folder.getDefaultFileEntryTypeId();
try
{
dlFileEntry = DLFileEntryLocalServiceUtil.addFileEntry(folder.getUserId(), groupId,
repositoryId, folder.getFolderId(), sourceFileName, MimeTypesUtil.getContentType(file),
uniqueTitle, description, changeLog, folder.getDefaultFileEntryTypeId(),
ddmFormValuesMap, file, is, size, serviceContext);
}
catch (Exception e)
{
e.printStackTrace();
}
Now if you want to change the status of document and media draft to Approved programmatically.
Use below code It will work as expected
int workFlowStatus = WorkflowConstants.STATUS_APPROVED;
dlFileEntry = DLFileEntryLocalServiceUtil.updateStatus(folder.getUserId(),dlFileEntry.getFileVersion().getFileVersionId(),workFlowStatus, serviceContext,new HashMap<String, Serializable>());
This is a piece of code that insert correctly fileentry into document library. Take care the serviceContext settings.
ServiceContext serviceContext = new ServiceContext();
serviceContext.setAddGroupPermissions(true);
serviceContext.setUserId(userDest.getUserId());
serviceContext.setScopeGroupId(userDest.getGroupId());
serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);
FileEntry newfile =
DLAppLocalServiceUtil.addFileEntry(
userDest.getUserId(),
userDest.getGroupId(),
folder.getFolderId(),
item.getFileName(),
MimeTypesUtil.getContentType(item.getFileName()),
item.getFileName(), null, null, bytes,
serviceContext);

Cannot figure out which route between two same method, one without parameter and one with

In my controller, I have two method like that :
public ActionResult NouvelleDemande()
{
int NumDossier = StructureData.DonneNumDossier((string)Session["Utilisateur"], (string)Session["MotDePasse"]);
List<Contact> ListeContacts = StructureData.DonneListeContact(NumDossier);
if (ListeContacts != null)
{ ViewBag.ListeContacts = ListeContacts; }
else
{ ViewBag.ListeContacts = null; }
return View();
}
public ActionResult NouvelleDemande(DemandeAssistance nouvelleDemande)
{
bool DemandeEnregistree = nouvelleDemande.EnregistrerDemande();
if (DemandeEnregistree)
{
return Index();
}
else
{
ViewBag.Error = "La demande n'a pas été enregistrée !";
return View();
}
}
So when I want just to display the view() associated to the method, I call the first one. In the view(), I have a form which when submitted, send an object DemandeAssistance to the second method. In the routes config, i did that :
routes.MapRoute(
name: "NouvelleDemande",
url: "{controller}/{action}",
defaults: new { controller = "Accueil", action = "NouvelleDemande" }
);
routes.MapRoute(
name: "AjouterNouvelleDemande",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Accueil", action = "NouvelleDemande", id = UrlParameter.Optional }
);
But it shows me an error when I want just to display the view saying that there is a misunderstanding between these two routes. What did I do wrong ?
I manage to find out what was missing even if I don't really understand why.
I've just put that :
// POST : /Accueil/NouvelleDemande
[HttpPost]
Upon the method which contains a parameter, as follows:
// POST : /Accueil/NouvelleDemande
[HttpPost]
public ActionResult NouvelleDemande(DemandeAssistance nouvelleDemande)
{
bool DemandeEnregistree = nouvelleDemande.EnregistrerDemande();
if (DemandeEnregistree)
{
return Index();
}
else
{
ViewBag.Error = "La demande n'a pas été enregistrée !";
return View();
}
}
Maybe those interested will have time to explain why it works actually.

Do I need to dispose SPWeb here...?

protected void getNews()
{
using (SPWeb web = getWeb("InternalNews"))
{
fetchNewsFromWeb(ref dtNews,true,"English",new string[] { "Internal news page" },web,startDate,endDate,false,true);
}
}
protected SPWeb getWeb(string contentTypeUrlKey)
{
try
{
List<string> urls = CTUrlWrapper.GetContentTypeUrl(contentTypeUrlKey, this.Page.Request.Url.ToString());
return SPContext.Current.Site.OpenWeb(urls[0].ToLowerInvariant().Replace(SPContext.Current.Site.Url.ToLowerInvariant(), "").TrimStart('/'));
}
catch
{
throw new Exception("Can not fetch value from CTUrl list, key: \"" + contentTypeUrlKey + "\"");
}
}
Do I really need to dispose the web in fetchNewsFromWeb method?
protected DataTable fetchNewsFromWeb(ref DataTable dtAllData, bool useCriticalField, string pageLanguage, string[] contentTypes, SPWeb web, DateTime? fromDate, DateTime? toDate, bool otherUnitNews, bool useHeaderPrefix)
{
SPSiteDataQuery sdq = GetQuery(useCriticalField);
StringBuilder sbQuery = new StringBuilder();
sbQuery.Append(getWhereClause(pageLanguage, fromDate, toDate, contentTypes, otherUnitNews));
sbQuery.Append(getOrderByClause(useCriticalField));
sdq.Query = sbQuery.ToString();
try
{
DataTable foundItems = web.GetSiteData(sdq);
if (foundItems.Rows.Count > 0)
{
foreach (DataRow row in foundItems.Rows)
{
try
{
object[] dtAlldataTemp = extractNewsFields(row, useHeaderPrefix);
dtAllData.Rows.Add(dtAlldataTemp);
}
catch (Exception ex)
{
}
}
}
}
catch (Exception ex)
{
}
finally {web.Dispose();}// do we really need this here?
return dtAllData;
}
protected SPWeb getWeb(string contentTypeUrlKey)
{
try
{
List<string> urls = CTUrlWrapper.GetContentTypeUrl(contentTypeUrlKey, this.Page.Request.Url.ToString());
return SPContext.Current.Site.OpenWeb(urls[0].ToLowerInvariant().Replace(SPContext.Current.Site.Url.ToLowerInvariant(), "").TrimStart('/'));
}
catch
{
throw new Exception("Can not fetch value from CTUrl list, key: \"" + contentTypeUrlKey + "\"");
}
}
No you don't.
The using will take care of disposing it already.
Did you ask SPDisposeCheck?
It depends on how getWeb function is returning the SPWeb.
If its just a SPContext.Current.Web - > Answer is No.
If its returned by opening a new web using OpenWeb() call. Answer is Yes.
Can you not pass the web by ref and have the outer dispose take are of it?

Resources