is this use of objects redundant and/or inefficient?

I’m fairly inexperienced with using objects so I would really like some input.

I’m trying to remove comments from a list that have certain “unwanted words” in them, both the comments and the list of “unwanted words” are in ArrayList objects.

This is inside of a class called FormHelper, which contains the private member comments as an ArrayList, the auditList ArrayList is created locally in a member function called populateComments(), which then calls this function (below). PopulateComments() is called by the constructor, and so this function only gets called once, when an instance of FormHelper is created.

private void filterComments(ArrayList <String> auditList) {
    for(String badWord : auditList) {
        for (String thisComment : this.comments) {
            if(thisComment.contains(badWord)) {
                int index = this.comments.indexOf(thisComment);
                this.comments.remove(index);
            }
        }
    }
}

something about the way I implemented this doesn’t feel right, I’m also concerned that I’m using ArrayList functions inefficiently. Is my suspicion correct?

Solution:

It is not particularly efficient. However, finding a more efficient solution is not straightforward.

Lets step back to a simpler problem.

private void findBadWords(List <String> wordList, List <String> auditList) {
    for(String badWord : auditList) {
        for (String word : wordList) {
            if (word.equals(badWord)) {
                System.err.println("Found a bad word");
            }
        }
    }
}

Suppose that wordList contains N words and auditList contains M words. Some simple analysis will show that the inner loop is executed N x M times. The N factor is unavoidable, but the M factor is disturbing. It means that the more “bad” words you have to check for the longer it takes to check.

There is a better way to do this:

private void findBadWords(List <String> wordList, HashSet<String> auditWords) {
    for (String word : wordList) {
        if (auditWords.contains(word))) {
            System.err.println("Found a bad word");
        }
    }
}

Why is that better? It is better (faster) because HashSet::contains doesn’t need to check all of the audit words one at a time. In fact, in the optimal case it will check none of them (!) and the average case just one or two of them. (I won’t go into why, but if you want to understand read the Wikipedia page on hash tables.)


But your problem is more complicated. You are using String::contains to test if each comment contains each bad word. That is not a simple string equality test (as per my simplified version).

What to do?

