Declaring Objects Using Constructors in Java

So, I had a dillema last night where I was really getting irritated with my code and how messy it was when declaring objects and their elements.

Coincidentally it was at this same time I started getting fired up about how I definitely remember doing this in C# with no issues whatsoever, so this began my hunt to figure out how to declare objects and their elements in Java.

For starters, we will use a Complex HashMap.

When typing it in your IDE you need to declare it as the following:

HashMap<Integer, HashMap<String, String>> testHash = new HashMap<Integer, HashMap<String, String>>();

Next, what I want you to do is before the semicolon put the following:

{ { } }

With this you will be able to start adding elements as if you are declaring them in a typical JSON Format.

A fun tip for you to keep in mind is that you can actually use the IDE AutoComplete of CTRL+Enter or CTRL+Space to see what options you have available.

When you are done you will end up with an example that is sort of like this if you use the IDE Code Formatting to make it pretty:

JSON Style Adding to Java Objects - Enhanced

Here is an example I did with a more complex HashMap:

JSON Style Adding to Java Objects - Complex Example

An important thing to note here is that the same thing can be done with both the List/ArrayList and any Java Classes that you declare as long as you have a constructor.

I had a great time putting this together so let me know your thoughts, feedback, criticism below in the comments.

 

Executing Javascript from the Managed Bean in ADF

Borrowed From:
http://www.baigzeeshan.com/2011/05/how-to-execute-javascript-in-java-in.html

import javax.faces.context.FacesContext;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;

FacesContext fctx = FacesContext.getCurrentInstance();
ExtendedRenderKitService erks =
Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
String myJavaScriptCode = “alert( “+”Hello World”+”);”;
erks.addScript(fctx, myJavaScriptCode );

Manually Parsing an Object to get a Value from a Field

So, in this use case we had an issue where entities in Java were throwing class cast exceptions for some reason or the other and it started to become a huge time barrier for us as we had no solutions or workarounds.

Many of the solutions I found online suggested deserializing the object and reserializing it and that is what we are doing here in these Utility Methods.

Getting a String from a Field:

public static String getStringFromField(Object objectName, String fieldName) {
String stringToReturn;

try {
//System.out.println(“Declaring the Class”);
Class<?> c = objectName.getClass();

//System.out.println(“Assigning the Field Name”);
Field f = c.getDeclaredField(fieldName);

//System.out.println(“Setting Field to Accessible”);
f.setAccessible(true);

try {
stringToReturn = (String) f.get(objectName).toString();
} catch (Exception exception) {
System.out.println(exception);
stringToReturn = “”;
}

return stringToReturn;
} catch (Exception exception) {
System.out.println(“Something went wrong with the getStringFromFieldMethod… Panic!”);
exception.printStackTrace();

stringToReturn = “Error, Contact System Admin!”;

return stringToReturn;
}
}

Getting an Integer from a Field:

public static Integer getIntegerFromField(Object objectName, String fieldName) {
Integer integerToReturn;

try {
Class<?> c = objectName.getClass();

Field f = c.getDeclaredField(fieldName);

f.setAccessible(true);

String integerToConvert = (String) f.get(objectName).toString();

integerToReturn = Integer.parseInt(integerToConvert);

return integerToReturn;
} catch (Exception exception) {
System.out.println(“Something went wrong with the getIntegerFromFieldMethod… Panic!”);
exception.printStackTrace();

integerToReturn = 0;

return integerToReturn;
}
}

Getting a BigDecimal from a Field:

public static BigDecimal getBigDecimalFromField(Object objectName, String fieldName) {
BigDecimal numberToReturn;

try {
Class<?> c = objectName.getClass();

Field f = c.getDeclaredField(fieldName);

f.setAccessible(true);

String numberToConvert = (String) f.get(objectName).toString();

numberToReturn = new BigDecimal(numberToConvert);

return numberToReturn;
} catch (Exception exception) {
System.out.println(“Something went wrong with the getBigDecimalFromFieldMethod… Panic!”);
exception.printStackTrace();

numberToReturn = new BigDecimal(0);

return numberToReturn;
}
}

Moving to the next step in BPM and Closing the Task Flow from the Controller

I had a special use case for this with a project I was working on and wanted to avoid using built in JDeveloper Data Control Utilities at all costs, personal preference I guess.

Here is the Utility method I wrote for this:

public static void moveToNextBpmStep(String action) {
action = action.toUpperCase();

// Perform original function
BindingContainer submitBindings = BindingContext.getCurrent().getCurrentBindingsEntry();
submitBindings = BindingContext.getCurrent().getCurrentBindingsEntry();
OperationBinding submitMethod;
submitMethod = submitBindings.getOperationBinding(action);
if (submitMethod != null) {
submitMethod.execute();
}

NavigationHandler nvHndlr = FacesContext.getCurrentInstance()
.getApplication()
.getNavigationHandler();
nvHndlr.handleNavigation(FacesContext.getCurrentInstance(), null, “closeTaskFlow”);
}

