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

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

Introduction

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

Prototype

public static String removeStart(final String str, final String remove) 

Source Link

Document

Removes a substring only if it is at the beginning of a source string, otherwise returns the source string.

A null source string will return null .

Usage

From source file:com.xpn.xwiki.plugin.skinx.CssSkinFileExtensionPlugin.java

/**
 * {@inheritDoc}// w w  w.  ja v a2  s. c om
 * 
 * @see AbstractSkinExtensionPlugin#getLink(String, XWikiContext)
 */
@Override
public String getLink(String filename, XWikiContext context) {
    boolean forceSkinAction = (Boolean) getParametersForResource(filename, context).get("forceSkinAction");
    StringBuilder result = new StringBuilder("<link rel='stylesheet' type='text/css' href='");
    result.append(context.getWiki().getSkinFile(filename, forceSkinAction, context));
    if (forceSkinAction) {
        String parameters = StringUtils.removeStart(parametersAsQueryString(filename, context), "&amp;");
        if (!StringUtils.isEmpty(parameters)) {
            result.append("?").append(parameters);
        }
    }
    result.append("'/>");
    return result.toString();
}

From source file:it.vige.greenarea.sgaplconsole.controllers.utils.RelativeViewHandler.java

/**
 * Transform the given URL to a relative URL <b>in the context of the
 * current faces request</b>. If the given URL is not absolute do nothing
 * and return the given url. The returned relative URL is "equal" to the
 * original url but will not start with a '/'. So the browser can request
 * the "same" resource but in a relative way and this is important behind
 * reverse proxies!//from w  w  w .jav  a 2 s.c o m
 * 
 * @param context
 * @param theURL
 * @return
 */
private String getRelativeURL(final FacesContext context, final String theURL) {
    final HttpServletRequest request = ((HttpServletRequest) context.getExternalContext().getRequest());
    logger.debug("Context Path <" + getPath(request) + "> e url originale <" + theURL + ">");
    String result = theURL;
    if (theURL.startsWith("/")) {
        int subpath = StringUtils.countMatches(getPath(request), "/") - 1;
        String pathPrefix = "";
        if (subpath > 0) {
            while (subpath > 0) {
                pathPrefix += "/..";
                subpath--;
            }
            pathPrefix = StringUtils.removeStart(pathPrefix, "/");
        }
        result = pathPrefix + result;
    }
    logger.debug("Result <<<" + result + ">>>>  ");
    logger.debug("--------------------------------------------------------------------");
    return result;
}

From source file:com.sonicle.webtop.core.sdk.bol.js.JsOptions.java

public Map<String, Object> getWithPrefix(String prefix) {
    JsOptions map = new JsOptions();
    for (Map.Entry<String, Object> entry : entrySet()) {
        if (StringUtils.startsWith(entry.getKey(), prefix)) {
            map.put(WordUtils.uncapitalize(StringUtils.removeStart(entry.getKey(), prefix)), entry.getValue());
        }/*from   w  w w  .  j  a  v a  2s . c  om*/
    }
    return map;
}

From source file:blue.lapis.pore.impl.event.PoreEventImplTest.java

@Test
public void checkName() {
    Class<?> bukkitEvent = eventImpl.getSuperclass();

    String poreName = event;// w  w w. j a  v a 2  s  .  c  o  m
    String porePackage = StringUtils.substringBeforeLast(poreName, ".");
    poreName = StringUtils.substringAfterLast(poreName, ".");

    String bukkitName = StringUtils.removeStart(bukkitEvent.getName(), BUKKIT_PREFIX);
    String bukkitPackage = StringUtils.substringBeforeLast(bukkitName, ".");
    bukkitName = StringUtils.substringAfterLast(bukkitName, ".");

    String expectedName = "Pore" + bukkitName;

    assertEquals(poreName + " should be called " + expectedName, poreName, expectedName);
    assertEquals(poreName + " is in wrong package: should be in " + PORE_PREFIX + bukkitPackage, porePackage,
            bukkitPackage);
}

From source file:com.xpn.xwiki.plugin.skinx.JsSkinFileExtensionPlugin.java

/**
 * {@inheritDoc}//from  www .ja v  a 2  s .  c o m
 * 
 * @see AbstractSkinExtensionPlugin#getLink(String, XWikiContext)
 */
@Override
public String getLink(String filename, XWikiContext context) {
    boolean forceSkinAction = BooleanUtils
            .toBoolean((Boolean) getParameter("forceSkinAction", filename, context));
    StringBuilder result = new StringBuilder("<script type='text/javascript' src='");
    result.append(context.getWiki().getSkinFile(filename, forceSkinAction, context));
    if (forceSkinAction) {
        String parameters = StringUtils.removeStart(parametersAsQueryString(filename, context), "&amp;");
        if (!StringUtils.isEmpty(parameters)) {
            result.append("?").append(parameters);
        }
    }
    // check if js should be deferred, defaults to the preference configured in the cfg file, which defaults to true
    String defaultDeferString = context.getWiki().Param(DEFER_DEFAULT_PARAM);
    Boolean defaultDefer = (!StringUtils.isEmpty(defaultDeferString)) ? Boolean.valueOf(defaultDeferString)
            : true;
    if (BooleanUtils.toBooleanDefaultIfNull((Boolean) getParameter("defer", filename, context), defaultDefer)) {
        result.append("' defer='defer");
    }
    result.append("'></script>\n");
    return result.toString();
}

