How to rewrite the iteration without a nested one? - java

Here are my iterations, but one of them is nested:
objects.forEach(obj -> {
if (obj.getType() == Type.APPLICATION) {
clientApplicationPriorities.add(getClientApplicationPriority(obj.getApplicationShortInfo().getId(), clientId, priority, null));
} else if (obj.getType() == Type.FOLDER) {
final FoldersShortInfo folderInfo = obj.getFolderShortInfo();
final String folderName = folderInfo.getName();
final List<ApplicationShortInfo> appInfos = folderInfo.getApplications();
appInfos.forEach(appInfo -> clientApplicationPriorities.add(getClientApplicationPriority(appInfo.getId(), clientId, priority, folderName)));
} else {
throw new FolderRequestException();
}
});
How can I rewrite it using Stream API?

Please share some more logic related to the implementation of your code.
you should use switch case rather than if-elseif-else loop for more clean code.
List<Employee> objects = new ArrayList<Employee>();
for (Employee emp : objects) {
switch (emp.getType()) {
case Type.application: {
clientApplicationPriorities.add(
getClientApplicationPriority(obj.getApplicationShortInfo().getId(), clientId, priority, null));
}
case Type.folder: {
final FoldersShortInfo folderInfo = obj.getFolderShortInfo();
final String folderName = folderInfo.getName();
final List<ApplicationShortInfo> appInfos = folderInfo.getApplications();
appInfos.forEach(appInfo -> clientApplicationPriorities
.add(getClientApplicationPriority(appInfo.getId(), clientId, priority, folderName)));
}
default: {
throw new FolderRequestException();
}
}
};

Related

How can I simplify if else using java 8 aproach

