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:ea.compoment.http.BinaryHttpResponseHandler.java

@Override
protected void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or MORE than one, Content-Type Header found!"), responseBody);
        return;/* w  ww  . j  av a  2  s  .c om*/
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody);
    }
}

From source file:cn.xdf.thinkutils.http2.BinaryHttpResponseHandler.java

@Override
protected void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;/* w  ww . j a  v a  2 s .  c  o m*/
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody);
    }
}

From source file:cn.caimatou.canting.utils.http.asynchttp.BinaryHttpResponseHandler.java

@Override
void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;//from www  . j a v  a 2s  .  c  o m
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody);
    }
}

From source file:edu.harvard.iq.dataverse.api.HarvestingServer.java

/**
 * create an OAI set from spec in path and other parameters from POST body
 * (as JSON). {"name":$set_name,//  w ww .jav  a2s . co m
 * "description":$optional_set_description,"definition":$set_search_query_string}.
 */
@POST
@Path("{specname}")
public Response createOaiSet(String jsonBody, @PathParam("specname") String spec,
        @QueryParam("key") String apiKey) throws IOException, JsonParseException {
    /*
    * authorization modeled after the UI (aka HarvestingSetsPage)
     */
    AuthenticatedUser dvUser;
    try {
        dvUser = findAuthenticatedUserOrDie();
    } catch (WrappedResponse wr) {
        return wr.getResponse();
    }
    if (!dvUser.isSuperuser()) {
        return badRequest(ResourceBundle.getBundle("Bundle")
                .getString("harvestserver.newSetDialog.setspec.superUser.required"));
    }

    StringReader rdr = new StringReader(jsonBody);

    try (JsonReader jrdr = Json.createReader(rdr)) {
        JsonObject json = jrdr.readObject();

        OAISet set = new OAISet();
        //Validating spec 
        if (!StringUtils.isEmpty(spec)) {
            if (spec.length() > 30) {
                return badRequest(ResourceBundle.getBundle("Bundle")
                        .getString("harvestserver.newSetDialog.setspec.sizelimit"));
            }
            if (!Pattern.matches("^[a-zA-Z0-9\\_\\-]+$", spec)) {
                return badRequest(ResourceBundle.getBundle("Bundle")
                        .getString("harvestserver.newSetDialog.setspec.invalid"));
                // If it passes the regex test, check 
            }
            if (oaiSetService.findBySpec(spec) != null) {
                return badRequest(ResourceBundle.getBundle("Bundle")
                        .getString("harvestserver.newSetDialog.setspec.alreadyused"));
            }

        } else {
            return badRequest(ResourceBundle.getBundle("Bundle")
                    .getString("harvestserver.newSetDialog.setspec.required"));
        }
        set.setSpec(spec);
        String name, desc, defn;

        try {
            name = json.getString("name");
        } catch (NullPointerException npe_name) {
            return badRequest(ResourceBundle.getBundle("Bundle")
                    .getString("harvestserver.newSetDialog.setspec.required"));
        }
        try {
            defn = json.getString("definition");
        } catch (NullPointerException npe_defn) {
            throw new JsonParseException("definition unspecified");
        }
        try {
            desc = json.getString("description");
        } catch (NullPointerException npe_desc) {
            desc = ""; //treating description as optional
        }
        set.setName(name);
        set.setDescription(desc);
        set.setDefinition(defn);
        oaiSetService.save(set);
        return created("/harvest/server/oaisets" + spec, oaiSetAsJson(set));
    }

}

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

