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.farmafene.commons.cas.LoginTGT.java

/**
 * @param target//from  ww w  . ja  v  a  2  s.  co  m
 *            cadena a buscar el atributo
 * @param name
 *            atributo a buscar
 * @return el valor del atributo, si existe (<code>null</code> si no
 *         existe);
 */
private String search(String target, String name) {
    String search = null;
    if (target != null) {
        if (Pattern.matches(".*\\sname\\s*=\"" + name + "\"\\s.*", target)) {
            Pattern p = Pattern.compile(".*\\svalue\\s*=\"(.*)\"\\s.*");
            Matcher m = p.matcher(target);
            if (m.matches()) {
                search = m.group(1);
            }
        }
    }
    return search;
}

From source file:org.apache.calcite.runtime.SqlFunctions.java

/** SQL {@code SIMILAR} function with escape. */
public static boolean similar(String s, String pattern, String escape) {
    final String regex = Like.sqlToRegexSimilar(pattern, escape);
    return Pattern.matches(regex, s);
}

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

/**
* Checks whether resource group exists.//from w  w w. j ava2  s.  c  om
*
* @param resourceGroupName Required. The name of the resource group to
* check. The name is case insensitive.
* @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 Resource group information.
*/
@Override
public ResourceGroupExistsResult checkExistence(String resourceGroupName) 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");
    }

    // 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);
        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");
    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
        ResourceGroupExistsResult result = null;
        // Deserialize Response
        result = new ResourceGroupExistsResult();
        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();
        }
    }
}

From source file:com.smanempat.controller.ControllerEvaluation.java

