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

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

Introduction

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

Prototype

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

Source Link

Document

Case insensitive check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:com.quinsoft.zeidon.objectdefinition.EntityDef.java

@Override
public void setAttribute(PortableFileReader reader) {
    String attributeName = reader.getAttributeName();

    switch (attributeName.charAt(0)) {
    case 'A':
        if (reader.getAttributeName().equals("ACT_LIMIT")) {
            activateLimit = Integer.parseInt(reader.getAttributeValue());
        } else if (reader.getAttributeName().equals("AUTOLOADFROMPARENT")) {
            autoloadFromParent = reader.getAttributeValue().startsWith("Y");
        }/*  w w w . ja  va 2s.  c  om*/
        break;

    case 'C':
        if (reader.getAttributeName().equals("CREATE")) {
            create = reader.getAttributeValue().startsWith("Y");
        } else if (reader.getAttributeName().equals("CARDMAX")) {
            maxcardinality = Integer.parseInt(reader.getAttributeValue());
        } else if (reader.getAttributeName().equals("CARDMIN")) {
            minCardinality = Integer.parseInt(reader.getAttributeValue());
        }
        break;

    case 'D':
        if (reader.getAttributeName().equals("DELETE")) {
            delete = reader.getAttributeValue().startsWith("Y");
        } else if (reader.getAttributeName().equals("DERIVED")) {
            derived = true;
            derivedPath = true;
        } else if (reader.getAttributeName().equals("DEBUGCHG")) {
            // Set up a listener to write stack trace when an entity is changed.
            if (StringUtils.startsWithIgnoreCase(reader.getAttributeValue(), "Y"))
                eventListener = new EventStackTrace();
        }
        if (reader.getAttributeName().equals("DEBUGINCRE")) {
            debugIncrementalFlag = StringUtils.startsWithIgnoreCase(reader.getAttributeValue(), "Y");
        } else if (reader.getAttributeName().equals("DUPENTIN")) {
            duplicateEntity = true;
            lodDef.setHasDuplicateInstances(true);
        }

        break;

    case 'E':
        if (reader.getAttributeName().equals("ECESRCFILE")) {
            sourceFileName = reader.getAttributeValue();
            if (!sourceFileName.contains("."))
                sourceFileName = getLodDef().getApplication().getPackage() + "." + sourceFileName;
        } else if (reader.getAttributeName().equals("ECESRCTYPE")) {
            sourceFileType = SourceFileType.parse(reader.getAttributeValue());
        } else if (reader.getAttributeName().equals("ECEOPER")) {
            constraintOper = reader.getAttributeValue().intern();
        } else if (reader.getAttributeName().equals("ECCR")) {
            hasCreateConstraint = StringUtils.startsWithIgnoreCase(reader.getAttributeValue(), "Y");
        } else if (reader.getAttributeName().equals("ECDEL")) {
            hasDeleteConstraint = StringUtils.startsWithIgnoreCase(reader.getAttributeValue(), "Y");
        } else if (reader.getAttributeName().equals("ECINC")) {
            hasIncludeConstraint = StringUtils.startsWithIgnoreCase(reader.getAttributeValue(), "Y");

            // Include constraints take some work.  Since nobody appears to use them let's not
            // worry about implementing them for now.
            throw new UnsupportedOperationException("Include constraints not supported yet.");
        } else if (reader.getAttributeName().equals("ECEXC")) {
            hasExcludeConstraint = StringUtils.startsWithIgnoreCase(reader.getAttributeValue(), "Y");
        } else if (reader.getAttributeName().equals("ECACC")) {
            hasAcceptConstraint = StringUtils.startsWithIgnoreCase(reader.getAttributeValue(), "Y");
        } else if (reader.getAttributeName().equals("ECCAN")) {
            hasCancelConstraint = StringUtils.startsWithIgnoreCase(reader.getAttributeValue(), "Y");
        } else if (reader.getAttributeName().equals("ERENT_TOK")) {
            erEntityToken = reader.getAttributeValue().intern();
        } else if (reader.getAttributeName().equals("ERREL_TOK")) {
            erRelToken = reader.getAttributeValue().intern();
        } else if (reader.getAttributeName().equals("ERREL_LINK")) {
            erRelLink = reader.getAttributeValue().equals("1");
        } else if (reader.getAttributeName().equals("EXCLUDE")) {
            exclude = reader.getAttributeValue().startsWith("Y");
        }
        break;

    case 'I':
        if (reader.getAttributeName().equals("INCLUDE")) {
            include = reader.getAttributeValue().startsWith("Y");
        } else if (reader.getAttributeName().equals("INCLSRC")) {
            includeSrc = reader.getAttributeValue().startsWith("Y");
        }
        break;

    case 'L':
        if (reader.getAttributeName().equals("LAZYLOAD")) {
            getLazyLoadConfig().setFlag(LazyLoadFlags.IS_LAZYLOAD);
            if (getParent() == null)
                throw new ZeidonException("LAZYLOAD is invalid for root entity");

            LazyLoadConfig parentConfig = getParent().getLazyLoadConfig();
            parentConfig.setFlag(LazyLoadFlags.HAS_LAZYLOAD_CHILD);
            getLodDef().setHasLazyLoadEntities(true);
        }
        break;

    case 'N':
        if (reader.getAttributeName().equals("NAME")) {
            name = reader.getAttributeValue().intern();
        }
        break;

    case 'P':
        if (reader.getAttributeName().equals("PDELETE")) {
            switch (reader.getAttributeValue().charAt(0)) {
            case 'D':
                parentDelete = true;
                break;

            case 'R':
                restrictParentDelete = true;
                getParent().setCheckRestrictedDelete(true);
                break;

            // It looks like we're supposed to ignore 'E'.
            }
        }
        break;

    case 'R':
        if (reader.getAttributeName().equals("RECURSIVE")) {
            // Check to see if this entity is recursive.
            for (EntityDef search = parent; search != null; search = search.getParent()) {
                if (search.getErEntityToken() == erEntityToken) {
                    search.recursiveChild = this;
                    this.recursive = true;
                    this.recursiveParent = search;

                    for (EntityDef child = search; child != null
                            && child.getDepth() > this.getDepth(); child = child.getNextHier()) {
                        child.recursivePath = true;
                    }

                    break;
                }
            }

            if (!recursive)
                throw new ZeidonException(
                        "Internal error: Recursive flag is set but no recursive parent found. %s", this);
        }
        break;

    case 'U':
        if (reader.getAttributeName().equals("UPDATE")) {
            update = reader.getAttributeValue().startsWith("Y");
        }
        break;
    }
}

