choice list in filenet - cmis

I am learning CMIS and Filenet P8 .
using library apache-chemistry for CMIS.
I have problem in ChoiceList.
A choice List is associated with the PropertyDefination.
I was trying to display the choice list related to each PropertyDefinition.
ItemIterable<ObjectType> v = session.getTypeChildren("cmis:document", true);
Iterator<ObjectType> i = v.iterator();
while(i.hasNext()){
ObjectType a = i.next();
if(a!=null)
{
Map<String, PropertyDefinition<?>> d = a.getPropertyDefinitions();
Iterator<String> itr = d.keySet().iterator();
while(itr.hasNext()){
String key = itr.next().toString();
if ((Boolean.FALSE.equals(d.get(key).isInherited()))) {
PropertyDefinition<?> value = d.get(key);
// Choice List
List<?> ch = value.getChoices();
System.out.println("value " + value.getDisplayName()+ " " + " choice list " + ch.toString());
for (Object object : ch) {
System.out.println(object.toString());
}
Customproperties properties = new Customproperties(value.getDisplayName(),value.getPropertyType().toString(),value.getCardinality().name(),value.isRequired());
customPropertyList1.add(properties);
}
}
}
}
Output
value Document Title choice list []
value From choice list []
value To choice list []
value Cc choice list []
value Subject choice list [[extensions=null], [extensions=null]]
[extensions=null]
[extensions=null]
value Sent On choice list []
value Received On choice list []
value Link IDs choice list []
// For the propertyDefination Subject there is a choice list but it's showing me null.. I can't retrieve the choice List properly.
How can I solve this issue?

List<Choice> ch = value.getChoices();
for (Choice Choice : ch) {
System.out.println(choice.getDisplayName());
}

You should cast the PropertyDefinition to the proper subclass.
You can see how they do it in the Converter.java (see the source of the apache chemistry how they did it).
Regards,
Magic

Related

Groovy: Get index of all occurences of sublist from arraylist

I am new to groovy and trying to find the indexes of all sublists in a list.
I am trying to use something like Collections.indexOfSubList like in java but it gives exception saying it applies on Lists and not ArrayLists.
So I am trying to define my own function. I am finding all the indices of all the elements in the smaller list existing in the longer list and then subtracting the indices of the result array. If it comes to 1 then I am considering that index to a sublist.
I know that I have the logic a little twisted. Can somebody guide with a better and efficient way of doing this.
Below is my code:
List list1 = [1,2,3,4,5,6,1,2,3]
List list2 = [1,2]
index1 = list1.findIndexValues {
it == list2[0];
}
index2 = list1.findIndexValues {
it == list2[1];
}
println index1
println index2
result = []
for (int i = 0; i < index1.size(); i++) {
result.add(index2[i]-index1[i]);
}
println result
Edit: no longer uses Collections due to new issue re: Elastic Search.
The following code traverses along the source list, creating a sublist. It checks the sublist to see if it starts with the target list. See the asserts below (e.g. the indexes are 0-based):
def listStartsWithSubList = { source, target ->
def result = false
if (source.size() >= target.size()) {
result = true
target.eachWithIndex { item, index ->
result = result && (item == source[index])
}
}
result
}
def indexOfSubLists = { source, target ->
def results = []
source.eachWithIndex { item, index ->
def tmpList = source[index..source.size()-1]
if (listStartsWithSubList(tmpList, target)) {
results << index
}
}
results
}
assert [1] == indexOfSubLists([1,2,3], [2,3])
assert [2] == indexOfSubLists([1,2,3], [3])
assert [] == indexOfSubLists([1,2,3], [4])
assert [0,6] == indexOfSubLists([1,2,3,4,5,6,1,2,3], [1,2])

Grails convert String to Map with comma in string values

