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

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

Introduction

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

Prototype

public static boolean startsWith(String str, String prefix) 

Source Link

Document

Check if a String starts with a specified prefix.

Usage

From source file:com.xx_dev.apn.proxy.ApnProxyPreHandler.java

private boolean preCheck(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        String originalHost = HostNamePortUtil.getHostName(httpRequest);

        LoggerUtil.info(httpRestLogger, ctx.channel().remoteAddress().toString(),
                httpRequest.getMethod().name(), httpRequest.getUri(), httpRequest.getProtocolVersion().text(),
                httpRequest.headers().get(HttpHeaders.Names.USER_AGENT));

        isPacRequest = false;//from ww w  .  j a  va 2 s. com

        // pac request
        if (StringUtils.equals(originalHost, ApnProxyConfig.getConfig().getPacHost())) {
            isPacRequest = true;

            String pacContent = null;
            if (ApnProxyConfig.getConfig().getListenType() == ApnProxyListenType.SSL) {
                pacContent = buildPacForSsl();
            } else {
                pacContent = buildPacForPlain();
            }

            ByteBuf pacResponseContent = Unpooled.copiedBuffer(pacContent, CharsetUtil.UTF_8);
            FullHttpMessage pacResponseMsg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, pacResponseContent);
            HttpHeaders.setContentLength(pacResponseMsg, pacResponseContent.readableBytes());
            HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-PAC", "OK");
            HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-URL", "https://github.com/apn-proxy/apn-proxy");
            HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-MSG", "We need more commiters!");

            ctx.write(pacResponseMsg);
            ctx.flush();
            return false;
        }

        // forbid request to proxy server internal network
        for (String forbiddenIp : forbiddenIps) {
            if (StringUtils.startsWith(originalHost, forbiddenIp)) {
                String errorMsg = "Forbidden";
                ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg));
                ctx.flush();
                return false;
            }
        }

        // forbid request to proxy server local
        if (StringUtils.equals(originalHost, "127.0.0.1") || StringUtils.equals(originalHost, "localhost")) {
            String errorMsg = "Forbidden Host";
            ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg));
            ctx.flush();
            return false;
        }

        // forbid reqeust to some port
        int originalPort = HostNamePortUtil.getPort(httpRequest);
        for (int fobiddenPort : forbiddenPorts) {
            if (originalPort == fobiddenPort) {
                String errorMsg = "Forbidden Port";
                ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg));
                ctx.flush();
                return false;
            }
        }

    } else {
        if (isPacRequest) {
            return false;
        }
    }

    return true;
}

From source file:com.steeleforge.aem.ironsites.wcm.page.IronSitemap.java

/**
 * Determine inclusion path level and ammend it to paths map
 * /*  w ww  .ja  v  a2s .  c o m*/
 * @param page root page
 */
private void populateInclusions(Page root) {
    int base = root.getDepth();
    int level = -1;
    for (String path : getInclusions()) {
        // handle external links gracefully, assume level 0
        if (StringUtils.startsWith(path, "/")) {
            level = base - StringUtils.countMatches(path, "/") - 1;
        } else {
            level = -1;
        }
        if (level < 0) {
            level = ROOT_LEVEL;
        }
        getPaths(level).add(path);
    }
}

From source file:com.adobe.acs.commons.users.impl.EnsureAce.java

/**
 * Ensures the ACEs for the Service User exists. Any extra ACEs for the Service User will be removed.
 *
 * @param resourceResolver/*from  w  w  w . j  av a 2 s.co  m*/
 *            the resource resolver to perform the user management
 * @param jcrAuthorizable
 *            the Jackrabbit Authorizable Object (User or Group) the Authorizable represents
 * @param authorizable
 *            the Authorizable to ensure
 * @return The number of ace entries that could not be processed
 * @throws RepositoryException
 */