public void proccessMining(JTable tableDataSetModel, JTable tableDataSetTesting, JTextField txtNumberOfK,
        JLabel labelPesanError, JTabbedPane jTabbedPane1, JTable tableResult, JTable tableConfMatrix,
        JTable tableTahunTesting, JLabel totalAccuracy, JPanel panelChart, JPanel panelChart1,
        JPanel panelChart2, JRadioButton singleTesting, JRadioButton multiTesting, JTextArea txtArea)
        throws SQLException {
    Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
    modelEvaluation = new ModelEvaluation();
    int rowCountModel = tableDataSetModel.getRowCount();
    int rowCountTest = tableDataSetTesting.getRowCount();
    int[] tempK;// ww  w  .j  a  va  2s.co m
    double[][] tempEval;
    double[][] evalValue;
    boolean valid = false;

    /*Validasi Dataset Model dan Dataset Uji*/
    if (rowCountModel == 0) {
        JOptionPane.showMessageDialog(null, "Pilih dataset model terlebih dahulu!", "Error",
                JOptionPane.INFORMATION_MESSAGE,
                new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
        txtNumberOfK.requestFocus();
    } else if (rowCountTest == 0) {
        JOptionPane.showMessageDialog(null, "Pilih dataset uji terlebih dahulu!", "Error",
                JOptionPane.INFORMATION_MESSAGE,
                new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
        txtNumberOfK.requestFocus();
    } else {
        valid = true;
    }
    /*Validasi Dataset Model dan Dataset Uji*/

    if (valid == true) {
        if (multiTesting.isSelected()) {
            String iterasi = JOptionPane.showInputDialog("Input Jumlah Iterasi Pengujian :");
            boolean validMulti = false;

            if (iterasi != null) {

                /*Validasi Jumlah Iterasi*/
                if (Pattern.matches("[0-9]+", iterasi) == false && iterasi.length() > 0) {
                    JOptionPane.showMessageDialog(null, "Nilai iterasi tidak valid!", "Error",
                            JOptionPane.INFORMATION_MESSAGE,
                            new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                } else if (iterasi.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "Nilai iterasi tidak boleh kosong!", "Error",
                            JOptionPane.INFORMATION_MESSAGE,
                            new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                } else if (iterasi.length() == 9) {
                    JOptionPane.showMessageDialog(null, "Nilai iterasi terlalu panjang!", "Error",
                            JOptionPane.INFORMATION_MESSAGE,
                            new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                } else if (rowCountTest > rowCountModel) {

                    JOptionPane.showMessageDialog(null, "Data Uji tidak boleh lebih besar daripada data Model!",
                            "Error", JOptionPane.INFORMATION_MESSAGE,
                            new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                } else {
                    validMulti = true;
                    System.out.println("valiMulti = " + validMulti + " Kok");
                }
                /*Validasi Jumlah Iterasi*/
            }

            if (validMulti == true) {
                tempK = new int[Integer.parseInt(iterasi)];
                evalValue = new double[3][tempK.length];
                for (int i = 0; i < Integer.parseInt(iterasi); i++) {
                    validMulti = false;
                    String k = JOptionPane
                            .showInputDialog("Input Nilai Nearest Neighbor (k) ke " + (i + 1) + " :");
                    if (k != null) {
                        /*Validasi Nilai K Tiap Iterasi*/
                        if (Pattern.matches("[0-9]+", k) == false && k.length() > 0) {
                            JOptionPane.showMessageDialog(null, "Nilai nearest neighbor (k) tidak valid!",
                                    "Error", JOptionPane.INFORMATION_MESSAGE,
                                    new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                        } else if (k.isEmpty()) {
                            JOptionPane.showMessageDialog(null,
                                    "Nilai nearest neighbor (k) tidak boleh kosong!", "Error",
                                    JOptionPane.INFORMATION_MESSAGE,
                                    new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                        } else if (k.length() == 9) {
                            JOptionPane.showMessageDialog(null, "Nilai nearest neighbor (k) terlalu panjang!",
                                    "Error", JOptionPane.INFORMATION_MESSAGE,
                                    new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                        } else {
                            validMulti = true;
                        }
                        /*Validasi Nilai K Tiap Iterasi*/
                    }

                    if (validMulti == true) {
                        tempK[i] = Integer.parseInt(k);
                        System.out.println(tempK[i]);
                    } else {
                        break;
                    }
                }

                if (validMulti == true) {
                    for (int i = 0; i < tempK.length; i++) {
                        int kValue = tempK[i];
                        String[][] modelValue = getModelValue(rowCountModel, tableDataSetModel);
                        double[][] testValue = getTestvalue(rowCountTest, tableDataSetTesting);
                        String[] knnValue = getKNNValue(rowCountModel, rowCountTest, modelValue, testValue,
                                kValue);
                        tempEval = evaluationModel(tableResult, tableConfMatrix, totalAccuracy,
                                tableTahunTesting, tableDataSetTesting, knnValue, i, tempK, panelChart);
                        //Menampung nilai Accuracy
                        evalValue[0][i] = tempEval[0][i];
                        //Menampung nilai Recall
                        evalValue[1][i] = tempEval[1][i];
                        //Menampung nilai Precision
                        evalValue[2][i] = tempEval[2][i];
                        jTabbedPane1.setSelectedIndex(1);
                        txtArea.append(
                                "Tingkat Keberhasilan Sistem dengan Nilai Number of Nearest Neighbor (K) = "
                                        + tempK[i] + "\n");
                        txtArea.append("Akurasi\t\t: " + evalValue[0][i] * 100 + " %\n");
                        txtArea.append("Recall\t\t: " + evalValue[1][i] * 100 + " %\n");
                        txtArea.append("Precision\t: " + evalValue[2][i] * 100 + " %\n");
                        txtArea.append(
                                "=============================================================================\n");
                    }
                    showChart(tempK, evalValue, panelChart, panelChart1, panelChart2);
                }
            }
        } else if (singleTesting.isSelected()) {
            boolean validSingle = false;
            String k = txtNumberOfK.getText();
            int nilaiK = 0;
            evalValue = new double[3][1];

            /*Validasi Nilai Number of Nearest Neighbor*/
            if (Pattern.matches("[0-9]+", k) == false && k.length() > 0) {
                labelPesanError.setText("Number of Nearest Neighbor tidak valid");
                JOptionPane.showMessageDialog(null, "Number of Nearest Neighbor tidak valid!", "Error",
                        JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                txtNumberOfK.requestFocus();
            } else if (k.isEmpty()) {
                JOptionPane.showMessageDialog(null, "Number of Nearest Neighbor tidak boleh kosong!", "Error",
                        JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                labelPesanError.setText("Number of Nearest Neighbor tidak boleh kosong");
                txtNumberOfK.requestFocus();
            } else if (rowCountModel == 0 && Integer.parseInt(k) >= rowCountModel) {
                JOptionPane.showMessageDialog(null, "Pilih dataset model terlebih dahulu!", "Error",
                        JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                txtNumberOfK.requestFocus();
            } else if (rowCountTest == 0 && Integer.parseInt(k) >= rowCountTest) {
                JOptionPane.showMessageDialog(null, "Pilih dataset uji terlebih dahulu!", "Error",
                        JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                txtNumberOfK.requestFocus();
            } else if (Integer.parseInt(k) >= rowCountModel) {
                JOptionPane.showMessageDialog(null,
                        "Number of Nearest Neighbor tidak boleh lebih dari " + rowCountModel + " !", "Error",
                        JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                txtNumberOfK.requestFocus();
            } else {
                validSingle = true;
                nilaiK = Integer.parseInt(k);
            }
            /*Validasi Nilai Number of Nearest Neighbor*/

            if (validSingle == true) {
                int confirm;
                int i = 0;
                confirm = JOptionPane.showOptionDialog(null, "Yakin ingin memproses data?",
                        "Proses Klasifikasi", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                        null, null);
                if (confirm == JOptionPane.OK_OPTION) {

                    int kValue = Integer.parseInt(txtNumberOfK.getText());
                    String[][] modelValue = getModelValue(rowCountModel, tableDataSetModel);
                    double[][] testValue = getTestvalue(rowCountTest, tableDataSetTesting);
                    String[] knnValue = getKNNValue(rowCountModel, rowCountTest, modelValue, testValue, kValue);
                    tempEval = evaluationModel(tableResult, tableConfMatrix, totalAccuracy, tableTahunTesting,
                            tableDataSetTesting, knnValue, nilaiK, panelChart);
                    evalValue[0][i] = tempEval[0][0];
                    evalValue[1][i] = tempEval[1][0];
                    evalValue[2][i] = tempEval[2][0];
                    jTabbedPane1.setSelectedIndex(1);
                }
                System.out.println("com.smanempat.controller.ControllerEvaluation.proccessMining()OKOKOK");
                showChart(nilaiK, evalValue, panelChart, panelChart1, panelChart2);
                Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
            }
        }
    }

}

From source file:jenkins.plugins.git.AbstractGitSCMSource.java

/**
 * Returns true if the branchName isn't matched by includes or is matched by excludes.
 * //from  w ww  . j  a  v a 2 s . com
 * @param branchName
 * @return true if branchName is excluded or is not included
 */
protected boolean isExcluded(String branchName) {
    return !Pattern.matches(getPattern(getIncludes()), branchName)
            || (Pattern.matches(getPattern(getExcludes()), branchName));
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.MultiTAdminServiceImpl.java

/**
 * @see TenantAdminService.createTenant()
 *//*from w ww.ja va  2s.c  o  m*/
public void createTenant(final String tenantDomain, final char[] tenantAdminRawPassword,
        String rootContentStoreDir, List<ContentStoreDefinition> stores) {
    logger.debug("[MultiTAdminServiceImpl::createTenant] BEGIN");
    // Check that all the passed values are not null
    ParameterCheck.mandatory("tenantDomain", tenantDomain);
    ParameterCheck.mandatory("tenantAdminRawPassword", tenantAdminRawPassword);

    if (!Pattern.matches(REGEX_VALID_TENANT_NAME, tenantDomain)) {
        throw new IllegalArgumentException(
                tenantDomain + " is not a valid tenant name (must match " + REGEX_VALID_TENANT_NAME + ")");
    }

    if (existsTenant(tenantDomain)) {
        throw new AlfrescoRuntimeException("Tenant already exists: " + tenantDomain);
    } else {
        authenticationComponent.setSystemUserAsCurrentUser();

        // Se rootContentStoreDir e' null o vuoto, lo riempo col path del repository padre
        if (rootContentStoreDir == null || rootContentStoreDir.length() == 0) {
            rootContentStoreDir = tenantFileContentStore.getDefaultRootDir();
        }

        logger.debug("[MultiTAdminServiceImpl::createTenant] rootContentStoreDir: " + rootContentStoreDir);

        // init - need to enable tenant (including tenant service) before stores bootstrap
        Tenant t = new Tenant(tenantDomain, true, rootContentStoreDir);
        // MB: Imposto i contentStore
        t.setContentStores(stores);

        putTenantAttributes(tenantDomain, t);

        AuthenticationUtil.runAs(new RunAsWork<Object>() {
            public Object doWork() {
                logger.info("[MultiTAdminServiceImpl::createTenant] INIT doWork");
                dictionaryComponent.init();
                // DoQui 06/05/2008
                // WORKAROUND:
                //   Nella configurazione multirepository il metodo init() esegue
                //   l'inizializzazione per tutti i repository configurati, ma in
                //   questo caso e` necessario inizializzare solo il repository
                //   corrente.
                //   Il metodo onEnableTenant() esegue la stessa operazione, ma solo
                //   sul repository corrente (vedere implementazione della classe
                //   it.doqui.index.ecmengine.business.personalization.multirepository.TenantRoutingFileContentStore
                //   per i dettagli).
                //tenantFileContentStore.init();
                tenantFileContentStore.onEnableTenant();

                // create tenant-specific stores
                bootstrapUserTenantStore(tenantDomain, tenantAdminRawPassword);
                bootstrapSystemTenantStore(tenantDomain);
                bootstrapVersionTenantStore(tenantDomain);
                bootstrapSpacesArchiveTenantStore(tenantDomain);
                bootstrapSpacesTenantStore(tenantDomain);

                List<TenantDeployer> tenantDeployers = getTenantDeployers();
                // notify listeners that tenant has been created & hence enabled
                for (TenantDeployer tenantDeployer : tenantDeployers) {
                    tenantDeployer.onEnableTenant();
                }

                /*
                // MB: Aggiorno la password dell'utente ADMIN, in modo da forzare la creazione
                // di una nuova alf_transaction. Questa transazione e' replicata fra i nodi
                // dei cluster, e anche sulla partizione batch, forzando la reindicizzazione
                // dell'utente admin. Utente che, a volte, non e' indicizzato e non permette
                // il login su partizioni batch, dopo la creazione di un tenant sulla partizione
                // online
                // Ci si accorge del problema, guardando la directory lucene degli user, che rimane
                // senza document
                */
                /*
                // Non risolve .. anzi .. potrebbe essere la causa di un errore di transaction already exist
                // Nel momento in cui un nodo dlave indicizza il grappolo di transazioni
                UserTransaction userTransaction = transactionService.getUserTransaction();
                try
                {
                    // Inizio la transazione
                  userTransaction.begin();
                        
                    // Cambio la PWD e creo una nuova transazione
                    authenticationService.updateAuthentication( getTenantAdminUser(tenantDomain)   ,
                                                                tenantAdminRawPassword             ,
                                                                tenantAdminRawPassword             );
                        
                    // Chiudo la transazione
                 userTransaction.commit();
                        
                } catch(Throwable e) {
                   logger.error("[MultiTAdminServiceImpl::createTenant] update user failed " + e);
                   try {
                     if (userTransaction != null) {
                         userTransaction.rollback();
                     }
                   } catch (Throwable ex) {}
                }
                // ---------------------------------------------------------------------------
                */

                logger.info("[MultiTAdminServiceImpl::createTenant] END doWork");

                return null;
            }
        }, getTenantAdminUser(tenantDomain));
    }

    logger.info("Tenant created: " + tenantDomain);
    logger.debug("[MultiTAdminServiceImpl::createTenant] END");
}

From source file:ambroafb.general.AnnotiationUtils.java

private static boolean checkValidationForContentISOAnnotation(Field field, Object currSceneController) {
    boolean contentIsCorrect = false;
    Annotations.ContentISO annotation = field.getAnnotation(Annotations.ContentISO.class);
    Object[] typeAndContent = getNodesTypeAndContent(field, currSceneController);

    if (!Pattern.matches(annotation.value(), (String) typeAndContent[1])) {
        String explainFromBundle = GeneralConfig.getInstance().getTitleFor(annotation.explain());
        String explain = explainFromBundle.replaceFirst("#", "" + Annotations.ContentISO.isoLen);
        changeNodeTitleLabelVisual((Node) typeAndContent[0], explain);
    } else {//from  w w w.  ja  v a  2s  . c  om
        changeNodeTitleLabelVisual((Node) typeAndContent[0], "");
        contentIsCorrect = true;
    }
    return contentIsCorrect;
}

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

/**
* Checks whether resource exists./*  w  ww.jav  a  2  s.  c  om*/
*
* @param resourceGroupName Required. The name of the resource group. The
* name is case insensitive.
* @param identity Required. Resource identity.
* @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 Resource group information.
*/
@Override
public ResourceExistsResult checkExistence(String resourceGroupName, ResourceIdentity identity)
        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 (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.");
    }

    // 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);
        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 + "/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
    HttpGet httpRequest = new HttpGet(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_OK && statusCode != HttpStatus.SC_NOT_FOUND) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        ResourceExistsResult result = null;
        // Deserialize Response
        result = new ResourceExistsResult();
        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_OK) {
            result.setExists(true);
        } else {
            result.setExists(false);
        }

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

From source file:com.btmatthews.atlas.jcr.impl.JCRTemplate.java

public <T> T withNodePath(final String workspaceName, final String path, final NodeCallback<T> found,
        final ErrorCallback<T> notFound, final ErrorCallback<T> error) {
    assert workspaceName != null && Pattern.matches(WORKSPACE_PATTERN, workspaceName);
    assert path != null && Pattern.matches(PATH_PATTERN, path);
    assert found != null;
    assert notFound != null;
    assert error != null;

    return withSession(workspaceName, session -> {
        try {/*  w w  w  .j av a2s .  c  o m*/
            final Node node = session.getNode(path);
            return found.doInSessionWithNode(session, node);
        } catch (PathNotFoundException e) {
            return notFound.doInSessionWithException(session, e);
        } catch (final RepositoryException e) {
            return error.doInSessionWithException(session, e);
        }
    });
}

From source file:net.spfbl.whois.Domain.java

/**
 * Verifica se o endereo  um e-mail vlido.
 * @param address o endereo a ser verificado.
 * @return verdadeiro se o endereo  um e-mail vlido.
 *//*from  w  w w  .  ja  va 2s.c  o m*/
public static boolean isEmail(String address) {
    if (address == null) {
        return false;
    } else {
        address = address.trim();
        address = address.toLowerCase();
        if (Pattern.matches("^" + "[0-9a-zA-Z--?--?----._%/+=-]+" + "@"
                + "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9_-]{0,61}[a-zA-Z0-9])"
                + "(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9_-]{0,61}[a-zA-Z0-9]))*)" + "$", address)) {
            int index = address.indexOf('@');
            String domain = address.substring(index + 1);
            return Domain.isHostname(domain);
        } else {
            return false;
        }
    }
}