I want convert string to Map in grails. I already have a function of string to map conversion. Heres the code,
static def StringToMap(String reportValues){
Map result=[:]
result=reportValues.replace('[','').replace(']','').replace(' ','').split(',').inject([:]){map,token ->
List tokenizeStr=token.split(':');
tokenizeStr.size()>1?tokenizeStr?.with {map[it[0]?.toString()?.trim()]=it[1]?.toString()?.trim()}:tokenizeStr?.with {map[it[0]?.toString()?.trim()]=''}
map
}
return result
}
But, I have String with comma in the values, so the above function doesn't work for me. Heres my String
[program_type:, subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC, INC]
my function returns ABC only. not ABC, INC. I googled about it but couldnt find any concrete help.
Generally speaking, if I have to convert a Stringified Map to a Map object I try to make use of Eval.me. Your example String though isn't quite right to do so, if you had the following it would "just work":
// Note I have added '' around the values.
​String a = "[program_type:'', subsidiary_code:'', groupName:'', termination_date:'', effective_date:'', subsidiary_name:'ABC']"
Map b = Eval.me(a)​
// returns b = [program_type:, subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC]
If you have control of the String then if you can create it following this kind of pattern, it would be the easiest solution I suspect.
In case it is not possible to change the input parameter, this might be a not so clean and not so short option. It relies on the colon instead of comma values.
​String reportValues = "[program_type:, subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC, INC]"
reportValues = reportValues[1..-2]
def m = reportValues.split(":")
def map = [:]
def length = m.size()
m.eachWithIndex { v, i ->
if(i != 0) {
List l = m[i].split(",")
if (i == length-1) {
map.put(m[i-1].split(",")[-1], l.join(","))
} else {
map.put(m[i-1].split(",")[-1], l[0..-2].join(","))
}
}
}
map.each {key, value -> println "key: " + key + " value: " + value}
BTW: Only use eval on trusted input, AFAIK it executes everything.
You could try messing around with this bit of code:
String tempString = "[program_type:11, 'aa':'bb', subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC, INC]"
List StringasList = tempString.tokenize('[],')
def finalMap=[:]
StringasList?.each { e->
def f = e?.split(':')
finalMap."${f[0]}"= f.size()>1 ? f[1] : null
}
println """-- tempString: ${tempString.getClass()} StringasList: ${StringasList.getClass()}
finalMap: ${finalMap.getClass()} \n Results\n finalMap ${finalMap}
"""
Above produces:
-- tempString: class java.lang.String StringasList: class java.util.ArrayList
finalMap: class java.util.LinkedHashMap
Results
finalMap [program_type:11, 'aa':'bb', subsidiary_code:null, groupName:null, termination_date:null, effective_date:null, subsidiary_name:ABC, INC:null]
It tokenizes the String then converts ArrayList by iterating through the list and passing each one again split against : into a map. It also has to check to ensure the size is greater than 1 otherwise it will break on f[1]

Incomprehensible technical interview