@SuppressWarnings("squid:S3776")
public int ensureAces(ResourceResolver resourceResolver, Authorizable jcrAuthorizable,
        AbstractAuthorizable authorizable) throws RepositoryException {
    int failures = 0;
    final Session session = resourceResolver.adaptTo(Session.class);

    final JackrabbitAccessControlManager accessControlManager = (JackrabbitAccessControlManager) session
            .getAccessControlManager();
    final List<JackrabbitAccessControlList> acls = findAcls(resourceResolver, authorizable.getPrincipalName(),
            accessControlManager);

    // For each rep:policy (ACL) this service user participates in ...
    for (final JackrabbitAccessControlList acl : acls) {
        final JackrabbitAccessControlEntry[] aces = (JackrabbitAccessControlEntry[]) acl
                .getAccessControlEntries();
        final boolean serviceUserCoversThisPath = authorizable.hasAceAt(acl.getPath());

        for (final JackrabbitAccessControlEntry ace : aces) {

            if (!StringUtils.equals(authorizable.getPrincipalName(), ace.getPrincipal().getName())) {
                // Only care about ACEs that this service user participates in
                continue;
            }

            // Pertains to this service user
            if (StringUtils.startsWith(acl.getPath(), jcrAuthorizable.getPath())) {
                // Skip the corner case of ACL's under the system user itself; Do nothing to these.

            } else if (!serviceUserCoversThisPath) {
                // Remove all ACE's for this user from this ACL since this Service User is not configured to cover
                // this path
                log.debug("Service user does NOT cover the path yet has an ACE; ensure removal of the ace! {}",
                        ace.toString());
                acl.removeAccessControlEntry(ace);

            } else {
                final Ace serviceUserAce = authorizable.getAce(ace, acl.getPath());
                if (serviceUserAce == null) {
                    acl.removeAccessControlEntry(ace);
                    log.debug("Removed System ACE as it doesn't exist in Service User [ {} ] configuration",
                            authorizable.getPrincipalName());
                } else {
                    serviceUserAce.setExists(true);
                    log.debug("No-op on System ACE as it already matches Service User [ {} ] configuration",
                            authorizable.getPrincipalName());

                }
            }
        }

        accessControlManager.setPolicy(acl.getPath(), acl);
    }

    // Create an ACEs that do not yet exist
    for (Ace ace : authorizable.getMissingAces()) {
        if (resourceResolver.getResource(ace.getContentPath()) == null) {
            log.warn(
                    "Unable to apply Service User [ {} ] privileges due to missing path at [ {} ]. Please create the path and re-ensure this service user.",
                    authorizable.getPrincipalName(), ace.getContentPath());
            failures++;
            continue;
        }

        final JackrabbitAccessControlList acl = AccessControlUtils.getAccessControlList(session,
                ace.getContentPath());
        final Map<String, Value> restrictions = new HashMap<String, Value>();
        final Map<String, Value[]> multiRestrictions = new HashMap<String, Value[]>();

        final ValueFactory valueFactory = session.getValueFactory();

        // Add rep:glob restriction
        if (ace.hasRepGlob()) {
            restrictions.put(AccessControlConstants.REP_GLOB,
                    valueFactory.createValue(ace.getRepGlob(), PropertyType.STRING));
        }

        // Add rep:ntNames restriction
        if (ace.hasRepNtNames()) {
            multiRestrictions.put(AccessControlConstants.REP_NT_NAMES,
                    getMultiValues(valueFactory, ace.getRepNtNames(), PropertyType.NAME));
        }

        // Add rep:itemNames
        if (ace.hasRepItemNames()) {
            multiRestrictions.put(AccessControlConstants.REP_ITEM_NAMES,
                    getMultiValues(valueFactory, ace.getRepItemNames(), PropertyType.NAME));
        }

        // Add rep:prefixes
        if (ace.hasRepPrefixes()) {
            multiRestrictions.put(AccessControlConstants.REP_PREFIXES,
                    getMultiValues(valueFactory, ace.getRepPrefixes(), PropertyType.STRING));
        }

        // Add ACE to the ACL
        acl.addEntry(jcrAuthorizable.getPrincipal(),
                ace.getPrivileges(accessControlManager).toArray(new Privilege[] {}), ace.isAllow(),
                restrictions, multiRestrictions);

        // Update the ACL on the content
        accessControlManager.setPolicy(ace.getContentPath(), acl);

        log.debug("Added Service User ACE for [ {} ] to [ {} ]", authorizable.getPrincipalName(),
                ace.getContentPath());
    }

    return failures;
}

