Example usage for java.util.regex Pattern matches

List of usage examples for java.util.regex Pattern matches

Introduction

In this page you can find the example usage for java.util.regex Pattern matches.

Prototype

public static boolean matches(String regex, CharSequence input) 

Source Link

Document

Compiles the given regular expression and attempts to match the given input against it.

Usage

From source file:com.gote.downloader.kgs.KGSDownloader.java

/**
 * Try to found out if a game has been already played or by looking into archives page by page.
 * //  w  w w. j a v a 2  s  .com
 * @param pGame Game to found and update
 * @param pPlayerArchivePages List of archive pages
 */
private void retrieveAndUpdateGame(Game pGame, List<Document> pPlayerArchivePages) {
    stage = "Etape 3/3 - Rcupration de la partie";
    for (Document playerArchivePage : pPlayerArchivePages) {
        Elements tableRows = playerArchivePage.select("tr");

        for (Element row : tableRows) {
            if (Pattern.matches(regexGame, row.toString())) {
                // LOGGER.log(Level.INFO, "[TRACE] New row checked " + row.toString());

                // "Visible", "Blanc", "Noir", "Genre", "Debutee le", "Type", "Resultat"
                Elements tableCells = row.getElementsByTag("td");

                String gameUrl = isPublicGame(tableCells.get(GAMEURL));

                // May check with time if you can leave or continue
                if (gameUrl != null && !gameUrl.isEmpty()) {
                    if (gameUrl.toLowerCase().contains(pGame.getBlack().getPseudo().toLowerCase())
                            && gameUrl.toLowerCase().contains(pGame.getWhite().getPseudo().toLowerCase())) {
                        pGame.setGameUrl(gameUrl);
                        pGame.setResult(getStdResultFromKGSResult(tableCells.get(RESULT).text()));
                        File sgf = new File(AppUtil.PATH_TO_TOURNAMENTS + tournament.getTitle() + "/"
                                + AppUtil.PATH_TO_SGFS + tournament.getTitle().trim() + "_round"
                                + pGame.getBlack().getPseudo() + "_" + pGame.getWhite().getPseudo() + ".sgf");
                        try {
                            URL url = new URL(gameUrl);
                            FileUtils.copyURLToFile(url, sgf);
                        } catch (MalformedURLException e) {
                            log(Level.WARNING, "URL " + gameUrl + " malformee", e);
                        } catch (IOException e) {
                            log(Level.WARNING, "Erreur lors de l'ecriture du fichier", e);
                        }

                        // Leave the process
                        return;
                    }
                } else {
                    log(Level.INFO, "La partie " + tableCells
                            + " n'est pas visible ou un probleme a eu lieu lors de la recuperation de l'url");
                }
            }
        }
    }
}

From source file:fr.univlorraine.mondossierweb.controllers.AdresseController.java