This was a question asked in a recent programming interview.
Given a string "str" and pair of "N" swapping indices, generate a lexicographically largest string. Swapping indices can be reused any number times.
Eg:
String = "abdc"
Indices:
(1,4)
(3,4)
Answer:
cdba, cbad, dbac,dbca
You should print only "dbca" which is lexicographically largest.
This might sound naive, but I completely fail to follow the question. Can someone please help me understand what the question means?
I think it's saying that, given the string mystring = "abdc", you are instructed to switch characters at the specified index pairs such that you produce the lexicographically "largest" string (i.e. such that if you lex-sorted all possible strings, it would end up at the last index). So you have two valid operations: (1) switch mystring[1] with mystring[4] ("abdc" --> "cbda"), and (2) switch mystring[3] with mystring[4] ("abdc" --> "abcd"). Also, you can multiply chain operations: either operation (1) followed by (2) ("abdc" --> "cbda" --> "cbad"), or vice versa ("abdc" --> "abcd" --> "dbca"), and so on and so forth ("abdc" --> "cbda" --> "cbad" --> "dbac").
Then you (reverse) lex-sort these and pop off the top index:
>>> allPermutations = ['abcd', 'cbad', 'abdc', 'cbda', 'dbca', 'dbac']
>>> lexSorted = sorted(allPermutations, reverse=True) # ['dbca', 'dbac', 'cbda', 'cbad', 'abdc', 'abcd']
>>> lexSorted.pop(0)
'dbca'
Based on the clarification by #ncemami I came up with this solution.
public static String swap(String str, Pair<Integer, Integer> p1, Pair<Integer, Integer> p2){
TreeSet<String> set = new TreeSet<>();
String s1 = swap(str, p1.getKey(), p1.getValue());
set.add(s1);
String s2 = swap(s1, p2.getKey(), p2.getValue());
set.add(s2);
String s3 = swap(str, p2.getKey(), p2.getValue());
set.add(s3);
String s4 = swap(s3, p1.getKey(), p1.getValue());
set.add(s4);
return set.last();
}
private static String swap(String str, int a, int b){
StringBuilder sb = new StringBuilder(str);
char temp1 = str.charAt(a);
char temp2 = str.charAt(b);
sb.setCharAt(a, temp2);
sb.setCharAt(b, temp1);
return sb.toString();
}
Here my Java solution:
String swapLexOrder(String str, int[][] pairs) {
Map<Integer, Set<Integer>> neighbours = new HashMap<>();
for (int[] pair : pairs) {
// It contains all the positions that are reachable from the index present in the pairs
Set<Integer> reachablePositionsL = neighbours.get(pair[0]);
Set<Integer> temp = neighbours.get(pair[1]); // We use it just to merge the two sets if present
if (reachablePositionsL == null) {
reachablePositionsL = (temp == null ? new TreeSet<>() : temp);
} else if (temp != null) {
// Changing the reference so every addition to "reachablePositionsL" will reflect on both positions
for (Integer index: temp) {
neighbours.put(index, reachablePositionsL);
}
reachablePositionsL.addAll(temp);
}
reachablePositionsL.add(pair[0]);
reachablePositionsL.add(pair[1]);
neighbours.put(pair[0], reachablePositionsL);
neighbours.put(pair[1], reachablePositionsL);
}
StringBuilder result = new StringBuilder(str);
for (Set<Integer> set : neighbours.values()) {
Iterator<Character> orderedCharacters = set.stream()
.map(i -> str.charAt(i - 1))
.sorted(Comparator.reverseOrder())
.iterator();
set.forEach(i -> result.setCharAt(i - 1, orderedCharacters.next()));
}
return result.toString();
}
Here an article that explain my the problem.
String = "abcd"
co_ord = [(1,4),(3,4)]
def find_combinations(co_ord, String):
l1 = []
for tup_le in co_ord:
l1.extend(tup_le)
l1 = [x-1 for x in l1]
l1 = list(set(l1))
l2 = set(range(len(String)))-set(l1)
return l1,int(''.join(str(i) for i in l2))
def perm1(lst):
if len(lst) == 0:
return []
elif len(lst) == 1:
return [lst]
else:
l = []
for i in range(len(lst)):
x = lst[i]
xs = lst[:i] + lst[i+1:]
for p in perm1(xs):
l.append([x]+p)
return l
lx, ly = find_combinations(co_ord, String)
final = perm1(lx)
print(final)
temp = []
final_list=[]
for i in final:
for j in i:
temp.append(String[j])
final_list.append(''.join(temp))
temp=[]
final_list = [ i[:ly] + String[ly] + i[ly:] for i in final_list]
print(sorted(final_list,reverse=True)[0])

Object isn't recognized as part of collection

