Example usage for org.apache.commons.lang3 StringUtils startsWith

List of usage examples for org.apache.commons.lang3 StringUtils startsWith

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils startsWith.

Prototype

public static boolean startsWith(final CharSequence str, final CharSequence prefix) 

Source Link

Document

Check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:com.thruzero.applications.faces.demo.beans.page.DashboardBean.java

public List<InfoNodeElement> getDashboard() {
    if (dashboardPanels == null) {
        DscInfoNodeService dscInfoNodeService = ServiceLocator.locate(DscInfoNodeService.class); // locate Data Store version
        EntityPath nodePath = new EntityPath("/jq-test-mobile/", "dashboard.xml");
        InfoNodeElement dashboard = dscInfoNodeService.getInfoNode(nodePath);

        // print some diagnostic info if DscInfoNodeService is used
        DscUtils.assertValidInfoNode(dashboard, "dashboard", dscInfoNodeService, nodePath);

        try {/*  w  ww . j a  v a 2s. c  o m*/
            dashboard.enableRootNode();
            @SuppressWarnings("unchecked")
            List<InfoNodeElement> allPanels = (List<InfoNodeElement>) dashboard.findAll("//panel");
            dashboardPanels = allPanels;

            // make adjustments for the mobile implementation TODO-p0(george) Eliminate the need for this [possibly have a local and remove URL definition in dynamic content - or support substitution vars]
            @SuppressWarnings("unchecked")
            List<InfoNodeElement> allLinks = (List<InfoNodeElement>) dashboard.findAll("//link");
            for (InfoNodeElement link : allLinks) {
                // add context to links, if needed
                Attribute href = link.getAttribute("href");
                if (StringUtils.startsWith(href.getValue(), "/")) {
                    href.setValue("/" + FacesUtils.getServletContextName() + href.getValue());
                }
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        }
    }

    return dashboardPanels;
}

From source file:com.adeptj.modules.security.jwt.internal.JwtKeys.java

static PrivateKey createSigningKey(JwtConfig jwtConfig, SignatureAlgorithm signatureAlgo) {
    LOGGER.info("Creating RSA signing key!!");
    String keyData = jwtConfig.privateKey();
    Assert.isTrue(StringUtils.startsWithAny(keyData, PRIVATE_ENCRYPTED_KEY_HEADER, PRIVATE_KEY_HEADER),
            INVALID_PRIVATE_KEY_MSG);//from   www  .  j a va 2 s. c o  m
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(signatureAlgo.getFamilyName());
        if (StringUtils.startsWith(keyData, PRIVATE_ENCRYPTED_KEY_HEADER)) {
            LOGGER.info("Creating PKCS8EncodedKeySpec from private [encrypted] key !!");
            Assert.hasText(jwtConfig.privateKeyPassword(), KEYPASS_NULL_MSG);
            byte[] privateKeyData = decodePrivateKeyData(keyData, true);
            EncryptedPrivateKeyInfo privateKeyInfo = new EncryptedPrivateKeyInfo(privateKeyData);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(privateKeyInfo.getAlgName());
            PBEKeySpec keySpec = new PBEKeySpec(jwtConfig.privateKeyPassword().toCharArray());
            SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance(privateKeyInfo.getAlgName());
            cipher.init(DECRYPT_MODE, secretKey, privateKeyInfo.getAlgParameters());
            return keyFactory.generatePrivate(privateKeyInfo.getKeySpec(cipher));
        }
        LOGGER.info("Creating PKCS8EncodedKeySpec from private key !!");
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decodePrivateKeyData(keyData, false)));
    } catch (GeneralSecurityException | IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new KeyInitializationException(ex.getMessage(), ex);
    }
}

From source file:de.micromata.genome.gwiki.page.impl.wiki.rte.els.RteImageDomElementListener.java

