The question says everything. When I am printing an Attribute it is:
cn: WF-008-DAM-PS
The code snippet is:
private void searchGroup() throws NamingException {
NamingEnumeration<SearchResult> searchResults = getLdapDirContext().search(groupDN, "(objectclass=groupOfUniqueNames)", getSearchControls());
String searchGroupCn = getCNForBrand(m_binder.getLocal("brandId"), m_binder.getLocal("brandName"));
Log.info(searchGroupCn);
while (searchResults.hasMore()) {
SearchResult searchResult = searchResults.next();
Attributes attributes = searchResult.getAttributes();
Attribute groupCn = attributes.get("cn");
if(groupCn != null) {
Log.info(groupCn.toString());
}
}
}
How can I only get the value that is: WF-008-DAM-PS, that is without the key portion?
Regards.
The solution is:
Attribute groupCn = attributes.get("cn");
String value = groupCn.get();
Invoke the getValue() method or the getValue(int) method.
General
Let's say that we have:
Attributes attributes;
Attribute a = attributes.get("something");
if(a.size() == 1)
then you can use a.get() or a.get(0) to get the unique value
if(a.size() > 1)
iterate through all the values:
for ( int i = 0 ; i < a.size() ; i++ ) {
Object currentVal = a.get(i);
// do something with currentVal
}
If you use a.get() here, it will return only the first value, because its internal implementation (in BasicAttribute) looks like this:
public Object get() throws NamingException {
if (values.size() == 0) {
throw new NoSuchElementException("Attribute " + getID() + " has no value");
} else {
return values.elementAt(0);
}
}
Both methods (get(int) and get()) throws a NamingException.
Practical example
(when the Attribute instance has multiple values)
LdapContext ctx = new InitialLdapContext(env, null);
Attributes attributes = ctx.getAttributes("", new String[] { "supportedSASLMechanisms" });
System.out.println(attributes); // {supportedsaslmechanisms=supportedSASLMechanisms: GSSAPI, EXTERNAL, DIGEST-MD5}
Attribute a = atts.get("supportedsaslmechanisms");
System.out.println(a); // supportedSASLMechanisms: GSSAPI, EXTERNAL, DIGEST-MD5
System.out.println(a.get()); // GSSAPI
for (int i = 0; i < a.size(); i++) {
System.out.print(a.get(i) + " "); // GSSAPI EXTERNAL DIGEST-MD5
}
This worked:(checking attribute present or not before fetching attribute value)
Attributes attributes = searchResult.getAttributes();
Attribute mail = attributes.get("mail");
if (mail != null)
{
System.out.println(" Mail-id value from LDAP :"+mail.get());
}
Related
I have a problem with java that I have been trying to solve for several hours and can not.
I have an object of Ad, I use this object with arrayList.
I want to select the object of Ad - which are inside the arrayList - I want to select the object according to its attributes, I do this in the function:
I get attributes that an ad object has - I want to filter the Ad by attributes.
public class filterAds {
public class Ad {
String domain;
String role;
String area;
public Ad(String domain, String role, String area) {
this.area = area;
this.domain = domain;
this.role = role;
}
}
List<Ad> adList = new ArrayList<Ad>();
public String[] getAds(String role, String domain, String area) {
boolean filter = true;
if(role != null)
{
//use it in search
}
if(area != null)
{
//use it in search
}
if(domain != null)
{
//use it in search
}
List<String> adIDsList = new ArrayList<String>();
for (int i = 0; i < adList.size(); i++) {
if (filter /* && also other conditions*/) {
adIDsList.add(adList.get(i).id);
}
}
String[] adIDs = new String[adIDsList.size()];;
adIDs = adIDsList.toArray(adIDs);
return adIDs;
}
}
I think the problem is not big, just need to fix the if conditions - but I have not been able to for hours.
quite standard way to organize such search is:
List<String> adIDsList = new ArrayList<String>();
for (int i = 0; i < adList.size(); i++) {
Ad ad = adList.get(i);
if (
(role == null || role.equals(ad.role)) &&
(area == null || area.equals(ad.area)) &&
(domain == null || domain.equals(ad.domain))
) {
adIDsList.add(ad.id);
}
}
so, we handle null and non-null in the same condition
You can use stream api to filter data from list.
Below is the rough code that may give you idea how you can do.
List<String> adIDsList = adList.stream()
.filter(ad -> role.equals(ad.role))
.filter(ad -> domain.equals(ad.domain))
.filter(ad -> area.equals(ad.area))
.map(Ad::id)
.collect(Collectors.toList());
Array of objects and static/non-static methods.
class Foititis //Dimiourgeia twn antikeimenwn typou foititis
{
private String onoma, epitheto;
private short AriMit, EtosEis;
public Foititis (String on, String ep, short AM, short EE)
{
onoma = on;
epitheto = ep;
AriMit = AM;
EtosEis = EE;
}
public String getEpwnymo() //Prosbash sto epitheto apo tis alles klaseis
{
return epitheto;
}
public String toString()
{
String emf;
emf = "--------------------" + "\n";
emf = "Onoma" + onoma + "\n";
emf = "Epwnymo" + epitheto + "\n";
emf = "Arithmos Mitrwoy" + AriMit + "\n";
emf = "Etos Eisagwnis" + EtosEis + "\n";
emf = "--------------------";
return emf;
}
}
class MyUtils01 //Anazitisi Me Epwnymo, Seiriaki Anazitisi
{
public static int AnazitisiMeEpwnymo(Foititis[] a, String key)
{
boolean flag = false;
int j = 0;
return -1;
while ( !flag && j < a.length)
{
if (a[j].getEpwnymo.equals(key))
{
flag = true;
return j;
}
j += 1;
}
}
}
At this program, I have an array (named pinakas) and sent to the method "AnazitisiMeEpwnymo" of the class "MyUtils01", and renamed "a" (in order to be used). The array is an array of objects of the type "Foititis". So I want to have access from the class "MyUtils01" at the attribute "epitheto", which is private, that's why I tried to use a get method, but I get an error message.
Thank you in advance, I know that my thread may be covered somehow at another post, but none (from those that I found) where not using array of objects, and did not try to call the method like above.
You're missing some parentheses
a[j].getEpwnymo().equals(key)
^^
not
a[j].getEpwnymo.equals(key)
I have a scenario where I need to fetch 500 from web service api and display the final output values as comma separated values like id,name,owner,account,path,ccvalues. To achieve this I am writing a method where Iam getting all this information and setting to one java object. Fields are below. Finally i created one list which holds this Video objects. videos.add(video)
String identifier;
String name;
String ownerName;
String accountName;
String mediaPath;
List<KalturaLanguage> ccList;
Now how to display my output from videos list object. Please help me resolving this.
code is:
for (String mediaId : mediaList) {
if (mediaId != null) {
String mediaFullPath = getMediaPath(mediaId);
entryInfo = getMedia(mediaId);
metadataList = getMetadata(mediaId);
ccs = getClosedCaptions(mediaId);
if (entryInfo != null) {
video = new Video();
System.out.println("entryInfo.id"
+ entryInfo.id);
System.out.println("entryInfo.name"
+ entryInfo.name);
System.out.println("mediaFullPath"
+ mediaFullPath);
video.setIdentifier(entryInfo.id);
video.setName(entryInfo.name);
video.setMediaPath(mediaFullPath);
}
if (metadataList != null
&& metadataList.totalCount != 0) {
List<KalturaMetadata> metadataObjs = metadataList.objects;
if (metadataObjs != null
&& metadataObjs.size() > 0) {
for (int i = 0; i < metadataObjs.size(); i++) {
KalturaMetadata metadata = metadataObjs
.get(i);
if (metadata != null) {
if (metadata.xml != null) {
metadataValues = parseXml(metadata.xml);
if (metadataValues.size() != 0) {
ibmAccountList = metadataValues
.get(0);
for (String account : ibmAccountList) {
System.out
.println("IBM Account Name ------->"
+ account);
video.setAccountName(account);
}
ownerList = metadataValues
.get(1);
for (String owner : ownerList) {
System.out
.println("Account Owner Name ------->"
+ owner);
video.setOwnerName(owner);
}
}
}
}
}
}
}
}
if (ccs.size() != 0) {
for (Map.Entry<String, List<KalturaCaptionAsset>> entry : ccs
.entrySet()) {
String key = entry.getKey();
List<KalturaCaptionAsset> values = entry
.getValue();
// System.out.println("Key = " + key);
for (KalturaCaptionAsset asset : values) {
System.out.println(" CC value : "
+ asset.language);
ccList.add(asset.language);
video.setCcList(ccList);
videos.add(video);
}
}
}
}
You are going in a wrong direction. Just implement your toString method inside Video class.
When you iterate over list and print video object it calls toString method inside the video class.
While providing implementation in video class, generate a String in required format.
I’m working on UCM project and the workflow is to read on a metadata filed (xComments , which will have SSN #’s separated by commas) and submit a separate document for each SSN found in the xComments and replace the SSN’s with the custom metadata filed Name xSSN.
Just to be brief:
If document “A” has xComments filed value 1,2,3 and xSSN value “ multiple” then I want my script/java code to create “Document A”, “Document B”, “Document c”, having a xSSN filed 1,2 and 3
public class ContentCheckInHandler implements FilterImplementor{
public int doFilter(Workspace ws, DataBinder binder, ExecutionContext cxt)
throws DataException, ServiceException
{
//boolean isCheckin = StringUtils.convertToBool(binder.getLocal("isCheckin"), false);
//boolean isNew = StringUtils.convertToBool(binder.getLocal("isNew"), false);
String dDocType = binder.getLocal("dDocType");
String xRegion = binder.getLocal("xRegion");
String xSSN = binder.getLocal("xSSN");
String xComments = binder.getLocal("xComments");
String [] SSNListSeparate = xComments.split(",");
int[]convertxComments = new int[xComments.length()];
boolean chkxComments = false;
String primaryFile = getFilePath(binder, "primaryFile");
if(xSSN == "Multiple" || xSSN == "multiple" && xComments.length() > 0)
{
for(int i = 0; i < SSNListSeparate.length; i++)
{
convertxComments[i] = Integer.parseInt(SSNListSeparate[i]);
DataBinder b = new DataBinder();
b.putLocal("dID", binder.getLocal("dID"));
b.putLocal("dDocName", binder.getLocal("dDocName"));
b.putLocal("xAccountNumber", binder.getLocal("xAccountNumber"));
b.putLocal("xSSN",SSNListSeparate[i]);
b.putLocal("xRegion", xRegion);
b.putLocal("xFirstName", "");
b.putLocal("xLastName", "");
b.putLocal("xFSADocType", binder.getLocal("xFSADocType"));
b.putLocal("xPLDocType", binder.getLocal("xPLDocType"));
b.putLocal("xDocSource", binder.getLocal("xDocSource"));
ws.execute("CHECKIN_NEW_SUB", b);
}
}
else
{
chkxComments = false;
SystemUtils.trace("TrainingDocument", "SSN value: " + xSSN);//just for testing
}
return CONTINUE;
}
public String getFilePath(DataBinder binder, String fileKey)
throws DataException
{
return ServerFileUtils.getTemporaryFilePath(binder, fileKey);
}
}
I have an issue with an Apache POI XSSF in that it is not reading blank cell value.
I hava a class that implements DefaultHandler. In that class all non-blank cells are able to read from startElement and endElement methods.
I want to read blank cells in middle of the data cells.
Can anyone provide an example of how to do so or directions as to how to debug this?
Ran into this very same problem today. I was using the XSSF event model. But XSSF wouldn't give a column element nor a value element for the blank columns. Most probably because the backing XML is that way.
The key is to check the attribute for the cell reference (you know the A1, A2, A3 that Excel uses). Attributes are passed to the startElement() callback method. We can then detect missing cell references. So if we got L1 for the previous column element and get N1 for the current column element, we know M1 is the blank/missing cell.
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (qName.equals("c")) {
String newColRef = atts.getValue("r");
coverColumnDistanceWithNulls(currentColRef, newColRef);
And coverColumnDistanceWithNulls() simply adds nulls for each missing cell reference between currentColRef and newColRef
private void coverColumnDistanceWithNulls(String fromColRefString, String toColRefString) {
int colRefDistance = getDistance(fromColRefString, toColRefString);
while (colRefDistance > 1) {
logger.debug("Covering distance with null");
rowValues.add(null);
--colRefDistance;
}
}
private int getDistance(String fromColRefString, String toColRefString) {
String fromColRef = getExcelCellRef(fromColRefString);
String toColRef = getExcelCellRef(toColRefString);
logger.debug("fromCol: {} toCol: {}", new Object[] {fromColRefString, toColRefString});
return excelCellReferenceOrder.get(toColRef) - excelCellReferenceOrder.get(fromColRef);
}
private String getExcelCellRef(String fromColRef) {
if (fromColRef != null) {
int i = 0;
for (;i < fromColRef.length(); i++) {
if (Character.isDigit(fromColRef.charAt(i))) {
break;
}
}
if (i == 0) {
return fromColRef;
}
else {
return fromColRef.substring(0, i);
}
}
return null;
}
Building off Sab Than's answer:
private void coverColumnDistance(String fromColRefString, String toColRefString) {
int colRefDistance = getDistance(fromColRefString, toColRefString);
while (colRefDistance > 0) {
c = getRow().addCell("");
colRefDistance--;
}
}
private int getDistance(String fromColRefString, String toColRefString) {
String fromColRef = getExcelCellRef(fromColRefString);
String toColRef = getExcelCellRef(toColRefString);
int distance = 0;
if (fromColRef == null || fromColRef.compareTo(toColRef) > 0)
return getDistance("A", toColRefString) + 1;
if (fromColRef != null && toColRef != null) {
while (fromColRef.length() < toColRef.length() || fromColRef.compareTo(toColRef) < 0) {
distance++;
fromColRef = increment(fromColRef);
}
}
return distance;
}
public String increment(String s) {
int length = s.length();
char c = s.charAt(length - 1);
if(c == 'Z') {
return length > 1 ? increment(s.substring(0, length - 1)) + 'A' : "AA";
}
return s.substring(0, length - 1) + ++c;
}
private String getExcelCellRef(String fromColRef) {
if (fromColRef != null) {
int i = 0;
for (; i < fromColRef.length(); i++) {
if (Character.isDigit(fromColRef.charAt(i))) {
break;
}
}
if (i == 0) {
return fromColRef;
}
else {
return fromColRef.substring(0, i);
}
}
return null;
}
If I remember correctly if you try and read a cell value that has not been assigned a value you get a NullPointerException or similar. You could surround the code that is examining the cell in a try-catch statement and then write your own code to deal with such scenario.
If my memory does not serve me correctly and tthe error thrown is not a NullPointerException then change the catch exception class to the relevant one.