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.
Related
Using the same for-each loop inside 2 different method, is there any way to reduce code duplication here?
1st code
for (AjaxControlBean controlBean : requestData.getControls()) {
if (StringUtils.isAnyBlank(controlBean.getId(), controlBean.getName()) || "repeat".equalsIgnoreCase(controlBean.getType()))
{
continue;
}
FormInstanceControl control = formInstance.getControl(controlBean.getId());
if (control == null) {
control = new FormInstanceControl();
control.setFormInstance(formInstance);
control.setControlId(controlBean.getId());
formInstance.putControl(control);
}
if (controlBean.getValues() != null) {
if (control.getData() != null)
control.getData().clear();
else
control.setData(new ArrayList<FormInstanceData>());
for (String value : controlBean.getValues()) {
FormInstanceData data = new FormInstanceData();
data.setControl(control);
data.setType(FormInstanceData.TYPE_TEXT);
data.setText(value);
control.getData().add(data);
}
}
}
2nd code
for (AjaxControlBean controlBean : requestData.getControls()) {
if (StringUtils.isAnyBlank(controlBean.getId(), controlBean.getName()) || "repeat".equalsIgnoreCase(controlBean.getType())) {
continue;
}
FormInstanceControl control = formInstance.getControl(controlBean.getId());
if (control == null) {
control = new FormInstanceControl();
control.setFormInstance(formInstance);
control.setControlId(controlBean.getId());
formInstance.putControl(control);
}
if (controlBean.getValues() != null) {
if (control.getData() != null) {
control.getData().clear();
}
else
{
control.setData(new ArrayList<FormInstanceData>());
}
int i = 0;
for (String value : controlBean.getValues()) {
FormInstanceData data = new FormInstanceData();
data.setControl(control);
data.setType(FormInstanceData.TYPE_TEXT);
data.setText(value);
data.setIdx(i++);
control.getData().add(data);
}
}
}
the only difference it has is the data.setIdx(i++); Please let me know if there is anything i can do to reduce number of lines
You could factor out a method that takes a FormInstanceControl and a AjaxControlBean as arguments. Then you've got all you need:
private void addBeanData( FormInstanceControl control, AjaxControlBean controlBean) {
int i = 0;
for (String value : controlBean.getValues()) {
FormInstanceData data = new FormInstanceData();
data.setControl(control);
data.setType(FormInstanceData.TYPE_TEXT);
data.setText(value);
data.setIdx(i++);
control.getData().add(data);
}
}
This assumes, the first snippet doesn't break if the Idx is set, even if it's not done there in the original code.
Usage: Where before you had the for-loops, you just do addBeanData( control, controlBean );
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());
I'm having a trouble passing the value of error i get when im returning the results of a table.
I have a method in my ServiceImpl class which return results for the table and also counts the amount of errors.
public List<Flow> getAllProcessContextWithCriteriaAndFlowCode(
String startDate, String endDate, String flowCode) {
List<FlowDto> flowDtos = new ArrayList<>(500);
flowDtos = processContextRepository
.fetch(startDate,
endDate, flowCode);
List<Flow> flows = new ArrayList();
// bodyguard
if (flowDtos == null || flowDtos.size() == 0) {
return flows;
}
int counter = 0;
StringBuilder idFonctionnelBuilder = new StringBuilder();
FlowDto currentFlowDto = null;
FlowState flowState = new FlowState();
FlowDto nextFlowDto = null;
Flow flowTemp = null;
Map<String, String> mapFlowIdsAndIdF = new HashMap<>();
int iNbreError = 0;
String sTempError = "";
for (int i = 0; i < flowDtos.size(); i++) {
currentFlowDto = flowDtos.get(i);
if ((i + 1) < flowDtos.size()) {
nextFlowDto = flowDtos.get(i + 1);
if (((nextFlowDto.getFlowId()
.equals(currentFlowDto.getFlowId())))) {
idFonctionnelBuilder.append(currentFlowDto.getIdf() + ", ");
continue;
} else {
flowTemp = new Flow();
flowTemp.setFlowId(currentFlowDto.getFlowId());
flowTemp.setLogRole(currentFlowDto.getLogRole());
Date date = null;
try {
date = inputFormat.parse(currentFlowDto
.getContextTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
flowTemp.setContextTime(outputFormat.format(date));
if (currentFlowDto.getLogRole() != null) {
iNbreError++;
flowTemp.setNbreError(iNbreError);
} else {
flowTemp.setNbreError(iNbreError);
}
flowTemp.setNbreError(iNbreError);
flows.add(flowTemp);
}
} else {
flowTemp = new Flow();
if (currentFlowDto.getLogRole() != null) {
iNbreError++;
flowTemp.setNbreError(iNbreError);
} else {
flowTemp.setNbreError(iNbreError);
}
flowTemp.setContextTime(outputFormat.format(date));
flows.add(flowTemp);
}
}
LOGGER.info("[ getAllProcessContextWithCriteriaAndFlowCode ] iNbreError : "
+ iNbreError);
getNbreError(iNbreError);
return flows;
}
Then i have another method in the same class ServiceImpl who get the number of errors and set it in a variable, the result print is always the right one here.
public int getNbreError( int iNbreError){
System.out.println("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH");
System.out.println(iNbreError);
setCountError(iNbreError);
System.out.println("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH");
System.out.println(countError);
return countError;
}
What i want to do is send this value(counterror) to my RestController which is in another class called RestController so i can send it to my angular front
#GetMapping(value = "/nbreError")
public int getCountError() {
FMServiceImpl flows = new FMServiceImpl();
int countError = 0;
int iNbreError = 0;
return fmService.getNbreError( iNbreError);
}
}
Actually the result is always 0.
Thanks for your any help or advice :)
Don't use getMethod to modify data, check principle Command–query separation (CQS)
Don't create FMServiceImpl manually, Inject FMServiceImpl as dependence to your controller. in spring, Service keeps the state by default.
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());
}
I am trying to write a simple template engine to parse if statements.
<{if $value == true}>
say hello
<{/if}>
I have written working code However, If I have multiple if statements in the file I am parsing then if grabs only the first and last if statement. For example.
<{if $value1 == true}>
say hello
<{/if}>
...
<{if $value2 == true}>
say hello
<{/if}>
...
The code parses and returns:
say hello
<{/if}>
...
<{if $value2 == true}>
say hello
Rather than just returning say hello.
Thanks for your help In advance the code is as follows:
public class Templates {
private static String escape(String value) {
return value.replaceAll("\\$", "\\\\\\$");
}
public static String load(String name) {
return load(name, null);
}
public static String load(String name, Map<String, String> parse) {
String page = new Resources().getTextResource("lib/tpl/" + name);
if (page == null) {
return "The template, " + name + " was NOT FOUND.";
}
if (parse != null) {
Iterator it = parse.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
value = escape(value); // Prevents java exception. Can't deal with $
page = page.replaceAll("\\<\\{\\$" + key + "\\}\\>", value);
}
Pattern ptrn = Pattern.compile("\\<\\{if \\$([a-z]+)\\s*(==|!=|eq|neq|or|and)\\s*(\\w+)\\}\\>(\\p{ASCII}+)\\<\\{/if\\}\\>");
Matcher mtch = ptrn.matcher(page);
System.out.println("\n\n\n");
while(mtch.find()) {
System.out.println("Key is: " + mtch.group(1));
//System.out.println("Key: " + dateMatcher.group(2));
System.out.println("Value is: " + mtch.group(3));
System.out.println("Data is: " + mtch.group(4));
if(parse.get(mtch.group(1)).equals(mtch.group(3))) {
System.out.println("\n\n\nREPLACE");
page = page.replaceAll(ptrn.pattern(), escape(mtch.group(4)));
} else {
//dateMatcher.appendReplacement(page, "");
System.out.println("\n\n\nREMOVE - " + ptrn.pattern());
page = page.replaceAll(ptrn.pattern(), "");
}
}
System.out.println("\n\n\n");
}
return page;
}
}
This might be due to greedy nature.
Try this,
(\\p{ASCII}+?) instead of (\\p{ASCII}+)