Example usage for java.util StringTokenizer countTokens

List of usage examples for java.util StringTokenizer countTokens

Introduction

In this page you can find the example usage for java.util StringTokenizer countTokens.

Prototype

public int countTokens() 

Source Link

Document

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

Usage

From source file:com.irets.datadownloader.SearchPropertyServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
    long reqInputArrivalTime = System.currentTimeMillis();
    Date resultdate = new Date(reqInputArrivalTime);
    System.out.println("Calling Me @:" + sdf.format(resultdate) + ", from: " + request.getRemoteAddr()
            + ", with url> " + request.getRequestURL() + "?" + request.getQueryString());

    long startTime = reqInputArrivalTime;

    WebApplicationContext wac = WebApplicationContextUtils
            .getRequiredWebApplicationContext(getServletContext());
    SearchService propServices = this.getSearchService(wac);
    propServices.setContextPath(this.getUrl3(request));
    //propServices.setServer(this.getServer(request));
    Filter filer = new Filter();
    ArrayList<FilterItem> filterItemArrayList = new ArrayList<FilterItem>(1);
    ArrayList<FilterItem> exactFilterItemArrayList = new ArrayList<FilterItem>(1);
    ArrayList<FilterItem> multipleFilterItemArrayList = new ArrayList<FilterItem>(1);
    ArrayList<String> keywordArrayList = new ArrayList<String>(1);
    Vector<SimpleRange> rangeVector = new Vector<SimpleRange>(1);
    GeoParameter geoParam = null;//w w w  .j  a  va 2  s  . co m
    //        SimpleRange aRange = new SimpleRange("price_list",null,50000);
    //        filer.setRanges(new SimpleRange[]{aRange});
    int start = 0;
    int limit = -1;
    //        if(request.getParameter("ListingId") != null){
    //           FilterItem filterItem = new FilterItem();
    //            filterItem.setField("number_MLS");
    //            filterItem.setValue(request.getParameter("ListingId"));
    //            filterItemArrayList.add(filterItem);
    //        }
    if (request.getParameter("ListPrice") != null) {
        SimpleRange aRange;
        String listPrice = request.getParameter("ListPrice");
        System.out.println("List price is " + listPrice);
        String min = "";
        String max = "";
        if (!listPrice.equalsIgnoreCase("No Min-No Max")) {
            if (listPrice.indexOf(":") != -1) {
                //                 System.out.println("listPrice : -->>"+listPrice);
                min = listPrice.substring(0, listPrice.indexOf(":"));
                max = listPrice.substring(listPrice.indexOf(":") + 1, listPrice.length());
                aRange = new SimpleRange("price_list", min, max);
            } else if (listPrice.endsWith("+")) {
                //                 System.out.println("listPrice +-->>"+listPrice);
                min = listPrice.substring(0, listPrice.indexOf("+"));
                aRange = new SimpleRange("price_list", min, null);
            } else if (listPrice.endsWith("-")) {
                //                 System.out.println("listPrice - -->>"+listPrice);
                max = listPrice.substring(0, listPrice.indexOf("-"));
                aRange = new SimpleRange("price_list", null, max);
            } else if (listPrice.length() > 0) { // Exact match....
                min = listPrice.substring(0, listPrice.length());
                max = min;
                aRange = new SimpleRange("price_list", min, max);
            } else {
                aRange = new SimpleRange("price_list", null, null);
            }

            rangeVector.add(aRange);
        }
    }

    if (request.getParameter("Bedrooms") != null) {
        SimpleRange aRange;
        String bedrooms = request.getParameter("Bedrooms");
        String min = "";
        String max = "";
        if (!bedrooms.equalsIgnoreCase("No Min-No Max")) {
            if (bedrooms.indexOf(":") != -1) {
                //                 System.out.println("Bedrooms: -->>"+bedrooms);
                min = bedrooms.substring(0, bedrooms.indexOf(":"));
                max = bedrooms.substring(bedrooms.indexOf(":") + 1, bedrooms.length());
                aRange = new SimpleRange("number_beds_Total", min, max);
            } else if (bedrooms.endsWith("+")) {
                //                 System.out.println("Bedrooms+ -->>"+bedrooms);
                min = bedrooms.substring(0, bedrooms.indexOf("+"));
                aRange = new SimpleRange("number_beds_Total", min, null);
            } else if (bedrooms.endsWith("-")) {
                //                 System.out.println("Bedrooms- -->>"+bedrooms);
                max = bedrooms.substring(0, bedrooms.indexOf("-"));
                aRange = new SimpleRange("number_beds_Total", null, max);
            } else if (bedrooms.length() > 0) { // Exact match....
                min = bedrooms.substring(0, bedrooms.length());
                max = min;
                aRange = new SimpleRange("number_beds_Total", min, max);
            } else {
                aRange = new SimpleRange("number_beds_Total", null, null);
            }
            rangeVector.add(aRange);
        }
    }
    if (request.getParameter("FullBathrooms") != null) {
        SimpleRange aRange;
        String fullBath = request.getParameter("FullBathrooms");
        String min = "";
        String max = "";
        if (!fullBath.equalsIgnoreCase("No Min-No Max")) {
            if (fullBath.indexOf(":") != -1) {
                //                 System.out.println("FullBathrooms: -->>"+fullBath);
                min = fullBath.substring(0, fullBath.indexOf(":"));
                max = fullBath.substring(fullBath.indexOf(":") + 1, fullBath.length());
                aRange = new SimpleRange("number_baths_Full", min, max);
            } else if (fullBath.endsWith("+")) {
                //                 System.out.println("FullBathrooms+ -->>"+fullBath);
                min = fullBath.substring(0, fullBath.indexOf("+"));
                aRange = new SimpleRange("number_baths_Full", min, null);
            } else if (fullBath.endsWith("-")) {
                //                 System.out.println("FullBathrooms- -->>"+fullBath);
                max = fullBath.substring(0, fullBath.indexOf("-"));
                aRange = new SimpleRange("number_baths_Full", null, max);
            } else if (fullBath.length() > 0) {
                min = fullBath.substring(0, fullBath.length());
                max = min;
                aRange = new SimpleRange("number_baths_Full", min, max);
            } else {
                aRange = new SimpleRange("number_baths_Full", null, null);
            }
            rangeVector.add(aRange);
        }
    }

    if (request.getParameter("SqFt") != null) {
        SimpleRange aRange;
        String sqFt = request.getParameter("SqFt");
        String min = "";
        String max = "";
        if (!sqFt.equalsIgnoreCase("No Min-No Max")) {
            if (sqFt.indexOf(":") != -1) {
                //                 System.out.println("SqFt: -->>"+sqFt);
                min = sqFt.substring(0, sqFt.indexOf(":"));
                max = sqFt.substring(sqFt.indexOf(":") + 1, sqFt.length());
                aRange = new SimpleRange("sqft_Structure", min, max);
            } else if (sqFt.endsWith("+")) {
                //                 System.out.println("SqFt+ -->>"+sqFt);
                min = sqFt.substring(0, sqFt.indexOf("+"));
                aRange = new SimpleRange("sqft_Structure", min, null);
            } else if (sqFt.endsWith("-")) {
                //                 System.out.println("SqFt- -->>"+sqFt);
                max = sqFt.substring(0, sqFt.indexOf("-"));
                aRange = new SimpleRange("sqft_Structure", null, max);
            } else if (sqFt.length() > 0) {
                min = sqFt.substring(0, sqFt.length());
                max = min;
                aRange = new SimpleRange("sqft_Structure", min, max);
            } else {
                aRange = new SimpleRange("sqft_Structure", null, null);
            }
            rangeVector.add(aRange);
        }
    }

    // Date range for the property.
    if (request.getParameter("Age") != null) {
        SimpleRange aRange;
        String age = request.getParameter("Age");
        String min = "";
        String max = "";
        if (!age.equalsIgnoreCase("No Min-No Max")) {
            if (age.indexOf(":") != -1) {
                System.out.println("age: -->>" + age);
                min = age.substring(0, age.indexOf(":"));
                max = age.substring(age.indexOf(":") + 1, age.length());
                aRange = new SimpleRange("date_Listing_Modification", min, max);
            } else if (age.endsWith("+")) {
                //                 System.out.println("SqFt+ -->>"+sqFt);
                min = age.substring(0, age.indexOf("+"));
                aRange = new SimpleRange("date_Listing_Modification", min, null);
            } else if (age.endsWith("-")) {
                //                 System.out.println("SqFt- -->>"+sqFt);
                max = age.substring(0, age.indexOf("-"));
                aRange = new SimpleRange("date_Listing_Modification", null, max);
            } else if (age.length() > 0) {
                min = age.substring(0, age.length());
                max = min;
                aRange = new SimpleRange("date_Listing_Modification", min, max);
            } else {
                aRange = new SimpleRange("date_Listing_Modification", null, null);
            }
            System.out.println("Range is " + aRange.getMinValue() + ", " + aRange.getMaxValue());
            rangeVector.add(aRange);
        }
    }

    // Range for Longitude
    if (request.getParameter("Longitude") != null) {
        SimpleRange aRange;
        String longitude = request.getParameter("Longitude");
        System.out.println("Longitude is " + longitude);
        String min = "";
        String max = "";
        if (longitude.indexOf(":") != -1) {
            min = longitude.substring(0, longitude.indexOf(":"));
            max = longitude.substring(longitude.indexOf(":") + 1, longitude.length());
            aRange = new SimpleRange("_long", min, max);
        } else {
            aRange = new SimpleRange("_long", null, null);
        }
        rangeVector.add(aRange);
    }

    // Range for Latitude
    if (request.getParameter("Latitude") != null) {
        SimpleRange aRange;
        String latitude = request.getParameter("Latitude");
        System.out.println("Latitude is " + latitude);
        String min = "";
        String max = "";
        if (latitude.indexOf(":") != -1) {
            min = latitude.substring(0, latitude.indexOf(":"));
            max = latitude.substring(latitude.indexOf(":") + 1, latitude.length());
            aRange = new SimpleRange("lat", min, max);
        } else {
            aRange = new SimpleRange("lat", null, null);
        }
        rangeVector.add(aRange);
    }

    // Near by homes
    // Format required is Latitude,Longitude,distance
    if (request.getParameter("NBH") != null) {
        String nbh = request.getParameter("NBH");
        String[] s = nbh.split(",");
        if (s.length == 3) {
            Float f = Float.valueOf(s[2]);
            if (f >= 10) // 10 miles radius max
                s[2] = "10";
            else if (f < 0) // if negative distance
                s[2] = "1";
            geoParam = new GeoParameter(s[0], s[1], s[2]);
        }
    } else {
        // City and Zip are optional if NBH is provided.
        if (request.getParameter("Zip") != null) {
            FilterItem filterItem = new FilterItem();
            filterItem.setField("zipCode");
            // remove the space first
            String inZipcode = request.getParameter("Zip");
            StringBuffer zipBuffer = new StringBuffer();
            if (inZipcode.indexOf(",") > -1) {
                StringTokenizer sToken = new StringTokenizer(inZipcode, ",");
                while (sToken.hasMoreElements()) {
                    String object = (String) sToken.nextElement();
                    zipBuffer.append("'");
                    zipBuffer.append(object);
                    zipBuffer.append("'");
                    if (sToken.countTokens() > 0)
                        zipBuffer.append(",");
                }
            } else {
                zipBuffer.append("'");
                zipBuffer.append(inZipcode);
                zipBuffer.append("'");
            }

            //System.out.println(zipBuffer.toString());
            filterItem.setValue(zipBuffer.toString());
            multipleFilterItemArrayList.add(filterItem);

        }

        if (request.getParameter("City") != null) {
            FilterItem filterItem = new FilterItem();
            filterItem.setField("name_City");

            String cityList = request.getParameter("City");
            StringBuffer cityMod = new StringBuffer();
            if (cityList.indexOf(",") > -1) {
                StringTokenizer sToken = new StringTokenizer(cityList, ",");
                while (sToken.hasMoreElements()) {
                    String object = (String) sToken.nextElement();
                    cityMod.append("'");
                    cityMod.append(getCity(object));
                    cityMod.append("'");
                    if (sToken.countTokens() > 0)
                        cityMod.append(",");
                }
            } else {
                cityMod.append("'");
                cityMod.append(getCity(cityList));
                cityMod.append("'");
            }

            filterItem.setValue(cityMod.toString());
            multipleFilterItemArrayList.add(filterItem);
        }
    }

    // Status of property, link Active or Pending
    // For backward compatibility, Status=A. we added extra checks
    // for Status=ACTIVE or PENDING
    /*
     * if(request.getParameter("Status") != null &&
      (request.getParameter("Status").equalsIgnoreCase("ACTIVE")||
      request.getParameter("Status").equalsIgnoreCase("PENDING"))){
       FilterItem filterItem = new FilterItem();
    filterItem.setField("status_Listing");
    filterItem.setValue(request.getParameter("Status"));
    if (request.getParameter("Status").equalsIgnoreCase("PENDING")){
       filterItem.setValue(propServices.getPendingStatus());
    }           
    filterItemArrayList.add(filterItem);
    }
    */
    if (request.getParameter("Status") != null && (request.getParameter("Status").equalsIgnoreCase("ACTIVE")
            || request.getParameter("Status").equalsIgnoreCase("PENDING"))) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("status_Listing");
        StringBuffer statusMod = new StringBuffer();
        String statusList = null;
        if (request.getParameter("Status").equalsIgnoreCase("ACTIVE")) {
            statusList = propServices.getActiveStatus();
        } else if (request.getParameter("Status").equalsIgnoreCase("PENDING")) {
            statusList = propServices.getPendingStatus();
        }
        if (statusList.indexOf(",") > -1) {
            StringTokenizer sToken = new StringTokenizer(statusList, ",");
            while (sToken.hasMoreElements()) {
                String object = (String) sToken.nextElement();
                statusMod.append("'");
                statusMod.append(object);
                statusMod.append("'");
                if (sToken.countTokens() > 0)
                    statusMod.append(",");
            }
        } else {
            statusMod.append("'");
            statusMod.append(statusList);
            statusMod.append("'");
        }
        System.out.println("Status query..: " + statusMod.toString());
        filterItem.setValue(statusMod.toString());
        multipleFilterItemArrayList.add(filterItem);
    }

    if (request.getParameter("ListingId") != null) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("number_MLS");
        String listingId = request.getParameter("ListingId");
        String mlsNumberPrefix = propServices.getMlsNumberPrefix();
        StringBuffer listingIdList = new StringBuffer();
        if (listingId.indexOf(",") > -1) {
            StringTokenizer sToken = new StringTokenizer(listingId, ",");
            while (sToken.hasMoreElements()) {
                String object = (String) sToken.nextElement();
                if ((mlsNumberPrefix != null) && (!mlsNumberPrefix.equals(""))
                        && (!object.contains(mlsNumberPrefix))) {
                    listingIdList.append("'" + mlsNumberPrefix);
                } else {
                    listingIdList.append("'");
                }
                listingIdList.append(object);
                listingIdList.append("'");
                if (sToken.countTokens() > 0)
                    listingIdList.append(",");
            }
        } else {
            if ((mlsNumberPrefix != null) && (!mlsNumberPrefix.equals(""))
                    && (!listingId.contains(mlsNumberPrefix)))
                listingIdList.append("'" + mlsNumberPrefix);
            else
                listingIdList.append("'");
            listingIdList.append(listingId);
            listingIdList.append("'");
        }

        filterItem.setValue(listingIdList.toString());
        multipleFilterItemArrayList.add(filterItem);
        //System.out.println("got listing id "+ request.getParameter("ListingId"));
    }

    if (request.getParameter("ListingAgentLic") != null) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("listing_license_number");
        String listingId = request.getParameter("ListingAgentLic");

        if (listingId.indexOf(",") > -1) {
            StringTokenizer sToken = new StringTokenizer(listingId, ",");
            while (sToken.hasMoreElements()) {
                keywordArrayList.add((String) sToken.nextElement());
            }
        } else {
            keywordArrayList.add(listingId);
        }
        //System.out.println("got listing agent lic "+ request.getParameter("ListingAgentLic"));

    }

    if (request.getParameter("offset") != null) {
        start = Integer.parseInt(request.getParameter("offset"));
    }
    if (request.getParameter("limit") != null) {
        limit = Integer.parseInt(request.getParameter("limit"));
    }
    String sort = request.getParameter("sort");
    if (sort != null) {
        if (sort.equalsIgnoreCase("City")) {
            sort = "name_City";
        } else if (sort.equalsIgnoreCase("YearBuilt")) {
            sort = "year_Built";
        } else if (sort.equalsIgnoreCase("ListPrice")) {
            sort = "price_List";
        } else if (sort.equalsIgnoreCase("Sqft")) {
            sort = "sqft_Structure";
        } else if (sort.equalsIgnoreCase("LotSqFt")) {
            sort = "Size_Lot";
        } else if (sort.equalsIgnoreCase("Type")) {
            sort = "";
        } else if (sort.equalsIgnoreCase("Bedrooms")) {
            sort = "number_beds_Total";
        } else if (sort.equalsIgnoreCase("FullBathrooms")) {
            sort = "number_baths_Full";
        } else if (sort.equalsIgnoreCase("ExteriorFeatures")) {
            sort = "type_Property";
        } else if (sort.equalsIgnoreCase("none")) {
            sort = null;
        }
    }

    String sort_direction = request.getParameter("sort_direction");
    if (sort_direction != null) {
        if (sort_direction.equalsIgnoreCase("none")) {
            sort_direction = null;
        } else if (sort_direction.equalsIgnoreCase("ASC")) {
            sort_direction = "asc";
        } else {
            sort_direction = "desc";
        }

    } else { //{TOD: why do we need this??
        if (request.getParameter("ListingAgentLic") != null) {
            sort = "price_List";
            sort_direction = "desc"; // with agent listing, they want desc
        } else {
            sort_direction = "asc"; // default sorting order
        }

    }

    // Type of property, link Single Family, Townhouse, Condominium
    if (request.getParameter("ExteriorFeatures") != null) {
        String param = request.getParameter("ExteriorFeatures");
        FilterItem filterItem = new FilterItem();
        filterItem.setField("type_Property");
        List<ExteriorFeaturesData> extFeatureData = propServices.getExtFeaturesData();
        // Getting ExFeatures list from properties files
        if (extFeatureData != null) {
            System.out.println("Exterior Features param is " + param);
            for (ExteriorFeaturesData efd : extFeatureData) {
                if (efd.getName().equalsIgnoreCase(param)) {
                    filterItem.setValue(efd.getInSearchFields());
                    break;
                }
            }
            if (filterItem.getValue() != null) {
                System.out.println("Exterior Features value " + filterItem.getValue());
                multipleFilterItemArrayList.add(filterItem);
            }
        } else {// Getting ExFeatures list from DB                        
            filterItem.setValue(param);
            System.out.println("Exterior Features (single) " + filterItem.getValue());
            filterItemArrayList.add(filterItem);
        }

    }

    // Adding the search parameter for Full Address
    if (request.getParameter("FullAddress") != null) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("address_Filtered");
        filterItem.setValue(request.getParameter("FullAddress"));
        filterItemArrayList.add(filterItem);
    }

    boolean returnOpenHouseData = false;
    if (request.getParameter("OpenHouse") != null) {
        if (request.getParameter("OpenHouse").equals("1")) {
            returnOpenHouseData = true;
        }
    }

    // Put the keyword search (using it for license id)
    String[] filterArrayKeyword = new String[keywordArrayList.size()];
    filterArrayKeyword = keywordArrayList.toArray(filterArrayKeyword);
    filer.setKeywords(filterArrayKeyword);

    // Put range in the filter
    SimpleRange[] sRangeArray = new SimpleRange[rangeVector.size()];
    sRangeArray = rangeVector.toArray(sRangeArray);
    filer.setRanges(sRangeArray);

    // Put single value item in the filter with '%value%'
    FilterItem[] filterArray = new FilterItem[filterItemArrayList.size()];
    filterArray = filterItemArrayList.toArray(filterArray);
    filer.setFilters(filterArray);

    // Put single value item in the filter, with exact search with 'value'
    FilterItem[] exactFilterArray = new FilterItem[exactFilterItemArrayList.size()];
    exactFilterArray = exactFilterItemArrayList.toArray(exactFilterArray);
    filer.setExactFilters(exactFilterArray);

    // Put the multiple values (',' separated) item in the filter.
    FilterItem[] filterItemA = new FilterItem[multipleFilterItemArrayList.size()];
    filterItemA = multipleFilterItemArrayList.toArray(filterItemA);
    filer.setSearchForFieldItems(filterItemA);

    //System.out.println("time in making query:"+(new Date().getTime()-startTime)+" msecs");   
    //System.out.println("limit " + request.getParameter("limit") + ", offset " + 
    //      request.getParameter("offset") +", sort " + sort + ", sort direction "+ sort_direction);

    Object returnObj = null;
    startTime = new Date().getTime();

    // Create a Timer and a TimerTask
    Timer timer = new Timer();
    TimerTask task = new SearchPropertyTimerTask(request, response, this.getOutputType());

    // Set timer for 30 sec, method takes args in milliseconds.
    timer.schedule(task, 30 * 1000);
    boolean timedoutResponse = true;// Default is timed out response.

    try {
        /* for testing of timer functionality.
        try {
         Thread.sleep(10000);
        } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }*/

        Properties prop = propServices.searchForProperties(start, limit, sort, sort_direction, filer, geoParam,
                returnOpenHouseData);
        prop.setElapsedTime(BigInteger.valueOf(System.currentTimeMillis() - reqInputArrivalTime));

        if (this.getOutputType().equalsIgnoreCase("json")) {
            returnObj = getJSONReturnObj(prop);
        } else {
            returnObj = prop;
        }
    } catch (LargeResultSetException e) {
        Errors errors = new Errors();
        com.irets.generated.Error error = new com.irets.generated.Error();
        error.setCode(e.getErrorCode());
        error.setDescription(e.getMessage());
        errors.getError().add(error);
        errors.setTotalcount(BigInteger.valueOf(e.getTotalCount()));
        errors.setElapsedtime(BigInteger.valueOf(System.currentTimeMillis() - reqInputArrivalTime));
        returnObj = errors;
        System.out.println(e.getMessage());
    } finally {
        if (task.cancel()) {
            timedoutResponse = false;// No timeout, send normal response.             
        }
    }

    System.out.println("time in database call:" + (new Date().getTime() - startTime) + " msecs");

    //startTime = new Date().getTime();
    //GSONHelper.serializeToJSON(prop, response.getOutputStream());
    if (!timedoutResponse) {
        if (this.getOutputType().equalsIgnoreCase("json")) {
            response.setContentType("application/json");
            JacksonJSONHelper.serializeToJSON(returnObj, response.getOutputStream(), response);
        } else {
            response.setContentType("text/xml");
            JAXBHelper.serializeToXML(returnObj, response.getOutputStream());
        }
    }
    //System.out.println("time in making output:"+(new Date().getTime()-startTime)+" msecs");
    System.out.println("Done!!!! elapsed time: " + (System.currentTimeMillis() - reqInputArrivalTime));
}

