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.vuze.plugin.azVPN_PIA.Checker.java

private boolean matchesVPNIP(InetAddress address) {
    if (address == null) {
        return false;
    }//from  w w w.j a  va 2s . co m
    String regex = config.getPluginStringParameter(PluginPIA.CONFIG_VPN_IP_MATCHING);
    return Pattern.matches(regex, address.getHostAddress());
}

From source file:com.google.code.rees.scope.struts2.StrutsActionProvider.java

private UrlSet buildUrlSet(List<URL> resourceUrls) throws IOException {
    ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
    UrlSet urlSet = new UrlSet(resourceUrls);
    urlSet.include(new UrlSet(classLoaderInterface, this.fileProtocols));

    //excluding the urls found by the parent class loader is desired, but fails in JBoss (all urls are removed)
    if (excludeParentClassLoader) {
        //exclude parent of classloaders
        ClassLoaderInterface parent = classLoaderInterface.getParent();
        //if reload is enabled, we need to step up one level, otherwise the UrlSet will be empty
        //this happens because the parent of the realoding class loader is the web app classloader
        if (parent != null && isReloadEnabled())
            parent = parent.getParent();

        if (parent != null)
            urlSet = urlSet.exclude(parent);

        try {//from  www. j  a  v  a 2  s  .  c  om
            // This may fail in some sandboxes, ie GAE
            ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
            urlSet = urlSet.exclude(new ClassLoaderInterfaceDelegate(systemClassLoader.getParent()));

        } catch (SecurityException e) {
            if (LOG.isWarnEnabled())
                LOG.warn(
                        "Could not get the system classloader due to security constraints, there may be improper urls left to scan");
        }
    }

    //try to find classes dirs inside war files
    urlSet = urlSet.includeClassesUrl(classLoaderInterface, new UrlSet.FileProtocolNormalizer() {
        public URL normalizeToFileProtocol(URL url) {
            return fileManager.normalizeToFileProtocol(url);
        }
    });

    urlSet = urlSet.excludeJavaExtDirs();
    urlSet = urlSet.excludeJavaEndorsedDirs();
    try {
        urlSet = urlSet.excludeJavaHome();
    } catch (NullPointerException e) {
        // This happens in GAE since the sandbox contains no java.home directory
        if (LOG.isWarnEnabled())
            LOG.warn("Could not exclude JAVA_HOME, is this a sandbox jvm?");
    }
    urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", ""));
    urlSet = urlSet.exclude(".*/JavaVM.framework/.*");

    if (includeJars == null) {
        urlSet = urlSet.exclude(".*?\\.jar(!/|/)?");
    } else {
        //jar urls regexes were specified
        List<URL> rawIncludedUrls = urlSet.getUrls();
        Set<URL> includeUrls = new HashSet<URL>();
        boolean[] patternUsed = new boolean[includeJars.length];

        for (URL url : rawIncludedUrls) {
            if (fileProtocols.contains(url.getProtocol())) {
                //it is a jar file, make sure it macthes at least a url regex
                for (int i = 0; i < includeJars.length; i++) {
                    String includeJar = includeJars[i];
                    if (Pattern.matches(includeJar, url.toExternalForm())) {
                        includeUrls.add(url);
                        patternUsed[i] = true;
                        break;
                    }
                }
            } else {
                //it is not a jar
                includeUrls.add(url);
            }
        }

        if (LOG.isWarnEnabled()) {
            for (int i = 0; i < patternUsed.length; i++) {
                if (!patternUsed[i]) {
                    LOG.warn("The includeJars pattern [#0] did not match any jars in the classpath",
                            includeJars[i]);
                }
            }
        }
        return new UrlSet(includeUrls);
    }

    return urlSet;
}

From source file:com.microsoft.azure.management.resources.ResourceOperationsImpl.java

