Example usage for java.lang StringBuilder indexOf

List of usage examples for java.lang StringBuilder indexOf

Introduction

In this page you can find the example usage for java.lang StringBuilder indexOf.

Prototype

@Override
    public int indexOf(String str) 

Source Link

Usage

From source file:org.wso2.carbon.apimgt.hostobjects.AssetStoreHostObject.java

private static boolean doSearch(GovernanceArtifact artifact, String searchTerm, Scriptable thisObj)
        throws GovernanceException {
    String[] terms = searchTerm.split(" ");
    // we can have multiple search terms which are separated by spaces.
    for (int i = 0; i < terms.length;) {
        StringBuilder temp = new StringBuilder();
        do {/*from w ww  .j  a  v a  2  s. c  o  m*/
            temp.append(" ").append(terms[i++]);
            // values of some parts can have spaces in them too. (ex:- names with spaces)
        } while (temp.indexOf(":") < 0 && i < terms.length);
        String[] parts = temp.substring(1).split(":");
        if (parts.length == 1) {
            // There were no parts. In that case, this is a name.
            parts = new String[] { null, parts[0] };
        } else if (parts[0].indexOf(" ") > 0) {
            // The name part can be the first, which will not need a qualifier in that case.
            i--;
            parts = new String[] { null, parts[0].substring(0, parts[0].lastIndexOf(" ")) };
        }
        String actual;
        if (parts[0] == null || parts[0].equals("name")) {
            actual = artifact.getQName().getLocalPart();
        } else if (parts[0].equals("id")) {
            actual = artifact.getId();
        } else if (parts[0].equals("provider")) {
            actual = getProviderFromArtifact(artifact);
        } else if (parts[0].equals("version")) {
            actual = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        } else if (parts[0].equals("state")) {
            actual = getLifecycleState(artifact);
        } else if (parts[0].equals("type")) {
            actual = getArtifactType(artifact, thisObj);
        } else {
            actual = artifact.getAttribute(parts[0]);
        }
        // If anything fails to match, then we return that, or we continue finding for a
        // failure.
        if (actual == null) {
            return false;
        } else {
            String[] subTerms = parts[1].split(",");
            boolean result = false;
            for (String subTerm : subTerms) {
                if (result = doSearch(actual, subTerm)) {
                    break;
                }
            }
            if (!result) {
                return false;
            }
        }
    }
    return true;
}

From source file:org.wso2.carbon.appmgt.hostobjects.AssetStoreHostObject.java

private static boolean doSearch(GovernanceArtifact artifact, String searchTerm, Scriptable thisObj)
        throws GovernanceException {
    String[] terms = searchTerm.split(" ");
    // we can have multiple search terms which are separated by spaces.
    for (int i = 0; i < terms.length;) {
        StringBuilder temp = new StringBuilder();
        do {/*from   w  w  w.j  a  v a2 s . c om*/
            temp.append(" ").append(terms[i++]);
            // values of some parts can have spaces in them too. (ex:- names with spaces)
        } while (temp.indexOf(":") < 0 && i < terms.length);
        String[] parts = temp.substring(1).split(":");
        if (parts.length == 1) {
            // There were no parts. In that case, this is a name.
            parts = new String[] { null, parts[0] };
        } else if (parts[0].indexOf(" ") > 0) {
            // The name part can be the first, which will not need a qualifier in that case.
            i--;
            parts = new String[] { null, parts[0].substring(0, parts[0].lastIndexOf(" ")) };
        }
        String actual;
        if (parts[0] == null || parts[0].equals("name")) {
            actual = artifact.getQName().getLocalPart();
        } else if (parts[0].equals("id")) {
            actual = artifact.getId();
        } else if (parts[0].equals("provider")) {
            actual = getProviderFromArtifact(artifact);
        } else if (parts[0].equals("version")) {
            actual = artifact.getAttribute(AppMConstants.API_OVERVIEW_VERSION);
        } else if (parts[0].equals("state")) {
            actual = getLifecycleState(artifact);
        } else if (parts[0].equals("type")) {
            actual = getArtifactType(artifact, thisObj);
        } else {
            actual = artifact.getAttribute(parts[0]);
        }
        // If anything fails to match, then we return that, or we continue finding for a
        // failure.
        if (actual == null) {
            return false;
        } else {
            String[] subTerms = parts[1].split(",");
            boolean result = false;
            for (String subTerm : subTerms) {
                if (result = doSearch(actual, subTerm)) {
                    break;
                }
            }
            if (!result) {
                return false;
            }
        }
    }
    return true;
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}//from w  w  w.  ja v  a2s. c o  m
 */