From source file:com.meltmedia.cadmium.cli.UpdateCommand.java

/**
 * Validates the branch name that will be sent to the given prefix.
 * /*from   w w  w. ja va 2  s  . c  o  m*/
 * @param branch 
 * @param prefix
 * @return
 */
public static boolean isValidBranchName(String branch, String prefix) throws Exception {
    if (StringUtils.isNotBlank(prefix) && StringUtils.isNotBlank(branch)) {
        if (StringUtils.startsWithIgnoreCase(branch, prefix + "-")) {
            return true;
        } else {
            System.err.println("Branch name must start with prefix \"" + prefix + "-\".");
        }
    } else {
        return true;
    }
    return false;
}

From source file:net.java.jaspicoil.SimpleBasicServerAuthModule.java

/**
 * Authenticate a received service request.
 * <p/>/*  w w  w  .j a v a2  s .  c o  m*/
 * This method is called to transform the mechanism-specific request message
 * acquired by calling getRequestMessage (on messageInfo) into the validated
 * application message to be returned to the message processing runtime. If
 * the received message is a (mechanism-specific) meta-message, the method
 * implementation must attempt to transform the meta-message into a
 * corresponding mechanism-specific response message, or to the validated
 * application request message. The runtime will bind a validated
 * application message into the the corresponding service invocation.
 * <p>
 * This method conveys the outcome of its message processing either by
 * returning an AuthStatus value or by throwing an AuthException.
 * <p/>
 * From a performance point of view this method will be called twice for
 * each resource with a security constraint on it. Resources with no
 * security constraint do not result in a call to this method.
 * 
 * @param messageInfo
 *            A contextual object that encapsulates the client request and
 *            server response objects, and that may be used to save state
 *            across a sequence of calls made to the methods of this
 *            interface for the purpose of completing a secure message
 *            exchange.
 * @param clientSubject
 *            A Subject that represents the source of the service request.
 *            It is used by the method implementation to store Principals
 *            and credentials validated in the request.
 * @param serviceSubject
 *            A Subject that represents the recipient of the service
 *            request, or null. It may be used by the method implementation
 *            as the source of Principals or credentials to be used to
 *            validate the request. If the Subject is not null, the method
 *            implementation may add additional Principals or credentials
 *            (pertaining to the recipient of the service request) to the
 *            Subject.
 * @return An AuthStatus object representing the completion status of the
 *         processing performed by the method. The AuthStatus values that
 *         may be returned by this method are defined as follows:
 *         <p/>
 *         <ul>
 *         <li>AuthStatus.SUCCESS when the application request message was
 *         successfully validated. The validated request message is
 *         available by calling getRequestMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_SUCCESS to indicate that
 *         validation/processing of the request message successfully
 *         produced the secured application response message (in
 *         messageInfo). The secured response message is available by
 *         calling getResponseMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_CONTINUE to indicate that message validation
 *         is incomplete, and that a preliminary response was returned as
 *         the response message in messageInfo.
 *         <p/>
 *         When this status value is returned to challenge an application
 *         request message, the challenged request must be saved by the
 *         authentication module such that it can be recovered when the
 *         module's validateRequest message is called to process the request
 *         returned for the challenge.
 *         <p/>
 *         <li>AuthStatus.SEND_FAILURE to indicate that message validation
 *         failed and that an appropriate failure response message is
 *         available by calling getResponseMessage on messageInfo.
 *         </ul>
 * @throws AuthException When the message processing failed without
 *         establishing a failure response message (in messageInfo).
 */
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {
    // Get the servlet context
    final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    final HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
    final String auth = request.getHeader(AUTHORIZATION_HEADER);
    // Test prefix for HTTP BASIC Auth
    if (auth != null && StringUtils.startsWithIgnoreCase(auth, "basic ")) {
        // We might have a valid header, so try to decode it
        final String data = new String(Base64.decodeBase64(auth.substring(BASIC_PREFIX_LENGTH)), UTF_8);
        final int splitIndex = data.indexOf(':');
        if (splitIndex < 0) {
            return sendErrorAndAuthenticateRequest(request, response, "Wrong WWW-Authenticate header format");
        }
        final String username = data.substring(splitIndex);
        final char[] password = data.substring(splitIndex + 1, data.length()).toCharArray();

        // Prepare the JAAS callback to feed any LoginModule with user and password
        final NameCallback nameCallback = new NameCallback("username");
        nameCallback.setName(username);

        final PasswordCallback passwordCallback = new PasswordCallback(getRealm(request), false);
        passwordCallback.setPassword(password);

        final CallbackHandler delegatedHandler = new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    final Callback c = callbacks[i];
                    if (c instanceof NameCallback) {
                        ((NameCallback) c).setName(username);
                    } else if (c instanceof PasswordCallback) {
                        ((PasswordCallback) c).setPassword(password);
                    } else {
                        throw new UnsupportedOperationException(
                                String.format("Callback type %s (%s) is not supported yet.", c.getClass(), c));
                    }
                }
            }
        };

        if (this.jaasContextName == null) {
            throw new UnsupportedOperationException(
                    "No delegate JAAS context found. As per JASPIC JAAS Bridge profile, this parameter is requiered.");
        }

        try {
            // Create a new JAAS context with the delegated data & try to login
            final LoginContext context = new LoginContext(this.jaasContextName, delegatedHandler);
            context.login();

            // Get the authenticated subject from the JAAS context
            Subject authenticatedSubject = context.getSubject();

            final PasswordValidationCallback passwordValidationCallback = new PasswordValidationCallback(
                    authenticatedSubject, username, password);

            // notify JASPIC containerr for the name, password and subject
            this.handler.handle(new Callback[] { passwordValidationCallback });

        } catch (final LoginException ex) {
            // If there was any issue during the JAAS login, fail the process
            final AuthException aex = new AuthException(
                    String.format("Fail to login user %s with the delegated JAAS context %s", username,
                            this.jaasContextName));
            aex.initCause(ex);
        } catch (final IOException e) {
            LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e);
        } catch (final UnsupportedCallbackException e) {
            LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e);
        }

    } else if (this.mandatory) {
        return sendErrorAndAuthenticateRequest(request, response,
                "AuthModule was mandatory but no valid credential was provided");
    } else {
        LOG.info("No authentication was provided bu Basic AuthModule is not mandatory so return SUCCESS.");
    }

    return AuthStatus.SUCCESS;
}