public List<String> majAdresses(Adresse adresseAnnuelle, Adresse adresseFixe) {
    List<String> retour = new LinkedList<String>();

    //1-vrification des parametres
    boolean erreur = false;
    boolean succes = false;
    boolean adresseIdentique = false;
    boolean boolAnEtranger = false;
    boolean boolFixeEtranger = false;
    String message = "";
    if (adresseAnnuelle.getType() == null || adresseAnnuelle.getType().equals("")) {
        message = applicationContext.getMessage("modificationAdressesWindow.erreur.an.hebergement", null,
                Locale.getDefault());
        retour.add(message);/*from www .j  av a  2 s  . c o m*/
        erreur = true;
    } else {
        adresseIdentique = adresseAnnuelle.getType().equals(COD_HEBERG_DOMICILE_PARENTAL);
    }
    boolAnEtranger = !adresseAnnuelle.getCodPays().equals(COD_PAY_FRANCE);
    boolFixeEtranger = !adresseFixe.getCodPays().equals(COD_PAY_FRANCE);

    if (!adresseIdentique) {
        if (!StringUtils.hasText(adresseAnnuelle.getAdresse1())) {
            message = applicationContext.getMessage("modificationAdressesWindow.erreur.an.detail", null,
                    Locale.getDefault());
            retour.add(message);
            erreur = true;
        }
        if (!StringUtils.hasText(adresseAnnuelle.getCodePostal()) && !boolAnEtranger) {
            message = applicationContext.getMessage("modificationAdressesWindow.erreur.an.codepostal", null,
                    Locale.getDefault());
            retour.add(message);
            erreur = true;
        }
        if (!StringUtils.hasText(adresseAnnuelle.getVille()) && !boolAnEtranger) {
            message = applicationContext.getMessage("modificationAdressesWindow.erreur.an.ville", null,
                    Locale.getDefault());
            retour.add(message);
            erreur = true;
        }
        if (!StringUtils.hasText(adresseAnnuelle.getCodPays())) {
            message = applicationContext.getMessage("modificationAdressesWindow.erreur.an.pays", null,
                    Locale.getDefault());
            retour.add(message);
            erreur = true;
        }
        if (adresseAnnuelle.getNumerotel() != null
                && (!Pattern.matches("[0-9[.]]*", adresseAnnuelle.getNumerotel().replaceAll(" ", "")))) {
            message = applicationContext.getMessage("modificationAdressesWindow.erreur.an.telephone", null,
                    Locale.getDefault());
            retour.add(message);
            erreur = true;
        }
        if (!StringUtils.hasText(adresseAnnuelle.getAdresseetranger()) && boolAnEtranger) {
            message = applicationContext.getMessage("modificationAdressesWindow.erreur.an.villeetrangere", null,
                    Locale.getDefault());
            retour.add(message);
            erreur = true;
        }

    }

    if (!StringUtils.hasText(adresseFixe.getAdresse1())) {
        message = applicationContext.getMessage("modificationAdressesWindow.erreur.af.detail", null,
                Locale.getDefault());
        retour.add(message);
        erreur = true;
    }
    if (!StringUtils.hasText(adresseFixe.getCodePostal()) && !boolFixeEtranger) {
        message = applicationContext.getMessage("modificationAdressesWindow.erreur.af.codepostal", null,
                Locale.getDefault());
        retour.add(message);
        erreur = true;
    }
    if (!StringUtils.hasText(adresseFixe.getVille()) && !boolFixeEtranger) {
        message = applicationContext.getMessage("modificationAdressesWindow.erreur.af.ville", null,
                Locale.getDefault());
        retour.add(message);
        erreur = true;
    }
    if (!StringUtils.hasText(adresseFixe.getCodPays())) {
        message = applicationContext.getMessage("modificationAdressesWindow.erreur.af.pays", null,
                Locale.getDefault());
        retour.add(message);
        erreur = true;
    }
    if (adresseFixe.getNumerotel() != null
            && (!Pattern.matches("[0-9[.]]*", adresseFixe.getNumerotel().replaceAll(" ", "")))) {
        message = applicationContext.getMessage("modificationAdressesWindow.erreur.af.telephone", null,
                Locale.getDefault());
        retour.add(message);
        erreur = true;
    }
    if (!StringUtils.hasText(adresseFixe.getAdresseetranger()) && boolFixeEtranger) {
        message = applicationContext.getMessage("modificationAdressesWindow.erreur.af.villeetrangere", null,
                Locale.getDefault());
        retour.add(message);
        erreur = true;
    }

    //2-maj les attribut utiles au changement d'adresse du bean etudiant
    if (!erreur) {

        //Si les deux adresses sont identiques
        if (adresseIdentique) {
            //on rapatrie le type d'hebergement dans adresse fixe
            adresseFixe.setType(adresseAnnuelle.getType());
            //on fait la maj dans apogee en utilisant l'adresse fixe
            succes = majAdressesApogee(adresseFixe, adresseFixe,
                    MainUI.getCurrent().getEtudiant().getCod_etu());
        } else {
            //on fait la maj dans apogee en utilisant l'adresse fixe et l'adresse annuelle
            succes = majAdressesApogee(adresseAnnuelle, adresseFixe,
                    MainUI.getCurrent().getEtudiant().getCod_etu());
        }

        if (!succes) {
            message = applicationContext.getMessage("modificationAdressesWindow.erreur.ws", null,
                    Locale.getDefault());
            retour.add(message);
        } else {
            retour.add("OK");
        }

    }

    return retour;
}