@SuppressWarnings("unchecked")
@Override
public List<String> findVolumesDigitized(List<Integer> volNums, List<String> volLetExts) {
    StringBuilder stringBuilder = new StringBuilder(" FROM Image WHERE ");
    for (int i = 0; i < volNums.size(); i++) {
        if (volNums.get(i) != null) {
            if (stringBuilder.indexOf("volNum") != -1) {
                stringBuilder.append(" or ");
            }
            stringBuilder.append("(volNum=");
            stringBuilder.append(volNums.get(i));
            stringBuilder.append(" and volLetExt ");
            if (StringUtils.isEmpty(volLetExts.get(i))) {
                stringBuilder.append(" is null");
            } else {
                stringBuilder.append("='");
                stringBuilder.append(volLetExts.get(i));
                stringBuilder.append('\'');
            }
            stringBuilder.append(" and imageOrder=1) ");
        }
    }
    List<String> returnValues = new ArrayList<String>(0);

    if (stringBuilder.indexOf("volNum") != -1) {
        Query query = getEntityManager().createQuery(stringBuilder.toString());

        List<Image> result = (List<Image>) query.getResultList();

        for (int i = 0; i < result.size(); i++) {
            returnValues.add(VolumeUtils.toMDPFormat(result.get(i).getVolNum(), result.get(i).getVolLetExt()));
        }
    }

    return returnValues;
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}/*from  w  ww . j a v a2 s  . c om*/
 */
@SuppressWarnings("unchecked")
@Override
public List<String> findDocumentsDigitized(List<Integer> volNums, List<String> volLetExts,
        List<Integer> folioNums, List<String> folioMods) {
    StringBuilder stringBuilder = new StringBuilder("FROM Image WHERE ");
    for (int i = 0; i < volNums.size(); i++) {
        if (folioNums.get(i) != null) {
            if (stringBuilder.indexOf("volNum") != -1) {
                stringBuilder.append(" or ");
            }
            stringBuilder.append("(volNum=");
            stringBuilder.append(volNums.get(i));
            stringBuilder.append(" and volLetExt ");
            if (StringUtils.isEmpty(volLetExts.get(i))) {
                stringBuilder.append("is null");
            } else {
                stringBuilder.append("='");
                stringBuilder.append(volLetExts.get(i));
                stringBuilder.append('\'');
            }

            stringBuilder.append(" and imageName like '%_C_");

            stringBuilder.append(ImageUtils.formatFolioNumber(folioNums.get(i), folioMods.get(i)));
            stringBuilder.append("_%.tif')");
        }
    }

    List<String> returnValues = new ArrayList<String>(0);
    if (stringBuilder.indexOf("volNum") != -1) {
        Query query = getEntityManager().createQuery(stringBuilder.toString());

        List<Image> result = (List<Image>) query.getResultList();

        for (int i = 0; i < result.size(); i++) {
            if (ImageUtils.extractFolioExtension(result.get(i).getImageName()) != null) {
                returnValues.add(DocumentUtils.toMDPAndFolioFormat(result.get(i).getVolNum(),
                        result.get(i).getVolLetExt(),
                        ImageUtils.extractFolioNumber(result.get(i).getImageName()),
                        ImageUtils.extractFolioExtension(result.get(i).getImageName()).toLowerCase()));
            } else {
                returnValues.add(DocumentUtils.toMDPAndFolioFormat(result.get(i).getVolNum(),
                        result.get(i).getVolLetExt(),
                        ImageUtils.extractFolioNumber(result.get(i).getImageName()), null));
            }
        }
    }
    return returnValues;
}

From source file:org.apereo.portal.url.UrlSyntaxProviderImpl.java