/**
* Create a resource./*from w w  w.  j  a  va 2 s.  c  om*/
*
* @param resourceGroupName Required. The name of the resource group. The
* name is case insensitive.
* @param identity Required. Resource identity.
* @param parameters Required. Create or update resource parameters.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Resource information.
*/
@Override
public ResourceCreateOrUpdateResult createOrUpdate(String resourceGroupName, ResourceIdentity identity,
        GenericResource parameters) throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (resourceGroupName != null && resourceGroupName.length() > 1000) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (identity == null) {
        throw new NullPointerException("identity");
    }
    if (identity.getResourceName() == null) {
        throw new NullPointerException("identity.");
    }
    if (identity.getResourceProviderApiVersion() == null) {
        throw new NullPointerException("identity.");
    }
    if (identity.getResourceProviderNamespace() == null) {
        throw new NullPointerException("identity.");
    }
    if (identity.getResourceType() == null) {
        throw new NullPointerException("identity.");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("resourceGroupName", resourceGroupName);
        tracingParameters.put("identity", identity);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createOrUpdateAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourcegroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + URLEncoder.encode(identity.getResourceProviderNamespace(), "UTF-8");
    url = url + "/";
    if (identity.getParentResourcePath() != null) {
        url = url + identity.getParentResourcePath();
    }
    url = url + "/";
    url = url + identity.getResourceType();
    url = url + "/";
    url = url + URLEncoder.encode(identity.getResourceName(), "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + URLEncoder.encode(identity.getResourceProviderApiVersion(), "UTF-8"));
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // Serialize Request
    String requestContent = null;
    JsonNode requestDoc = null;

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode genericResourceValue = objectMapper.createObjectNode();
    requestDoc = genericResourceValue;

    if (parameters.getProperties() != null) {
        ((ObjectNode) genericResourceValue).put("properties",
                objectMapper.readTree(parameters.getProperties()));
    }

    if (parameters.getProvisioningState() != null) {
        ((ObjectNode) genericResourceValue).put("provisioningState", parameters.getProvisioningState());
    }

    if (parameters.getPlan() != null) {
        ObjectNode planValue = objectMapper.createObjectNode();
        ((ObjectNode) genericResourceValue).put("plan", planValue);

        if (parameters.getPlan().getName() != null) {
            ((ObjectNode) planValue).put("name", parameters.getPlan().getName());
        }

        if (parameters.getPlan().getPublisher() != null) {
            ((ObjectNode) planValue).put("publisher", parameters.getPlan().getPublisher());
        }

        if (parameters.getPlan().getProduct() != null) {
            ((ObjectNode) planValue).put("product", parameters.getPlan().getProduct());
        }

        if (parameters.getPlan().getPromotionCode() != null) {
            ((ObjectNode) planValue).put("promotionCode", parameters.getPlan().getPromotionCode());
        }
    }

    ((ObjectNode) genericResourceValue).put("location", parameters.getLocation());

    if (parameters.getTags() != null) {
        ObjectNode tagsDictionary = objectMapper.createObjectNode();
        for (Map.Entry<String, String> entry : parameters.getTags().entrySet()) {
            String tagsKey = entry.getKey();
            String tagsValue = entry.getValue();
            ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue);
        }
        ((ObjectNode) genericResourceValue).put("tags", tagsDictionary);
    }

    StringWriter stringWriter = new StringWriter();
    objectMapper.writeValue(stringWriter, requestDoc);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        ResourceCreateOrUpdateResult result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ResourceCreateOrUpdateResult();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                GenericResourceExtended resourceInstance = new GenericResourceExtended();
                result.setResource(resourceInstance);

                JsonNode propertiesValue = responseDoc.get("properties");
                if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                    JsonNode provisioningStateValue = propertiesValue.get("provisioningState");
                    if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                        String provisioningStateInstance;
                        provisioningStateInstance = provisioningStateValue.getTextValue();
                        resourceInstance.setProvisioningState(provisioningStateInstance);
                    }
                }

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    String propertiesInstance;
                    propertiesInstance = propertiesValue2.getTextValue();
                    resourceInstance.setProperties(propertiesInstance);
                }

                JsonNode provisioningStateValue2 = responseDoc.get("provisioningState");
                if (provisioningStateValue2 != null && provisioningStateValue2 instanceof NullNode == false) {
                    String provisioningStateInstance2;
                    provisioningStateInstance2 = provisioningStateValue2.getTextValue();
                    resourceInstance.setProvisioningState(provisioningStateInstance2);
                }

                JsonNode planValue2 = responseDoc.get("plan");
                if (planValue2 != null && planValue2 instanceof NullNode == false) {
                    Plan planInstance = new Plan();
                    resourceInstance.setPlan(planInstance);

                    JsonNode nameValue = planValue2.get("name");
                    if (nameValue != null && nameValue instanceof NullNode == false) {
                        String nameInstance;
                        nameInstance = nameValue.getTextValue();
                        planInstance.setName(nameInstance);
                    }

                    JsonNode publisherValue = planValue2.get("publisher");
                    if (publisherValue != null && publisherValue instanceof NullNode == false) {
                        String publisherInstance;
                        publisherInstance = publisherValue.getTextValue();
                        planInstance.setPublisher(publisherInstance);
                    }

                    JsonNode productValue = planValue2.get("product");
                    if (productValue != null && productValue instanceof NullNode == false) {
                        String productInstance;
                        productInstance = productValue.getTextValue();
                        planInstance.setProduct(productInstance);
                    }

                    JsonNode promotionCodeValue = planValue2.get("promotionCode");
                    if (promotionCodeValue != null && promotionCodeValue instanceof NullNode == false) {
                        String promotionCodeInstance;
                        promotionCodeInstance = promotionCodeValue.getTextValue();
                        planInstance.setPromotionCode(promotionCodeInstance);
                    }
                }

                JsonNode idValue = responseDoc.get("id");
                if (idValue != null && idValue instanceof NullNode == false) {
                    String idInstance;
                    idInstance = idValue.getTextValue();
                    resourceInstance.setId(idInstance);
                }

                JsonNode nameValue2 = responseDoc.get("name");
                if (nameValue2 != null && nameValue2 instanceof NullNode == false) {
                    String nameInstance2;
                    nameInstance2 = nameValue2.getTextValue();
                    resourceInstance.setName(nameInstance2);
                }

                JsonNode typeValue = responseDoc.get("type");
                if (typeValue != null && typeValue instanceof NullNode == false) {
                    String typeInstance;
                    typeInstance = typeValue.getTextValue();
                    resourceInstance.setType(typeInstance);
                }

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    resourceInstance.setLocation(locationInstance);
                }

                JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                    Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                    while (itr.hasNext()) {
                        Map.Entry<String, JsonNode> property = itr.next();
                        String tagsKey2 = property.getKey();
                        String tagsValue2 = property.getValue().getTextValue();
                        resourceInstance.getTags().put(tagsKey2, tagsValue2);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.cloud.server.ConfigurationServerImpl.java

private void generateDefaultKeystore(String keystorePath) throws IOException {
    String cn = "Cloudstack User";
    String ou;/*from  w  w w .  ja  va 2s.c  o  m*/

    try {
        ou = InetAddress.getLocalHost().getCanonicalHostName();
        String[] group = ou.split("\\.");

        // Simple check to see if we got IP Address...
        boolean isIPAddress = Pattern.matches("[0-9]$", group[group.length - 1]);
        if (isIPAddress) {
            ou = "cloud.com";
        } else {
            ou = group[group.length - 1];
            for (int i = group.length - 2; i >= 0 && i >= group.length - 3; i--)
                ou = group[i] + "." + ou;
        }
    } catch (UnknownHostException ex) {
        s_logger.info("Fail to get user's domain name. Would use cloud.com. ", ex);
        ou = "cloud.com";
    }

    String o = ou;
    String c = "Unknown";
    String dname = "cn=\"" + cn + "\",ou=\"" + ou + "\",o=\"" + o + "\",c=\"" + c + "\"";
    Script script = new Script(true, "keytool", 5000, null);
    script.add("-genkey");
    script.add("-keystore", keystorePath);
    script.add("-storepass", "vmops.com");
    script.add("-keypass", "vmops.com");
    script.add("-keyalg", "RSA");
    script.add("-validity", "3650");
    script.add("-dname", dname);
    String result = script.execute();
    if (result != null) {
        throw new IOException("Fail to generate certificate!: " + result);
    }
}

From source file:edu.harvard.iq.dataverse.HarvestingClientsPage.java

public boolean validateNickname() {

    if (!StringUtils.isEmpty(getNewNickname())) {

        if (getNewNickname().length() > 30 || (!Pattern.matches("^[a-zA-Z0-9\\_\\-]+$", getNewNickname()))) {
            //input.setValid(false);
            FacesContext.getCurrentInstance().addMessage(getNewClientNicknameInputField().getClientId(),
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "",
                            JH.localize("harvestclients.newClientDialog.nickname.invalid")));
            return false;

            // If it passes the regex test, check 
        } else if (harvestingClientService.findByNickname(getNewNickname()) != null) {
            //input.setValid(false);
            FacesContext.getCurrentInstance().addMessage(getNewClientNicknameInputField().getClientId(),
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "",
                            JH.localize("harvestclients.newClientDialog.nickname.alreadyused")));
            return false;
        }/*from  ww w .  j  av a2 s . c o  m*/
        return true;
    }

    // Nickname field is empty:
    FacesContext.getCurrentInstance().addMessage(getNewClientNicknameInputField().getClientId(),
            new FacesMessage(FacesMessage.SEVERITY_ERROR, "",
                    JH.localize("harvestclients.newClientDialog.nickname.required")));
    return false;
}