From source file:com.xpn.xwiki.web.CommentAddAction.java

/**
 * {@inheritDoc}//from w  w w .  ja v a 2s  .  c  o  m
 * 
 * @see XWikiAction#action(com.xpn.xwiki.XWikiContext)
 */
@Override
public boolean action(XWikiContext context) throws XWikiException {
    // CSRF prevention
    if (!csrfTokenCheck(context)) {
        return false;
    }

    XWiki xwiki = context.getWiki();
    XWikiResponse response = context.getResponse();
    XWikiDocument doc = context.getDoc();
    ObjectAddForm oform = (ObjectAddForm) context.getForm();

    // Make sure this class exists
    BaseClass baseclass = xwiki.getCommentsClass(context);
    if (doc.isNew()) {
        return true;
    } else if (context.getUser().equals(XWikiRightService.GUEST_USER_FULLNAME) && !checkCaptcha(context)) {
        ((VelocityContext) context.get("vcontext")).put("captchaAnswerWrong", Boolean.TRUE);
    } else {
        // className = XWiki.XWikiComments
        String className = baseclass.getName();
        BaseObject object = doc.newObject(className, context);
        // TODO The map should be pre-filled with empty strings for all class properties, just like in
        // ObjectAddAction, so that properties missing from the request are still added to the database.
        baseclass.fromMap(oform.getObject(className), object);
        // Comment author checks
        if (XWikiRightService.GUEST_USER_FULLNAME.equals(context.getUser())) {
            // Guests should not be allowed to enter names that look like real XWiki user names.
            String author = ((BaseProperty) object.get(AUTHOR_PROPERTY_NAME)).getValue() + "";
            author = StringUtils.remove(author, ':');
            while (author.startsWith(USER_SPACE_PREFIX)) {
                author = StringUtils.removeStart(author, USER_SPACE_PREFIX);
            }
            object.set(AUTHOR_PROPERTY_NAME, author, context);
        } else {
            // A registered user must always post with his name.
            object.set(AUTHOR_PROPERTY_NAME, context.getUser(), context);
        }
        doc.setAuthor(context.getUser());
        // Consider comments not being content.
        doc.setContentDirty(false);
        // if contentDirty is false, in order for the change to create a new version metaDataDirty must be true.
        doc.setMetaDataDirty(true);
        xwiki.saveDocument(doc, context.getMessageTool().get("core.comment.addComment"), true, context);
    }
    // If xpage is specified then allow the specified template to be parsed.
    if (context.getRequest().get("xpage") != null) {
        return true;
    }
    // forward to edit
    String redirect = Utils.getRedirect("edit", context);
    sendRedirect(response, redirect);
    return false;
}

From source file:ch.cyberduck.core.aquaticprime.DictionaryLicense.java

protected void verify(final NSDictionary dictionary, final String publicKey) throws InvalidLicenseException {
    if (null == dictionary) {
        throw new InvalidLicenseException();
    }/*from w  ww. ja  v  a  2  s.c  o  m*/
    final NSData signature = (NSData) dictionary.objectForKey("Signature");
    if (null == signature) {
        log.warn(String.format("Missing key 'Signature' in dictionary %s", dictionary));
        throw new InvalidLicenseException();
    }
    // Append all values
    StringBuilder values = new StringBuilder();
    final ArrayList<String> keys = new ArrayList<>(dictionary.keySet());
    // Sort lexicographically by key
    Collections.sort(keys, new NaturalOrderComparator());
    for (String key : keys) {
        if ("Signature".equals(key)) {
            continue;
        }
        values.append(dictionary.objectForKey(key).toString());
    }
    byte[] signaturebytes = signature.bytes();
    byte[] plainbytes = values.toString().getBytes(Charset.forName("UTF-8"));
    try {
        final BigInteger modulus = new BigInteger(StringUtils.removeStart(publicKey, "0x"), 16);
        final BigInteger exponent = new BigInteger(Base64.decodeBase64("Aw=="));
        final KeySpec spec = new RSAPublicKeySpec(modulus, exponent);

        final PublicKey rsa = KeyFactory.getInstance("RSA").generatePublic(spec);
        final Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsaCipher.init(Cipher.DECRYPT_MODE, rsa);
        final MessageDigest sha1Digest = MessageDigest.getInstance("SHA1");
        if (!Arrays.equals(rsaCipher.doFinal(signaturebytes), sha1Digest.digest(plainbytes))) {
            throw new InvalidLicenseException();
        }
    } catch (NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException
            | InvalidKeySpecException | NoSuchAlgorithmException e) {
        log.warn(String.format("Signature verification failure for key %s", file));
        throw new InvalidLicenseException();
    }
    if (log.isInfoEnabled()) {
        log.info(String.format("Valid key in %s", file));
    }
}

