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

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

Introduction

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

Prototype

public static boolean isAlphanumeric(String str) 

Source Link

Document

Checks if the String contains only unicode letters or digits.

Usage

From source file:net.malariagen.gatk.test.WalkerTest.java

private void qcMD5s(String name, List<String> md5s) {
    final String exampleMD5 = "709a1f482cce68992c637da3cff824a8";
    for (String md5 : md5s) {
        if (md5 == null)
            throw new IllegalArgumentException("Null MD5 found in test " + name);
        if (md5.equals("")) // ok
            continue;
        if (!StringUtils.isAlphanumeric(md5))
            throw new IllegalArgumentException(
                    "MD5 contains non-alphanumeric characters test " + name + " md5=" + md5);
        if (md5.length() != exampleMD5.length())
            throw new IllegalArgumentException(
                    "Non-empty MD5 of unexpected number of characters test " + name + " md5=" + md5);
    }//from   ww w  .  ja v  a  2  s .co  m
}

From source file:com.laex.cg2d.screeneditor.handlers.ImportScreenContentsDialog.java

/**
 * Validate suffix.//ww  w . j  av  a  2s  .  c  o  m
 */
private void validateSuffix() {
    boolean isAlphaNumeric = StringUtils.isAlphanumeric(txtSuffix.getText());
    boolean isEmpty = StringUtils.isEmpty(txtSuffix.getText());

    if (isEmpty) {
        getButton(OK).setEnabled(false);
        setErrorMessage("Please provide a suffix");
        return;
    }

    // validate suffix
    // for the suffix to be valid
    if (!isAlphaNumeric || isEmpty) {
        getButton(OK).setEnabled(false);
        setErrorMessage("Suffix should be alphanumeric");
        return;
    }

    getButton(OK).setEnabled(true);
    setErrorMessage(null);
}

From source file:ezbake.deployer.EzBakeDeployerHandler.java

@Override
public void stageServiceDeployment(ArtifactManifest manifest, ByteBuffer artifact, EzSecurityToken token)
        throws TException {
    checkSecurityToken(token);/*  w w w  . j  a  v  a 2  s. co m*/
    log.info("Artifact " + getFqAppId(manifest) + " requested to be staged for deployment.");
    if (!StringUtils.isAlphanumeric(getServiceId(manifest))) {
        log.error("ServiceId must be alphanumeric: " + getServiceId(manifest));
        throw new DeploymentException("Service ids must be alphanumeric");
    }
    DeploymentMetadata oldVersion = null;
    try {
        oldVersion = ezDeployerStore.getLatestApplicationMetaDataFromStore(getAppId(manifest),
                getServiceId(manifest));
    } catch (DeploymentException e) {
        //it's okay if it doesn't already exist
    }
    if (oldVersion != null) {
        switch (oldVersion.getStatus()) {
        case Denied:
        case Undeployed:
        case Staged:
            //In these cases, the user is replacing the artifact, so go ahead and remove the old data
            ezDeployerStore.removeFromStore(oldVersion);
            break;
        default:
            break;
        }
    }
    ezDeployerStore.writeArtifactToStore(manifest, artifact, DeploymentStatus.Staged);
}

From source file:com.manydesigns.portofino.model.database.DatabaseLogic.java