From source file:edu.stanford.muse.util.Util.java

public static String getTLD(String link) {
    int idx = link.indexOf("://");
    // strip the protocol like http:// if present
    // need to handle trailing :// or /
    if (idx > 0 && idx + 1 + "://".length() <= link.length())
        link = link.substring(idx + "://".length());

    // strip out www* if the site starts with that
    if (link.startsWith("www")) {
        int idxDot = link.indexOf(".");
        if (idxDot >= 0 && idxDot + 1 <= link.length())
            link = link.substring(idxDot + 1);
    }/*from www. ja va2s.  c  o  m*/
    int idxSlash = link.indexOf("/");
    if (idxSlash >= 0)
        link = link.substring(0, idxSlash);
    StringTokenizer st = new StringTokenizer(link, ".");
    int nTokens = st.countTokens();
    int tokensNeeded = 2;
    for (int i = 0; i < (nTokens - tokensNeeded); i++)
        st.nextToken();
    String result = "";
    for (int i = 0; i < tokensNeeded; i++) {
        if (!st.hasMoreTokens())
            break;
        if (result.length() > 0)
            result += ".";
        result += st.nextToken();
    }

    return result.toLowerCase();
}

From source file:org.alfresco.repo.security.person.PersonServiceImpl.java

private List<NodeRef> getPeopleFtsList(String pattern, PagingRequest pagingRequest) throws Throwable {
    // Think this code is based on org.alfresco.repo.jscript.People.getPeopleImplSearch(String, StringTokenizer, int, int)
    List<NodeRef> people = null;

    SearchParameters params = new SearchParameters();
    params.addQueryTemplate("_PERSON", "|%firstName OR |%lastName OR |%userName");
    params.setDefaultFieldName("_PERSON");

    StringBuilder query = new StringBuilder(256);

    query.append("TYPE:\"").append(ContentModel.TYPE_PERSON).append("\" AND (");

    StringTokenizer t = new StringTokenizer(pattern, " ");

    if (t.countTokens() == 1) {
        // fts-alfresco property search i.e. location:"maidenhead"
        query.append('"').append(pattern).append("*\"");
    } else {//  ww w  .j  a va  2s  . c o  m
        // multiple terms supplied - look for first and second name etc.
        // assume first term is first name, any more are second i.e.
        // "Fraun van de Wiels"
        // also allow fts-alfresco property search to reduce results
        params.setDefaultOperator(SearchParameters.Operator.AND);
        StringBuilder multiPartNames = new StringBuilder(pattern.length());
        int numOfTokens = t.countTokens();
        int counter = 1;
        String term = null;
        // MNT-8539, in order to support firstname and lastname search
        while (t.hasMoreTokens()) {
            term = t.nextToken();
            // ALF-11311, in order to support multi-part
            // firstNames/lastNames, we need to use the whole tokenized term for both
            // firstName and lastName
            if (term.endsWith("*")) {
                term = term.substring(0, term.lastIndexOf("*"));
            }
            multiPartNames.append("\"");
            multiPartNames.append(term);
            multiPartNames.append("*\"");
            if (numOfTokens > counter) {
                multiPartNames.append(' ');
            }
            counter++;
        }
        // ALF-11311, in order to support multi-part firstNames/lastNames,
        // we need to use the whole tokenized term for both firstName and lastName.
        // e.g. "john junior lewis martinez", where "john junior" is the first
        // name and "lewis martinez" is the last name.
        if (multiPartNames.length() > 0) {
            query.append("firstName:");
            query.append(multiPartNames);
            query.append(" OR lastName:");
            query.append(multiPartNames);
        }
    }
    query.append(")");

    // define the search parameters
    params.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);
    params.addStore(this.storeRef);
    params.setQuery(query.toString());
    if (pagingRequest.getMaxItems() > 0) {
        params.setLimitBy(LimitBy.FINAL_SIZE);
        params.setLimit(pagingRequest.getMaxItems());
    }

    ResultSet results = null;
    try {
        results = searchService.query(params);
        people = results.getNodeRefs();
    } catch (Throwable err) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to execute people search: " + query.toString(), err);
        }

        throw err;
    } finally {
        if (results != null) {
            results.close();
        }
    }

    return people;
}