protected String handleDataImage(DomElementEvent event, String pageId) {
    if (StringUtils.isBlank(pageId) == true) {
        return pageId;
    }//  w w  w. jav a2 s .  c om
    String src = event.getAttr("src");
    // handle data:image/png;base64,iVBORw...
    if (StringUtils.startsWith(src, "data:image") == false) {
        return pageId;
    }
    int edix = src.indexOf(';');
    if (edix == -1) {
        return pageId;
    }
    String mime = src.substring(5, edix);
    int suffixidx = mime.indexOf('/');
    String suffix = null;
    if (suffixidx != -1) {
        suffix = mime.substring(suffixidx + 1);
    }
    String rest = src.substring(edix + 1);
    if (rest.startsWith("base64,") == false) {
        return pageId;
    }
    rest = rest.substring("base64,".length());
    byte[] data;
    try {
        data = Base64.getDecoder().decode(rest);
    } catch (IllegalArgumentException ex) {
        GLog.warn(GWikiLogCategory.Wiki, "Cannot decode image base64");
        return pageId;
    }
    String cpid = event.getParseContext().getCurrentPageId();
    if (src.equals(pageId) == true) {

        if (cpid == null) {
            GLog.warn(GWikiLogCategory.Wiki, "Non editPageId set. Cannot convert base64 image");
            return pageId;
        }
        pageId = getAutoImgPageId(event, cpid, suffix);
        if (pageId == null) {
            GLog.warn(GWikiLogCategory.Wiki, "Cannot create new image page id for base64image");
            return pageId;
        }
    }
    GWikiElement imageElement = event.getWikiContext().getWikiWeb().findElement(pageId);
    if ((imageElement instanceof GWikiFileAttachment) == false) {
        if (imageElement != null) {
            GLog.warn(GWikiLogCategory.Wiki, "Cannot overwrite non attachment with image: " + pageId);
            return pageId;
        }
        String metaTemplateId = "admin/templates/FileWikiPageMetaTemplate";
        imageElement = GWikiWebUtils.createNewElement(event.getWikiContext(), pageId, metaTemplateId, null);
        imageElement.getElementInfo().getProps().setStringValue(GWikiPropKeys.PARENTPAGE, cpid);
    }
    GWikiFileAttachment fat = (GWikiFileAttachment) imageElement;

    GWikiBinaryAttachmentArtefakt mpart = (GWikiBinaryAttachmentArtefakt) imageElement.getMainPart();
    mpart.setStorageData(data);
    event.getWikiContext().getWikiWeb().saveElement(event.getWikiContext(), fat, false);

    return pageId;
}

From source file:lolthx.autohome.buy.AutohomePriceListFetch.java