From source file:com.brick.sms.email.MailTest.java

public static boolean isVaildEmail(String email) {
    // String/*from   w  ww  .j a  v a 2s  . c o  m*/
    // emailPattern="[a-zA-Z0-9][a-zA-Z0-9._-]{2,16}[a-zA-Z0-9]@[a-zA-Z0-9]+.[a-zA-Z0-9]+";
    //String emailPattern = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    //String emailPattern = "\\p{Alpha}\\w{2,15}[@][a-z0-9]{3,}[.]\\p{Lower}{2,}";
    //String emailPattern = "\\w+(\\.\\w+)*@\\w+(\\.\\w+)+";

    String emailPattern1 = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
    String emailPattern2 = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
    String aa = "1.?<a href ='###' onclick='if(typeof(CreateNewTabWin) == 'function'){CreateNewTabWin('../JHSoft.Web.HrmAttendance/Attendance_Leave_Approve.aspx?Vmt3SVhrRzBCTWVUU1BRUythQTJBN1BjSHlKVkVrREdDeTZOcFdUcStoNE9BVjB1NDFLcGhES2ZkQlRsMWlUeFZtVGc2NEZwRGJjeDQ5aHBTSDJoTkFNV2tIOFhHRmllSTFubU43eVBBQkVZMlJPdjhxOEsrMDFWS21McXY3MFpEckl6VjYvYjdpUT0=&&');} else{parent.CreateNewTabWin('../JHSoft.Web.HrmAttendance/Attendance_Leave_Approve.aspx?Vmt3SVhrRzBCTWVUU1BRUythQTJBN1BjSHlKVkVrREdDeTZOcFdUcStoNE9BVjB1NDFLcGhES2ZkQlRsMWlUeFZtVGc2NEZwRGJjeDQ5aHBTSDJoTkFNV2tIOFhHRmllSTFubU43eVBBQkVZMlJPdjhxOEsrMDFWS21McXY3MFpEckl6VjYvYjdpUT0=&&');}'>?</a>";
    boolean result = Pattern.matches(emailPattern2, email);
    String rrr = "(?:<a[^>]*>)(.*?)(?:<\\/a[^>]*>)/gi";
    aa.matches(rrr);
    System.out.println(aa.matches(rrr));
    return result;
}