From source file:com.haulmont.cuba.web.security.idp.BaseIdpSessionFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // send static files without authentication
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (StringUtils.startsWith(httpRequest.getRequestURI(), httpRequest.getContextPath() + "/VAADIN/")) {
        chain.doFilter(request, response);
        return;//from w w w.ja va2  s . c om
    }

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String idpBaseURL = webIdpConfig.getIdpBaseURL();
    if (Strings.isNullOrEmpty(idpBaseURL)) {
        log.error("Application property cuba.web.idp.url is not set");
        httpResponse.setStatus(500);
        return;
    }

    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }

    String requestUrl = httpRequest.getRequestURL().toString();
    if (StringUtils.startsWith(requestUrl, idpBaseURL)) {
        chain.doFilter(httpRequest, response);
        return;
    }

    HttpSession session = httpRequest.getSession(true);
    Lock sessionLock = (Lock) session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
    if (sessionLock == null) {
        sessionCheckLock.lock();
        try {
            sessionLock = (Lock) session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
            if (sessionLock == null) {
                sessionLock = new ReentrantLock();
                session.setAttribute(IDP_SESSION_LOCK_ATTRIBUTE, sessionLock);
            }
        } finally {
            sessionCheckLock.unlock();
        }
    }

    IdpSession boundIdpSession;
    sessionLock.lock();

    try {
        session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
    } catch (IllegalStateException e) {
        // Someone might have invalidated the session between fetching the lock and acquiring it.
        sessionLock.unlock();

        log.debug("Invalidated session {}", session.getId());
        httpResponse.sendRedirect(httpRequest.getRequestURL().toString());
        return;
    }

    try {
        if ("GET".equals(httpRequest.getMethod())
                && httpRequest.getParameter(IDP_TICKET_REQUEST_PARAM) != null) {
            String idpTicket = httpRequest.getParameter(IDP_TICKET_REQUEST_PARAM);

            IdpSession idpSession;
            try {
                idpSession = getIdpSession(idpTicket);
            } catch (IdpActivationException e) {
                log.error("Unable to obtain IDP session by ticket", e);
                httpResponse.setStatus(500);
                return;
            }

            if (idpSession == null) {
                log.warn("Used old IDP ticket {}, send redirect", idpTicket);
                // used old ticket, send redirect
                httpResponse.sendRedirect(getIdpRedirectUrl());
                return;
            }

            session.invalidate();

            session = httpRequest.getSession(true);
            session.setAttribute(IDP_SESSION_LOCK_ATTRIBUTE, sessionLock);
            session.setAttribute(IDP_SESSION_ATTRIBUTE, idpSession);

            log.debug("IDP session {} obtained, redirect to application", idpSession);

            // redirect to application without parameters
            httpResponse.sendRedirect(httpRequest.getRequestURL().toString());
            return;
        }

        if (session.getAttribute(IDP_SESSION_ATTRIBUTE) == null) {
            if ("GET".equals(httpRequest.getMethod()) && !StringUtils.startsWith(httpRequest.getRequestURI(),
                    httpRequest.getContextPath() + "/PUSH")) {
                httpResponse.sendRedirect(getIdpRedirectUrl());
            }
            return;
        }

        boundIdpSession = (IdpSession) session.getAttribute(IDP_SESSION_ATTRIBUTE);
    } finally {
        sessionLock.unlock();
    }

    HttpServletRequest authenticatedRequest = new IdpServletRequestWrapper(httpRequest,
            new IdpSessionPrincipalImpl(boundIdpSession));

    chain.doFilter(authenticatedRequest, response);
}