From source file:fr.paris.lutece.plugins.mylutece.modules.wssodatabase.authentication.service.ImportWssoDatabaseUserService.java

/**
 * {@inheritDoc}/* w ww  .  j a  va  2s. c o  m*/
 */
@Override
protected List<CSVMessageDescriptor> readLineOfCSVFile(String[] strLineDataArray, int nLineNumber,
        Locale locale, String strBaseUrl) {
    Plugin databasePlugin = PluginService.getPlugin(WssoDatabasePlugin.PLUGIN_NAME);
    List<CSVMessageDescriptor> listMessages = new ArrayList<CSVMessageDescriptor>();
    int nIndex = 0;

    String strGuid = strLineDataArray[nIndex++];

    if (StringUtils.isBlank(strGuid)) {
        String strErrorMessage = I18nService.getLocalizedString(MESSAGE_GUID_EMPTY, null, locale);
        CSVMessageDescriptor error = new CSVMessageDescriptor(CSVMessageLevel.ERROR, nLineNumber,
                strErrorMessage);
        listMessages.add(error);
    }

    String strLastName = strLineDataArray[nIndex++];

    if (StringUtils.isBlank(strLastName)) {
        String strErrorMessage = I18nService.getLocalizedString(MESSAGE_LAST_NAME_EMPTY, null, locale);
        CSVMessageDescriptor error = new CSVMessageDescriptor(CSVMessageLevel.ERROR, nLineNumber,
                strErrorMessage);
        listMessages.add(error);
    }

    String strFirstName = strLineDataArray[nIndex++];

    if (StringUtils.isBlank(strFirstName)) {
        String strErrorMessage = I18nService.getLocalizedString(MESSAGE_FIRST_NAME_EMPTY, null, locale);
        CSVMessageDescriptor error = new CSVMessageDescriptor(CSVMessageLevel.ERROR, nLineNumber,
                strErrorMessage);
        listMessages.add(error);
    }

    String strEmail = strLineDataArray[nIndex++];

    if (StringUtils.isBlank(strEmail)) {
        String strErrorMessage = I18nService.getLocalizedString(MESSAGE_EMAIL_EMPTY, null, locale);
        CSVMessageDescriptor error = new CSVMessageDescriptor(CSVMessageLevel.ERROR, nLineNumber,
                strErrorMessage);
        listMessages.add(error);
    } else {
        if (!Pattern.matches(CONSTANT_EMAIL, strEmail)) {
            String strErrorMessage = I18nService.getLocalizedString(MESSAGE_EMAIL_INVALID, null, locale);
            CSVMessageDescriptor error = new CSVMessageDescriptor(CSVMessageLevel.ERROR, nLineNumber,
                    strErrorMessage);
            listMessages.add(error);
        }
    }

    if (CollectionUtils.isNotEmpty(listMessages)) {
        return listMessages;
    }

    boolean bUpdateUser = getUpdateExistingUsers();
    int nUserId = 0;

    if (bUpdateUser) {
        int nAccessCodeUserId = WssoUserHome.findDatabaseUserIdFromGuid(strGuid, databasePlugin);

        if (nAccessCodeUserId > 0) {
            nUserId = nAccessCodeUserId;
        }

        bUpdateUser = nUserId > 0;
    }

    WssoUser wssoUser = new WssoUser();

    wssoUser.setGuid(strGuid);
    wssoUser.setLastName(strLastName);
    wssoUser.setFirstName(strFirstName);
    wssoUser.setEmail(strEmail);

    if (bUpdateUser) {
        wssoUser.setMyluteceWssoUserId(nUserId);
        // We update the user
        WssoUserHome.update(wssoUser, databasePlugin);
    } else {
        // We create the user
        WssoUserHome.create(wssoUser, databasePlugin);
        notifyUserAccountCreated(wssoUser, locale, AppPathService.getProdUrl(strBaseUrl));
    }

    // We remove old roles, groups and attributes of the user
    WssoUserRoleHome.deleteRolesForUser(wssoUser.getMyluteceWssoUserId(), databasePlugin);
    //        DatabaseHome.removeGroupsForUser( user.getUserId( ), databasePlugin );
    IdxWSSODatabaseHome.removeProfilsForUser(wssoUser.getMyluteceWssoUserId(), databasePlugin);
    MyLuteceUserFieldService.doRemoveUserFields(wssoUser.getMyluteceWssoUserId(), locale);

    // We get every attributes, roles and groups of the user
    List<String> listRoles = new ArrayList<String>();

    //        List<String> listGroups = new ArrayList<String>( );
    List<String> listProfils = new ArrayList<String>();

    while (nIndex < strLineDataArray.length) {
        String strValue = strLineDataArray[nIndex];

        if (StringUtils.isNotBlank(strValue) && (strValue.indexOf(getAttributesSeparator()) > 0)) {
            int nSeparatorIndex = strValue.indexOf(getAttributesSeparator());
            String strLineId = strValue.substring(0, nSeparatorIndex);

            if (StringUtils.isNotBlank(strLineId)) {
                if (StringUtils.equalsIgnoreCase(strLineId, CONSTANT_ROLE)) {
                    String strRole = strValue.substring(nSeparatorIndex + 1);
                    Role role = RoleHome.findByPrimaryKey(strRole);

                    if (role == null) {
                        Object[] args = { strRole };
                        String strErrorMessage = I18nService.getLocalizedString(MESSAGE_ROLE_UNKNOWN, args,
                                locale);
                        CSVMessageDescriptor error = new CSVMessageDescriptor(CSVMessageLevel.ERROR,
                                nLineNumber, strErrorMessage);
                        listMessages.add(error);
                    } else {
                        listRoles.add(strRole);
                    }
                }

                //                    else if ( StringUtils.equalsIgnoreCase( strLineId, CONSTANT_GROUP ) )
                //                    {
                //                       String strGroup = strValue.substring( nSeparatorIndex + 1 );
                //                       Group group = GroupHome.findByPrimaryKey(strGroup);
                //                       if(group == null) {
                //                           Object[] args = { strGroup };
                //                            String strErrorMessage = I18nService.getLocalizedString( MESSAGE_GROUP_UNKNOWN, args, locale );
                //                            CSVMessageDescriptor error = new CSVMessageDescriptor( CSVMessageLevel.ERROR, nLineNumber, strErrorMessage );
                //                            listMessages.add( error );
                //                       }
                //                       else{
                //                          listGroups.add( strGroup );
                //                       }
                //                    }
                else {
                    String strProfil = strValue.substring(nSeparatorIndex + 1);
                    WssoProfil profil = WssoProfilHome.findWssoProfilByCode(strProfil, databasePlugin);

                    if (profil == null) {
                        Object[] args = { strProfil };
                        String strErrorMessage = I18nService.getLocalizedString(MESSAGE_PROFIL_UNKNOWN, args,
                                locale);
                        CSVMessageDescriptor error = new CSVMessageDescriptor(CSVMessageLevel.ERROR,
                                nLineNumber, strErrorMessage);
                        listMessages.add(error);
                    } else {
                        listProfils.add(strProfil);
                    }
                }
            }
        }

        nIndex++;
    }

    // We create roles
    if (CollectionUtils.isNotEmpty(listRoles)) {
        for (String strRole : listRoles) {
            WssoUserRoleHome.createRoleForUser(wssoUser.getMyluteceWssoUserId(), strRole, databasePlugin);
        }
    }

    // We create groups
    //        for ( String strGoup : listGroups )
    //        {
    //            DatabaseHome.addGroupForUser( user.getUserId( ), strGoup, databasePlugin );
    //        }
    if (CollectionUtils.isNotEmpty(listProfils)) {
        for (String profil : listProfils) {
            IdxWSSODatabaseHome.addUserForProfil(wssoUser.getMyluteceWssoUserId(), profil, databasePlugin);
        }
    }

    return listMessages;
}