Well one potential solution is to split the the comments into an array of words (e.g. using String::split and then user the HashSet lookup approach. However:

  • That changes the behavior of your code. (In a good way actually: read up on the Scunthorpe problem!) You will now only match the audit words is they are actual words in the comment text.

  • Splitting a string into words is not cheap. If you use String::split it entails creating and using a Pattern object to find the word boundaries, creating substrings for each word and putting them into an array. You can probably do better, but it is always going to be a non-trivial calculation.

So the real question will be whether the optimization is going to pay off. That is ultimately going to depend on the value of M; i.e. the number of bad words you are looking for. The larger M is, the more likely it will be to split the comments into words and use a HashSet to test the words.

Another possible solution doesn’t involve splitting the comments. You could take the list of audit words and assemble them into a single regex like this: \b(word-1|word-2|...|word-n)\b. Then use this regex with Matcher::find to search each comment string for bad words. The performance will depend on the optimizing capability of the regex engine in your Java platform. It has the potential to be faster than splitting.


My advice would be to benchmark and profile your entire application before you start. Only optimize:

  1. when the benchmarking says that the overall performance of the requests where this comment checking occurs is concerning. (If it is OK, don’t waste your time optimizing.)

  2. when the profiling says that this method is a performance hotspot. (There is a good chance that the real hotspots are somewhere else. If so, you should optimize them rather than this method.)

Note there is an assumption that you have (sufficiently) completed your application and created a realistic benchmark for it before you think about optimizing. (Premature optimization is a bad idea … unless you really know what you are doing.)

Copy constructor isn't working

iv’e just started learning about copy constructors in java (OOP).
but for some reason it doesn’t work for me. this is what I did :
class Date:

public class Date {
private int day;
private int month;
private int year;
//regular build function
public Date(int day,int month, int year)
{
  this.day=day;
  this.month=month;
  this.year=year;
}    
//copy constructor
public Date (Date date){
    this.day = date.day;
    this.year = date.year;
    this.month = date.month;
}   
public String toString()
{
  return this.day+"/"+this.month+"/"+this.year;
}
}

the class Passport :

 public class Passport {
private String name; //the name property
private int number; //the number property
private Date expiryDate; //the expiryDate property
//a regular building constructor
public Passport(String name,int number, Date expiryDate)
{
  this.name=name;
  this.number=number;
  Date copyExpiryDate = new Date(this.expiryDate);  
  this.expiryDate = copyExpiryDate;
} 
//a copy constructor
public Passport(Passport passport)
{
  this.name = passport.name;
  this.number = passport.number;
  this.expiryDate = passport.expiryDate;
}   

the main method is :

 import java.util.*;
 public class Check {
static Scanner reader=new Scanner(System.in);
//checking if the classes are working properly
public static void main(String[] args){
    int numtraveler,passNum,passDay,passMonth,passYear,pay,planDay,planMonth,planYear;
    String name; 
    boolean isPay=false;
    System.out.println("how many travelers are you?");
    numtraveler=reader.nextInt();
    for(int i=0 ; i<numtraveler ; i++){
        System.out.println("enter your passport : ");
        System.out.println("enter name : ");
        name=reader.next();
        System.out.println("enter passport number : ");
        passNum=reader.nextInt();
        System.out.println("enter your passport's expiry date : (day then month then year) ");
        passDay=reader.nextInt();
        passMonth=reader.nextInt();
        passYear=reader.nextInt();
        Date d1=new Date(passDay,passMonth,passYear);
        System.out.println(d1);
        Passport p1=new Passport(name,passNum,d1);
        System.out.println(p1);
        Traveler t1=new Traveler(p1,isPay);
        System.out.println("do you want to pay? :(enter o if yes and 1 if not) ");
        pay=reader.nextInt();
        if(pay==0){
            t1.pay();
        }
        System.out.println("when are you planning to travel?(enter day then month then year)");
        planDay=reader.nextInt();
        planMonth=reader.nextInt();
        planYear=reader.nextInt();
        Date dPlan=new Date(planDay,planMonth,planYear);
        if(t1.checkTravel(dPlan)){
            System.out.println("The travel is possible");
        }
        else
            System.out.println("The travel isn't possible");            
    }
}
}

I have omitted some unimportant information from the class- the get and set from date, some other functions they both had and another class called Traveler because They aren’t that relevant to the problem. The Traveler class uses the Passport copy constructor but it has the same problem there.
When I run the main method it gets to the date,creates the object d1 and displays the date but when it gets to creating the object p1 from the Passport class it run an error : “Exception in thread “main” java.lang.NullPointerException”.
However, when I change in the Passport class to :

 Date copyExpiryDate = new Date(expiryDate.getDay(), 
        expiryDate.getMonth(), expiryDate.getYear());

it workes. anyone knows what I’m doing wrong with the copy constructor?
I’ll be very thankful for any one who helps!

Solution:

In the Passport copy constructor you are not creating a copy of the expiration date.

Change

public Passport(Passport passport)
{
  this.name = passport.name;
  this.number = passport.number;
  this.expiryDate = passport.expiryDate;
} 

to

public Passport(Passport passport)
{
  this.name = passport.name;
  this.number = passport.number;
  this.expiryDate = new Date(passport.expiryDate);
}  

The other constructor also has an issue.

public Passport(String name,int number, Date expiryDate)
{
  this.name=name;
  this.number=number;
  Date copyExpiryDate = new Date(this.expiryDate);  
  this.expiryDate = copyExpiryDate;
}

should be

public Passport(String name,int number, Date expiryDate)
{
  this.name=name;
  this.number=number;
  this.expiryDate = new Date(expiryDate);
} 

i.e. you should create a copy of the passed expiryDate, not a copy of this.expiryDate.

Chef: Nodes and Search

node1node2

    1. Now login to your chef-node/chef-client and type ohai. Ohai is automatically bootstraped when we install chef.
      You will get an output similar to below:
      ……
      “OPEN_MAX”: 1024,
      “PAGESIZE”: 4096,
      “PAGE_SIZE”: 4096,
      “PASS_MAX”: 8192,
      “PTHREAD_DESTRUCTOR_ITERATIONS”: 4,
      “PTHREAD_KEYS_MAX”: 1024,
      “PTHREAD_STACK_MIN”: 16384,
      “PTHREAD_THREADS_MAX”: null,
      “SCHAR_MAX”: 127,
      “SCHAR_MIN”: -128,
      “SHRT_MAX”: 32767,
      “SHRT_MIN”: -32768,
      “SSIZE_MAX”: 32767,
      “TTY_NAME_MAX”: 32,
      “TZNAME_MAX”: 6,
      “UCHAR_MAX”: 255,
      “UINT_MAX”: 4294967295,
      “UIO_MAXIOV”: 1024,
      “ULONG_MAX”: 18446744073709551615,
      “USHRT_MAX”: 65535,
      “WORD_BIT”: 32,
      “_AVPHYS_PAGES”: 768366,
      “_NPROCESSORS_CONF”: 2,
      “_NPROCESSORS_ONLN”: 2,
      “_PHYS_PAGES”: 970577,
      “_POSIX_ARG_MAX”: 2097152,
      “_POSIX_ASYNCHRONOUS_IO”: 200809,
      “_POSIX_CHILD_MAX”: 15019,
      “_POSIX_FSYNC”: 200809,
      “_POSIX_JOB_CONTROL”: 1,
      “_POSIX_MAPPED_FILES”: 200809,
      “_POSIX_MEMLOCK”: 200809,
      “_POSIX_MEMLOCK_RANGE”: 200809,
      “_POSIX_MEMORY_PROTECTION”: 200809,
      “_POSIX_MESSAGE_PASSING”: 200809,
      “_POSIX_NGROUPS_MAX”: 65536,
      “_POSIX_OPEN_MAX”: 1024,
      “_POSIX_PII”: null,
      “_POSIX_PII_INTERNET”: null,
      “_POSIX_PII_INTERNET_DGRAM”: null,
      “_POSIX_PII_INTERNET_STREAM”: null,
      “_POSIX_PII_OSI”: null,
      “_POSIX_PII_OSI_CLTS”: null,
      “_POSIX_PII_OSI_COTS”: null,
      “_POSIX_PII_OSI_M”: null,
      “_POSIX_PII_SOCKET”: null,
      “_POSIX_PII_XTI”: null,
      “_POSIX_POLL”: null,
      “_POSIX_PRIORITIZED_IO”: 200809,
      “_POSIX_PRIORITY_SCHEDULING”: 200809,
      “_POSIX_REALTIME_SIGNALS”: 200809,
      “_POSIX_SAVED_IDS”: 1,
      “_POSIX_SELECT”: null,
      “_POSIX_SEMAPHORES”: 200809,
      “_POSIX_SHARED_MEMORY_OBJECTS”: 200809,
      “_POSIX_SSIZE_MAX”: 32767,
      “_POSIX_STREAM_MAX”: 16,
      “_POSIX_SYNCHRONIZED_IO”: 200809,
      “_POSIX_THREADS”: 200809,
      “_POSIX_THREAD_ATTR_STACKADDR”: 200809,
      “_POSIX_THREAD_ATTR_STACKSIZE”: 200809,
      “_POSIX_THREAD_PRIORITY_SCHEDULING”: 200809,
      “_POSIX_THREAD_PRIO_INHERIT”: 200809,
      “_POSIX_THREAD_PRIO_PROTECT”: 200809,
      “_POSIX_THREAD_ROBUST_PRIO_INHERIT”: null,
      “_POSIX_THREAD_ROBUST_PRIO_PROTECT”: null,
      “_POSIX_THREAD_PROCESS_SHARED”: 200809,
      “_POSIX_THREAD_SAFE_FUNCTIONS”: 200809,
      “_POSIX_TIMERS”: 200809,
      “TIMER_MAX”: null,
      “_POSIX_TZNAME_MAX”: 6,
      “_POSIX_VERSION”: 200809,
      “_T_IOV_MAX”: null,
      “_XOPEN_CRYPT”: 1,
      “_XOPEN_ENH_I18N”: 1,
      “_XOPEN_LEGACY”: 1,
      “_XOPEN_REALTIME”: 1,
      “_XOPEN_REALTIME_THREADS”: 1,
      “_XOPEN_SHM”: 1,
      “_XOPEN_UNIX”: 1,
      “_XOPEN_VERSION”: 700,
      “_XOPEN_XCU_VERSION”: 4,
      “_XOPEN_XPG2”: 1,
      “_XOPEN_XPG3”: 1,
      “_XOPEN_XPG4”: 1,
      “BC_BASE_MAX”: 99,
      “BC_DIM_MAX”: 2048,
      “BC_SCALE_MAX”: 99,
      “BC_STRING_MAX”: 1000,
      “CHARCLASS_NAME_MAX”: 2048,
      “COLL_WEIGHTS_MAX”: 255,
      “EQUIV_CLASS_MAX”: null,
      “EXPR_NEST_MAX”: 32,
      “LINE_MAX”: 2048,
      “POSIX2_BC_BASE_MAX”: 99,
      “POSIX2_BC_DIM_MAX”: 2048,
      “POSIX2_BC_SCALE_MAX”: 99,
      “POSIX2_BC_STRING_MAX”: 1000,
      “POSIX2_CHAR_TERM”: 200809,
      “POSIX2_COLL_WEIGHTS_MAX”: 255,
      “POSIX2_C_BIND”: 200809,
      “POSIX2_C_DEV”: 200809,
      “POSIX2_C_VERSION”: null,
      “POSIX2_EXPR_NEST_MAX”: 32,
      “POSIX2_FORT_DEV”: null,
      “POSIX2_FORT_RUN”: null,
      “_POSIX2_LINE_MAX”: 2048,
      “POSIX2_LINE_MAX”: 2048,
      “POSIX2_LOCALEDEF”: 200809,
      “POSIX2_RE_DUP_MAX”: 32767,
      “POSIX2_SW_DEV”: 200809,
      “POSIX2_UPE”: null,
      “POSIX2_VERSION”: 200809,
      “RE_DUP_MAX”: 32767,
      “PATH”: “/usr/bin”,
      “CS_PATH”: “/usr/bin”,
      “LFS_CFLAGS”: null,
      “LFS_LDFLAGS”: null,
      “LFS_LIBS”: null,
      “LFS_LINTFLAGS”: null,
      “LFS64_CFLAGS”: “-D_LARGEFILE64_SOURCE”,
      “LFS64_LDFLAGS”: null,
      “LFS64_LIBS”: null,
      “LFS64_LINTFLAGS”: “-D_LARGEFILE64_SOURCE”,
      “_XBS5_WIDTH_RESTRICTED_ENVS”: “XBS5_LP64_OFF64”,
      “XBS5_WIDTH_RESTRICTED_ENVS”: “XBS5_LP64_OFF64”,
      “_XBS5_ILP32_OFF32”: null,
      “XBS5_ILP32_OFF32_CFLAGS”: null,
      “XBS5_ILP32_OFF32_LDFLAGS”: null,
      “XBS5_ILP32_OFF32_LIBS”: null,
      “XBS5_ILP32_OFF32_LINTFLAGS”: null,
      “_XBS5_ILP32_OFFBIG”: null,
      “XBS5_ILP32_OFFBIG_CFLAGS”: null,
      “XBS5_ILP32_OFFBIG_LDFLAGS”: null,
      “XBS5_ILP32_OFFBIG_LIBS”: null,
      “XBS5_ILP32_OFFBIG_LINTFLAGS”: null,
      “_XBS5_LP64_OFF64”: 1,
      “XBS5_LP64_OFF64_CFLAGS”: “-m64”,
      “XBS5_LP64_OFF64_LDFLAGS”: “-m64”,
      “XBS5_LP64_OFF64_LIBS”: null,
      “XBS5_LP64_OFF64_LINTFLAGS”: null,
      “_XBS5_LPBIG_OFFBIG”: null,
      “XBS5_LPBIG_OFFBIG_CFLAGS”: null,
      “XBS5_LPBIG_OFFBIG_LDFLAGS”: null,
      “XBS5_LPBIG_OFFBIG_LIBS”: null,
      “XBS5_LPBIG_OFFBIG_LINTFLAGS”: null,
      “_POSIX_V6_ILP32_OFF32”: null,
      “POSIX_V6_ILP32_OFF32_CFLAGS”: null,
      “POSIX_V6_ILP32_OFF32_LDFLAGS”: null,
      “POSIX_V6_ILP32_OFF32_LIBS”: null,
      “POSIX_V6_ILP32_OFF32_LINTFLAGS”: null,
      “_POSIX_V6_WIDTH_RESTRICTED_ENVS”: “POSIX_V6_LP64_OFF64”,
      “POSIX_V6_WIDTH_RESTRICTED_ENVS”: “POSIX_V6_LP64_OFF64”,
      “_POSIX_V6_ILP32_OFFBIG”: null,
      “POSIX_V6_ILP32_OFFBIG_CFLAGS”: null,
      “POSIX_V6_ILP32_OFFBIG_LDFLAGS”: null,
      “POSIX_V6_ILP32_OFFBIG_LIBS”: null,
      “POSIX_V6_ILP32_OFFBIG_LINTFLAGS”: null,
      “_POSIX_V6_LP64_OFF64”: 1,
      “POSIX_V6_LP64_OFF64_CFLAGS”: “-m64”,
      “POSIX_V6_LP64_OFF64_LDFLAGS”: “-m64”,
      “POSIX_V6_LP64_OFF64_LIBS”: null,
      “POSIX_V6_LP64_OFF64_LINTFLAGS”: null,
      “_POSIX_V6_LPBIG_OFFBIG”: null,
      “POSIX_V6_LPBIG_OFFBIG_CFLAGS”: null,
      “POSIX_V6_LPBIG_OFFBIG_LDFLAGS”: null,
      “POSIX_V6_LPBIG_OFFBIG_LIBS”: null,
      “POSIX_V6_LPBIG_OFFBIG_LINTFLAGS”: null,
      “_POSIX_V7_ILP32_OFF32”: null,
      “POSIX_V7_ILP32_OFF32_CFLAGS”: null,
      “POSIX_V7_ILP32_OFF32_LDFLAGS”: null,
      “POSIX_V7_ILP32_OFF32_LIBS”: null,
      “POSIX_V7_ILP32_OFF32_LINTFLAGS”: null,
      “_POSIX_V7_WIDTH_RESTRICTED_ENVS”: “POSIX_V7_LP64_OFF64”,
      “POSIX_V7_WIDTH_RESTRICTED_ENVS”: “POSIX_V7_LP64_OFF64”,
      “_POSIX_V7_ILP32_OFFBIG”: null,
      “POSIX_V7_ILP32_OFFBIG_CFLAGS”: null,
      “POSIX_V7_ILP32_OFFBIG_LDFLAGS”: null,
      “POSIX_V7_ILP32_OFFBIG_LIBS”: null,
      “POSIX_V7_ILP32_OFFBIG_LINTFLAGS”: null,
      “_POSIX_V7_LP64_OFF64”: 1,
      “POSIX_V7_LP64_OFF64_CFLAGS”: “-m64”,
      “POSIX_V7_LP64_OFF64_LDFLAGS”: “-m64”,
      “POSIX_V7_LP64_OFF64_LIBS”: null,
      “POSIX_V7_LP64_OFF64_LINTFLAGS”: null,
      “_POSIX_V7_LPBIG_OFFBIG”: null,
      “POSIX_V7_LPBIG_OFFBIG_CFLAGS”: null,
      “POSIX_V7_LPBIG_OFFBIG_LDFLAGS”: null,
      “POSIX_V7_LPBIG_OFFBIG_LIBS”: null,
      “POSIX_V7_LPBIG_OFFBIG_LINTFLAGS”: null,
      “_POSIX_ADVISORY_INFO”: 200809,
      “_POSIX_BARRIERS”: 200809,
      “_POSIX_BASE”: null,
      “_POSIX_C_LANG_SUPPORT”: null,
      “_POSIX_C_LANG_SUPPORT_R”: null,
      “_POSIX_CLOCK_SELECTION”: 200809,
      “_POSIX_CPUTIME”: 200809,
      “_POSIX_THREAD_CPUTIME”: 200809,
      “_POSIX_DEVICE_SPECIFIC”: null,
      “_POSIX_DEVICE_SPECIFIC_R”: null,
      “_POSIX_FD_MGMT”: null,
      “_POSIX_FIFO”: null,
      “_POSIX_PIPE”: null,
      “_POSIX_FILE_ATTRIBUTES”: null,
      “_POSIX_FILE_LOCKING”: null,
      “_POSIX_FILE_SYSTEM”: null,
      “_POSIX_MONOTONIC_CLOCK”: 200809,
      “_POSIX_MULTI_PROCESS”: null,
      “_POSIX_SINGLE_PROCESS”: null,
      “_POSIX_NETWORKING”: null,
      “_POSIX_READER_WRITER_LOCKS”: 200809,
      “_POSIX_SPIN_LOCKS”: 200809,
      “_POSIX_REGEXP”: 1,
      “_REGEX_VERSION”: null,
      “_POSIX_SHELL”: 1,
      “_POSIX_SIGNALS”: null,
      “_POSIX_SPAWN”: 200809,
      “_POSIX_SPORADIC_SERVER”: null,
      “_POSIX_THREAD_SPORADIC_SERVER”: null,
      “_POSIX_SYSTEM_DATABASE”: null,
      “_POSIX_SYSTEM_DATABASE_R”: null,
      “_POSIX_TIMEOUTS”: 200809,
      “_POSIX_TYPED_MEMORY_OBJECTS”: null,
      “_POSIX_USER_GROUPS”: null,
      “_POSIX_USER_GROUPS_R”: null,
      “POSIX2_PBS”: null,
      “POSIX2_PBS_ACCOUNTING”: null,
      “POSIX2_PBS_LOCATE”: null,
      “POSIX2_PBS_TRACK”: null,
      “POSIX2_PBS_MESSAGE”: null,
      “SYMLOOP_MAX”: null,
      “STREAM_MAX”: 16,
      “AIO_LISTIO_MAX”: null,
      “AIO_MAX”: null,
      “AIO_PRIO_DELTA_MAX”: 20,
      “DELAYTIMER_MAX”: 2147483647,
      “HOST_NAME_MAX”: 64,
      “LOGIN_NAME_MAX”: 256,
      “MQ_OPEN_MAX”: null,
      “MQ_PRIO_MAX”: 32768,
      “_POSIX_DEVICE_IO”: null,
      “_POSIX_TRACE”: null,
      “_POSIX_TRACE_EVENT_FILTER”: null,
      “_POSIX_TRACE_INHERIT”: null,
      “_POSIX_TRACE_LOG”: null,
      “RTSIG_MAX”: 32,
      “SEM_NSEMS_MAX”: null,
      “SEM_VALUE_MAX”: 2147483647,
      “SIGQUEUE_MAX”: 15019,
      “FILESIZEBITS”: 64,
      “POSIX_ALLOC_SIZE_MIN”: 4096,
      “POSIX_REC_INCR_XFER_SIZE”: null,
      “POSIX_REC_MAX_XFER_SIZE”: null,
      “POSIX_REC_MIN_XFER_SIZE”: 4096,
      “POSIX_REC_XFER_ALIGN”: 4096,
      “SYMLINK_MAX”: null,
      “GNU_LIBC_VERSION”: “glibc 2.17”,
      “GNU_LIBPTHREAD_VERSION”: “NPTL 2.17”,
      “POSIX2_SYMLINKS”: 1,
      “LEVEL1_ICACHE_SIZE”: 32768,
      “LEVEL1_ICACHE_ASSOC”: 8,
      “LEVEL1_ICACHE_LINESIZE”: 64,
      “LEVEL1_DCACHE_SIZE”: 32768,
      “LEVEL1_DCACHE_ASSOC”: 8,
      “LEVEL1_DCACHE_LINESIZE”: 64,
      “LEVEL2_CACHE_SIZE”: 2097152,
      “LEVEL2_CACHE_ASSOC”: 8,
      “LEVEL2_CACHE_LINESIZE”: 64,
      “LEVEL3_CACHE_SIZE”: 0,
      “LEVEL3_CACHE_ASSOC”: 0,
      “LEVEL3_CACHE_LINESIZE”: 0,
      “LEVEL4_CACHE_SIZE”: 0,
      “LEVEL4_CACHE_ASSOC”: 0,
      “LEVEL4_CACHE_LINESIZE”: 0,
      “IPV6”: 200809,
      “RAW_SOCKETS”: 200809
      },
      “time”: {
      “timezone”: “UTC”
      }
      }
      It gives information about our node.
    2. Suppose if I want to retrieve the ipaddress of node then we can execute the command:
      ohai ipaddressOutput will be as follows:
      [
      “192.168.1.240”
      ]
      We can use these attributes in our code.
      ohai hostname
      [
      “chef-node”
      ]
      ohai | grep ipaddress
      “ipaddress”: “192.168.1.240”
      ohai cpu
      {
      “0”: {
      “vendor_id”: “GenuineIntel”,
      “family”: “6”,
      “model”: “61”,
      “model_name”: “Intel Core Processor (Broadwell)”,
      “stepping”: “2”,
      “mhz”: “2095.146”,
      “cache_size”: “4096 KB”,
      “physical_id”: “0”,
      “core_id”: “0”,
      “cores”: “1”,
      “flags”: [
      “fpu”,
      “vme”,
      “de”,
      “pse”,
      “tsc”,
      “msr”,
      “pae”,
      “mce”,
      “cx8”,
      “apic”,
      “sep”,
      “mtrr”,
      “pge”,
      “mca”,
      “cmov”,
      “pat”,
      “pse36”,
      “clflush”,
      “mmx”,
      “fxsr”,
      “sse”,
      “sse2”,
      “ss”,
      “syscall”,
      “nx”,
      “pdpe1gb”,
      “rdtscp”,
      “lm”,
      “constant_tsc”,
      “rep_good”,
      “nopl”,
      “eagerfpu”,
      “pni”,
      “pclmulqdq”,
      “vmx”,
      “ssse3”,
      “fma”,
      “cx16”,
      “pcid”,
      “sse4_1”,
      “sse4_2”,
      “x2apic”,
      “movbe”,
      “popcnt”,
      “tsc_deadline_timer”,
      “aes”,
      “xsave”,
      “avx”,
      “f16c”,
      “rdrand”,
      “hypervisor”,
      “lahf_lm”,
      “abm”,
      “3dnowprefetch”,
      “arat”,
      “tpr_shadow”,
      “vnmi”,
      “flexpriority”,
      “ept”,
      “vpid”,
      “fsgsbase”,
      “bmi1”,
      “hle”,
      “avx2”,
      “smep”,
      “bmi2”,
      “erms”,
      “invpcid”,
      “rtm”,
      “rdseed”,
      “adx”,
      “smap”,
      “xsaveopt”
      ]
      },
      “1”: {
      “vendor_id”: “GenuineIntel”,
      “family”: “6”,
      “model”: “61”,
      “model_name”: “Intel Core Processor (Broadwell)”,
      “stepping”: “2”,
      “mhz”: “2095.146”,
      “cache_size”: “4096 KB”,
      “physical_id”: “1”,
      “core_id”: “0”,
      “cores”: “1”,
      “flags”: [
      “fpu”,
      “vme”,
      “de”,
      “pse”,
      “tsc”,
      “msr”,
      “pae”,
      “mce”,
      “cx8”,
      “apic”,
      “sep”,
      “mtrr”,
      “pge”,
      “mca”,
      “cmov”,
      “pat”,
      “pse36”,
      “clflush”,
      “mmx”,
      “fxsr”,
      “sse”,
      “sse2”,
      “ss”,
      “syscall”,
      “nx”,
      “pdpe1gb”,
      “rdtscp”,
      “lm”,
      “constant_tsc”,
      “rep_good”,
      “nopl”,
      “eagerfpu”,
      “pni”,
      “pclmulqdq”,
      “vmx”,
      “ssse3”,
      “fma”,
      “cx16”,
      “pcid”,
      “sse4_1”,
      “sse4_2”,
      “x2apic”,
      “movbe”,
      “popcnt”,
      “tsc_deadline_timer”,
      “aes”,
      “xsave”,
      “avx”,
      “f16c”,
      “rdrand”,
      “hypervisor”,
      “lahf_lm”,
      “abm”,
      “3dnowprefetch”,
      “arat”,
      “tpr_shadow”,
      “vnmi”,
      “flexpriority”,
      “ept”,
      “vpid”,
      “fsgsbase”,
      “bmi1”,
      “hle”,
      “avx2”,
      “smep”,
      “bmi2”,
      “erms”,
      “invpcid”,
      “rtm”,
      “rdseed”,
      “adx”,
      “smap”,
      “xsaveopt”
      ]
      },
      “total”: 2,
      “real”: 2,
      “cores”: 2
      }
      ohai platform
      [
      “centos”
      ]
      ohai platform_family

      [
      “rhel”
      ]

    3. Lets edit the apache cookbook we created in previous post.
      Edit default.rb

      if node['platform_family'] == "rhel"
              package = "httpd"
      elsif node['platform_family'] == "debian"
              package = "apache2"
      end
      
      package 'apache2' do
              package_name package
              action :install
      end
      
      service 'apache2' do
              service_name package
              action [:start, :enable]
      end
      
      
    4. Now create a recipe motd.rb with the following content:
      
      hostname = node['hostname']
      file '/etc/motd' do
              content "Hostname is this #{hostname}"
      end
      
      

      Add the code to git repo. Then upload the cookbook to chef-server. Then add the recipe to the run_list with the command:
      knife node run_list add chef-node ‘recipe[motd]’

    5. Now if you run chef-client then you will get the following error:
      Error Resolving Cookbooks for Run List:
      ================================================================================

      Missing Cookbooks:
      ——————
      The following cookbooks are required by the client but don’t exist on the server
      * motd

      We called motd but motd is not a cookbook it is a recipe inside the apache cookbook.
      Now go ahead and remove the recipe from run_list.
      knife node run_list remove chef-node ‘recipe[motd]’
      Then add the recipe as:
      knife node run_list add chef-node ‘recipe[apache::motd]’

    6. Then run the chef-client the motd recipe will be executed. View the contents of /etc/motd you will see the content updated there.

Search

search1.png

search2.png

search3search4

search5

search6

Execute the following command to find nodes having platform_family as rhel

knife search ‘platform_family:rhel’
Output:

Environment: _default
FQDN:
IP: 192.168.1.240
Run List: recipe[apache::websites], recipe[apache], recipe[apache::motd]
Roles:
Recipes: apache::websites, apache, apache::default, apache::motd
Platform: centos 7.2.1511
Tags:


Execute the following command to find nodes having recipes:apache
knife search ‘recipes:apache’

To find the recipe websites in cookbook apache:
knife search ‘recipes:apache\:\:websites’
knife search ‘recipes:apache\:\:websites*’

If you want to retrieve a list of hostnames of the nodes which have platform of centos:
knife search ‘platfor?:centos’ -a hostname
With -a we are specifying the attribute we want.

If you want to list all nodes:
knife search ‘*:*’

If you want to search the nodes with role web:
knife search role ‘role:web’
You can also execute the following:
knife search ‘*.*’ -a recipes