I somehow get a StackOverFlowError when testing my following method. The tests and helper functions are 100% correct. I'm trying to implement a delete-method for a BinarySearchTree using the insert-method I already implemented (and works).
Here is my code:
public void delete(TreeNode toDelete) {
TreeNode _rootTmp = _root;
RedBlackTree tree = new RedBlackTree();
if(_root == null) {
tree.insert(_root);
}
if(_rootTmp.left != _nil) {
if(!_rootTmp.left.equals(toDelete)) {
tree.insert(_rootTmp.left);
}
delete(_rootTmp.left);
}
if(_rootTmp.right != _nil) {
if(!_rootTmp.right.equals(toDelete)) {
tree.insert(_rootTmp.right);
}
delete(_rootTmp.right);
}
if(_rootTmp.left == _nil && _rootTmp.right == _nil) {
_root = tree._root;
}
}
At our RedBlackTree Class we use _nil instead of null for checking if there is another node or not.
Thanks for your help!!
I would like to auto complete using more than one word, for example:
> we can<TAB>
welcome_trashcan pecan_seaweed yeswecan canwest
So all the suggestions should contain both of the keywords. Ideally, it should work for unlimited keywords.
I read the completion wiki, but I don't know which path to follow to achieve this.
I ended up implementing a new Interface (its written in groovy):
class MatchAnyCompleter implements Completer {
protected final List<Candidate> candidateList = []
MatchAnyCompleter(List<String> list) {
assert list
list.each {
candidateList << new Candidate(AttributedString.stripAnsi(it), it, null, null, null, null, true)
}
}
#Override
void complete(final LineReader reader, final ParsedLine commandLine, final List<Candidate> selected) {
assert commandLine != null
assert selected != null
selected.addAll(candidateList.findAll {
Candidate candidate ->
commandLine.words().stream().allMatch {
String keyword ->
candidate.value().contains(keyword)
}
})
}
}
Test:
class MatchAnyCompleterTest extends Specification {
def "Testing matches"() {
setup:
def mac = new MatchAnyCompleter([
"somevalue",
"welcome_trashcan",
"pecan_seaweed",
"yeswecan",
"canwest",
"nomatchhere"
])
def cmdLine = new ParsedLine() {
// non-implemented methods were removed for simplicity
#Override
List<String> words() {
return ["we","can"]
}
}
List<Candidate> selected = []
mac.complete(null, cmdLine, selected)
expect:
selected.each {
println it.value()
}
assert selected.size() == 4
}
}
output:
welcome_trashcan
pecan_seaweed
yeswecan
canwest
I'm using ZK and I have this code that works me statically
<zscript>
<![CDATA[
List tipo_servicios = new ArrayList();
List tipo_servicios_enc = new ArrayList();
DTO.Tiposervicio tipo_servicios_select;
DTO.Tiposervicio tiposervicio = new DTO.Tiposervicio();
tiposervicio.setId(1);
tiposervicio.setName("Mustang");
tiposervicio.setDescripcion("New Mustang 2018");
tiposervicio.setEstatus('A');
tipo_servicios.add(tiposervicio);
void buscarTipoServicios()
{
if (keywordBox.getValue() != null && !keywordBox.getValue().trim().equals(""))
{
tipo_servicios_enc.clear();
for (DTO.Tiposervicio tipo_serv : tipo_servicios)
{
if (tipo_serv.getName().toLowerCase().contains(keywordBox.getValue().trim().toLowerCase()) || tipo_serv.getName().toLowerCase().contains(keywordBox.getValue().trim().toLowerCase()))
{
tipo_servicios_enc.add(tipo_serv);
}
}
binder.loadAll();
}
}
]]>
</zscript>
It's a search engine
void buscarTipoServicios()
And I have in my service package my next code that is used to load my array from the database
public class ConsultarTipoServicio extends SelectorComposer
{
private List<Tiposervicio> listaTipoServicio;
private TiposervicioJpaController tipoServicioJpaController;
public ConsultarTipoServicio() throws Exception
{
EntityManagerFactory emf =Persistence.createEntityManagerFactory("ProyectoLabIIPU");
tipoServicioJpaController=new TiposervicioJpaController(emf);
listaTipoServicio= tipoServicioJpaController.findTiposervicioEntities();
}
public List<Tiposervicio> getlistaTipoServicio()
{
return listaTipoServicio;
}
}
I want somehow to assign to my
List tipo_servicios = new ArrayList();
The array already loaded from
getlistaTypeServicio ()
I'm trying something like this but it gives me error
List tipo_servicios = Servicios.ConsultarTipoServicios.getlistaTipoServicio();
I solved it this way
consultar = new Servicios.ConsultarTipoServicio();
List tipo_servicios = consultar.getlistaTipoServicio();
List tipo_servicios_enc = new ArrayList();
DTO.Tiposervicio tipo_servicios_select;
I have to convert the following NamedSqlParameterSource in Hibernate:-
final List<MenuActionMapping> menusList;
MapSqlParameterSource sqlParams = new MapSqlParameterSource();
menusList = namedParameterJdbcTemplate.query("call sp_proc()",sqlParams ,new RowMapper<MenuActionMapping>() {
#Override
public MenuActionMapping mapRow(ResultSet resultset, int i)
throws SQLException {
MenuActionMapping menuActionMapping=new MenuActionMapping();
menuActionMapping.setMenuKey(resultset.getString("KMM_MENU_KEY"));
menuActionMapping.setDisplayName(resultset.getString("KMM_DISPLAY_NAME"));
menuActionMapping.setMenuActionFlag(resultset.getInt("KMM_ACTION_FLAG"));
menuActionMapping.setMenuActive(resultset.getInt("KMM_ACTIVE"));
menuActionMapping.setMenuLevel(resultset.getInt("str_len"));
String str=resultset.getString("menu_actions");
String [] actions=str.split(",");
if(resultset.getInt("KRMM_ACTIVE")==1)
{
menuActionMapping.setActive(true);
}
else
{
menuActionMapping.setActive(false);
}
for(String strAct:actions)
{
if(strAct.equals("ADD"))
{
menuActionMapping.setAddCheckBox(true);
menuActionMapping.setAddCheckBoxDisabled("true");
}
if(strAct.equals("VIEW"))
{
menuActionMapping.setViewCheckBox(true);
menuActionMapping.setViewCheckBoxDisabled("true");
}
if(strAct.equals("DELETE"))
{
menuActionMapping.setDeleteCheckBox(true);
menuActionMapping.setDeleteCheckBoxDisabled("true");
}
if(strAct.equals("EDIT"))
{
menuActionMapping.setEditCheckBox(true);
menuActionMapping.setEditCheckBoxDisabled("true");
}
if(strAct.equals("DOWNLOAD"))
{
menuActionMapping.setDownloadCheckBox(true);
menuActionMapping.setDownloadCheckBoxDisabled("true");
}
}
return menuActionMapping;
}
});
System.out.println(menusList);
return menusList;
I dont have idea about how namedJdbcTemplate and Map Row Works so i am getting a Problem..
I also wrote alternate code in hibernate but it doesnt work:-
final List<MenuActionMapping> menusList;
Query query= getSession().createSQLQuery("call kyc.sp_proc()");
menusList=query.list();
System.out.println(menusList);
return menusList;
I think I am not setting MenuAction Mapping Object so how to achive the purpose?
Also I want to Manipulate the columns before setting it into the object how can i do it in hibernate....
The main code that is troubling me is this:-
String str=resultset.getString("menu_actions");
String [] actions=str.split(",");
if(resultset.getInt("KRMM_ACTIVE")==1)
{
menuActionMapping.setActive(true);
}
else
{
menuActionMapping.setActive(false);
}
for(String strAct:actions)
{
if(strAct.equals("ADD"))
{
menuActionMapping.setAddCheckBox(true);
menuActionMapping.setAddCheckBoxDisabled("true");
}
if(strAct.equals("VIEW"))
{
menuActionMapping.setViewCheckBox(true);
menuActionMapping.setViewCheckBoxDisabled("true");
}
if(strAct.equals("DELETE"))
{
menuActionMapping.setDeleteCheckBox(true);
menuActionMapping.setDeleteCheckBoxDisabled("true");
}
if(strAct.equals("EDIT"))
{
menuActionMapping.setEditCheckBox(true);
menuActionMapping.setEditCheckBoxDisabled("true");
}
if(strAct.equals("DOWNLOAD"))
{
menuActionMapping.setDownloadCheckBox(true);
menuActionMapping.setDownloadCheckBoxDisabled("true");
}
How to set mutiple attribute based in 1 column in hibernate...
namedJdbcTemplate helps you to reduce the boilerplate code like getting,closing connection etc while Row mapper helps you to iterate over returned result set and map it to desired Java class.
Check this http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/
Thanks To #Pratik on How to map columns in hibernate with class attributes?
I got the answer to my question i can achieve the same as row mappper of jdbc template in hibernate using BasicTransformerAdapter in hibernate. My code is as follows:-
final List<MenuActionMapping> menusList;
menusList = getSession().createSQLQuery("CALL kyc.sp_proc()").setResultTransformer(new BasicTransformerAdapter() {
private static final long serialVersionUID = 1L;
#Override
public Object transformTuple(Object[] tuple, String[] aliases)
{
MenuActionMapping menuActionMapping=new MenuActionMapping();
menuActionMapping.setMenuId((Integer)tuple[0]);
menuActionMapping.setMenuKey((String)tuple[1]);
menuActionMapping.setDisplayName((String)tuple[3]);
menuActionMapping.setMenuActionFlag((Integer)tuple[5]);
final Boolean b=(Boolean)tuple[6];
menuActionMapping.setMenuActive(b? 1 : 0);
final BigInteger big=(BigInteger) tuple[9];
menuActionMapping.setMenuLevel(big.intValue());
String str=(String)tuple[10];
String [] actions=str.split(",");
if(b==true)
{
menuActionMapping.setActive(true);
}
else
{
menuActionMapping.setActive(false);
}
for(String strAct:actions)
{
if(strAct.equals("ADD"))
{
menuActionMapping.setAddCheckBox(true);
menuActionMapping.setAddCheckBoxDisabled("true");
}
if(strAct.equals("VIEW"))
{
menuActionMapping.setViewCheckBox(true);
menuActionMapping.setViewCheckBoxDisabled("true");
}
if(strAct.equals("DELETE"))
{
menuActionMapping.setDeleteCheckBox(true);
menuActionMapping.setDeleteCheckBoxDisabled("true");
}
if(strAct.equals("EDIT"))
{
menuActionMapping.setEditCheckBox(true);
menuActionMapping.setEditCheckBoxDisabled("true");
}
if(strAct.equals("DOWNLOAD"))
{
menuActionMapping.setDownloadCheckBox(true);
menuActionMapping.setDownloadCheckBoxDisabled("true");
}
}
return menuActionMapping;
}
}).list();
I'm using PropertyUtils.setProperty(object, name, value) method of Apache Commons Bean Utils:
Giving these classes:
public class A {
B b;
}
public class B {
C c;
}
public class C {
}
And this:
A a = new A();
C c = new C();
PropertyUtils.setProperty(a, "b.c", c); //exception
If I try that I get:
org.apache.commons.beanutils.NestedNullException: Null property value for 'b.c' on bean class 'class A'
Is it possible to tell PropertyUtils that if a nested property has a null value try to instantiate it (default constructor) before trying to go deeper?
Any other approach?
Thank you
I solved it by doing this:
private void instantiateNestedProperties(Object obj, String fieldName) {
try {
String[] fieldNames = fieldName.split("\\.");
if (fieldNames.length > 1) {
StringBuffer nestedProperty = new StringBuffer();
for (int i = 0; i < fieldNames.length - 1; i++) {
String fn = fieldNames[i];
if (i != 0) {
nestedProperty.append(".");
}
nestedProperty.append(fn);
Object value = PropertyUtils.getProperty(obj, nestedProperty.toString());
if (value == null) {
PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(obj, nestedProperty.toString());
Class<?> propertyType = propertyDescriptor.getPropertyType();
Object newInstance = propertyType.newInstance();
PropertyUtils.setProperty(obj, nestedProperty.toString(), newInstance);
}
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
}
I know the question is about apache commons PropertyUtils.setProperty but there is very similar functionality available in
Spring Expression Language "SpEL" which does exactly what you want. Better still it deals with lists and arrays too. The doc link above is for spring 4.x but the code below works for me in spring 3.2.9.
StockOrder stockOrder = new StockOrder(); // Your root class here
SpelParserConfiguration config = new SpelParserConfiguration(true,true); // auto create objects if null
ExpressionParser parser = new SpelExpressionParser(config);
StandardEvaluationContext modelContext = new StandardEvaluationContext(stockOrder);
parser.parseExpression("techId").setValue(modelContext, "XXXYYY1");
parser.parseExpression("orderLines[0].partNumber").setValue(modelContext, "65498");
parser.parseExpression("orderLines[0].inventories[0].serialNumber").setValue(modelContext, "54686513216");
System.out.println(ReflectionToStringBuilder.toString(stockOrder));
A little correction:
String fn = fieldNames[i];
if (i != 0) {
nestedProperty.append(".");
}
nestedProperty.append(fn);
Object value = PropertyUtils.getProperty(obj, nestedProperty.toString());
IMHO, the best solution is to get rid of the commons-beanutils and use Spring Framework org.springframework.beans.PropertyAccessorFactory
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(targetObject);
wrapper.setAutoGrowNestedPaths(true);
I won't delve into details of how it works, but if you want to check it out, go take a look at the link above, this API is quite intuitive, but you'll need to have Spring Framework Core configured on your classpath, so I wouldn't recommend that you add spring just for the sake of this feature.
However,
If you only have commons-beanutils as your ally, this following code snippet may help you to grow your nested paths, as you set the values, therefore, you won't need to concern about the null objects along the path properties.
In this example I used with JPA Tuple Query to construct a custom object with some specific property paths with its corresponding values to be set.
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Tuple;
import javax.persistence.TupleElement;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.expression.DefaultResolver;
public class TupleToObject<T> {
public List<T> transformResult(List<Tuple> result, Class<T> targetClass) {
try {
List<T> objects = new ArrayList<>();
for (Tuple tuple : result) {
T target = targetClass.newInstance();
List<TupleElement<?>> elements = tuple.getElements();
for (TupleElement<?> tupleElement : elements) {
String alias = tupleElement.getAlias();
Object value = tuple.get(alias);
if (value != null) {
instantiateObject(target, alias);
PropertyUtils.setNestedProperty(target, alias, value);
}
}
objects.add(target);
}
return objects;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void instantiateObject(T target, String propertyPath) throws Exception {
DefaultResolver resolver = new DefaultResolver();
Object currentTarget = target;
while (resolver.hasNested(propertyPath)) {
final String property = resolver.next(propertyPath);
Object value = PropertyUtils.getSimpleProperty(currentTarget, property);
if (value == null) {
Class<?> propertyType = PropertyUtils.getPropertyType(currentTarget, property);
value = propertyType.newInstance();
PropertyUtils.setSimpleProperty(currentTarget, property, value);
}
currentTarget = value;
propertyPath = resolver.remove(propertyPath);
}
}
}
This code is using commons-beanutils-1.9.3.jar
Hope it helps!
I have used only reflection w/o Apache library to achieve this. The assumption is that all object to be traversed are all POJOs, and default construction is publicly accessible. This way, there is no need to construct the reference path for each loop.
public Object getOrCreateEmbeddedObject(Object inputObj,String[] fieldNames) throws Exception {
Object cursor = inputObj;
//Loop until second last index
for (int i = 0; i < fieldNames.length - 1; i++){
Field ff = getClassFieldFrom(cursor,fieldNames[i]);
Object child = ff.get(cursor);
if(null == child) {
Class<?> cls=ff.getType();
child = cls.newInstance();
ff.set(cursor, child);
}
cursor = child;
}
return cursor;
}
private Field getClassFieldFrom(Object object, String fieldStr)
throws NoSuchFieldException {
java.lang.reflect.Field ff = object.getClass().getDeclaredField(fieldStr);
ff.setAccessible(true);
return ff;
}
If you have any suggestion to my solution , please let me know.
I went for the very basic approach of just instantiating each of the objects by default:
public class A {
B b = new B();
}
public class B {
C c = new C();
}
public class C {
}
Not ideal, but it worked for my situation and didn't involve complicated fixes.
After doing some research, the short answer to "Is it possible..." question is No.