From source file:es.juntadeandalucia.panelGestion.negocio.vo.TaskVO.java

public void preareFileColumns() throws PanelException {
    fileColumns = new LinkedList<ColumnVO>();
    if (taskEntity.isUpdate()) {
        for (ColumnVO column : tableColumns) {
            if ((column.getFilePosition() >= 0) || column.isFromCoordinates()) {
                fileColumns.add(column);
            }// w w w. j  a v  a2  s .  co m
        }
    } else {
        for (ColumnVO column : columns) {
            if (column.isInTable()) {
                // checks valid column name
                String columnNameOnTable = column.getNameOnTable();
                if (StringUtils.isEmpty(columnNameOnTable)) {
                    columnNameOnTable = column.getText();
                }
                if (StringUtils.isEmpty(columnNameOnTable)) {
                    throw new PanelException("nombre de columna vaco");
                } else if (!Utils.isValidName(columnNameOnTable)) {
                    throw new PanelException("nombre de columna invlido: " + columnNameOnTable);
                }

                String dbType = column.getType();
                Integer sqlType = PanelSettings.dataBaseTypes.get(dbType);
                if (sqlType == Types.OTHER) { // geometry type
                    if (Pattern.compile(".*\\s*(X|lat)\\s*.*", Pattern.CASE_INSENSITIVE).matcher(dbType)
                            .matches()) {
                        column.setCoordinateX(true);
                    } else if (!Pattern.matches("geometry", dbType.toLowerCase())
                            && Pattern.compile(".*\\s*(Y|lon)\\s*.*", Pattern.CASE_INSENSITIVE).matcher(dbType)
                                    .matches()) {
                        column.setCoordinateY(true);
                    } else {
                        getTaskEntity().getTable().setGeomField(column.getNameOnTable());
                    }
                }
                column.setSqlType(sqlType);
                fileColumns.add(column);
            }
        }
    }
}