From source file:com.conversantmedia.mapreduce.tool.DistributedResourceManager.java

@SuppressWarnings("unchecked")
protected void configureBeanDistributedResources(Object annotatedBean)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
    MaraAnnotationUtil util = MaraAnnotationUtil.INSTANCE;
    Distribute distribute;/* www  . j a v a 2 s.co  m*/
    // Search for annotated resources to distribute
    List<Field> fields = util.findAnnotatedFields(annotatedBean.getClass(), Distribute.class);
    for (Field field : fields) {
        distribute = field.getAnnotation(Distribute.class);
        String key = StringUtils.isBlank(distribute.name()) ? field.getName() : distribute.name();

        field.setAccessible(true);
        Object value = field.get(annotatedBean);
        if (value != null) {
            registerResource(key, value);
        }
    }

    // Search for annotated methods
    List<Method> methods = util.findAnnotatedMethods(annotatedBean.getClass(), Distribute.class);
    for (Method method : methods) {
        distribute = AnnotationUtils.findAnnotation(method, Distribute.class);
        // Invoke the method to retrieve the cache file path. Needs to return either a String or a Path
        String defaultName = StringUtils.uncapitalize(StringUtils.removeStart(method.getName(), "get"));
        String key = StringUtils.isBlank(distribute.name()) ? defaultName : distribute.name();
        Object value = method.invoke(annotatedBean);
        if (value != null) {
            registerResource(key, value);
        }
    }
}

From source file:ch.cyberduck.core.aquaticprime.DonationKey.java

/**
 * @return True if valid license key//from   w  ww  . j a  v  a 2 s  .  com
 */
@Override
public boolean verify() {
    if (null == dictionary) {
        return false;
    }
    final NSData signature = (NSData) dictionary.objectForKey("Signature");
    if (null == signature) {
        log.warn(String.format("Missing key 'Signature' in dictionary %s", dictionary));
        return false;
    }
    // Append all values
    StringBuilder values = new StringBuilder();
    final ArrayList<String> keys = new ArrayList<>(dictionary.keySet());
    // Sort lexicographically by key
    Collections.sort(keys, new NaturalOrderComparator());
    for (String key : keys) {
        if ("Signature".equals(key)) {
            continue;
        }
        values.append(dictionary.objectForKey(key).toString());
    }
    byte[] signaturebytes = signature.bytes();
    byte[] plainbytes = values.toString().getBytes(Charset.forName("UTF-8"));
    final boolean valid;
    try {
        final BigInteger modulus = new BigInteger(StringUtils.removeStart(this.getPublicKey(), "0x"), 16);
        final BigInteger exponent = new BigInteger(Base64.decodeBase64("Aw=="));
        final KeySpec spec = new RSAPublicKeySpec(modulus, exponent);

        final PublicKey rsa = KeyFactory.getInstance("RSA").generatePublic(spec);
        final Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsaCipher.init(Cipher.DECRYPT_MODE, rsa);
        final MessageDigest sha1Digest = MessageDigest.getInstance("SHA1");
        valid = Arrays.equals(rsaCipher.doFinal(signaturebytes), sha1Digest.digest(plainbytes));
    } catch (NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException
            | InvalidKeySpecException | NoSuchAlgorithmException e) {
        log.warn(String.format("Signature verification failure for key %s", file));
        return false;
    }
    if (valid) {
        if (log.isInfoEnabled()) {
            log.info(String.format("Valid key in %s", file));
        }
    } else {
        log.warn(String.format("Not a valid key in %s", file));
    }
    return valid;
}

From source file:info.magnolia.ui.vaadin.integration.contentconnector.JcrContentConnector.java

@Override
public String getItemUrlFragment(Object itemId) {
    try {//www . j av  a  2s  .c  o m
        if (itemId instanceof JcrItemId) {
            JcrItemId jcrItemId = (JcrItemId) itemId;
            javax.jcr.Item selected = JcrItemUtil.getJcrItem(jcrItemId);
            String selectedPath = JcrItemUtil.getItemPath(selected);
            String rootPath = getRootPath();
            String urlFragment = StringUtils.removeStart(selectedPath, "/".equals(rootPath) ? "" : rootPath);
            if (itemId instanceof JcrNewNodeItemId) {
                if (!urlFragment.endsWith("/")) {
                    urlFragment += "/";
                }
                urlFragment += ((JcrNewNodeItemId) jcrItemId).getName();
            }
            return urlFragment;
        }
    } catch (RepositoryException e) {
        log.error("Failed to convert item id to URL fragment: " + e.getMessage(), e);
    }
    return null;
}