From source file:com.ariht.maven.plugins.config.io.DirectoryReader.java

/**
 * Has a directory or specific file been excluded from config generation?
 *///from   www  .  j  av  a  2s.  co m
private boolean isFileToIgnore(final File file, final List<File> filesToIgnore) {
    for (File f : filesToIgnore) {
        if (StringUtils.startsWith(file.getAbsolutePath(), f.getAbsolutePath())) {
            log.debug(
                    "Matched prefix so will ignore: \n" + file.getAbsolutePath() + "\n" + f.getAbsolutePath());
            return true;
        }
    }
    return false;
}

From source file:com.adobe.acs.commons.workflow.bulk.execution.model.Payload.java

public static String dereference(String str) {
    if (!StringUtils.startsWith(str, "-")) {
        str = "-" + str;
    }// www . ja v  a2  s  .  co  m

    return str;
}

From source file:com.nridge.ds.content.ds_content.ContentExtractor.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 ww.ja  v a2  s  .  c o m*/
 * @return Matching property value.
 */
public String getCfgString(String aSuffix) {
    String propertyName;

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

    return mAppMgr.getString(propertyName);
}

From source file:com.btobits.automator.fix.comparator.MailComparator.java

public static final String getHeaderField(final String inName, final SMTPMessage inSmtpMessage) {
    final List<Object> lines = inSmtpMessage.getDataLines();
    for (final Object obj : lines) {
        final String val = (String) obj;
        final String header = inName + ": ";
        if (!StringUtils.isBlank(val)) {
            if (StringUtils.startsWith(val, header)) {
                return StringUtils.substringAfter(val, header);
            }//  ww w  . j  a  v a  2  s  .  com
        } else {
            break; // data field
        }
    }
    return null;
}

From source file:com.activecq.tools.flipbook.components.impl.FlipbookServiceImpl.java

public List<Resource> getPages(final Resource resource) throws RepositoryException {
    final ResourceResolver resourceResolver = resource.getResourceResolver();
    final PageManager pageManager = resourceResolver.adaptTo(PageManager.class);

    final List<Resource> pages = new ArrayList<Resource>();

    final Map<String, String> map = new HashMap<String, String>();
    map.put("type", "cq:Component");

    map.put("orderby", "@jcr:title");
    map.put("orderby.sort", "asc");

    map.put("p.offset", "0");
    // Cowardly refusing to return more than 10000 results
    // If you have more than 10,000 components something is seriously wrong
    // with your design approach
    map.put("p.limit", String.valueOf(MAX_RESULTS));

    final Query query = queryBuilder.createQuery(PredicateGroup.create(map),
            resourceResolver.adaptTo(Session.class));
    final SearchResult result = query.getResult();

    for (Hit hit : result.getHits()) {
        final ValueMap props = hit.getProperties();
        final String path = hit.getPath();
        boolean hide = true;

        for (final String validPathPrefix : this.getPaths(pageManager.getContainingPage(resource))) {
            if (StringUtils.startsWith(path, validPathPrefix.concat("/"))) {
                hide = false;//from   ww w  . j a v  a2s.  c  o m
            }
        }

        if (!hide) {
            if (!this.getShowHidden(resource.adaptTo(ValueMap.class))) {
                hide = StringUtils.equals(props.get("componentGroup", HIDDEN_COMPONENT_GROUP), "");
            }
        }

        if (!hide) {
            hide = props.get("hideInFlipbook", false);
        }

        if (!hide) {
            pages.add(hit.getResource());
        }
    }

    return pages;
}

From source file:mitm.common.util.MiscArrayUtilsTest.java

private void testMaxRadix(byte[] bytes) {
    String radix = MiscArrayUtils.toMaxRadix(bytes);

    assertFalse(StringUtils.startsWith(radix, "-"));

    byte[] fromString = MiscArrayUtils.fromMaxRadix(radix);

    assertEquals(0, MiscArrayUtils.compareArray(bytes, fromString));
}