From source file:dhbw.ka.mwi.businesshorizon2.ui.login.LogInScreenPresenter.java

/**
 * Prueft ob es sich um einen gltigen Vorname handelt. Gibt "true" fuer
 * gltig und "false" fuer nicht gltig zurueck. Ein Vorname muss mit einem
 * Grobuchstaben beginnen und darf maximal 20 Zeichen lang sein. Beginnt er nicht mit einem Grobuchstabe,
 * wird der erste Buchstabe automatisch in einen Grobuchstabe konvertiert. Weiterhin
 * ist ein Bindestrich "-" erlaubt. Bei keiner Uebereinstimmung wird zudem
 * eine Fehlermeldung an die ViewImpl zur Ausgabe zurueckgegeben.
 * //from   w  w w  . j a v a  2s  . c o m
 * @author Marcel Rosenberger, Annika Weis, Marco Glaser
 * @return Ob es sich um einen gltigen Vornamen handelt.
 */
private boolean validateFirstName() {
    boolean validFirstName;

    // hier wird der Vorname berprft
    if (Pattern.matches("^[A-Z][a-zA-Z\\ \\-]{1,19}$", firstName)) {
        validFirstName = true;
        logger.debug("Vorname gltig.");
    } else if (Pattern.matches("^[a-zA-Z\\ \\-]{1,19}$", firstName)) {
        validFirstName = true;
        char firstLetter = firstName.charAt(0);
        firstLetter = Character.toUpperCase(firstLetter);
        String upperCaseName = firstLetter + firstName.substring(1);
        this.firstName = upperCaseName;
    } else {
        validFirstName = false;
        getView().showErrorMessage("Bitte geben Sie einen gltigen Vornamen ein.");
        logger.debug("Vorname ungltig.");
    }

    return validFirstName;
}

From source file:com.baidu.rigel.biplatform.parser.CompileSection.java