From source file:eu.openanalytics.rsb.component.JobsResource.java

private Map<String, Serializable> getJobMeta(final HttpHeaders httpHeaders) {
    final Map<String, Serializable> meta = new HashMap<String, Serializable>();

    for (final Entry<String, List<String>> multiValues : httpHeaders.getRequestHeaders().entrySet()) {
        if (!StringUtils.startsWithIgnoreCase(multiValues.getKey(), Constants.RSB_META_HEADER_HTTP_PREFIX)) {
            continue;
        }//  w w  w.  j a  v a 2s . c  o  m

        if (multiValues.getValue().size() > 1) {
            throw new IllegalArgumentException("Multiple values found for header: " + multiValues.getKey());
        }

        meta.put(StringUtils.substring(multiValues.getKey(), Constants.RSB_META_HEADER_HTTP_PREFIX.length()),
                multiValues.getValue().get(0));
    }

    return Util.normalizeJobMeta(meta);
}

From source file:com.sonicle.webtop.core.app.ServiceDescriptor.java

public ArrayList<SqlUpgradeScript> getUpgradeScripts() {
    ArrayList<SqlUpgradeScript> scripts = new ArrayList<>();
    String resName = null;//w w  w  . j av a  2  s  .c  o  m

    try {
        String pkgPath = MessageFormat.format("{0}/meta/db/", LangUtils.packageToPath(manifest.getId()));
        ServiceVersion fileVersion = null;
        // List all .sql files in dedicated package and defines the right set
        for (String file : LangUtils.listPackageFiles(getClass(), pkgPath)) {
            try {
                if (StringUtils.startsWithIgnoreCase(file, "init"))
                    continue;
                fileVersion = SqlUpgradeScript.extractVersion(file);
                if (fileVersion.compareTo(manifest.getOldVersion()) <= 0)
                    continue; // Skip all version sections below oldVersion (included)
                if (fileVersion.compareTo(manifest.getVersion()) > 0)
                    continue; // Skip all version sections after manifestVersion

                resName = "/" + pkgPath + file;
                logger.debug("Reading upgrade script [{}]", resName);
                scripts.add(new SqlUpgradeScript(resName));

            } catch (IOException | UnsupportedOperationException ex1) {
                logger.warn(ex1.getMessage());
                //TODO: increment error counter...
            }
        }

        // Filename ordering may not be valid, so reorder the set
        // using the version information
        Collections.sort(scripts, new Comparator<SqlUpgradeScript>() {
            @Override
            public int compare(SqlUpgradeScript o1, SqlUpgradeScript o2) {
                return o1.getFileVersion().compareTo(o2.getFileVersion());
            }
        });

    } catch (Exception ex) {
        logger.error("Error loading upgrade scripts", ex);
    }
    //TODO: return also error counter...
    return scripts;
}