@Override
public void parse(String result, Task task) throws Exception {
    if (StringUtils.isBlank(result)) {
        return;/*from   www  .  j a  va  2 s  . co  m*/
    }

    Date start = task.getStartDate();
    Date end = task.getEndDate();

    Document doc = Jsoup.parse(result);
    Elements lis = doc.select("li.price-item");

    AutohomePriceInfoBean bean = new AutohomePriceInfoBean();

    for (Element li : lis) {

        try {
            Elements postTimeEl = li.select("div.user-name span");
            String postTime = "";
            if (!postTimeEl.isEmpty()) {
                postTime = StringUtils.trim(
                        StringUtils.substringBefore(postTimeEl.first().text(), "?").replaceAll("", ""));

                if (!isTime(postTime, start, end)) {
                    continue;
                }
            }
            bean.setPostTime(postTime);
            bean.setUrl(task.getUrl());
            bean.setForumId(StringUtils.substringBefore(task.getExtra(), ":"));
            bean.setProjectName(task.getProjectName());
            bean.setKeyword(StringUtils.substringAfter(task.getExtra(), ":"));

            // post id
            Elements id = li.select("div.price-share a.share");
            if (!id.isEmpty()) {
                String idStr = id.first().attr("data-target");
                idStr = StringUtils.substringAfterLast(idStr, "_");
                if (StringUtils.isBlank(idStr)) {
                    continue;
                }

                bean.setId(idStr);
            }

            // 
            Elements user = li.select("div.user-name a");
            if (!user.isEmpty()) {
                String userUrl = user.first().absUrl("href");
                String userId = StringUtils.substringAfterLast(userUrl, "/");
                String userName = user.first().text();

                bean.setUserId(userId);
                bean.setUserUrl(userUrl);
                bean.setUserName(userName);
            }

            Elements dataLis = li.select("div.price-item-bd li");
            for (Element dataLi : dataLis) {
                String data = dataLi.text();

                if (StringUtils.startsWith(data, "")) {
                    bean.setCar(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }

                if (StringUtils.startsWith(data, "")) {
                    bean.setPrice(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }

                if (StringUtils.startsWith(data, "")) {
                    bean.setGuidePrice(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }

                if (StringUtils.startsWith(data, "?")) {
                    bean.setTotalPrice(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }

                if (StringUtils.startsWith(data, "")) {
                    bean.setPurchaseTax(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }

                if (StringUtils.startsWith(data, "?")) {
                    bean.setCommercialInsurance(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }

                if (StringUtils.startsWith(data, "")) {
                    bean.setVehicleUseTax(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }
                if (StringUtils.startsWith(data, "")) {
                    bean.setCompulsoryInsurance(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }
                if (StringUtils.startsWith(data, "")) {
                    bean.setLicenseFee(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }
                if (StringUtils.startsWith(data, "?")) {
                    bean.setPromotion(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }
                if (StringUtils.startsWith(data, "")) {
                    bean.setBuyTime(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }
                if (StringUtils.startsWith(data, "")) {
                    String area = StringUtils.trim(StringUtils.substringAfter(data, ""));
                    String[] pAndC = StringUtils.splitByWholeSeparator(area, ",", 2);

                    if (pAndC.length == 1) {
                        bean.setBuyProvince(pAndC[0]);
                        bean.setBuyCity(pAndC[0]);
                    }

                    if (pAndC.length == 2) {
                        bean.setBuyProvince(pAndC[0]);
                        bean.setBuyCity(pAndC[1]);
                    }

                }
                if (StringUtils.startsWith(data, "")) {
                    Elements level = dataLi.select("span.level");
                    // 
                    if (!level.isEmpty()) {
                        bean.setSellerComment(level.first().text());
                    }

                    // ?
                    Elements seller = dataLi.select("a.title");
                    if (!seller.isEmpty()) {
                        String sellerUrl = seller.first().absUrl("href");
                        String sellerName = seller.first().text();
                        String sellerId = StringUtils.substringAfterLast(sellerUrl, "/");

                        bean.setSellerId(sellerId);
                        bean.setSellerName(sellerName);
                        bean.setSellerUrl(sellerUrl);
                    }

                    // ?
                    Elements sellerPhone = dataLi.select("em.phone-num");
                    if (!sellerPhone.isEmpty()) {
                        bean.setSellerPhone(sellerPhone.first().text());
                    }

                    // ?
                    // Elements sellerAddress =
                    // dataLi.select("em.phone-num");

                }
                if (StringUtils.startsWith(data, "?")) {
                    bean.setBuyFeeling(StringUtils.trim(StringUtils.substringAfter(data, "")));
                }
            }
            bean.saveOnNotExist();
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }
    }
}

From source file:com.quatico.base.aem.test.api.setup.Components.java

protected String getComponentPath(Resource pageResource, String relativePath) {
    String result = pageResource.getPath();
    Resource content = pageResource.getChild(JCR_CONTENT);
    if (content != null) {
        result = result + "/" + JCR_CONTENT;
    }/*from   ww  w . j av a2s  .co m*/
    if (!StringUtils.startsWith(relativePath, "/")) {
        result += "/";
    }
    return result + relativePath;
}

From source file:ch.cyberduck.core.googledrive.DriveListService.java

@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener)
        throws BackgroundException {
    try {/*w w  w  . j ava  2s  . co m*/
        final AttributedList<Path> children = new AttributedList<Path>();
        String page = null;
        do {
            final FileList list = session.getClient().files().list()
                    .setQ(String.format("'%s' in parents",
                            new DriveFileidProvider(session).getFileid(directory)))
                    .setPageToken(page).setFields("nextPageToken, files").setPageSize(pagesize).execute();
            for (File f : list.getFiles()) {
                final PathAttributes attributes = new PathAttributes();
                if (null != f.getExplicitlyTrashed()) {
                    if (f.getExplicitlyTrashed()) {
                        log.warn(String.format("Skip file %s", f));
                        continue;
                    }
                }
                if (!DRIVE_FOLDER.equals(f.getMimeType())) {
                    if (StringUtils.startsWith(f.getMimeType(), GOOGLE_APPS_PREFIX)) {
                        log.warn(String.format("Skip file %s", f));
                        continue;
                    }
                }
                if (null != f.getSize()) {
                    attributes.setSize(f.getSize());
                }
                attributes.setVersionId(f.getId());
                if (f.getModifiedTime() != null) {
                    attributes.setModificationDate(f.getModifiedTime().getValue());
                }
                if (f.getCreatedTime() != null) {
                    attributes.setCreationDate(f.getCreatedTime().getValue());
                }
                attributes.setChecksum(Checksum.parse(f.getMd5Checksum()));
                final EnumSet<AbstractPath.Type> type = DRIVE_FOLDER.equals(f.getMimeType())
                        ? EnumSet.of(Path.Type.directory)
                        : EnumSet.of(Path.Type.file);
                final Path child = new Path(directory, PathNormalizer.name(f.getName()), type, attributes);
                children.add(child);
            }
            listener.chunk(directory, children);
            page = list.getNextPageToken();
        } while (page != null);
        return children;
    } catch (IOException e) {
        throw new DriveExceptionMappingService().map("Listing directory failed", e, directory);
    }
}

From source file:com.nridge.ds.solr.SolrTransform.java

/**
 * Convenience method that returns the value of an application
 * manager configuration property using the concatenation of
 * the property prefix and suffix values.
 *
 * @param aSuffix Property name suffix./*from  w  w w.ja  v a 2s. co m*/
 *
 * @return Matching property values in a string array.
 */
public String[] getCfgStrings(String aSuffix) {
    String[] cfgValues;
    String propertyName;

    if (StringUtils.startsWith(aSuffix, "."))
        propertyName = mCfgPropertyPrefix + aSuffix;
    else
        propertyName = mCfgPropertyPrefix + "." + aSuffix;

    if (mAppMgr.isPropertyMultiValue(propertyName))
        cfgValues = mAppMgr.getStringArray(propertyName);
    else {
        cfgValues = new String[1];
        String cfgValue = mAppMgr.getString(propertyName);
        if (StringUtils.isEmpty(cfgValue))
            cfgValue = StringUtils.EMPTY;
        cfgValues[0] = cfgValue;
    }

    return cfgValues;
}

From source file:de.micromata.genome.gdbfs.AbstractFileSystem.java

@Override
public boolean isTextMimeType(String mimeType) {
    return StringUtils.startsWith(mimeType, "text/") == true;
}

From source file:io.wcm.config.core.override.impl.SystemPropertyOverrideProvider.java

@Activate
void activate(final ComponentContext ctx) {
    Dictionary config = ctx.getProperties();
    final boolean enabled = PropertiesUtil.toBoolean(config.get(PROPERTY_ENABLED), DEFAULT_ENABLED);

    Map<String, String> map = new HashMap<>();
    if (enabled) {
        Properties properties = System.getProperties();
        Enumeration<Object> keys = properties.keys();
        while (keys.hasMoreElements()) {
            Object keyObject = keys.nextElement();
            if (keyObject instanceof String) {
                String key = (String) keyObject;
                if (StringUtils.startsWith(key, SYSTEM_PROPERTY_PREFIX)) {
                    map.put(StringUtils.substringAfter(key, SYSTEM_PROPERTY_PREFIX), System.getProperty(key));
                }/* www .ja  v a 2s  . c om*/
            }
        }
    }
    this.overrideMap = ImmutableMap.copyOf(map);
}

From source file:com.moviejukebox.plugin.ImdbPluginTest.java

@Test
public void testImdbTvShow() {
    LOG.info("testImdbTvShow");
    PropertiesUtil.setProperty("mjb.includeEpisodePlots", true);
    PropertiesUtil.setProperty("imdb.full.info", true);
    ImdbPlugin imdbPlugin = new ImdbPlugin();

    Movie movie = new Movie();
    movie.setMovieType(Movie.TYPE_TVSHOW);
    movie.setId(ImdbPlugin.IMDB_PLUGIN_ID, "tt0369179");

    MovieFile mf1 = new MovieFile();
    mf1.setSeason(8);//from  w  w  w . j a v  a2s. c  om
    mf1.setFirstPart(12);
    mf1.setLastPart(12);
    movie.addMovieFile(mf1);
    MovieFile mf2 = new MovieFile();
    mf2.setSeason(8);
    mf2.setFirstPart(16);
    mf2.setLastPart(16);
    movie.addMovieFile(mf2);

    assertTrue("Failed scan", imdbPlugin.scan(movie));
    assertEquals("(1st) Incorrect title", "Chocolate Diddlers or My Puppy's Dead", mf1.getTitle(12));
    assertTrue("(1st) Incorrect plot",
            StringUtils.startsWith(mf1.getPlot(12), "When Charlie and Courtney break up"));
    assertEquals("(1st) Incorrect aired date", "13 Dec. 2010", mf1.getFirstAired(12));
    assertEquals("(last) Incorrect title", "That Darn Priest", mf2.getTitle(16));
    assertTrue("(last) Incorrect plot",
            StringUtils.startsWith(mf2.getPlot(16), "Rose becomes wise to Alan's Ponzi scheme"));
    assertEquals("(last) Incorrect aired", "28 Mar. 2011", mf2.getFirstAired(16));
}