From source file:com.csipsimple.service.DownloadLibService.java

private boolean isCompatibleStack(JSONObject filter) throws SecurityException, NoSuchFieldException,
        ClassNotFoundException, IllegalArgumentException, IllegalAccessException, JSONException {

    //For each filter keys, we check if the filter is not invalid
    Iterator<?> iter = filter.keys();
    while (iter.hasNext()) {
        //Each filter key correspond to a android class which values has to be checked
        String class_filter = (String) iter.next();
        //Get this class
        Class<?> cls = Class.forName(class_filter);

        //Then for this class, we have to check if each static field matches defined regexp rule
        Iterator<?> cls_iter = filter.getJSONObject(class_filter).keys();

        while (cls_iter.hasNext()) {
            String field_name = (String) cls_iter.next();
            Field field = cls.getField(field_name);
            //Get the current value on the system
            String current_value = field.get(null).toString();
            //Get the filter for this value
            String regexp_filter = filter.getJSONObject(class_filter).getString(field_name);

            //Check if matches
            if (!Pattern.matches(regexp_filter, current_value)) {
                Log.d(THIS_FILE, "Regexp not match : " + current_value + " matches /" + regexp_filter + "/");
                return false;
            }//from   www  .j  a v a 2 s  . c  o m
        }
    }
    return true;
}