private Node resolveToken(String token) {
    if (StringUtils.isNotBlank(token)) {
        // 1.???2???
        // 2.//from www  .j  av a 2s .c om
        if (token.startsWith(CompileExpression.SECTION_PRE)) {
            return resolveNodes.get(token);
        } else if (Pattern.matches(ParserConstant.VARIABLE_PATTERN_STR, token)) {
            // token????
            return new VariableNode(token);
        } else if (Pattern.matches(ParserConstant.NUMBER_PATTERN_STR, token)) {
            return new DataNode(new BigDecimal(token));
        } else {
            throw new IllegalTokenException(token, "CAN NOT RECONIZE TOKEN:" + token);
        }
    } else {
        throw new IllegalTokenException(token, "NULL TOKEN");
    }

}

From source file:net.sf.taverna.t2.activities.beanshell.BeanshellActivity.java

@Override
public void executeAsynch(final Map<String, T2Reference> data, final AsynchronousActivityCallback callback) {
    callback.requestRun(new Runnable() {

        public void run() {

            // Workflow run identifier (needed when classloader sharing is
            // set to 'workflow').
            String procID = callback.getParentProcessIdentifier();
            String workflowRunID;
            if (procID.contains(":")) {
                workflowRunID = procID.substring(0, procID.indexOf(':'));
            } else {
                workflowRunID = procID; // for tests, will be an empty
                // string
            }//w  ww  .j a va  2s .c  o m

            synchronized (interpreter) {

                // Configure the classloader for executing the Beanshell
                if (classLoader == null) {
                    try {
                        classLoader = findClassLoader(json, workflowRunID);
                        interpreter.setClassLoader(classLoader);
                    } catch (RuntimeException rex) {
                        String message = "Unable to obtain the classloader for Beanshell service";
                        callback.fail(message, rex);
                        return;
                    }
                }

                ReferenceService referenceService = callback.getContext().getReferenceService();

                Map<String, T2Reference> outputData = new HashMap<String, T2Reference>();

                clearInterpreter();
                try {
                    // set inputs
                    for (String inputName : data.keySet()) {
                        ActivityInputPort inputPort = getInputPort(inputName);
                        Object input = referenceService.renderIdentifier(data.get(inputName),
                                inputPort.getTranslatedElementClass(), callback.getContext());
                        inputName = sanatisePortName(inputName);
                        interpreter.set(inputName, input);
                    }
                    // run
                    interpreter.eval(json.get("script").asText());
                    // get outputs
                    for (OutputPort outputPort : getOutputPorts()) {
                        String name = outputPort.getName();
                        Object value = interpreter.get(name);
                        if (value == null) {
                            ErrorDocumentService errorDocService = referenceService.getErrorDocumentService();
                            value = errorDocService.registerError(
                                    "No value produced for output variable " + name, outputPort.getDepth(),
                                    callback.getContext());
                        }
                        outputData.put(name, referenceService.register(value, outputPort.getDepth(), true,
                                callback.getContext()));
                    }
                    callback.receiveResult(outputData, new int[0]);
                } catch (EvalError e) {
                    logger.error(e);
                    try {
                        int lineNumber = e.getErrorLineNumber();

                        callback.fail("Line " + lineNumber + ": " + determineMessage(e));
                    } catch (NullPointerException e2) {
                        callback.fail(determineMessage(e));
                    }
                } catch (ReferenceServiceException e) {
                    callback.fail("Error accessing beanshell input/output data for " + this, e);
                }
                clearInterpreter();
            }
        }

        /**
         * Removes any invalid characters from the port name. For example,
         * xml-text would become xmltext.
         * 
         * @param name
         * @return
         */
        private String sanatisePortName(String name) {
            String result = name;
            if (Pattern.matches("\\w++", name) == false) {
                result = "";
                for (char c : name.toCharArray()) {
                    if (Character.isLetterOrDigit(c) || c == '_') {
                        result += c;
                    }
                }
            }
            return result;
        }
    });

}

From source file:ambroafb.general.AnnotiationUtils.java