@Override
public String generateUrl(HttpServletRequest request, IPortalActionUrlBuilder portalActionUrlBuilder) {
    final String redirectLocation = portalActionUrlBuilder.getRedirectLocation();
    //If no redirect location just generate the portal url
    if (redirectLocation == null) {
        return this.generateUrl(request, (IPortalUrlBuilder) portalActionUrlBuilder);
    }//from w  ww . j av a 2 s .c o m

    final String renderUrlParamName = portalActionUrlBuilder.getRenderUrlParamName();
    //If no render param name just return the redirect url
    if (renderUrlParamName == null) {
        return redirectLocation;
    }

    //Need to stick the generated portal url onto the redirect url

    final StringBuilder redirectLocationBuilder = new StringBuilder(redirectLocation);

    final int queryParamStartIndex = redirectLocationBuilder.indexOf("?");
    //Already has parameters, add the new one correctly
    if (queryParamStartIndex > -1) {
        redirectLocationBuilder.append('&');
    }
    //No parameters, add parm seperator
    else {
        redirectLocationBuilder.append('?');
    }

    //Generate the portal url
    final String portalRenderUrl = this.generateUrl(request, (IPortalUrlBuilder) portalActionUrlBuilder);

    //Encode the render param name and the render url
    final String encoding = this.getEncoding(request);
    final String encodedRenderUrlParamName;
    final String encodedPortalRenderUrl;
    try {
        encodedRenderUrlParamName = URLEncoder.encode(renderUrlParamName, encoding);
        encodedPortalRenderUrl = URLEncoder.encode(portalRenderUrl, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Encoding '" + encoding + "' is not supported.", e);
    }

    return redirectLocationBuilder.append(encodedRenderUrlParamName).append("=").append(encodedPortalRenderUrl)
            .toString();
}

From source file:org.jivesoftware.community.util.StringUtils.java

public static StringBuilder replaceAllKeys(StringBuilder stb, Map store) {
    List uuids = new ArrayList(store.keySet());
    int loopCount = 0;
    label0: for (int maxLoops = uuids.size(); uuids.size() > 0 && loopCount < maxLoops; loopCount++) {
        Iterator i$ = store.keySet().iterator();
        do {/*from w  w  w  . j a  v  a2s.c  o m*/
            if (!i$.hasNext())
                continue label0;
            String uuid = (String) i$.next();
            String value = (String) store.get(uuid);
            int idx = stb.indexOf(uuid);
            if (idx != -1) {
                stb.replace(idx, idx + uuid.length(), value);
                uuids.remove(uuid);
            }
        } while (true);
    }

    return stb;
}

From source file:org.apache.olio.workload.driver.UIDriver.java

@BenchmarkOperation(name = "EventDetail", max90th = 2, timing = Timing.AUTO)
public void doEventDetail() throws Exception {
    //select random event
    logger.finer("doEventDetail");
    if (selectedEvent == null) {
        logger.warning("In event detail and select event is null");
        http.fetchURL(homepageURL);//from   w  w w . j a  v a  2  s .  co m
        StringBuilder responseBuffer = http.getResponseBuffer();
        selectedEvent = RandomUtil.randomEvent(random, responseBuffer);
        if (selectedEvent == null) {
            throw new IOException("In event detail and select event is null");
        }
    }

    http.fetchURL(eventDetailURL + selectedEvent);
    StringBuilder responseBuffer = http.getResponseBuffer();
    if (responseBuffer.length() == 0) {
        throw new IOException("Received empty response");
    }
    boolean canAddAttendee = isLoggedOn && responseBuffer.indexOf("Unattend") == -1;

    Set<String> images = parseImages(responseBuffer);
    loadStatics(eventDetailStatics);
    loadImages(images);
    if (ctx.isTxSteadyState()) {
        driverMetrics.eventDetailImages += images.size();
    }
    if (canAddAttendee) {
        // 10% of the time we can add ourselves, we will.
        int card = random.random(0, 9);
        if (card == 0) {
            doAddAttendee();
            if (ctx.isTxSteadyState()) {
                ++driverMetrics.addAttendeeCount;
            }
        }
        if (ctx.isTxSteadyState()) {
            ++driverMetrics.addAttendeeReadyCount;
        }
    }
}

From source file:org.apache.olio.workload.driver.UIDriver.java

@BenchmarkOperation(name = "AddPerson", max90th = 3, timing = Timing.AUTO)
@NegativeExponential(cycleType = CycleType.CYCLETIME, cycleMean = 5000, cycleMin = 2000, truncateAtMin = false, cycleDeviation = 2)
public void doAddPerson() throws Exception {
    logger.finer("doAddPerson");
    if (isLoggedOn) {
        doLogout();//from  w  w  w  .  j ava  2  s. c  om
    }

    String[] parameters = preparePerson();
    ArrayList<Part> params = new ArrayList();
    // Debug
    if (parameters[0] == null || parameters[0].length() == 0) {
        logger.warning("Username is null!");
    } else {
        logger.finer("addPerson adding user: " + parameters[0]);
    }
    params.add(new NullContentTypePart("user[username]", parameters[0]));
    http.readURL(checkNameURL, "name=" + parameters[0]);

    params.add(new NullContentTypePart("user[password]", parameters[1]));
    params.add(new NullContentTypePart("user[password_confirmation]", parameters[1]));
    params.add(new NullContentTypePart("user[firstname]", parameters[2]));
    params.add(new NullContentTypePart("user[lastname]", parameters[3]));
    params.add(new NullContentTypePart("user[email]", parameters[4]));
    String[] addressArr = prepareAddress();
    params.add(new NullContentTypePart("address[street1]", addressArr[0]));
    params.add(new NullContentTypePart("address[street2]", addressArr[1]));
    params.add(new NullContentTypePart("address[city]", addressArr[2]));
    params.add(new NullContentTypePart("address[state]", addressArr[3]));
    params.add(new NullContentTypePart("address[zip]", addressArr[4]));
    params.add(new NullContentTypePart("address[country]", addressArr[5]));
    params.add(new NullContentTypePart("user[telephone]", parameters[5]));
    params.add(new NullContentTypePart("user[timezone]", parameters[7]));
    params.add(new NullContentTypePart("user[summary]", parameters[6]));
    params.add(new FilePart("user_image", personImg, "image/jpeg", null));

    http.readURL(addPersonURL);
    loadStatics(addPersonStatics);
    StringBuilder response = ((ApacheHC3Transport) http).fetchURL(addPersonResultURL, params);

    int status = http.getResponseCode();
    String[] locationHeader = http.getResponseHeader("location");

    if (locationHeader != null) {
        logger.fine("redirectLocation is " + locationHeader[0]);
        response = http.fetchURL(locationHeader[0]);
    } else if (status != HttpStatus.SC_OK) {
        throw new IOException("Multipart post did not work, returned " + "status code: " + status);
    }
    String message = "Succeeded in creating user.";
    if (response.indexOf(message) == -1) {
        throw new Exception("Could not find success message '" + message + " in result body");
    }
    ++driverMetrics.addPersonTotal;
}

From source file:org.apache.olio.workload.driver.UIDriver.java

@BenchmarkOperation(name = "AddEvent", max90th = 4, timing = Timing.AUTO)
@NegativeExponential(cycleType = CycleType.CYCLETIME, cycleMean = 5000, cycleMin = 3000, truncateAtMin = false, cycleDeviation = 2)
public void doAddEvent() throws Exception {
    logger.finer("entering doAddEvent()");
    if (!isLoggedOn) {
        throw new IOException("User not logged when trying to add an event");
    }//w w  w  .  ja  va 2  s .  c om

    ArrayList<Part> params = new ArrayList<Part>();
    String[] parameters = prepareEvent();
    if (parameters[0] == null || parameters[0].length() == 0) {
        logger.warning("Socialevent title is null!");
    } else {
        logger.finer("addEvent adding event title: " + parameters[0]);
    }

    params.add(new NullContentTypePart("event[title]", parameters[0]));
    params.add(new NullContentTypePart("event[summary]", parameters[1]));
    params.add(new NullContentTypePart("event[description]", parameters[2]));
    params.add(new NullContentTypePart("event[telephone]", parameters[3]));
    // What about timezone ?
    params.add(new NullContentTypePart("event[event_timestamp(1i)]", parameters[5]));
    params.add(new NullContentTypePart("event[event_timestamp(2i)]", parameters[6]));
    params.add(new NullContentTypePart("event[event_timestamp(3i)]", parameters[7]));
    params.add(new NullContentTypePart("event[event_timestamp(4i)]", parameters[8]));
    params.add(new NullContentTypePart("event[event_timestamp(5i)]", parameters[9]));

    params.add(new NullContentTypePart("tag_list", parameters[10]));
    // No submitter_user_name ?
    //add the address
    String[] addressArr = prepareAddress();
    params.add(new NullContentTypePart("address[street1]", addressArr[0]));
    params.add(new NullContentTypePart("address[street2]", addressArr[1]));
    params.add(new NullContentTypePart("address[city]", addressArr[2]));
    params.add(new NullContentTypePart("address[state]", addressArr[3]));
    params.add(new NullContentTypePart("address[zip]", addressArr[4]));
    params.add(new NullContentTypePart("address[country]", addressArr[5]));

    params.add(new FilePart("event_image", eventImg, "image/jpeg", null));
    params.add(new FilePart("event_document", eventPdf, "application/pdf", null));
    params.add(new NullContentTypePart("commit", "Create"));

    // GET the new event form within a user session
    StringBuilder responseBuffer = http.fetchURL(addEventURL);
    loadStatics(addEventStatics);
    if (responseBuffer.length() == 0) {
        throw new IOException("Received empty response");
    }

    // Parse the authenticity_token from the response
    String token = parseAuthToken(responseBuffer);
    if (token != null) {
        params.add(new NullContentTypePart("authenticity_token", token));
    }

    StringBuilder response = ((ApacheHC3Transport) http).fetchURL(addEventResultURL, params);

    int status = http.getResponseCode();
    String[] locationHeader = http.getResponseHeader("location");

    if (locationHeader != null) {
        logger.fine("redirectLocation is " + locationHeader[0]);
        response = http.fetchURL(locationHeader[0]);
    } else if (status != HttpStatus.SC_OK) {
        throw new IOException("Multipart post did not work, returned " + "status code: " + status);
    }
    String message = "Event was successfully created.";
    if (response.indexOf(message) == -1) {
        throw new Exception("Could not find success message '" + message + " in result body");
    }
    ++driverMetrics.addEventTotal;
}

From source file:edu.umn.msi.tropix.persistence.dao.hibernate.TropixObjectDaoImpl.java

public List<TropixObject> searchObjects(final String userId, final Class<? extends TropixObject> objectType,
        final String name, final String description, final String ownerId) {
    final StringBuilder queryBuilder = new StringBuilder(
            getSession().getNamedQuery("baseSearch").getQueryString());
    if (StringUtils.hasText(description)) {
        queryBuilder.append(" and o.description like :description ");
    }//from w  w  w .ja  va 2s .c  o m
    if (StringUtils.hasText(name)) {
        queryBuilder.append(" and o.name like :name ");
    }
    if (StringUtils.hasText(ownerId)) {
        queryBuilder.append(
                " and (select count(*) from DirectPermission ownerRole join ownerRole.users owner join ownerRole.objects ownerObject where ownerObject.id=o.id and owner.cagridId = :ownerId and ownerRole.role='owner' ) > 0");
    }
    final String objectTypeStr = objectType == null ? "TropixObject" : objectType.getSimpleName();
    final String typeStr = "TropixObject";
    final int typePos = queryBuilder.indexOf(typeStr);
    queryBuilder.replace(typePos, typePos + typeStr.length(), objectTypeStr);
    final Query query = getSession().createQuery(queryBuilder.toString());
    query.setParameter("userId", userId);
    if (StringUtils.hasText(name)) {
        query.setParameter("name", name);
    }
    if (StringUtils.hasText(description)) {
        query.setParameter("description", description);
    }
    if (StringUtils.hasText(ownerId)) {
        query.setParameter("ownerId", ownerId);
    }
    query.setMaxResults(maxSearchResults);
    @SuppressWarnings("unchecked")
    final List<TropixObject> results = query.list();

    return results;
}