/**
* Get a list of deployments operations.//from w ww  .j  a v a 2s .c  om
*
* @param resourceGroupName Required. The name of the resource group. The
* name is case insensitive.
* @param deploymentName Required. The name of the deployment.
* @param operationId Required. Operation Id.
* @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 Deployment operation.
*/
@Override
public DeploymentOperationsGetResult get(String resourceGroupName, String deploymentName, String operationId)
        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 (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (operationId == null) {
        throw new NullPointerException("operationId");
    }

    // 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);
        tracingParameters.put("operationId", operationId);
        CloudTracing.enter(invocationId, this, "getAsync", 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");
    url = url + "/operations/";
    url = url + URLEncoder.encode(operationId, "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
    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) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        DeploymentOperationsGetResult result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DeploymentOperationsGetResult();
            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) {
                DeploymentOperation operationInstance = new DeploymentOperation();
                result.setOperation(operationInstance);

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

                JsonNode operationIdValue = responseDoc.get("operationId");
                if (operationIdValue != null && operationIdValue instanceof NullNode == false) {
                    String operationIdInstance;
                    operationIdInstance = operationIdValue.getTextValue();
                    operationInstance.setOperationId(operationIdInstance);
                }

                JsonNode propertiesValue = responseDoc.get("properties");
                if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                    DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties();
                    operationInstance.setProperties(propertiesInstance);

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

                    JsonNode timestampValue = propertiesValue.get("timestamp");
                    if (timestampValue != null && timestampValue instanceof NullNode == false) {
                        Calendar timestampInstance;
                        timestampInstance = DatatypeConverter.parseDateTime(timestampValue.getTextValue());
                        propertiesInstance.setTimestamp(timestampInstance);
                    }

                    JsonNode statusCodeValue = propertiesValue.get("statusCode");
                    if (statusCodeValue != null && statusCodeValue instanceof NullNode == false) {
                        String statusCodeInstance;
                        statusCodeInstance = statusCodeValue.getTextValue();
                        propertiesInstance.setStatusCode(statusCodeInstance);
                    }

                    JsonNode statusMessageValue = propertiesValue.get("statusMessage");
                    if (statusMessageValue != null && statusMessageValue instanceof NullNode == false) {
                        String statusMessageInstance;
                        statusMessageInstance = statusMessageValue.getTextValue();
                        propertiesInstance.setStatusMessage(statusMessageInstance);
                    }

                    JsonNode targetResourceValue = propertiesValue.get("targetResource");
                    if (targetResourceValue != null && targetResourceValue instanceof NullNode == false) {
                        TargetResource targetResourceInstance = new TargetResource();
                        propertiesInstance.setTargetResource(targetResourceInstance);

                        JsonNode idValue2 = targetResourceValue.get("id");
                        if (idValue2 != null && idValue2 instanceof NullNode == false) {
                            String idInstance2;
                            idInstance2 = idValue2.getTextValue();
                            targetResourceInstance.setId(idInstance2);
                        }

                        JsonNode resourceNameValue = targetResourceValue.get("resourceName");
                        if (resourceNameValue != null && resourceNameValue instanceof NullNode == false) {
                            String resourceNameInstance;
                            resourceNameInstance = resourceNameValue.getTextValue();
                            targetResourceInstance.setResourceName(resourceNameInstance);
                        }

                        JsonNode resourceTypeValue = targetResourceValue.get("resourceType");
                        if (resourceTypeValue != null && resourceTypeValue instanceof NullNode == false) {
                            String resourceTypeInstance;
                            resourceTypeInstance = resourceTypeValue.getTextValue();
                            targetResourceInstance.setResourceType(resourceTypeInstance);
                        }
                    }
                }
            }

        }
        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.cloudsynch.quickshare.http.BinaryHttpResponseHandler.java

@Override
void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        // malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;//from   w  ww .  j  a v  a 2s.  c  o  m
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        // Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody);
    }
}

From source file:com.pyj.http.BinaryHttpResponseHandler.java

@Override
void sendResponseMessage(HttpResponse response, int reqType) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody, reqType);
        return;/*from ww w  .  j a  va 2  s.  c  o  m*/
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody, reqType);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null, reqType);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody, reqType);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody, reqType);
    }
}

From source file:com.fanniemae.ezpie.common.StringUtilities.java

public static boolean isDouble(String value) {
    if (isNullOrEmpty(value))
        return false;
    value = value.trim();//from   ww w . j a v  a2  s  .c  o  m
    if (value.indexOf('.') == -1)
        return false;
    return Pattern.matches(DOUBLE_REGEX, value);
}

From source file:cn.kuwo.sing.phone4tv.commons.http.BinaryHttpResponseHandler.java

@Override
void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;//from   w ww . j a  v a  2s  . c o m
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (anAllowedContentType.equals("*")
                || Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody);
    }
}

From source file:com.adobe.people.jedelson.cq.urlfilter.impl.UrlFilter.java

boolean check(String value, String allowedArrayPropertyName, String allowedPatternPropertyName,
        ValueMap properties) {//from   w w  w. ja va2  s  .  c om
    if (value == null) {
        // no value is always allowed
        return true;
    }
    String[] allowedValues = properties.get(allowedArrayPropertyName, String[].class);
    if (allowedValues != null) {
        if (allowedValues.length == 0) {
            logger.debug("{} was empty, therefore not allowing any value.", allowedArrayPropertyName);
            return false;
        } else if (!ArrayUtils.contains(allowedValues, value)) {
            logger.debug("{} did not contain our string {}. checking the pattern.", allowedArrayPropertyName,
                    value);
            String allowedPattern = properties.get(allowedPatternPropertyName, String.class);
            if (allowedPattern == null || !Pattern.matches(allowedPattern, value)) {
                logger.debug("allowedPattern ({}) did not match our string {}", allowedPattern, value);
                return false;
            } else {
                logger.debug("allowedPattern ({}) did match our string {}", allowedPattern, value);
                return true;
            }
        } else {
            return true;
        }
    } else {
        String allowedPattern = properties.get(allowedPatternPropertyName, String.class);
        if (allowedPattern != null && !Pattern.matches(allowedPattern, value)) {
            logger.debug("allowedPattern ({}) did not match our string {}", allowedPattern, value);
            return false;
        } else {
            return true;
        }
    }
}