From source file:dk.defxws.fedoragsearch.server.Config.java

private void checkConfig() throws ConfigException {

    if (logger.isDebugEnabled())
        logger.debug("fedoragsearch.properties=" + fgsProps.toString());

    //     Check for unknown properties, indicating typos or wrong property names
    String[] propNames = { "fedoragsearch.deployFile", "fedoragsearch.soapBase", "fedoragsearch.soapUser",
            "fedoragsearch.soapPass", "fedoragsearch.defaultNoXslt",
            "fedoragsearch.defaultGfindObjectsRestXslt", "fedoragsearch.defaultUpdateIndexRestXslt",
            "fedoragsearch.defaultBrowseIndexRestXslt", "fedoragsearch.defaultGetRepositoryInfoRestXslt",
            "fedoragsearch.defaultGetIndexInfoRestXslt", "fedoragsearch.mimeTypes", "fedoragsearch.maxPageSize",
            "fedoragsearch.defaultBrowseIndexTermPageSize", "fedoragsearch.defaultGfindObjectsHitPageSize",
            "fedoragsearch.defaultGfindObjectsSnippetsMax", "fedoragsearch.defaultGfindObjectsFieldMaxLength",
            "fedoragsearch.repositoryNames", "fedoragsearch.indexNames", "fedoragsearch.updaterNames",
            "fedoragsearch.searchResultFilteringModule", "fedoragsearch.searchResultFilteringType" };
    //checkPropNames("fedoragsearch.properties", fgsProps, propNames);

    //     Check rest stylesheets
    checkRestStylesheet("fedoragsearch.defaultNoXslt");
    checkRestStylesheet("fedoragsearch.defaultGfindObjectsRestXslt");
    checkRestStylesheet("fedoragsearch.defaultUpdateIndexRestXslt");
    checkRestStylesheet("fedoragsearch.defaultBrowseIndexRestXslt");
    checkRestStylesheet("fedoragsearch.defaultGetRepositoryInfoRestXslt");
    checkRestStylesheet("fedoragsearch.defaultGetIndexInfoRestXslt");

    //     Check mimeTypes  
    checkMimeTypes("fedoragsearch", fgsProps, "fedoragsearch.mimeTypes");

    //     Check resultPage properties
    try {/*from  ww w .jav a2  s. c om*/
        maxPageSize = Integer.parseInt(fgsProps.getProperty("fedoragsearch.maxPageSize"));
    } catch (NumberFormatException e) {
        errors.append("\n*** maxPageSize is not valid:\n" + e.toString());
    }
    try {
        defaultBrowseIndexTermPageSize = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultBrowseIndexTermPageSize"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultBrowseIndexTermPageSize is not valid:\n" + e.toString());
    }
    try {
        defaultGfindObjectsHitPageSize = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsHitPageSize"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultGfindObjectsHitPageSize is not valid:\n" + e.toString());
    }
    try {
        defaultGfindObjectsSnippetsMax = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsSnippetsMax"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultGfindObjectsSnippetsMax is not valid:\n" + e.toString());
    }
    try {
        defaultGfindObjectsFieldMaxLength = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsFieldMaxLength"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultGfindObjectsFieldMaxLength is not valid:\n" + e.toString());
    }

    // Check updater properties
    String updaterProperty = fgsProps.getProperty("fedoragsearch.updaterNames");
    if (updaterProperty == null) {
        updaterNameToProps = null; // No updaters will be created
    } else {
        updaterNameToProps = new Hashtable();
        StringTokenizer updaterNames = new StringTokenizer(updaterProperty);
        while (updaterNames.hasMoreTokens()) {
            String updaterName = updaterNames.nextToken();
            try {
                InputStream propStream = null;
                try {
                    propStream = getResourceInputStream("/updater/" + updaterName + "/updater.properties");
                } catch (ConfigException e) {
                    errors.append("\n" + e.getMessage());
                }
                Properties props = new Properties();
                props.load(propStream);
                propStream.close();

                //MIH
                convertProperties(props);
                if (logger.isInfoEnabled()) {
                    logger.info(
                            configName + "/updater/" + updaterName + "/updater.properties=" + props.toString());
                }

                // Check properties
                String propsNamingFactory = props.getProperty("java.naming.factory.initial");
                String propsProviderUrl = props.getProperty("java.naming.provider.url");
                String propsConnFactory = props.getProperty("connection.factory.name");
                String propsClientId = props.getProperty("client.id");

                if (propsNamingFactory == null) {
                    errors.append("\n*** java.naming.factory.initial not provided in " + configName
                            + "/updater/" + updaterName + "/updater.properties");
                }
                if (propsProviderUrl == null) {
                    errors.append("\n*** java.naming.provider.url not provided in " + configName + "/updater/"
                            + updaterName + "/updater.properties");
                }
                if (propsConnFactory == null) {
                    errors.append("\n*** connection.factory.name not provided in " + configName + "/updater/"
                            + updaterName + "/updater.properties");
                }
                if (propsClientId == null) {
                    errors.append("\n*** client.id not provided in " + configName + "/updater/" + updaterName
                            + "/updater.properties");
                }

                updaterNameToProps.put(updaterName, props);
            } catch (IOException e) {
                errors.append("\n*** Error loading " + configName + "/updater/" + updaterName + ".properties:\n"
                        + e.toString());
            }
        }
    }

    // Check searchResultFilteringModule property
    searchResultFilteringModuleProperty = fgsProps.getProperty("fedoragsearch.searchResultFilteringModule");
    if (searchResultFilteringModuleProperty != null && searchResultFilteringModuleProperty.length() > 0) {
        try {
            getSearchResultFiltering();
        } catch (ConfigException e) {
            errors.append(e.getMessage());
        }
        String searchResultFilteringTypeProperty = fgsProps
                .getProperty("fedoragsearch.searchResultFilteringType");
        StringTokenizer srft = new StringTokenizer("");
        if (searchResultFilteringTypeProperty != null) {
            srft = new StringTokenizer(searchResultFilteringTypeProperty);
        }
        int countTokens = srft.countTokens();
        if (searchResultFilteringTypeProperty == null || countTokens == 0 || countTokens > 1) {
            errors.append("\n*** " + configName + ": fedoragsearch.searchResultFilteringType="
                    + searchResultFilteringTypeProperty
                    + ": one and only one of 'presearch', 'insearch', 'postsearch' must be stated.\n");
        } else {
            for (int i = 0; i < countTokens; i++) {
                String token = srft.nextToken();
                if (!("presearch".equals(token) || "insearch".equals(token) || "postsearch".equals(token))) {
                    errors.append("\n*** " + configName + ": fedoragsearch.searchResultFilteringType="
                            + searchResultFilteringTypeProperty
                            + ": only 'presearch', 'insearch', 'postsearch' may be stated, not '" + token
                            + "'.\n");
                }
            }
        }
    }

    //     Check repository properties
    Enumeration repositoryNames = repositoryNameToProps.keys();
    while (repositoryNames.hasMoreElements()) {
        String repositoryName = (String) repositoryNames.nextElement();
        Properties props = (Properties) repositoryNameToProps.get(repositoryName);
        if (logger.isDebugEnabled())
            logger.debug(configName + "/repository/" + repositoryName + "/repository.properties="
                    + props.toString());

        //        Check for unknown properties, indicating typos or wrong property names
        String[] reposPropNames = { "fgsrepository.repositoryName", "fgsrepository.fedoraSoap",
                "fgsrepository.fedoraUser", "fgsrepository.fedoraPass", "fgsrepository.fedoraObjectDir",
                "fgsrepository.fedoraVersion", "fgsrepository.defaultGetRepositoryInfoResultXslt",
                "fgsrepository.trustStorePath", "fgsrepository.trustStorePass" };
        //checkPropNames(configName+"/repository/"+repositoryName+"/repository.properties", props, reposPropNames);

        //        Check repositoryName
        String propsRepositoryName = props.getProperty("fgsrepository.repositoryName");
        if (!repositoryName.equals(propsRepositoryName)) {
            errors.append("\n*** " + configName + "/repository/" + repositoryName
                    + ": fgsrepository.repositoryName must be=" + repositoryName);
        }

        //        Check fedoraObjectDir
        //          String fedoraObjectDirName = insertSystemProperties(props.getProperty("fgsrepository.fedoraObjectDir"));
        //          File fedoraObjectDir = new File(fedoraObjectDirName);
        //          if (fedoraObjectDir == null) {
        //             errors.append("\n*** "+configName+"/repository/" + repositoryName
        //                   + ": fgsrepository.fedoraObjectDir="
        //                   + fedoraObjectDirName + " not found");
        //          }

        //        Check result stylesheets
        checkResultStylesheet("/repository/" + repositoryName, props,
                "fgsrepository.defaultGetRepositoryInfoResultXslt");
    }

    //     Check index properties
    Enumeration indexNames = indexNameToProps.keys();
    while (indexNames.hasMoreElements()) {
        String indexName = (String) indexNames.nextElement();
        Properties props = (Properties) indexNameToProps.get(indexName);
        if (logger.isDebugEnabled())
            logger.debug(configName + "/index/" + indexName + "/index.properties=" + props.toString());

        //        Check for unknown properties, indicating typos or wrong property names
        String[] indexPropNames = { "fgsindex.indexName", "fgsindex.indexBase", "fgsindex.indexUser",
                "fgsindex.indexPass", "fgsindex.operationsImpl", "fgsindex.defaultUpdateIndexDocXslt",
                "fgsindex.defaultUpdateIndexResultXslt", "fgsindex.defaultGfindObjectsResultXslt",
                "fgsindex.defaultBrowseIndexResultXslt", "fgsindex.defaultGetIndexInfoResultXslt",
                "fgsindex.indexDir", "fgsindex.analyzer", "fgsindex.untokenizedFields",
                "fgsindex.defaultQueryFields", "fgsindex.snippetBegin", "fgsindex.snippetEnd",
                "fgsindex.maxBufferedDocs", "fgsindex.mergeFactor", "fgsindex.ramBufferSizeMb",
                "fgsindex.defaultWriteLockTimeout", "fgsindex.defaultSortFields", "fgsindex.uriResolver" };
        //checkPropNames(configName+"/index/"+indexName+"/index.properties", props, indexPropNames);

        //        Check indexName
        String propsIndexName = props.getProperty("fgsindex.indexName");
        if (!indexName.equals(propsIndexName)) {
            errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.indexName must be="
                    + indexName);
        }

        //        Check operationsImpl class
        String operationsImpl = props.getProperty("fgsindex.operationsImpl");
        if (operationsImpl == null || operationsImpl.equals("")) {
            errors.append(
                    "\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl must be set in "
                            + configName + "/index/ " + indexName + ".properties");
        }
        try {
            Class operationsImplClass = Class.forName(operationsImpl);
            try {
                GenericOperationsImpl ops = (GenericOperationsImpl) operationsImplClass
                        .getConstructor(new Class[] {}).newInstance(new Object[] {});
            } catch (InstantiationException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            } catch (IllegalAccessException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            } catch (InvocationTargetException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            } catch (NoSuchMethodException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            }
        } catch (ClassNotFoundException e) {
            errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                    + operationsImpl + ": class not found.\n" + e);
        }

        //        Check result stylesheets
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultUpdateIndexDocXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultUpdateIndexResultXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultGfindObjectsResultXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultBrowseIndexResultXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultGetIndexInfoResultXslt");

        //        Check indexDir
        String indexDir = insertSystemProperties(props.getProperty("fgsindex.indexDir"));
        File indexDirFile = new File(indexDir);
        if (indexDirFile == null) {
            errors.append("\n*** " + configName + "/index/" + indexName + " fgsindex.indexDir=" + indexDir
                    + " must exist as a directory");
        }

        //        Check analyzer class for lucene and solr
        if (operationsImpl.indexOf("fgslucene") > -1 || operationsImpl.indexOf("fgssolr") > -1) {
            String analyzer = props.getProperty("fgsindex.analyzer");
            if (analyzer == null || analyzer.equals("")) {
                analyzer = defaultAnalyzer;
            }
            try {
                Class analyzerClass = Class.forName(analyzer);
                try {
                    Analyzer a = (Analyzer) analyzerClass.getConstructor(new Class[] {})
                            .newInstance(new Object[] {});
                } catch (InstantiationException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString());
                } catch (IllegalAccessException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString());
                } catch (InvocationTargetException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString());
                } catch (NoSuchMethodException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error:\n" + e.toString());
                }
            } catch (ClassNotFoundException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.analyzer=" + analyzer
                        + ": class not found:\n" + e.toString());
            }
        }

        //        Add untokenizedFields property for lucene
        if (operationsImpl.indexOf("fgslucene") > -1) {
            String defaultUntokenizedFields = props.getProperty("fgsindex.untokenizedFields");
            if (defaultUntokenizedFields == null)
                props.setProperty("fgsindex.untokenizedFields", "");
            if (indexDirFile != null) {
                StringBuffer untokenizedFields = new StringBuffer(
                        props.getProperty("fgsindex.untokenizedFields"));
                IndexReader ir = null;
                try {
                    ir = IndexReader.open(FSDirectory.open(new File(indexDir)), true);
                    int max = ir.numDocs();
                    if (max > 10)
                        max = 10;
                    for (int i = 0; i < max; i++) {
                        Document doc = ir.document(i);
                        for (ListIterator li = doc.getFields().listIterator(); li.hasNext();) {
                            Field f = (Field) li.next();
                            if (!f.isTokenized() && f.isIndexed() && untokenizedFields.indexOf(f.name()) < 0) {
                                untokenizedFields.append(" " + f.name());
                            }
                        }
                    }
                } catch (Exception e) {
                }
                props.setProperty("fgsindex.untokenizedFields", untokenizedFields.toString());
                if (logger.isDebugEnabled())
                    logger.debug("indexName=" + indexName + " fgsindex.untokenizedFields=" + untokenizedFields);
            }
        }

        //        Check defaultQueryFields - how can we check this?
        String defaultQueryFields = props.getProperty("fgsindex.defaultQueryFields");

        //        Use custom URIResolver if given
        //MIH: also check for solr
        if (operationsImpl.indexOf("fgslucene") > -1 || operationsImpl.indexOf("fgssolr") > -1) {
            Class uriResolverClass = null;
            String uriResolver = props.getProperty("fgsindex.uriResolver");
            if (!(uriResolver == null || uriResolver.equals(""))) {
                try {
                    uriResolverClass = Class.forName(uriResolver);
                    try {
                        URIResolverImpl ur = (URIResolverImpl) uriResolverClass.getConstructor(new Class[] {})
                                .newInstance(new Object[] {});
                        if (ur != null) {
                            ur.setConfig(this);
                            indexNameToUriResolvers.put(indexName, ur);
                        }
                    } catch (InstantiationException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n"
                                + e.toString());
                    } catch (IllegalAccessException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n"
                                + e.toString());
                    } catch (InvocationTargetException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n"
                                + e.toString());
                    } catch (NoSuchMethodException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error:\n"
                                + e.toString());
                    }
                } catch (ClassNotFoundException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.uriResolver="
                            + uriResolver + ": class not found:\n" + e.toString());
                }
            }
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("configCheck configName=" + configName + " errors=" + errors.toString());
    if (errors.length() > 0)
        throw new ConfigException(errors.toString());
}

