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.example.pierre.applicompanies.library_http.BinaryHttpResponseHandler.java

@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders(AsyncHttpClient.HEADER_CONTENT_TYPE);
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(
                status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;//from www  . j  av a2s  . c o m
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
            Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e);
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(
                status.getStatusCode(), "Content-Type (" + contentTypeHeader.getValue() + ") not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}

From source file:com.microsoft.azure.management.network.UsageOperationsImpl.java

/**
* Lists compute usages for a subscription.
*
* @param location Required. The location upon which resource usage is
* queried.//  w  w  w . j  a  v a 2s.c  om
* @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 The List Usages operation response.
*/
@Override
public UsagesListResponse list(String location) throws IOException, ServiceException {
    // Validate
    if (location == null) {
        throw new NullPointerException("location");
    }
    if (location != null && location.length() > 1000) {
        throw new IllegalArgumentException("location");
    }
    if (Pattern.matches("^[-\\w\\._]+$", location) == false) {
        throw new IllegalArgumentException("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("location", location);
        CloudTracing.enter(invocationId, this, "listAsync", 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 + "/providers/";
    url = url + "Microsoft.Network";
    url = url + "/locations/";
    url = url + URLEncoder.encode(location, "UTF-8");
    url = url + "/usages";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-05-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
    HttpGet httpRequest = new HttpGet(url);

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

    // 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) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        UsagesListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new UsagesListResponse();
            ObjectMapper objectMapper = new ObjectMapper();
            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) {
                JsonNode valueArray = responseDoc.get("value");
                if (valueArray != null && valueArray instanceof NullNode == false) {
                    for (JsonNode valueValue : ((ArrayNode) valueArray)) {
                        Usage usageInstance = new Usage();
                        result.getUsages().add(usageInstance);

                        JsonNode unitValue = valueValue.get("unit");
                        if (unitValue != null && unitValue instanceof NullNode == false) {
                            String unitInstance;
                            unitInstance = unitValue.getTextValue();
                            usageInstance.setUnit(unitInstance);
                        }

                        JsonNode currentValueValue = valueValue.get("currentValue");
                        if (currentValueValue != null && currentValueValue instanceof NullNode == false) {
                            int currentValueInstance;
                            currentValueInstance = currentValueValue.getIntValue();
                            usageInstance.setCurrentValue(currentValueInstance);
                        }

                        JsonNode limitValue = valueValue.get("limit");
                        if (limitValue != null && limitValue instanceof NullNode == false) {
                            long limitInstance;
                            limitInstance = limitValue.getLongValue();
                            usageInstance.setLimit(limitInstance);
                        }

                        JsonNode nameValue = valueValue.get("name");
                        if (nameValue != null && nameValue instanceof NullNode == false) {
                            UsageName nameInstance = new UsageName();
                            usageInstance.setName(nameInstance);

                            JsonNode valueValue2 = nameValue.get("value");
                            if (valueValue2 != null && valueValue2 instanceof NullNode == false) {
                                String valueInstance;
                                valueInstance = valueValue2.getTextValue();
                                nameInstance.setValue(valueInstance);
                            }

                            JsonNode localizedValueValue = nameValue.get("localizedValue");
                            if (localizedValueValue != null
                                    && localizedValueValue instanceof NullNode == false) {
                                String localizedValueInstance;
                                localizedValueInstance = localizedValueValue.getTextValue();
                                nameInstance.setLocalizedValue(localizedValueInstance);
                            }
                        }
                    }
                }
            }

        }
        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.hx.template.ui.RegisterActivity.java

private boolean checkPhone() {
    if (TextUtils.isEmpty(username.getText().toString().trim())) {
        ToastUtils.showToast(getApplicationContext(), "???");
        return false;
    }/* w  w w.j  a  v  a2s. c o m*/
    if (!(Pattern.matches(Constant.phoneFormat, username.getText().toString().trim()))) {
        ToastUtils.showToast(getApplicationContext(), "??");
        return false;
    }
    return true;
}

From source file:com.lfrj.diancan.http.BinaryHttpResponseHandler.java

@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders(AsyncHttpClient.HEADER_CONTENT_TYPE);
    if (contentTypeHeaders.length != 1) {
        // malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(
                status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;//from w  ww .  j  a va  2 s .co  m
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
            Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e);
        }
    }
    if (!foundAllowedContentType) {
        // Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null,
                new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}

From source file:com.amytech.android.library.utils.asynchttp.BinaryHttpResponseHandler.java

@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders(AsyncHttpClient.HEADER_CONTENT_TYPE);
    if (contentTypeHeaders.length != 1) {
        // malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(
                status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;/*from w  w  w.jav a  2s.  c  o m*/
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
            Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e);
        }
    }
    if (!foundAllowedContentType) {
        // Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(
                status.getStatusCode(), "Content-Type (" + contentTypeHeader.getValue() + ") not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}

From source file:mobile.service.RNSService.java

/**
 * ?//from  w ww .  ja v  a2  s . c  o m
 *
 * @param title      
 * @param industryId Id
 * @param info       ??
 * @param price      
 * @param skillsTags 
 * @param attachs    ?Id??
 * @return
 */
public static ServiceVOResult<CommonVO> createService(String title, Long industryId, String info, String price,
        List<String> skillsTags, List<Long> attachs) {
    if (StringUtils.isBlank(title)) {
        return ServiceVOResult.error("100005", "?");
    }
    SkillTag tag = SkillTag.getTagById(industryId);
    if (null == tag || tag.getTagType() != SkillTag.TagType.CATEGORY) {
        return ServiceVOResult.error("100005", "Id" + industryId);
    }
    if (!Pattern.matches("^\\d{0,8}(\\.\\d)?$", price) && !"-1".equals(price)) {
        return ServiceVOResult.error("100005", "??8?1??");
    }
    if (null != attachs && attachs.size() > 5) {
        return ServiceVOResult.error("1005", "???");
    }

    ObjectNode data = Json.newObject();
    data.put("title", title);
    data.put("info", info);
    data.put("price", price);
    data.put("industry", industryId);
    data.set("tags", Json.toJson(skillsTags));
    if (null != attachs) {
        ArrayNode attachsNode = Json.newObject().arrayNode();
        for (Long attachId : attachs) {
            ObjectNode attachNode = Json.newObject();
            attachNode.put("attachId", attachId);
            attachsNode.add(attachNode);
        }
        data.set("attachs", attachsNode);
    }

    ObjectNodeResult objectNodeResult = new ObjectNodeResult();
    ServiceResult createResult = createOrUpdateService(data, objectNodeResult);
    if (!createResult.isSuccess()) {
        return ServiceVOResult.create(createResult);
    }

    if (!objectNodeResult.isSuccess()) {
        if ("800002".equals(objectNodeResult.getErrorCode())) {
            return ServiceVOResult.error("1002", objectNodeResult.getError());
        }
        Logger.error(objectNodeResult.getObjectNode().toString());
        return ServiceVOResult.error("100001", "");
    }

    CommonVO vo = CommonVO.create();
    vo.set("serviceId", objectNodeResult.getObjectNode().path("serviceId").asLong(-1));

    return ServiceVOResult.success(vo);
}

From source file:com.wyb.utils.util.PatternUtil.java

/**
 * ?/*from w w w .  ja va  2  s .  c o  m*/
 *
 * @param chinese 
 * @return ??true?false
 */
public static boolean isChinese(String chinese) {
    if (StringUtils.isNotBlank(chinese)) {
        String regex = "^[\u4E00-\u9FA5]+$";
        return Pattern.matches(regex, chinese);
    }
    return false;
}

From source file:fi.mikuz.boarder.gui.ZipImporter.java

@SuppressWarnings("rawtypes")
public void unzipArchive(final File archive, final File outputDir) {

    Thread t = new Thread() {
        public void run() {
            Looper.prepare();/*from ww w  .j  av a 2  s .co  m*/
            String archiveName = archive.getName();
            String boardName = archiveName.substring(0, archiveName.indexOf(".zip"));
            String boardDirectory = SoundboardMenu.mSbDir.getAbsolutePath() + "/" + boardName;

            try {
                File boardDirectoryFile = new File(boardDirectory);
                if (boardDirectoryFile.exists()) {
                    postMessage(boardDirectoryFile.getName() + " already exists.");
                } else {
                    ZipFile zipfile = new ZipFile(archive);
                    boolean normalStructure = true;

                    log = "Checking if zip structure is legal\n" + log;
                    for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
                        ZipEntry entry = (ZipEntry) e.nextElement();
                        File outputFile = new File(outputDir, entry.getName());

                        if (!Pattern.matches(boardDirectory + ".*", outputFile.getAbsolutePath())) {
                            normalStructure = false;
                            log = entry.getName() + " failed\n" + outputFile.getAbsolutePath()
                                    + "\ndoens't match\n" + boardDirectory + "\n\n" + log;
                            Log.e(TAG, entry.getName() + " failed\n" + outputFile.getAbsolutePath()
                                    + "\ndoens't match\n" + boardDirectory);
                        }
                    }

                    if (normalStructure) {
                        log = "\nGoing to extract\n" + log;
                        outputDir.mkdirs();
                        for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
                            ZipEntry entry = (ZipEntry) e.nextElement();
                            log = "Extracting " + entry.getName() + "\n" + log;
                            postMessage("Please wait\n\n" + log);
                            unzipEntry(zipfile, entry, outputDir);
                        }
                        log = "Success\n\n" + log;
                        postMessage(log);
                    } else {
                        postMessage("Zip was not extracted because it doesn't follow the normal structure.\n\n"
                                + "Please use another application to check the content of this zip file and extract it if you want to.\n\n"
                                + log);
                    }

                }
            } catch (Exception e) {
                log = "Couldn't extract " + archive + "\n\nError: \n" + e.getMessage() + "\n\n" + log;
                postMessage(log);
                Log.e(TAG, "Error while extracting file " + archive, e);
            }
            mHandler.post(showContinueButton);
        }
    };
    t.start();
}