From source file:anotadorderelacoes.model.Sentenca.java

/**
 * Detecta automaticamente os termos existentes na sentena passada como
 * parametro. Usa a expresso regular (TODO: Corrigir esta expresso e
 * expand-la. Por ex. Fundao de Amparo  Pesquisa no  identificado por
 * essa expresso)/*  www .  jav  a 2  s  . com*/
 * <blockquote>A+ | A+ (de A+ (a|os A+))+</blockquote>
 * para identificar termos compostos. Todos os substantivos e adjetivos
 * restantes so marcados como termos.
 * <p>
 * Seria interessante experimentar com aprendizado de mquina tambm pra
 * identificar termos
 */
public void detectarTermos() {

    // Comeamos desmarcando todos os termos desta sentena
    List<Termo> copia = new ArrayList<Termo>(getTermos());
    for (Termo termo : copia) {
        desmarcarTermo(termo);
    }

    // Marca alguns termos j pr-identificados como tais, presentes no
    // arquivo /recursos/lista_termos
    /*
    for ( int i = 0; i < getTokens().size(); ++i ) {
    if ( tokenEmTermo( i ) )
        continue;
    boolean marcou = false;
    for ( String t : Utilidades.listaTermosIdentificacao ) {
        String temp = getTokens().get(i).getToken().replace("=", " ");
        int j = i;
        while ( t.startsWith(temp) && j < getTokens().size() ) {
            int posFim = j;
            System.out.println(">>>>" + temp);
            if ( t.equals(temp) ) {
                marcarTermo(i, posFim, temp);
                marcou = true;
                break;
            }
            ++j;
            temp += " " + getTokens().get(j).getToken().replace("=", " ");
        }
        if ( marcou )
            break;
    }
    }
    */

    // Sequncias de palavras capitalizadas so marcadas como termos
    // Aqui comea a identificao usando o autmato finito
    int posicao = 0;
    int posInicio = -1;
    int posFim = -1;
    int estado = 0;

    for (Token token : getTokens()) {

        String classeGramatical = Utilidades.classeGramatical(token);

        // Se o token j faz parte de algum termo e estvamos identificando
        // algum termo, marcamos o termo e movemos para a proxima posio na
        // sentena
        if (tokenEmTermo(posicao)) {
            if (estado == 1 || estado == 2 || estado == 3) {
                List<Token> tokens = Utilidades.tokensJanela(this, posInicio, posFim - (estado - 1));
                String termo = tokens.get(0).getToken();
                for (int i = 1; i < tokens.size(); ++i)
                    termo += " " + tokens.get(i).getToken();
                marcarTermo(posInicio, posFim - (estado - 1), termo);
                estado = 0;
            }
            ++posicao;
            continue;
        }

        if (estado == 0) {

            posInicio = posicao;

            if (classeGramatical != null && classeGramatical.equals("ADV")) {
                estado = 4;
            } else if (token.getPos() != null && Pattern.matches(".*<.*(poss|dem).*>.*", token.getPos())
                    && !Pattern.matches(".*<.*artd.*>.*", token.getPos())) {
                // Alguns artigos so marcados como pronomes demonstrativos
                estado = 5;
            }
            // Se comea com letra maiscula, provavelmente  um termo
            else if (Utilidades.capitalizado(token) && classeGramatical != null
                    && (classeGramatical.equals("N") || classeGramatical.equals("ADJ"))) {
                posFim = posicao;
                estado = 1;
            }

        }
        // Token iniciado com letra maiscula
        else if (estado == 1) {

            if (Utilidades.capitalizado(token)) {
                posFim = posicao;
            } else if (token.getToken().equals("de") || token.getToken().equals("a")) {
                posFim = posicao;
                estado = 2;
            } else {
                List<Token> tokens = Utilidades.tokensJanela(this, posInicio, posFim);
                String termo = tokens.get(0).getToken();
                for (int i = 1; i < tokens.size(); ++i)
                    termo += " " + tokens.get(i).getToken();
                marcarTermo(posInicio, posFim, termo);
                estado = 0;
            }

        }
        // A + de/a
        else if (estado == 2) {

            if (Utilidades.capitalizado(token)) {
                posFim = posicao;
                estado = 1;
            } else if (token.getToken().equals("a") || token.getToken().equals("o")
                    || token.getToken().equals("as") || token.getToken().equals("os")) {
                posFim = posicao;
                estado = 3;
            } else {
                List<Token> tokens = Utilidades.tokensJanela(this, posInicio, posFim - 1);
                String termo = tokens.get(0).getToken();
                for (int i = 1; i < tokens.size(); ++i)
                    termo += " " + tokens.get(i).getToken();
                marcarTermo(posInicio, posFim - 1, termo);
                estado = 0;
            }

        }
        // A + de/a + a(s)/o(s)
        else if (estado == 3) {

            if (Utilidades.capitalizado(token)) {
                posFim = posicao;
                estado = 1;
            } else {
                List<Token> tokens = Utilidades.tokensJanela(this, posInicio, posFim - 2);
                String termo = tokens.get(0).getToken();
                for (int i = 1; i < tokens.size(); ++i)
                    termo += " " + tokens.get(i).getToken();
                marcarTermo(posInicio, posFim - 2, termo);
                estado = 0;
            }

        }
        // Advrbio
        else if (estado == 4) {

            if (Utilidades.capitalizado(token)) {
                posInicio = posicao;
                posFim = posicao;
                estado = 1;
            } else if (classeGramatical != null && classeGramatical.equals("ADJ")) {
                List<Token> tokens = Utilidades.tokensJanela(this, posInicio, posicao);
                String termo = tokens.get(0).getToken();
                for (int i = 1; i < tokens.size(); ++i)
                    termo += " " + tokens.get(i).getToken();
                marcarTermo(posInicio, posicao, termo);
                estado = 0;
            } else
                estado = 0;

        }
        // Pronome possessivo ou demonstrativo
        else if (estado == 5) {

            if (Utilidades.capitalizado(token)) {
                posInicio = posicao;
                posFim = posicao;
                estado = 1;
            } else if (classeGramatical != null && classeGramatical.equals("N")) {
                List<Token> tokens = Utilidades.tokensJanela(this, posInicio, posicao);
                String termo = tokens.get(0).getToken();
                for (int i = 1; i < tokens.size(); ++i)
                    termo += " " + tokens.get(i).getToken();
                marcarTermo(posInicio, posicao, termo);
                estado = 0;
            } else
                estado = 0;

        }

        ++posicao;

    }

    if (estado == 1 || estado == 2 || estado == 3) {
        List<Token> tokens = Utilidades.tokensJanela(this, posInicio, posFim - (estado - 1));
        String termo = tokens.get(0).getToken();
        for (int i = 1; i < tokens.size(); ++i)
            termo += " " + tokens.get(i).getToken();
        marcarTermo(posInicio, posFim - (estado - 1), termo);
    }

    // Todos os substantivos e adjetivos restantes so marcados como termos
    posicao = 0;
    for (Token token : getTokens()) {
        String classeGramatical = Utilidades.classeGramatical(token);
        if (!tokenEmTermo(posicao) && token.getToken().length() > 1 && classeGramatical != null
                && (classeGramatical.equals("N") || classeGramatical.equals("ADJ")))
            marcarTermo(posicao, posicao, token.getToken());
        ++posicao;
    }

}

From source file:com.microsoft.azure.management.resources.DeploymentOperationsImpl.java

/**
* Checks whether deployment exists./*w w w  . j a va  2  s .  co  m*/
*
* @param resourceGroupName Required. The name of the resource group to
* check. The name is case insensitive.
* @param deploymentName Required. The name of the deployment.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Deployment information.
*/
@Override
public DeploymentExistsResult checkExistence(String resourceGroupName, String deploymentName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (resourceGroupName != null && resourceGroupName.length() > 1000) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("resourceGroupName", resourceGroupName);
        tracingParameters.put("deploymentName", deploymentName);
        CloudTracing.enter(invocationId, this, "checkExistenceAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourcegroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-04-01-preview");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpHead httpRequest = new HttpHead(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_NO_CONTENT && statusCode != HttpStatus.SC_NOT_FOUND) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        DeploymentExistsResult result = null;
        // Deserialize Response
        result = new DeploymentExistsResult();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }
        if (statusCode == HttpStatus.SC_NO_CONTENT) {
            result.setExists(true);
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}