From source file:edu.stanford.muse.index.Indexer.java

private String cardStats(List<Card> clouds) {
    if (clouds == null)
        return "No top terms";

    StringBuilder sb = new StringBuilder();
    sb.append("Top terms: " + clouds.size() + " superdocs, ");
    int nWords = 0, nTags = 0;
    Map<Integer, Integer> colorFreq = new LinkedHashMap<Integer, Integer>(); // count of how many times a color occurs
    int nMultipleColorTags = 0;

    // docs with at least one term pointing to them
    Set<Document> docsCoveredByColors = new LinkedHashSet<Document>();
    for (Card tc : clouds) {
        for (CardTerm tct : tc.terms) {
            // count # of words
            StringTokenizer st = new StringTokenizer(tct.lookupTerm);
            int count = st.countTokens();
            nWords += count;/*from   w w w .jav a  2s.  c om*/
            nTags++;

            int color = tct.bestColor();
            if (color != -1) {
                Set<Document> docsWithPhrase = docsForQuery(tct.lookupTerm, -1);
                docsCoveredByColors.addAll(docsWithPhrase);
            }

            if (tct.colorWeights != null && tct.colorWeights.size() > 1)
                nMultipleColorTags++;
            // update color freqs
            Integer I = colorFreq.get(color);
            if (I == null)
                colorFreq.put(color, 1);
            else
                colorFreq.put(color, I + 1);
        }
    }
    sb.append(nTags + " phrases with " + nWords + " words\n");
    sb.append(nMultipleColorTags + " phrases with possibly multiple colors\n");
    sb.append(docsCoveredByColors.size() + " docs are pointed to by at least one term\n");
    sb.append("Color histogram for selected terms:\n"); // idea: show this as a protovis graph
    for (int c = -1; c < 100; c++) // randomly picking 100, should go to max # colors. TOFIX
    {
        Integer I = colorFreq.get(c);
        if (I != null)
            sb.append("Color: " + c + " : " + I + "\n");
    }
    return sb.toString();
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.AgentDispatchGameAction.java

private void copyPackValues(List<PackBean> packList) {
    PackBean packBean = null;// w w w. j av  a 2  s. c o m

    System.out.println("Agent PackNbr Array::" + getPackNbr());

    String[] packNbr = getPackNbr();
    System.out.println("Agent PackNbr.length:" + packNbr.length);

    HttpSession session = getRequest().getSession();
    OrderedGameBean agtOrderedGameBean = (OrderedGameBean) session.getAttribute("AGT_ORDERED_GAME");

    // create tokens and set values in the pack list
    if (packNbr != null) {

        if (packNbr.length == 1) {

            String packVal = null;
            StringTokenizer packTokens = new StringTokenizer(packNbr[0], ",");

            System.out.println("Agent Value Passed::" + packNbr[0]);
            System.out.println("Agent PackTokens::" + packTokens.countTokens());

            int i = 0;
            while (packTokens.hasMoreTokens()) {

                packVal = packTokens.nextToken();

                packVal = packVal.trim();

                if (packVal.indexOf("-") == -1 && packVal.length() > agtOrderedGameBean.getGameNbrDigits()) {
                    packVal = packVal.substring(0, agtOrderedGameBean.getGameNbrDigits()) + "-"
                            + packVal.substring(agtOrderedGameBean.getGameNbrDigits());
                }

                System.out.println(packVal);
                packBean = packList.get(i++);
                packBean.setPackNumber(packVal);
            }
        }
    }
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.AgentDispatchGameAction.java

private void copyBookValues(List<BookBean> bookList) {
    BookBean bookBean = null;//www  .  j  av  a2 s  . c  o m

    System.out.println("Agent BookNbr Array::" + getBookNbr());

    System.out.println("Nbr of boks to dispatch" + getNoOfBooksToDispatch());

    String[] bookNbr = getBookNbr();
    System.out.println("Agent BookNbr.length:" + bookNbr.length);

    HttpSession session = getRequest().getSession();
    OrderedGameBean agtOrderedGameBean = (OrderedGameBean) session.getAttribute("AGT_ORDERED_GAME");

    // create tokens and set values in the book list

    if (bookNbr != null) {

        if (bookNbr.length == 1) {

            String bookVal = null;
            StringTokenizer bookTokens = new StringTokenizer(bookNbr[0], ",");

            System.out.println("Agent Value Passed::" + bookNbr[0]);
            System.out.println("Agent BookTokens::" + bookTokens.countTokens());

            int i = 0;
            while (bookTokens.hasMoreTokens()) {

                bookVal = bookTokens.nextToken();
                System.out.println(bookVal);

                bookVal = bookVal.trim();
                if (bookVal.indexOf("-") == -1 && bookVal.length() > agtOrderedGameBean.getGameNbrDigits()) {
                    bookVal = bookVal.substring(0, agtOrderedGameBean.getGameNbrDigits()) + "-"
                            + bookVal.substring(agtOrderedGameBean.getGameNbrDigits());

                    bookBean = new BookBean();
                    bookBean.setValid(true);
                    bookBean.setBookNumber(bookVal);
                    bookList.add(bookBean);
                }
                i = i + 1;
                // bookBean = bookList.get(i++);
                // bookBean.setBookNumber(bookVal);
            }
            setBookList(bookList);
            System.out.println("After Setting BookList in copyBookValues::" + bookList);
        }
    }

    /*
     * for(String b : bookNbr) { System.out.println("Book:::" + b); }
     * 
     * 
     * 
     * if (bookNbr != null) { System.out.println("Inside NOt Null ---BookNbr
     * Array::" + getBookNbr()); for (int i = 0; i < bookNbr.length; i++) {
     * if (!bookNbr[i].trim().equals("")) { bookBean = new BookBean();
     * bookBean.setBookNumber(bookNbr[i]); bookList.add(bookBean); } } }
     */

}

From source file:it.classhidra.core.controller.bean.java

private Object getPrimitiveArgument(String name, String s_value) {

    Object primArgument = null;/*from  w  ww .  j  a va 2 s  . c om*/
    Class reqClass = (delegated == null) ? this.getClass() : delegated.getClass();
    if (name.indexOf('.') > -1) {
        StringTokenizer st = new StringTokenizer(name, ".");
        /*
              Vector allfields=new Vector();
              while(st.hasMoreTokens())
                 allfields.add(st.nextToken());
                
                         
              String complexName="";
              for(int i=0;i<allfields.size()-1;i++){
                 complexName+=allfields.get(i);
                 if(i!=allfields.size()-2) complexName+=".";
              }
                      
              name = (String)allfields.get(allfields.size()-1);
        */

        String complexName = "";
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (st.countTokens() > 0)
                complexName += token;
            if (st.countTokens() > 1)
                complexName += ".";
            if (st.countTokens() == 0)
                name = token;
        }

        Object writeObj = get(complexName);
        if (writeObj == null)
            return primArgument;
        reqClass = writeObj.getClass();

    }

    try {
        java.lang.reflect.Method mtd = null;
        Class[] cls = new Class[0];

        mtd = reqClass.getMethod("get" + util_reflect.adaptMethodName(name), cls);
        if (mtd != null) {
            Class primArgumentClass = mtd.getReturnType();
            if (primArgumentClass.equals(double.class)) {
                primArgument = Double.valueOf(s_value);
            } else if (primArgumentClass.equals(int.class)) {
                primArgument = Integer.valueOf(s_value);
            } else if (primArgumentClass.equals(boolean.class)) {
                primArgument = Boolean.valueOf(s_value);
            } else if (primArgumentClass.equals(char.class)) {
                primArgument = s_value;
            } else if (primArgumentClass.equals(byte.class)) {
                primArgument = Byte.valueOf(s_value);
            } else if (primArgumentClass.equals(short.class)) {
                primArgument = Short.valueOf(s_value);
            } else if (primArgumentClass.equals(long.class)) {
                primArgument = Long.valueOf(s_value);
            } else if (primArgumentClass.equals(float.class)) {
                primArgument = Float.valueOf(s_value);
            }
        }

    } catch (Exception e) {

    }
    return primArgument;
}

From source file:edu.nyu.vida.data_polygamy.utils.FrameworkUtils.java

/**
 * This function is used to split a String into a set of tokens seperated by
 * a delimiter//from ww  w  . j a  v  a2s  . c o  m
 * 
 * @param s
 * @param delimiter
 * @return The array of tokens
 * 
 * From Harish.
 */
public static String[] splitString(String s, String delimiter) {
    String[] ret = null;
    StringTokenizer tok;

    if (delimiter == null || delimiter.length() == 0) {
        tok = new StringTokenizer(s);
    } else {
        tok = new StringTokenizer(s, delimiter);
    }

    ret = new String[tok.countTokens()];
    for (int i = 0; i < ret.length; i++) {
        ret[i] = tok.nextToken();
    }
    return ret;
}

From source file:org.apache.usergrid.android.sdk.UGClient.java

protected static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens,
        boolean ignoreEmptyTokens) {
    if (str == null) {
        return null;
    }/*from   ww  w.  j  a v  a2  s  .c om*/

    StringTokenizer st = new StringTokenizer(str, delimiters);

    int numTokens = st.countTokens();
    List<String> listTokens;

    if (numTokens > 0) {

        listTokens = new ArrayList<String>(numTokens);

        while (st.hasMoreTokens()) {

            String token = st.nextToken();

            if (trimTokens) {
                token = token.trim();
            }

            if (!ignoreEmptyTokens || token.length() > 0) {
                listTokens.add(token);
            }
        }
    } else {
        listTokens = new ArrayList<String>();
    }

    return listTokens.toArray(new String[listTokens.size()]);
}