From source file:com.microsoft.azure.management.compute.UsageOperationsImpl.java

/**
* Lists compute usages for a subscription.
*
* @param location Required. The location upon which resource usage is
* queried./* ww w. ja v a 2  s.c  o m*/
* @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 The List Usages operation response.
*/
@Override
public ListUsagesResponse list(String location) throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (location == null) {
        throw new NullPointerException("location");
    }
    if (location != null && location.length() > 1000) {
        throw new IllegalArgumentException("location");
    }
    if (Pattern.matches("^[-\\w\\._]+$", location) == false) {
        throw new IllegalArgumentException("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("location", location);
        CloudTracing.enter(invocationId, this, "listAsync", 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 + "/providers/";
    url = url + "Microsoft.Compute";
    url = url + "/locations/";
    url = url + URLEncoder.encode(location, "UTF-8");
    url = url + "/usages";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-06-15");
    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");

    // 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) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        ListUsagesResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ListUsagesResponse();
            ObjectMapper objectMapper = new ObjectMapper();
            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) {
                JsonNode valueArray = responseDoc.get("value");
                if (valueArray != null && valueArray instanceof NullNode == false) {
                    for (JsonNode valueValue : ((ArrayNode) valueArray)) {
                        Usage usageInstance = new Usage();
                        result.getUsages().add(usageInstance);

                        JsonNode unitValue = valueValue.get("unit");
                        if (unitValue != null && unitValue instanceof NullNode == false) {
                            UsageUnit unitInstance;
                            unitInstance = Enum.valueOf(UsageUnit.class, unitValue.getTextValue());
                            usageInstance.setUnit(unitInstance);
                        }

                        JsonNode currentValueValue = valueValue.get("currentValue");
                        if (currentValueValue != null && currentValueValue instanceof NullNode == false) {
                            int currentValueInstance;
                            currentValueInstance = currentValueValue.getIntValue();
                            usageInstance.setCurrentValue(currentValueInstance);
                        }

                        JsonNode limitValue = valueValue.get("limit");
                        if (limitValue != null && limitValue instanceof NullNode == false) {
                            long limitInstance;
                            limitInstance = limitValue.getLongValue();
                            usageInstance.setLimit(limitInstance);
                        }

                        JsonNode nameValue = valueValue.get("name");
                        if (nameValue != null && nameValue instanceof NullNode == false) {
                            UsageName nameInstance = new UsageName();
                            usageInstance.setName(nameInstance);

                            JsonNode valueValue2 = nameValue.get("value");
                            if (valueValue2 != null && valueValue2 instanceof NullNode == false) {
                                String valueInstance;
                                valueInstance = valueValue2.getTextValue();
                                nameInstance.setValue(valueInstance);
                            }

                            JsonNode localizedValueValue = nameValue.get("localizedValue");
                            if (localizedValueValue != null
                                    && localizedValueValue instanceof NullNode == false) {
                                String localizedValueInstance;
                                localizedValueInstance = localizedValueValue.getTextValue();
                                nameInstance.setLocalizedValue(localizedValueInstance);
                            }
                        }
                    }
                }
            }

        }
        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.todoist.TodoistBase.java

protected <T> T execute(HttpGet request, final TypeReference<T> typeReference) {
    try {/*from ww w . jav a 2  s. c  o  m*/
        ResponseHandler<T> handler = new ResponseHandler<T>() {
            public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                String answer = EntityUtils.toString(response.getEntity());
                System.out.println("response: " + answer);

                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new TodoistException(response.getStatusLine().getReasonPhrase());
                }

                if (Pattern.matches("\".*\"", answer)) {
                    throw new TodoistException(answer);
                }

                return objectMapper.readValue(answer, typeReference);
            }
        };

        return client.execute(request, handler);
    } catch (ClientProtocolException e) {
        throw new TodoistException(e);
    } catch (IOException e) {
        throw new TodoistException(e);
    }
}