I'm trying to create a script which gathers puts elements from XML in a list and verifies that a specific object is a part of this list. Please find my script below:
class BaggageEntitlement{
String allowancePieces
String ruleType
String ruleId
String passengerNameRef
String segmentNumber
boolean equals(BaggageEntitlement that) {
return (
this.allowancePieces.equals(that.allowancePieces) &&
this.ruleType.equals(that.ruleType) &&
this.ruleId.equals(that.ruleId) &&
this.passengerNameRef.equals(that.passengerNameRef) &&
this.segmentNumber.equals(that.segmentNumber)
)
}
}
ArrayList<BaggageEntitlement> expectedEntitlements = new ArrayList<BaggageEntitlement>()
ArrayList<BaggageEntitlement> actualEntitlements = new ArrayList<BaggageEntitlement>()
BaggageEntitlement segment1Entitlement = new BaggageEntitlement(allowancePieces : '2', ruleType : 'OVERRIDE', ruleId : '15483', passengerNameRef: '01.01', segmentNumber: '1')
def cbfNode = new XmlSlurper().parseText(messageExchange.getResponseContentAsXml()).Body.CalculateBagFeesRS
def baggageEntitlementNode = cbfNode.AncillaryOffers.Itinerary.BaggageEntitlements
baggageEntitlementNode.EntitlementItineraryPart.each{
def baggageAllowanceEntitlementNode = it.BaggageAllowanceEntitlement
BaggageEntitlement baggageEntitlement = new BaggageEntitlement()
baggageEntitlement.allowancePieces = baggageAllowanceEntitlementNode.MaxPieces.text().toString()
baggageEntitlement.ruleType = baggageAllowanceEntitlementNode.#ruleType.toString()
baggageEntitlement.ruleId = baggageAllowanceEntitlementNode.#ruleId.toString()
baggageEntitlement.passengerNameRef = it.PassengerReference.#nameReferenceNumber.toString()
baggageEntitlement.segmentNumber = airIdToSegmentNumber[it.SegmentReference.#segmentNumber.toString()]
actualEntitlements.add(baggageEntitlement)
}
But after creating a collection, objects which are present in created collection aren't recognized as a part of collection. I've created the following piece of code to demonstrate this:
println "Is iterator in collection: ${actualEntitlements.contains(segment1Entitlement)}"
println "Is object equals (I) to iterator: ${actualEntitlements[0] == segment1Entitlement}"
println "Is object equals (II) to iterator: " + actualEntitlements[0].equals(segment1Entitlement)
println "Is 'allowancePieces' members are equal: " + (actualEntitlements[0].allowancePieces == segment1Entitlement.allowancePieces)
println "Is 'ruleType' members are equal: " + (actualEntitlements[0].ruleType == segment1Entitlement.ruleType)
println "Is 'ruleId' members are equal: " + (actualEntitlements[0].ruleId == segment1Entitlement.ruleId)
println "Is 'passengerNameRef' members are equal: " + (actualEntitlements[0].passengerNameRef == segment1Entitlement.passengerNameRef)
println "Is 'segmentNumber' members are equal: " + (actualEntitlements[0].segmentNumber == segment1Entitlement.segmentNumber)
And the console output for comparing object member by member is looks like:
Is iterator in collection: false
Is object equals (I) to iterator: true
Is object equals (II) to iterator: true
Is 'allowancePieces' members are equal: true
Is 'ruleType' members are equal: true
Is 'ruleId' members are equal: true
Is 'passengerNameRef' members are equal: true
Is 'segmentNumber' members are equal: true
Could you tell me why my object isn't considered to be a part of collection though member by member comparison returns 'true' for every member?
Because you did not override equals. You supplied your own equals method with a different signature. Override the correct equals method...
public boolean equals(Object o) {
... your code here...
}
...and the Collection will recognize your object, as by the Collection contract for Collection.contains(...)
Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).
(This means the correct equals method and not any equals method. The parameter must be an object, otherwise it is a different equals method and will not help you.)
Having a convenient method like boolean equals(BaggageEntitlement that) may be nice for other purposes (though I doubt it), but this method won't be called since most other classes will expect an Object and not a "BaggageEntitlement". Equals is one of the basic methods of Object, so you should always override that instead of creating your own different version.

Java Eclipse console terminates program before comparing values of user input and string value