private static boolean checkValidationForContentMapEditorAnnotation(Field field, Object currSceneController) {
    boolean contentIsCorrect = false;
    Annotations.ContentMapEditor annotation = field.getAnnotation(Annotations.ContentMapEditor.class);
    Object[] typeAndContent = getNodesTypeAndContent(field, currSceneController);
    MapEditor mapEditorComboBox = (MapEditor) typeAndContent[0];
    String editorContent = (String) typeAndContent[1];
    String keyPart = StringUtils.substringBefore(editorContent, mapEditorComboBox.getDelimiter()).trim();
    String valuePart = StringUtils.substringAfter(editorContent, mapEditorComboBox.getDelimiter()).trim();

    boolean keyMatch = Pattern.matches(mapEditorComboBox.getKeyPattern(), keyPart);
    boolean valueMatch = Pattern.matches(mapEditorComboBox.getValuePattern(), valuePart);
    String explain;//from   w  w w.  ja  v  a  2 s . c o  m
    if (!keyMatch || !valueMatch) {
        explain = (!keyMatch) ? annotation.explainKey() : annotation.explainValue();
        changeNodeTitleLabelVisual(mapEditorComboBox, explain);
    } else if ((keyPart.isEmpty() && !valuePart.isEmpty()) || (!keyPart.isEmpty() && valuePart.isEmpty())) {
        explain = annotation.explainEmpty();
        changeNodeTitleLabelVisual(mapEditorComboBox, explain);
    } else {
        changeNodeTitleLabelVisual(mapEditorComboBox, "");
        contentIsCorrect = true;
    }
    return contentIsCorrect;
}

From source file:com.vuze.plugin.azVPN_Helper.CheckerCommon.java

private final boolean matchesVPNIP(InetAddress address, NetworkInterface networkInterface) {
    if (address == null) {
        return false;
    }/*from w w  w  .  j  a v a2  s  .c  o  m*/

    String[] excludes = config.getPluginStringParameter(PluginConstants.CONFIG_IGNORE_ADDRESS).split(";");
    if (excludes != null && excludes.length > 0) {
        String hostAddress = address.getHostAddress();
        for (String exclude : excludes) {
            if (hostAddress.equals(exclude)) {
                PluginVPNHelper.log(exclude + " matched and excluded");
                return false;
            }
        }
    }

    String regex = config.getPluginStringParameter(PluginConstants.CONFIG_VPN_IP_MATCHING);
    boolean matches = Pattern.matches(regex, address.getHostAddress());

    if (matches && excludes != null && excludes.length > 0) {
        if (networkInterface == null) {
            try {
                networkInterface = NetUtils.getByInetAddress(address);
            } catch (SocketException e) {
            }
        }
        if (networkInterface != null) {
            String name = networkInterface.getName();
            for (String exclude : excludes) {
                if (exclude.equals(name)) {
                    PluginVPNHelper.log(exclude + " matched and excluded");
                    return false;
                }
            }
        }
    }

    return matches;
}

From source file:edu.kit.dama.rest.util.auth.AbstractAuthenticator.java

/**
 * Authenticate a service access using the provided HttpContext. Depending
 * on the authenticator implementation credentials are obtained from a
 * specific header field or a request parameter. The provided groupId is
 * used to complete the returned AuthorizationContext and to determine the
 * user's role in this context.//  w ww  .  j  a v a 2 s .  co  m
 *
 * @param httpContext The HttpContext provided by the user while accessing a
 * REST endpoint.
 * @param groupId The group on which behalf the user accessed the endpoint.
 *
 * @return The AuthorizationContext or a WebApplicationException containing
 * status UNAUTHORIZED.
 *
 * @throws UnauthorizedAccessAttemptException If not authorized.
 */
public final IAuthorizationContext authenticate(HttpContext httpContext, GroupId groupId)
        throws UnauthorizedAccessAttemptException {
    String baseUrl = httpContext.getRequest().getBaseUri().toString();
    if (!Pattern.matches(enableForPattern, baseUrl)) {
        throw new UnauthorizedAccessAttemptException("Authenticator not enabled for baseUrl '" + baseUrl
                + "'. EnablePattern is '" + enableForPattern + "'.");
    }

    return obtainAuthorizationContext(httpContext, groupId);
}