From source file:com.erudika.para.core.User.java

/**
 * Is the main identifier a Facebook id//from  w w w .  j av a  2 s .c o m
 * @return true if user is signed in with Facebook
 */
@JsonIgnore
public boolean isFacebookUser() {
    return StringUtils.startsWithIgnoreCase(identifier, Config.FB_PREFIX);
}

From source file:ch.cyberduck.core.s3.RequestEntityRestStorageService.java

@Override
protected boolean isXmlContentType(final String contentType) {
    if (null == contentType) {
        return false;
    }/*  ww  w.  ja  v a 2 s  . c  om*/
    if (StringUtils.startsWithIgnoreCase(contentType, "application/xml")) {
        return true;
    }
    if (StringUtils.startsWithIgnoreCase(contentType, "text/xml")) {
        return true;
    }
    return false;
}

From source file:architecture.ee.web.attachment.DefaultAttachmentManager.java

protected File getThumbnailFromCacheIfExist(Attachment attach, int width, int height) throws IOException {

    log.debug("thumbnail generation " + width + "x" + height);
    File dir = getAttachmentCacheDir();
    File file = new File(dir, toThumbnailFilename(attach, width, height));
    File originalFile = getAttachmentFromCacheIfExist(attach);
    log.debug("source: " + originalFile.getAbsoluteFile() + ", " + originalFile.length());
    log.debug("thumbnail:" + file.getAbsoluteFile());

    if (file.exists() && file.length() > 0) {
        attach.setThumbnailSize((int) file.length());
        return file;
    }//ww  w.  j a  v a  2  s .co m

    if (StringUtils.endsWithIgnoreCase(attach.getContentType(), "pdf")) {
        PDDocument document = PDDocument.load(originalFile);
        List<PDPage> pages = document.getDocumentCatalog().getAllPages();
        PDPage page = pages.get(0);
        BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 72);
        ImageIO.write(Thumbnails.of(image).size(width, height).asBufferedImage(), "png", file);
        attach.setThumbnailSize((int) file.length());
        return file;
    } else if (StringUtils.startsWithIgnoreCase(attach.getContentType(), "image")) {
        BufferedImage originalImage = ImageIO.read(originalFile);
        if (originalImage.getHeight() < height || originalImage.getWidth() < width) {
            attach.setThumbnailSize(0);
            return originalFile;
        }
        BufferedImage thumbnail = Thumbnails.of(originalImage).size(width, height).asBufferedImage();
        ImageIO.write(thumbnail, "png", file);
        attach.setThumbnailSize((int) file.length());
        return file;
    }

    return null;
}

From source file:com.erudika.para.core.User.java

/**
 * Is the main identifier a Google+ id//from w  w w.j  a  va 2s.  co m
 * @return true if user is signed in with Google+
 */
@JsonIgnore
public boolean isGooglePlusUser() {
    return StringUtils.startsWithIgnoreCase(identifier, Config.GPLUS_PREFIX);
}

From source file:com.erudika.para.core.User.java

/**
 * Is the main identifier a LinkedIn id/*from  www  . java2  s. c  o  m*/
 * @return true if user is signed in with LinkedIn
 */
@JsonIgnore
public boolean isLinkedInUser() {
    return StringUtils.startsWithIgnoreCase(identifier, Config.LINKEDIN_PREFIX);
}