So I'm making this program for my younger brother and I ran into a problem. The program is suppose to ask for the user's input and then compare it to multiple string values through a series of "if" statements. What happens instead is the user provides their input and then the program instantly terminates. I've been at this for hours and am starting to get pretty ticked about it. Here's the code that I've typed so far:
package package1;
import java.util.Scanner;
public class Psychic_Calculator {
#SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello user, please type your name below:");
String a = scan.nextLine();
System.out.println("Welcome " + a + ", think of a number. Once you have your number, type 'okay' below!");
String b = scan.nextLine();
if (b == "okay"){
System.out.println("Now, add '11' to your number and type 'okay' below.");
}
else if (b == "Okay"){
System.out.println("Please don't capitalize 'okay', try typing it again!");
String c = scan.nextLine();
if (c == "okay"){
System.out.println("Now, add '11' to your number and type 'okay' below.");
String d = scan.nextLine();
if (d == "okay"){
System.out.println("Now, add '2' to your new number, then type 'okay' below.");
String e = scan.nextLine();
if (e == "okay"){
System.out.println("Now, subtract your original number from your new number, then type 'okay' below.");
String f = scan.nextLine();
if (f == "okay"){
System.out.println("Your new number is '13'. Don't even try denying it.");
}
}
}
}
if (c == "Okay"){
System.out.println("I already told you not to capitalize 'okay', try typing it again, you idiot!");
String g = scan.nextLine();
if (g == "okay"){
System.out.println("Now, add '11' to your number and type 'okay' below.");
String h = scan.nextLine();
if (h == "okay"){
System.out.println("Now, add '2' to your new number, then type 'okay' below.");
String i = scan.nextLine();
if (i == "okay"){
System.out.println("Now, subtract your original number from your new number, then type 'okay' below.");
String j = scan.nextLine();
if (j == "okay"){
System.out.println("Your new number is '13'. Don't even try denying it.");
}
}
}
}
}
if (c != "okay") {
while (c != "okay") {
System.out.println("Do you even know how to spell 'okay'?" + "'" + c + "' does not spell 'okay', you moron! Try typing 'okay' again.");
String n = scan.nextLine();
if (n == "okay"){
System.out.println("Finally, you learned how to spell 'okay'. Your vocabulary is now one word larger, you're welcome. Now, please add '11' to your number and then type 'okay'(correctly this time).");
String k = scan.nextLine();
if (k == "okay"){
System.out.println("Now, add '2' to your new number, then type 'okay' below.");
String l = scan.nextLine();
if (l == "okay"){
System.out.println("Now, subtract your original number from your new number, then type 'okay' below.");
String m = scan.nextLine();
if (m == "okay"){
System.out.println("Your new number is '13'. Don't even try denying it.");
}
}
}
}
else {
System.out.println(a + ", " + "you have failed to type 'okay' too many times! You have no idea how to spell 'okay' you electricutin' motherboarder! Go shove your face in a pile of computer chips and grow a pair!");
System.out.println("(of RAM cartriges...I meant to say RAM cartriges).");
}
}
}
}
}
}
The problem is how you're comparing the strings. Change b == "okay" to b.equals("okay")
Change all the == comparisons to .equals() or .equalsIgnoreCase().
For negations, use (!(c.equals("okay"))
In Java, == will compare primitive types by value but will compare objects by memory address. In other words, when you say b == "okay" its not doing a value comparison, its checking to see whether or not those two objects point to the same memory address, which of course is false.
Update: Just a few things about the way you're going about writing this program.
1) You're creating a lot of string objects needlessly. You're better off re-using one string object until you absolutely need another one. This applies to any object you're using. Try not allocate objects needlessly.
2) Instead of all the if-statements, you can define an array of instructions, like such and condense your code:
String [] instr = {"Add 2", "Add 11", "Subtract Original"};//array of directions
String [] invalidResp = {"Wrong", "You can't spell", "Try Again", "No"};//array of responses to print if user doesnt type 'okay' properly
int instrCounter = 0;//you don't really need this but it helps with readability
String userInput = "";//only string object you'll need =)
while (instrCounter < instr.length){//I couldve just as easily used a for loop instead.
userInput = scan.nextLine();
while (!userInput.equals("okay")){
userInput = scan.nextLine();
System.out.println(invalidResp[(int) (Math.random()*invalidResp.length)]);
//will print a random invalid response from the invalidResp array
System.out.println(userInput + " is not how you spell okay");
}//end while
System.out.println("Great, now, " + instr[instrCounter]);
instrCounter++;
}//end outer while
Remember, when you write code, you want it to be fairly generic and flexible. The way I wrote my code, I can add to the instr array or add more invalid responses and im not needlessly creating objects.
Like I said in the inline comment, I could've just as easily used a for loop for the outer loop but for the sake of readability and making sure you understood what I was doing, I used a while loop as I believe they're more intuitive to read.
GAME:
while(running) {
System.out.println("---------------------------");
continue GAME;
//Name the while loop and then you can break; out.

Resources