static String checkOtherLetters(String letter) {
    letter = StringUtils.replaceChars(letter, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz");
    if (letter.equals("_") || letter.equals("$") || StringUtils.isAlphanumeric(letter)) {
        return letter;
    } else {/*from  ww w  .jav a  2s.  c o m*/
        return "_";
    }
}

From source file:eu.eidas.util.Preconditions.java

/**
 * Checks if the reference contains only Unicode letters or digits.
 * <p/>//  ww  w  .  ja  va2 s .  co  m
 * {@code null} will throw an {@code IllegalArgumentException}. An empty reference ({@code length()=0} ) will throw
 * an {@code IllegalArgumentException}.
 * <p/>
 * <pre>
 * Preconditions.isAlphanumeric(null)   = IllegalArgumentException
 * Preconditions.isAlphanumeric("")     = IllegalArgumentException
 * Preconditions.isAlphanumeric("  ")   = IllegalArgumentException
 * Preconditions.isAlphanumeric("abc")  = true
 * Preconditions.isAlphanumeric("ab c") = IllegalArgumentException
 * Preconditions.isAlphanumeric("ab2c") = true
 * Preconditions.isAlphanumeric("ab-c") = IllegalArgumentException
 * </pre>
 *
 * @param reference the value to check
 * @param referenceName the variable name which will appear in the exception message
 * @return the given {@code reference} when valid otherwise throws an IllegalArgumentException.
 * @throws IllegalArgumentException if {@code reference} contains non alphanumeric characters.
 */
public static String isAlphanumeric(@Nullable String reference, @Nonnull String referenceName)
        throws IllegalArgumentException {
    if (null == reference || reference.length() == 0 || !StringUtils.isAlphanumeric(reference)) {
        throw new IllegalArgumentException(referenceName + " is null or contains non alphanumeric characters");
    }
    return reference;
}

From source file:fr.treeptik.cloudunit.service.impl.ApplicationServiceImpl.java

@Override
@Transactional/*from w  ww .j  a  va2  s .  c om*/
public void addNewAlias(Application application, String alias) throws ServiceException, CheckException {

    logger.info("ALIAS VALUE IN addNewAlias : " + alias);

    if (checkAliasIfExists(alias)) {
        throw new CheckException(
                "This alias is already used by another application on this CloudUnit instance");
    }

    alias = alias.toLowerCase();
    if (alias.startsWith("https://") || alias.startsWith("http://") || alias.startsWith("ftp://")) {
        alias = alias.substring(alias.lastIndexOf("//") + 2, alias.length());
    }

    if (!StringUtils.isAlphanumeric(alias)) {
        throw new CheckException("This alias must be alphanumeric. Please remove all other characters");
    }

    try {
        Server server = application.getServers().get(0);
        application.getAliases().add(alias);
        hipacheRedisUtils.writeNewAlias(alias, application, server.getServerAction().getServerPort());
        applicationDAO.save(application);

    } catch (DataAccessException e) {
        throw new ServiceException(e.getLocalizedMessage(), e);
    }
}

From source file:com.att.aro.ui.view.menu.tools.RegexWizard.java

private String formatSpecialCharacters(String text) {
    boolean hasSpecialChars = !StringUtils.isAlphanumeric(text);
    StringBuffer sb = new StringBuffer();
    if (hasSpecialChars) {
        Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
        for (int i = 0; i < text.length(); i++) {
            Matcher match = pattern.matcher(text.substring(i, i + 1));
            if (match.find()) { // is a special character
                sb.append("\\" + text.charAt(i));
            } else {
                sb.append(text.charAt(i));
            }/*from  ww w .  j av  a2  s  .c o m*/
        }
        return sb.toString();
    } else {
        return text;
    }
}

From source file:metabest.transformations.MetaModel2Use.java

private String getNameSwitch(String name) {
    if (isReserved(name)) {
        String fixedName = name + "_RESERVEDWORD";
        nameSwitch.put(name, fixedName);
        return fixedName;
    }//  w w  w. j a  v a 2s.c  o  m

    if (!StringUtils.isAlphanumeric(name)) {
        //if(name.equals("Co-author")) System.out.println("entering");
        String fixedName = name;

        for (char c : name.toCharArray())
            if (!Character.isLetterOrDigit(c) && c != '_') {
                //if(name.equals("Co-author")) System.out.println("true");
                fixedName = fixedName.replaceAll(String.valueOf(c), "_NONALPHANUMERICCHAR_");
            }

        //if(name.equals("Co-author")) System.out.println("here: " + fixedName);

        nameSwitch.put(name, fixedName);
        return fixedName;

    }

    nameSwitch.put(name, name);
    return name;
}

From source file:edu.ku.brc.specify.Specify.java

/**
 * Restarts the app with a new or old database and user name and creates the core app UI.
 * @param window the login window//from  w w w. j  a  v  a 2 s  .co  m
 * @param databaseNameArg the database name
 * @param userNameArg the user name
 * @param startOver tells the AppContext to start over
 * @param firstTime indicates this is the first time in the app and it should create all the UI for the core app
 */
public void restartApp(final Window window, final String databaseNameArg, final String userNameArg,
        final boolean startOver, final boolean firstTime) {
    log.debug("restartApp"); //$NON-NLS-1$
    if (dbLoginPanel != null) {
        dbLoginPanel.getStatusBar().setText(getResourceString("Specify.INITIALIZING_APP")); //$NON-NLS-1$
    }

    if (!firstTime) {
        checkAndSendStats();
    }

    UIRegistry.dumpPaths();

    try {
        AppPreferences.getLocalPrefs().flush();
    } catch (BackingStoreException ex) {
    }

    AppPreferences.shutdownRemotePrefs();
    AppPreferences.shutdownPrefs();
    AppPreferences.setConnectedToDB(false);

    // Moved here because context needs to be set before loading prefs, we need to know the SpecifyUser
    //
    // NOTE: AppPreferences.startup(); is called inside setContext's implementation.
    //
    AppContextMgr.reset();
    AppContextMgr.CONTEXT_STATUS status = AppContextMgr.getInstance().setContext(databaseNameArg, userNameArg,
            startOver, firstTime, !firstTime);
    if (status == AppContextMgr.CONTEXT_STATUS.OK) {
        // XXX Temporary Fix!
        SpecifyUser spUser = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);

        if (spUser != null) {
            String dbPassword = spUser.getPassword();

            if (StringUtils.isNotEmpty(dbPassword) && (!StringUtils.isAlphanumeric(dbPassword)
                    || !UIHelper.isAllCaps(dbPassword) || dbPassword.length() < 25)) {
                String encryptedPassword = Encryption.encrypt(spUser.getPassword(), spUser.getPassword());
                spUser.setPassword(encryptedPassword);
                DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
                try {
                    session.beginTransaction();
                    session.saveOrUpdate(session.merge(spUser));
                    session.commit();

                } catch (Exception ex) {
                    session.rollback();
                    ex.printStackTrace();
                } finally {
                    session.close();
                }
            }
        }
    }

    UsageTracker.setUserInfo(databaseNameArg, userNameArg);

    SpecifyAppPrefs.initialPrefs();

    // Check Stats (this is mostly for the first time in.
    AppPreferences appPrefs = AppPreferences.getRemote();
    Boolean canSendStats = appPrefs.getBoolean(sendStatsPrefName, null); //$NON-NLS-1$
    Boolean canSendISAStats = appPrefs.getBoolean(sendISAStatsPrefName, null); //$NON-NLS-1$

    // Make sure we have the proper defaults
    if (canSendStats == null) {
        canSendStats = true;
        appPrefs.putBoolean("usage_tracking.send_stats", canSendStats); //$NON-NLS-1$
    }

    if (canSendISAStats == null) {
        canSendISAStats = true;
        appPrefs.putBoolean(sendISAStatsPrefName, canSendISAStats); //$NON-NLS-1$
    }

    if (status == AppContextMgr.CONTEXT_STATUS.OK) {
        // XXX Get the current locale from prefs PREF

        if (AppContextMgr.getInstance().getClassObject(Discipline.class) == null) {
            return;
        }

        // "false" means that it should use any cached values it can find to automatically initialize itself
        if (firstTime) {
            GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment()
                    .getDefaultScreenDevice().getDefaultConfiguration();

            initialize(gc);

            topFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
            UIRegistry.register(UIRegistry.FRAME, topFrame);
        } else {
            SubPaneMgr.getInstance().closeAll();
        }

        preInitializePrefs();

        initStartUpPanels(databaseNameArg, userNameArg);

        AppPrefsCache.addChangeListener("ui.formatting.scrdateformat", UIFieldFormatterMgr.getInstance());

        if (changeCollectionMenuItem != null) {
            changeCollectionMenuItem.setEnabled(
                    ((SpecifyAppContextMgr) AppContextMgr.getInstance()).getNumOfCollectionsForUser() > 1);
        }

        if (window != null) {
            window.setVisible(false);
        }

        // General DB Fixes independent of a release.
        if (!AppPreferences.getGlobalPrefs().getBoolean("CollectingEventsAndAttrsMaint1", false)) {
            // Temp Code to Fix issues with Release 6.0.9 and below
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    CollectingEventsAndAttrsMaint dbMaint = new CollectingEventsAndAttrsMaint();
                    dbMaint.performMaint();
                }
            });
        }

        /*if (!AppPreferences.getGlobalPrefs().getBoolean("FixAgentToDisciplinesV2", false))
        {
        // Temp Code to Fix issues with Release 6.0.9 and below
        SwingUtilities.invokeLater(new Runnable() 
        {
            @Override
            public void run()
            {
                FixDBAfterLogin fixer = new FixDBAfterLogin();
                fixer.fixAgentToDisciplines();
            }
        });
        }*/

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                performManualDBUdpatesAfterLogin();
            }
        });

        DataBuilder.mergeStandardGroups(AppContextMgr.getInstance().getClassObject(Collection.class));

    } else if (status == AppContextMgr.CONTEXT_STATUS.Error) {

        if (dbLoginPanel != null) {
            dbLoginPanel.getWindow().setVisible(false);
        }

        if (AppContextMgr.getInstance().getClassObject(Collection.class) == null) {

            // TODO This is really bad because there is a Database Login with no Specify login
            JOptionPane.showMessageDialog(null, getResourceString("Specify.LOGIN_USER_MISMATCH"), //$NON-NLS-1$
                    getResourceString("Specify.LOGIN_USER_MISMATCH_TITLE"), //$NON-NLS-1$
                    JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }

    }

    CommandDispatcher.dispatch(new CommandAction("App", firstTime ? "StartUp" : "AppRestart", null)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    TaskMgr.requestInitalContext();

    if (!UIRegistry.isRelease()) {
        DebugLoggerDialog dialog = new DebugLoggerDialog(null);
        dialog.configureLoggers();
    }

    showApp();

    if (dbLoginPanel != null) {
        dbLoginPanel.getWindow().setVisible(false);
        dbLoginPanel = null;
    }
    setDatabaseNameAndCollection();
}

From source file:gov.nih.nci.evs.browser.utils.DataUtils.java

public static String encodeTerm(String s) {
    if (s == null)
        return null;
    if (StringUtils.isAlphanumeric(s))
        return s;

    StringBuilder buf = new StringBuilder(s.length());
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (Character.isLetterOrDigit(c)) {
            buf.append(c);/*from w  w  w  .j a v a  2s. c o  m*/
        } else {
            buf.append("&#").append((int) c).append(";");
        }
    }
    return buf.toString();
}