public Pair<String, String> getSalesChannelDisplayData(DiscountRule rule, List<SalesChannelDto> allSalesChannels) {
String salesChannelDisplayNames = "";
String salesChannelDefaultCountryCodes = "";
Set<String> storeCodes = new HashSet<>();
if(rule.getConditions() != null) {
for (Condition condition : rule.getConditions()) {
if (condition instanceof ValueCondition) {
if (((ValueCondition) condition).getField() == Field.SALES_CHANNEL) {
Set<String> salesChannelIds = new HashSet<>();
if(((ValueCondition) condition).getOperator().equals(Operator.IN)){
salesChannelIds = ((ValueCondition) condition).getValues();
}else if (((ValueCondition) condition).getOperator().equals(Operator.NOT_IN)) {
salesChannelIds = allSalesChannels.stream().map(SalesChannelDto::getId).collect(Collectors.toSet());
salesChannelIds.removeAll(((ValueCondition) condition).getValues());
}
for (String salesChannelId : salesChannelIds) {
SalesChannelDto salesChannel = Beans.find(allSalesChannels, s-> s.getId().equals(salesChannelId));
salesChannelDisplayNames += salesChannel.getDisplayName() + ", ";
storeCodes.add(salesChannel.getDefaultCountryCode());
}
}
}
}
if (salesChannelDisplayNames.length()>1) {
salesChannelDisplayNames = salesChannelDisplayNames.substring(0,salesChannelDisplayNames.length()-2);
salesChannelDefaultCountryCodes = Joiner.on(", ").join(storeCodes);
}
return new Pair<>(salesChannelDisplayNames, salesChannelDefaultCountryCodes);
}
I want to simplify the above code using java stream API. Is that possible for replace the if, else if with java 8 approach?
The stream API is not a good choice to simplify your code. There are some parts in your code that you can modify them.
1- Not to need to check rule.getConditions() nullity.
if(rule.getConditions() != null) {...}
2- Don't repeat yourself by this: ((ValueCondition) condition) instead you can define a variable for it and use it.
ValueCondition vCondition = (ValueCondition) condition;
3- Instead concatenating salesChannelDisplayNames declare a List<String> salesChannelNames = new ArrayList<>(); and add channelName into it.
salesChannelNames.add(salesChannel.getDisplayName());
at the end use String.join(",", salesChannelNames) to add , delimeter between them.
This is a sample you can try out. I have tried to completely eliminate if-else.
public class FunctionalIfElse {
public static void main(String[] args) {
Product product1 = new Product(1, "Audi A8");
String category1 = "car";
System.out.println(ProductProxy.getEnrichedProduct.apply(product1, category1).toString());
Product product2 = new Product(2, "OnePlus 8 Pro");
String category2 = "mobile";
System.out.println(ProductProxy.getEnrichedProduct.apply(product2, category2).toString());
Product product3 = new Product(3, "Macbook Pro");
String category3 = "laptop";
System.out.println(ProductProxy.getEnrichedProduct.apply(product3, category3).toString());
Product product4 = new Product(4, "Emaar Palm Heights");
String category4 = "home";
System.out.println(ProductProxy.getEnrichedProduct.apply(product4, category4).toString());
}
}
#AllArgsConstructor
#Data
class Product {
private int productId;
private String productName;
}
class ProductProxy {
static BiFunction<Product, String, Product> getEnrichedProduct = (inputProduct, category) -> {
AtomicReference<Product> outputProduct = new AtomicReference<>();
Objects.requireNonNull(category, "The category is null");
Predicate<String> checkIsCar = productCategory -> productCategory.equalsIgnoreCase("car") ? true : false;
Predicate<String> checkIsMobile = productCategory -> productCategory.equalsIgnoreCase("mobile") ? true : false;
Predicate<String> checkIsLaptop = productCategory -> productCategory.equalsIgnoreCase("laptop") ? true : false;
Optional.ofNullable(category).filter(checkIsCar).map(input -> ProductService.enrichProductForCar.apply(inputProduct)).map(Optional::of).ifPresent(returnedProduct -> outputProduct.set(returnedProduct.get()));
Optional.ofNullable(category).filter(checkIsMobile).map(input -> ProductService.enrichProductForMobile.apply(inputProduct)).map(Optional::of).ifPresent(returnedProduct -> outputProduct.set(returnedProduct.get()));
Optional.ofNullable(category).filter(checkIsLaptop).map(input -> ProductService.enrichProductForLaptop.apply(inputProduct)).map(Optional::of).ifPresent(returnedProduct -> outputProduct.set(returnedProduct.get()));
Optional.ofNullable(outputProduct.get()).orElseThrow(() -> new RuntimeException("This is not a valid category"));
return outputProduct.get();
};
}
class ProductService {
static Function<Product, Product> enrichProductForCar = inputProduct -> {
inputProduct.setProductName(inputProduct.getProductName() + ":Car");
return inputProduct;
};
static Function<Product, Product> enrichProductForMobile = inputProduct -> {
inputProduct.setProductName(inputProduct.getProductName() + ":Mobile");
return inputProduct;
};
static Function<Product, Product> enrichProductForLaptop = inputProduct -> {
inputProduct.setProductName(inputProduct.getProductName() + ":Laptop");
return inputProduct;
};
}

How can I remove this child from my pane? [duplicate]

In my Java 8 code,
public ChangePersonsName(String email, final String password, final String wantedUsername, final String uuid, final long time, int latency, int[] requests, int[] proxyRequests) throws IOException {
final AtomicReference<Object> token = new AtomicReference<Object>();
final AtomicReference<ArrayList<?>> newHeaders = new AtomicReference<ArrayList<?>>();
new Thread(() -> {
boolean lock = true;
while (lock) {
if (time - System.currentTimeMillis() > 60000) continue;
Map<Header[], String> loginResults = null;
try {
loginResults = this.login(email, password, uuid);
}
catch (IOException e) {
e.printStackTrace();
}
String token = loginResults.entrySet().iterator().next().getValue();
Header[] headers = loginResults.entrySet().iterator().next().getKey();
newHeaders.set(new ArrayList<Object>());
for (Header header : headers) {
if (!header.toString().startsWith("Set-Cookie:")) continue;
((List<BasicHeader>)newHeaders.get()).add(new BasicHeader("Cookie", header.toString().split("Set-Cookie: ")[1]));
}
lock = false;
}
}
).start();
new Timer().schedule(new TimerTask(){
You'll notice that
String token = loginResults.entrySet().iterator().next().getValue();
throws a compile error,
Lambda expression's local variable token cannot redeclare another local variable defined in an enclosing scope.
My question is, How would one go about fixing this? I'm pretty new to Java, I should probably know how to fix this, but i don't.
You already have variable with name token in this scope. You've declared it in 2nd row. To fix just rename 2nd variable:
String newToken = loginResults.entrySet().iterator().next().getValue();

Why does this REST-service not return while the other does?

SITUATION
In the code below you can see 2 REST services which both should return a MessageVO. The first service (serviceThatDoesWork) returns a MessageVO as excpected, but the second service (serviceThatDoesNotWork) refuses to, it doesn't even give any output at all.
However returning a Response (java.ws.rs.core.Response) with serviceThatDoesNotWork does give an output. Even when I skip the 'doStuff'-methods and create a dummy-MessageVO that is exactly the same for each service, the 2nd one doesn't return anything.
QUESTION
Why does the 2nd service fail to return a MessageVO? It doens't return anything when I try returning a MessageVO, and nothing out of the ordinary appears in the logging.
The two services need to return exactly the same kind of thing but still one of them doesn't want to return anything, what am I not seeing here?
Could it be because of the path (and/or the amount of parameters)?
CODE
MyServices.java:
#Path("/myService")
...
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/myPath/{param1}/{param2}/{param3}")
public MessageVO serviceThatDoesWork(#PathParam("param1") Integer param1_id, #PathParam("param2") Integer param2_id, #PathParam("param2") Integer param2_id)
{
List<SomethingVO> lstO = MyRestServiceBusiness.doStuff(param1_id, param2_id, param3_id);
//return SUCCESS or FAIL message
MessageVO msg = new MessageVO();
if(lstO.size() > 0)
{
List<String> s = new ArrayList<String>();
for(SomethingVO k : lstO)
{
s.add(k.getId().toString());
}
msg.setItem_ids(s);
msg.setMsg("SUCCESS");
}
else
{
msg.setMsg("FAIL");
}
return msg;
}
...
#GET
#Path("/myPath/{param1}/{param2}/{param3}/{param4}/.../{param15}{a:(/a/[^/]+?)?}{b:(/b/[^/]+?)?}")
public Response serviceThatDoesNotWork(#PathParam("param1")Integer param1_id, ..., #PathParam("param15") Integer param15_id,
#PathParam("a") String a_id, #PathParam("b") String b_id)
{
//PUT 'OPTIONAL' PARAMS IN A LIST
List<Integer> lstI = new ArrayList<Integer>();
String aId = a_id != null ? a_id.split("/")[2] : null;
String bId = b_id != null ? b_id.split("/")[2] : null;
if(aId != null)
{
lstI.add(Integer.parseInt(aId ));
}
if(bId != null)
{
lstI.add(Integer.parseInt(bId ));
}
//DO STUFF
String afsId = "";
if(lstI.size() > 0)
{
afsId = MyRestServiceBusiness.doStuff(param1, ..., lstI);
}
//return SUCCESS or FAIL message
MessageVO msg = new MessageVO();
if(afsId != null && !afsId.isEmpty())
{
List<String> s = new ArrayList<String>();
s.add(afsId);
msg.setItem_ids(s);
msg.setMsg("SUCCESS");
}
else
{
List<String> s = new ArrayList<String>();
for(Integer i : lstI)
{
s.add(i.toString());
}
msg.setItem_ids(s);
msg.setMsg("FAIL");
}
//WENT THROUGH ALL ABOVE CODE AS EXPECTED, MESSAGEVO HAS BEEN FILLED PROPERLY
return msg;
}
CODE MessageVO.java:
#XmlRootElement
public class MessageVO
{
private String msg;
private List<String> item_ids;
//GETTERS
#XmlElement(name = "Message")
public String getMsg() {
return msg;
}
#XmlElement(name = "Item ID's")
public List<String> getItem_ids() {
return item_ids;
}
//SETTERS
public void setMsg(String msg) {
this.msg = msg;
}
public void setItem_ids(List<String> item_ids) {
this.item_ids = item_ids;
}
If I need to provide extra information please ask, this is my first attempt at (REST-) services.
As Vaseph mentioned in a comment I just forgot the #Produces annotation in the 2nd service.

How to eliminate repeat code in a for-loop?

I have implemented two member functions in the same class:
private static void getRequiredTag(Context context) throws IOException
{
//repeated begin
for (Record record : context.getContext().readCacheTable("subscribe")) {
String traceId = record.get("trace_id").toString();
if (traceSet.contains(traceId) == false)
continue;
String tagId = record.get("tag_id").toString();
try {
Integer.parseInt(tagId);
} catch (NumberFormatException e) {
context.getCounter("Error", "tag_id not a number").increment(1);
continue;
}
//repeated end
tagSet.add(tagId);
}
}
private static void addTagToTraceId(Context context) throws IOException
{
//repeated begin
for (Record record : context.getContext().readCacheTable("subscribe")) {
String traceId = record.get("trace_id").toString();
if (traceSet.contains(traceId) == false)
continue;
String tagId = record.get("tag_id").toString();
try {
Integer.parseInt(tagId);
} catch (NumberFormatException e) {
context.getCounter("Error", "tag_id not a number").increment(1);
continue;
}
//repeated end
Vector<String> ret = traceListMap.get(tagId);
if (ret == null) {
ret = new Vector<String>();
}
ret.add(traceId);
traceListMap.put(tagId, ret);
}
}
I will call that two member functions in another two member functions(so I can't merge them into one function):
private static void A()
{
getRequiredTag()
}
private static void B()
{
getRequiredTag()
addTagToTraceId()
}
tagSet is java.util.Set and traceListMap is java.util.Map.
I know DRY principle and I really want to eliminate the repeat code, so I come to this code:
private static void getTraceIdAndTagIdFromRecord(Record record, String traceId, String tagId) throws IOException
{
traceId = record.get("trace_id").toString();
tagId = record.get("tag_id").toString();
}
private static boolean checkTagIdIsNumber(String tagId)
{
try {
Integer.parseInt(tagId);
} catch (NumberFormatException e) {
return false;
}
return true;
}
private static void getRequiredTag(Context context) throws IOException
{
String traceId = null, tagId = null;
for (Record record : context.getContext().readCacheTable("subscribe")) {
getTraceIdAndTagIdFromRecord(record, traceId, tagId);
if (traceSet.contains(traceId) == false)
continue;
if (!checkTagIdIsNumber(tagId))
{
context.getCounter("Error", "tag_id not a number").increment(1);
continue;
}
tagSet.add(tagId);
}
}
private static void addTagToTraceId(Context context) throws IOException
{
String traceId = null, tagId = null;
for (Record record : context.getContext().readCacheTable("subscribe")) {
getTraceIdAndTagIdFromRecord(record, traceId, tagId);
if (traceSet.contains(traceId) == false)
continue;
if (!checkTagIdIsNumber(tagId))
{
context.getCounter("Error", "tag_id not a number").increment(1);
continue;
}
Vector<String> ret = traceListMap.get(tagId);
if (ret == null) {
ret = new Vector<String>();
}
ret.add(traceId);
traceListMap.put(tagId, ret);
}
}
It seems I got an new repeat... I have no idea to eliminate repeat in that case, could anybody give me some advice?
update 2015-5-13 21:15:12:
Some guys gives a boolean argument to eliminate repeat, but I know
Robert C. Martin's Clean Code Tip #12: Eliminate Boolean Arguments.(you can google it for more details).
Could you gives some comment about that?
The parts that changes requires the values of String tagId and String traceId so we will start by extracting an interface that takes those parameters:
public static class PerformingInterface {
void accept(String tagId, String traceId);
}
Then extract the common parts into this method:
private static void doSomething(Context context, PerformingInterface perform) throws IOException
{
String traceId = null, tagId = null;
for (Record record : context.getContext().readCacheTable("subscribe")) {
getTraceIdAndTagIdFromRecord(record, traceId, tagId);
if (traceSet.contains(traceId) == false)
continue;
if (!checkTagIdIsNumber(tagId))
{
context.getCounter("Error", "tag_id not a number").increment(1);
continue;
}
perform.accept(tagId, traceId);
}
}
Then call this method in two different ways:
private static void getRequiredTag(Context context) throws IOException {
doSomething(context, new PerformingInterface() {
#Override public void accept(String tagId, String traceId) {
tagSet.add(tagId);
}
});
}
private static void addTagToTraceId(Context context) throws IOException {
doSomething(context, new PerformingInterface() {
#Override public void accept(String tagId, String traceId) {
Vector<String> ret = traceListMap.get(tagId);
if (ret == null) {
ret = new Vector<String>();
}
ret.add(traceId);
traceListMap.put(tagId, ret);
}
});
}
Note that I am using lambdas here, which is a Java 8 feature (BiConsumer is also a functional interface defined in Java 8), but it is entirely possible to accomplish the same thing in Java 7 and less, it just requires some more verbose code.
Some other issues with your code:
Way too many things is static
The Vector class is old, it is more recommended to use ArrayList (if you need synchronization, wrap it in Collections.synchronizedList)
Always use braces, even for one-liners
You could use a stream (haven't tested):
private static Stream<Record> validRecords(Context context) throws IOException {
return context.getContext().readCacheTable("subscribe").stream()
.filter(r -> {
if (!traceSet.contains(traceId(r))) {
return false;
}
try {
Integer.parseInt(tagId(r));
return true;
} catch (NumberFormatException e) {
context.getCounter("Error", "tag_id not a number").increment(1);
return false;
}
});
}
private static String traceId(Record record) {
return record.get("trace_id").toString();
}
private static String tagId(Record record) {
return record.get("tag_id").toString();
}
Then could do just:
private static void getRequiredTag(Context context) throws IOException {
validRecords(context).map(r -> tagId(r)).forEach(tagSet::add);
}
private static void addTagToTraceId(Context context) throws IOException {
validRecords(context).forEach(r -> {
String tagId = tagId(r);
Vector<String> ret = traceListMap.get(tagId);
if (ret == null) {
ret = new Vector<String>();
}
ret.add(traceId(r));
traceListMap.put(tagId, ret);
});
}
tagId seems to be always null in your second attempt.
Nevertheless, one approach would be to extract the code that collects tagIds (this seems to be the same in both methods) into its own method. Then, in each of the two methods just iterate over the collection of returned tagIds and do different operations on them.
for (String tagId : getTagIds(context)) {
// do method specific logic
}
EDIT
Now I noticed that you also use traceId in the second method. The principle remains the same, just collect Records in a separate method and iterate over them in the two methods (by taking tagId and traceId from records).
Solution with lambdas is the most elegant one, but without them it involves creation of separate interface and two anonymous classes which is too verbose for this use case (honestly, here I would rather go with a boolean argument than with a strategy without lambdas).
Try this approach
private static void imYourNewMethod(Context context,Boolean isAddTag){
String traceId = null, tagId = null;
for (Record record : context.getContext().readCacheTable("subscribe")) {
getTraceIdAndTagIdFromRecord(record, traceId, tagId);
if (traceSet.contains(traceId) == false)
continue;
if (!checkTagIdIsNumber(tagId))
{
context.getCounter("Error", "tag_id not a number").increment(1);
continue;
}
if(isAddTag){
Vector<String> ret = traceListMap.get(tagId);
if (ret == null) {
ret = new Vector<String>();
}
ret.add(traceId);
traceListMap.put(tagId, ret);
}else{
tagSet.add(tagId);
}
}
call this method and pass one more parameter boolean true if you want to add otherwise false to get it.

How to Mock repository Items in ATG

I am trying to create a Mock class for droplet. I am able to mock the repository calls and req.getParameter but need help on how to mock the repository item list from the repository. Below is the sample code.
for (final RepositoryItem item : skuList) {
final String skuId = (String) item.getPropertyValue("id");
final String skuType = (String) item.getPropertyValue("skuType");
if (this.isLoggingDebug()) {
this.logDebug("skuType [ " + skuType + " ]");
}
final String skuActive = (String) item.getPropertyValue("isActive");
if EJSD.equalsIgnoreCase(skuType) && (skuActive.equals("1"))) {
eSkuList.add(item);
skuCode = (String) item.getPropertyValue(ESTConstants.SKU_MISC1);
} else (PJPROMIS.equalsIgnoreCase(skuType) && skuId.contains("PP") && (skuActive.equals("1"))) {
personalSkuList.add(item);
String tmp = "";
if (skuId.lastIndexOf("-") > -1) {
tmp = skuId.substring(skuId.lastIndexOf("-") + 1);
tmp = tmp.toUpperCase();
if (this.getDefaultDisplayNameMap() != null) {
String val = this.getDefaultDisplayNameMap().get(tmp);
if (StringUtils.isNotEmpty(val)) {
displayNameMap.put(skuId, val);
} else {
val = (String) item.getPropertyValue("displayName");
displayNameMap.put(skuId, val);
}
} else {
final String val = (String) item.getPropertyValue("displayName");
displayNameMap.put(skuId, val);
}
}
}
}
There are a multitude of ways to 'mock' the list. I've been doing it this was as I feel it is more readable.
#Mock private RepositoryItem skuMockA;
#Mock private RepositoryItem skuMockB;
List<RepositoryItem> skuList = new ArrayList<RepositoryItem>();
#BeforeMethod(groups = { "unit" })
public void setup() throws Exception {
testObj = new YourDropletName();
MockitoAnnotations.initMocks(this);
skuList = new ArrayList<RepositoryItem>();
skuList.add(skuMockA);
skuList.add(skuMockB);
Mockito.when(skuMockA.getPropertyValue("id")).thenReturn("skuA");
Mockito.when(skuMockA.getPropertyValue("skuType")).thenReturn(ActiveSkuDroplet.EJSD);
Mockito.when(skuMockA.getPropertyValue(ESTConstants.SKU_MISC1)).thenReturn("skuCodeA");
Mockito.when(skuMockA.getPropertyValue("displayName")).thenReturn("skuADisplayName");
Mockito.when(skuMockB.getPropertyValue("id")).thenReturn("skuB-PP");
Mockito.when(skuMockB.getPropertyValue("skuType")).thenReturn(ActiveSkuDroplet.PJPROMIS);
Mockito.when(skuMockB.getPropertyValue(ESTConstants.SKU_MISC1)).thenReturn("skuCodeB");
Mockito.when(skuMockB.getPropertyValue("displayName")).thenReturn("skuBDisplayName");
}
So when you then call this within a test it will be something like this:
Mockito.when(someMethodThatReturnsAList).thenReturn(skuList);
So the key really is that you are not mocking the List but instead the contents of the List.
Creating a mock using mockito is a good option.
But I am here explaining a different way of mocking the repository item.
Create a common implementation for RepositoryItem, say MockRepositoryItemImpl like this in your test package.
Public MockRepositoryItemImpl implements RepositoryItem {
private Map<String, Object> properties;
MockRepositoryItemImpl(){
properties = new HashMap<>();
}
#override
public Object getPropertyValue(String propertyName){
return properties.get(propertyName);
}
#override
public void setPropertyValue(String propertyName, Object propertyValue){
properties.put(propertyName, propertyValue);
}
}
Use this implementation to create the mock object in your test case.
RepositoryItem mockSKU = new MockRepositoryItemImpl();
mockSKU.setPropertyValue("id", "sku0001");
mockSKU.setPropertyValue("displayName", "Mock SKU");
mockSKU.setPropertyValue("skuType", "Type1");
mockSKU.setPropertyValue("isActive", "1");

Categories