Getting/Editing Data Control Values in ADF/BPM programmatically

Like mentioned in a previous post, I was new to ADF at the time so this one took me a while to figure out but now it looks really simple. Here are the Utility Methods I wrote to help with this.

Getting the Data Control Value:

public static String getDataControlFieldValue(String fieldValue) {
try {
BindingContainer attributeBindings = BindingContext.getCurrent().getCurrentBindingsEntry();
List<AttributeBinding> attributeBindingList = attributeBindings.getAttributeBindings();
for (AttributeBinding attributeBinding : attributeBindingList) {

//Checking if this Assessment is New or Saved, if Null this Assessment is New
if (attributeBinding.getName() == fieldValue) {
if (attributeBinding.getInputValue() != null &&
StringUtils.isBlank(attributeBinding.getInputValue().toString()) != true) {
return attributeBinding.getInputValue().toString();
} else {
return null;
}
}
}
} catch (Exception exception) {
System.out.println(“Nothing found in BPM to Load!”);
return null;
}
return null;
}

Setting the Data Control Value:

public static void setDataControlFieldValue(String fieldValue, String value) {
BindingContainer attributeBindings = BindingContext.getCurrent().getCurrentBindingsEntry();
List<AttributeBinding> attributeBindingList = attributeBindings.getAttributeBindings();
for (AttributeBinding attributeBinding : attributeBindingList) {

//Checking if this Assessment is New or Saved, if Null this Assessment is New
if (attributeBinding.getName() == fieldValue) {
attributeBinding.setInputValue(value);
}
}
}

 

Programmatically adding objects to an Iterator for ADF or BPM Arrays

This one took a week to figure out as I was new to ADF at the time but here it is:

Main Method:

//Iterate Control Tests
DCBindingContainer iteratorBindings =
(DCBindingContainer) BindingContext.getCurrent().getCurrentBindingsEntry();
DCIteratorBinding myIterator= iteratorBindings.findIteratorBinding(“dataControlIterator”);

RowSetIterator rsi = myIterator.getRowSetIterator();

for (MyObject object : myObjectList) {
Row lastRow = rsi.last();

int lastRowIndex = rsi.getRangeIndexOf(lastRow);

Row newRow = rsi.createRow();

newRow.setNewRowState(Row.STATUS_INITIALIZED);

newRow = setRowEditable(newRow);

newRow.setAttribute(“attributeName”, object .getId());

 

rsi.insertRowAtRangeIndex(lastRowIndex + 1, newRow);

rsi.setCurrentRow(newRow);

myIterator.getDataControl().commitTransaction();
}

Utility Methods:

public Row setRowEditable(Row row) {
int attribCount = row.getAttributeCount();
for (int i = 0; i < attribCount; i++) {
ViewAttributeDefImpl attrDef = (ViewAttributeDefImpl) row.getStructureDef().getAttributeDef(i);
attrDef.setEditable(true);
attrDef.setSDOHidden(false);
attrDef.setUpdateableFlag(ViewAttributeDefImpl.UPDATEABLE);
}
return row;
}

Programmatically removing objects from an Iterator for ADF or BPM Arrays

This one took me way too long to figure out but the ADF documentation finally revealed that you should declare another iterator and use that iterator to go through the RowSet.

//Iterate Control Tests
DCBindingContainer iteratorBindings =
(DCBindingContainer) BindingContext.getCurrent().getCurrentBindingsEntry();
DCIteratorBinding myIterator = iteratorBindings.findIteratorBinding(“dataControlBinding”);

RowSetIterator rsi = myIterator.getRowSetIterator();

RowSet rowSet = rsi.getRowSet();

RowSetIterator secondaryIterator = rowSet.createRowSetIterator(null);

//Remove all Existing Objects in BPM
if (rsi.getRowCount() == 1) {
System.out.println(“EXECUTING IF EQUALS 1”);
Row oneRow = rsi.getCurrentRow();
oneRow.remove();
}

if (rsi.getRowCount() > 1) {
System.out.println(“EXECUTING IF MORE THAN 1”);
Row cycledRow = secondaryIterator.getCurrentRow();

rsi.setCurrentRow(cycledRow);
rsi.removeCurrentRow();

myIterator.getDataControl().commitTransaction();

while (secondaryIterator.hasNext()) {
System.out.println(“EXECUTING WHILE LOOP”);
System.out.println(“Inside the While Loop for Iterator”);
cycledRow = secondaryIterator.next();
rsi.setCurrentRow(cycledRow);
rsi.removeCurrentRow();
myIterator.getDataControl().commitTransaction();
}
}