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:fr.paris.lutece.plugins.calendar.web.CalendarJspBean.java

/**
 * Process the Event modifications// w  ww. j  av  a 2s .  c o  m
 * 
 * @param request The Http request
 * @return Html form
 */
public String doModifyEvent(HttpServletRequest request) {
    //Retrieving the event object to update
    SimpleEvent event = CalendarHome
            .findEvent(Integer.parseInt(request.getParameter(Constants.PARAMETER_EVENT_ID)), getPlugin());

    //Retrieving parameters from form
    int nCalendarId = Integer.parseInt(request.getParameter(Constants.PARAMETER_CALENDAR_ID));

    String strEventTitle = (String) _mapParameters.get(Constants.PARAMETER_EVENT_TITLE);
    String strTopEvent = (String) _mapParameters.get(Constants.PARAMETER_EVENT_TOP_EVENT);
    String strEventDate = (String) _mapParameters.get(Constants.PARAMETER_EVENT_DATE);

    boolean bPeriociteModify = false;

    // Mandatory field: the date, the title and the description fields
    if (strEventDate.equals("") || strEventTitle.equals("") || _EventDescription.equals("")) {
        return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP);
    }

    //Convert the date in form to a java.util.Date object
    Date dateEvent = DateUtil.formatDate(strEventDate, getLocale());
    Date dateEventOld = event.getDate();

    //If event date is different, periodicity is re-initialized
    if (dateEvent.getTime() != dateEventOld.getTime()) {
        bPeriociteModify = true;
    }

    if (!Utils.isValidDate(dateEvent)) {
        return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATEFORMAT,
                AdminMessage.TYPE_STOP);
    }

    //Fields to Update
    event.setDate(dateEvent);
    event.setTitle(strEventTitle);
    event.setTopEvent(Integer.parseInt(strTopEvent));
    event.setDescription(_EventDescription);

    //String strOccurrence = request.getParameter( Constants.PARAMETER_OCCURRENCE );
    String strEventDateEnd = (String) _mapParameters.get(Constants.PARAMETER_EVENT_DATE_END);

    int nPeriodicity = event.getPeriodicity();

    Date dateEndEvent = null;

    if (StringUtils.isNotEmpty(strEventDateEnd)) {
        dateEndEvent = DateUtil.formatDate(strEventDateEnd, getLocale());

        if ((dateEndEvent == null) || !Utils.isValidDate(dateEndEvent)) {
            return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATEFORMAT,
                    AdminMessage.TYPE_STOP);
        }
    }

    //the number of occurrence is -1 by default
    int nOccurrence = -1;

    String[] arrayExcludedDays = (String[]) _mapParameters.get(Constants.PARAMETER_EXCLUDED_DAYS);
    boolean bExcludedDaysModified = false;
    if (arrayExcludedDays == null && event.getExcludedDays() != null && event.getExcludedDays().length != 0) {
        bExcludedDaysModified = true;
    } else if (arrayExcludedDays != null && (event.getExcludedDays() == null
            || (event.getExcludedDays() != null && event.getExcludedDays().length == 0))) {
        bExcludedDaysModified = true;
    } else if (arrayExcludedDays != null && event.getExcludedDays() != null
            && arrayExcludedDays.length != event.getExcludedDays().length) {
        bExcludedDaysModified = true;
    } else if (arrayExcludedDays != null && event.getExcludedDays() != null
            && event.getExcludedDays().length != 0
            && arrayExcludedDays.length == event.getExcludedDays().length) {
        for (int i = 0; i < arrayExcludedDays.length; i++) {
            if (!arrayExcludedDays[i].equals(event.getExcludedDays()[i])) {
                bExcludedDaysModified = true;
                break;
            }
        }
    }

    //compute the occurrence number depending on the date end chosen
    //If a date end is chosen
    if (dateEndEvent != null && (StringUtils.isNotEmpty(strEventDateEnd)
            && (event.getDateEnd().getTime() != dateEndEvent.getTime()) || bExcludedDaysModified)) {
        if (dateEndEvent.before(dateEvent)) {
            return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATE_END_BEFORE,
                    AdminMessage.TYPE_STOP);
        }
        nPeriodicity = 0;
        nOccurrence = Utils.getOccurrenceWithinTwoDates(dateEvent, dateEndEvent, arrayExcludedDays);
        bPeriociteModify = true;
    } else if (StringUtils.isEmpty(strEventDateEnd)) {
        return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATEFORMAT,
                AdminMessage.TYPE_STOP);
    }

    // Fields to Update
    if (nOccurrence > 0) {
        event.setOccurrence(nOccurrence);
    }

    event.setDateEnd(dateEndEvent);
    event.setPeriodicity(nPeriodicity);

    String strTimeStart = (String) _mapParameters.get(Constants.PARAMETER_EVENT_TIME_START);
    String strTimeEnd = (String) _mapParameters.get(Constants.PARAMETER_EVENT_TIME_END);
    String strEventTags = ((String) _mapParameters.get(Constants.PARAMETER_EVENT_TAGS)).trim();
    String strLocationAddress = ((String) _mapParameters.get(Constants.PARAMETER_EVENT_LOCATION_ADDRESS))
            .trim();
    String strLocation = ((String) _mapParameters.get(Constants.PARAMETER_LOCATION)).trim();
    String strLocationTown = ((String) _mapParameters.get(Constants.PARAMETER_LOCATION_TOWN)).trim();
    String strLocationZip = ((String) _mapParameters.get(Constants.PARAMETER_LOCATION_ZIP)).trim();
    String strLinkUrl = ((String) _mapParameters.get(Constants.PARAMETER_EVENT_LINK_URL)).trim();
    String strDocumentId = ((String) _mapParameters.get(Constants.PARAMETER_EVENT_DOCUMENT_ID)).trim();
    String strPageUrl = ((String) _mapParameters.get(Constants.PARAMETER_EVENT_PAGE_URL)).trim();
    String strMapUrl = ((String) _mapParameters.get(Constants.PARAMETER_EVENT_MAP_URL)).trim();

    //Tags
    String[] strTabEventTags = null;

    if ((strEventTags.length() > 0) && !strEventTags.equals("")) {
        //Test if there aren't special characters in strEventTags
        boolean isAllowedExp = Pattern.matches(PROPERTY_TAGS_REGEXP, strEventTags);

        if (!isAllowedExp) {
            return AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_TAG, AdminMessage.TYPE_STOP);
        }

        strTabEventTags = strEventTags.split("\\s");
    }

    //Categories
    List<Category> listCategories = new ArrayList<Category>();

    if (_EventCategories != null) {
        for (String strIdCategory : _EventCategories) {
            Category category = CategoryHome.find(Integer.parseInt(strIdCategory), getPlugin());

            if (category != null) {
                listCategories.add(category);
            }
        }
    }

    // Hours
    if (!Utils.checkTime(strTimeStart) || !Utils.checkTime(strTimeEnd)) {
        return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_TIMEFORMAT,
                AdminMessage.TYPE_STOP);
    }

    // Document
    int nDocumentId = -1;

    if ((strDocumentId.length() > 0) && !strDocumentId.equals("")) {
        try {
            nDocumentId = Integer.parseInt(strDocumentId);
        } catch (NumberFormatException e) {
            return AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_OCCURRENCE_NUMBER,
                    AdminMessage.TYPE_STOP);
        }
    }

    event.setTags(strTabEventTags);
    event.setDocumentId(nDocumentId);
    event.setListCategories(listCategories);
    event.setDateTimeStart(strTimeStart);
    event.setDateTimeEnd(strTimeEnd);
    event.setLocation(strLocation);
    event.setLocationAddress(strLocationAddress);
    event.setLocationTown(strLocationTown);
    event.setLocationZip(strLocationZip);
    event.setLinkUrl(strLinkUrl);
    event.setPageUrl(strPageUrl);
    event.setMapUrl(strMapUrl);
    event.setExcludedDays(arrayExcludedDays);

    if (_EventItem.getSize() >= 1) {
        ImageResource imageResource = new ImageResource();
        imageResource.setImage(_EventItem.get());
        imageResource.setMimeType(_EventItem.getContentType());
        event.setImageResource(imageResource);
    }

    _eventListService.doModifySimpleEvent(event, bPeriociteModify, null, getPlugin());

    List<OccurrenceEvent> listOccurencesEvent = _eventListService.getOccurrenceEvents(nCalendarId,
            event.getId(), Constants.SORT_ASC, getPlugin());

    for (OccurrenceEvent occ : listOccurencesEvent) {
        //Update occurence
        if (StringUtils.isBlank(occ.getDateTimeStart())) {
            occ.setDateTimeStart(event.getDateTimeStart());
        }

        if (StringUtils.isBlank(occ.getDateTimeEnd())) {
            occ.setDateTimeEnd(event.getDateTimeEnd());
        }

        // FIXME : Usefull ?
        //CalendarHome.updateOccurrence( occ, nCalendarId, getPlugin(  ) );

        // Index Occurrence
        IndexationService.addIndexerAction(Integer.toString(occ.getId()),
                AppPropertiesService.getProperty(CalendarIndexer.PROPERTY_INDEXER_NAME),
                IndexerAction.TASK_MODIFY);
        CalendarIndexerUtils.addIndexerAction(occ.getId(), IndexerAction.TASK_MODIFY);
    }

    _mapParameters = null;

    return JSP_EVENT_LIST + nCalendarId + "&" + Constants.PARAMETER_SORT_EVENTS + "="
            + request.getParameter(Constants.PARAMETER_SORT_EVENTS);
}

From source file:eu.apenet.dpt.standalone.gui.eaccpf.EacCpfPanel.java

protected static boolean matchWithDatePatterns(String text) {
    boolean pattern1 = Pattern.matches("\\d{4}", text); //yyyy
    boolean pattern2 = Pattern.matches("\\d{4}[\\-\\./:\\s]\\d{2}", text); //yyyy-MM
    boolean pattern3 = Pattern.matches("\\d{4}[\\-\\./:\\s]\\d{2}[\\-\\./:\\s]\\d{2}", text); //yyyy-MM-dd
    boolean pattern4 = Pattern.matches("\\d{2}[\\-\\./:\\s]\\d{2}[\\-\\./:\\s]\\d{4}", text); //dd-MM-yyyy
    boolean pattern5 = Pattern.matches("\\d{1}[\\-\\./:\\s]\\d{1}[\\-\\./:\\s]\\d{4}", text); //d-M-yyyy
    boolean pattern6 = Pattern.matches("\\d{1}[\\-\\./:\\s]\\d{2}[\\-\\./:\\s]\\d{4}", text); //d-MM-yyyy
    boolean pattern7 = Pattern.matches("\\d{2}[\\-\\./:\\s]\\d{1}[\\-\\./:\\s]\\d{4}", text); //dd-M-yyyy
    boolean pattern8 = Pattern.matches("\\d{4}[\\-\\./:\\s]\\d{1}[\\-\\./:\\s]\\d{2}", text); //yyyy-M-dd
    boolean pattern9 = Pattern.matches("\\d{4}[\\-\\./:\\s]\\d{2}[\\-\\./:\\s]\\d{1}", text); //yyyy-MM-d
    boolean pattern0 = Pattern.matches("\\d{4}[\\-\\./:\\s]\\d{1}[\\-\\./:\\s]\\d{1}", text); //yyyy-M-d
    return pattern0 || pattern1 || pattern2 || pattern3 || pattern4 || pattern5 || pattern6 || pattern7
            || pattern8 || pattern9;/*from   w ww .  ja va 2  s .c  o m*/
}

From source file:jp.primecloud.auto.service.impl.LoadBalancerServiceImpl.java

/**
 * {@inheritDoc}/*from  ww w  .jav a  2  s. c o m*/
 */
@Override
public void updateCloudstackLoadBalancer(Long loadBalancerNo, String loadBalancerName, String comment,
        Long componentNo, String algorithm, String pubricPort, String privatePort) {
    // ?
    if (loadBalancerNo == null) {
        throw new AutoApplicationException("ECOMMON-000003", "loadBalancerNo");
    }
    if (loadBalancerName == null || loadBalancerName.length() == 0) {
        throw new AutoApplicationException("ECOMMON-000003", "loadBalancerName");
    }
    if (componentNo == null) {
        throw new AutoApplicationException("ECOMMON-000003", "componentNo");
    }

    if (algorithm == null) {
        throw new AutoApplicationException("ECOMMON-000003", "algorithm");
    }

    if (pubricPort == null) {
        throw new AutoApplicationException("ECOMMON-000003", "pubricPort");
    }

    if (privatePort == null) {
        throw new AutoApplicationException("ECOMMON-000003", "privatePort");
    }

    // ??
    if (!Pattern.matches("^[0-9a-z]|[0-9a-z][0-9a-z-]*[0-9a-z]$", loadBalancerName)) {
        throw new AutoApplicationException("ECOMMON-000012", "loadBalancerName");
    }

    // TODO: ??

    // ???
    LoadBalancer loadBalancer = loadBalancerDao.read(loadBalancerNo);
    CloudstackLoadBalancer csloadBalancer = cloudstackLoadBalancerDao.read(loadBalancerNo);
    if (loadBalancer == null) {
        // ??????
        throw new AutoApplicationException("ESERVICE-000603", loadBalancerNo);
    }

    // ???????
    if (LoadBalancerStatus.fromStatus(loadBalancer.getStatus()) != LoadBalancerStatus.STOPPED) {
        // ??????????????????
        if (!StringUtils.equals(loadBalancer.getLoadBalancerName(), loadBalancerName)
                || !componentNo.equals(loadBalancer.getComponentNo())) {
            throw new AutoApplicationException("ESERVICE-000604", loadBalancer.getLoadBalancerName());
        }
        if (!StringUtils.equals(csloadBalancer.getAlgorithm(), algorithm)
                || !StringUtils.equals(csloadBalancer.getPublicport(), pubricPort)
                || !StringUtils.equals(csloadBalancer.getPrivateport(), privatePort)) {
            throw new AutoApplicationException("ESERVICE-000604", loadBalancer.getLoadBalancerName());
        }
    }

    // ?????
    if (!StringUtils.equals(loadBalancer.getLoadBalancerName(), loadBalancerName)) {
        // ??????
        LoadBalancer checkLoadBalancer = loadBalancerDao
                .readByFarmNoAndLoadBalancerName(loadBalancer.getFarmNo(), loadBalancerName);
        if (checkLoadBalancer != null && !loadBalancerNo.equals(checkLoadBalancer.getLoadBalancerNo())) {
            // ????????
            throw new AutoApplicationException("ESERVICE-000601", loadBalancerName);
        }

        // ????
        Instance checkInstance = instanceDao.readByFarmNoAndInstanceName(loadBalancer.getFarmNo(),
                loadBalancerName);
        if (checkInstance != null) {
            // ???????
            throw new AutoApplicationException("ESERVICE-000626", loadBalancerName);
        }
    }

    // ????
    long countComponent = componentDao.countByComponentNo(componentNo);
    if (countComponent == 0) {
        // ???????
        throw new AutoApplicationException("ESERVICE-000607", componentNo);
    }

    Farm farm = farmDao.read(loadBalancer.getFarmNo());
    // ??
    loadBalancer.setLoadBalancerName(loadBalancerName);
    loadBalancer.setComment(comment);
    loadBalancer.setFqdn(loadBalancerName + "." + farm.getDomainName());
    loadBalancer.setComponentNo(componentNo);
    loadBalancerDao.update(loadBalancer);

    // ??
    csloadBalancer.setAlgorithm(algorithm);
    csloadBalancer.setPublicport(pubricPort);
    csloadBalancer.setPrivateport(privatePort);
    cloudstackLoadBalancerDao.update(csloadBalancer);

    // 
    eventLogger.log(EventLogLevel.INFO, farm.getFarmNo(), farm.getFarmName(), null, null, null, null,
            "LoadBalancerUpdate", null, null, new Object[] { loadBalancerName });
}

From source file:eu.apenet.dpt.standalone.gui.eaccpf.EacCpfPanel.java

/**
 * Method to parse the value of the date to an ISO one if possible.
 *
 * @param text//from  w w  w . j  av a  2  s  .c om
 * @return the ISO date.
 */
protected static String parseStandardDate(String text) {
    String yearStandardDate = "";
    String monthStandardDate = "";
    String dateStandardDate = "";
    String reverseString = "";
    String type = "ymd";

    boolean pattern1 = Pattern.matches("\\d{4}", text); //yyyy
    boolean pattern2 = Pattern.matches("\\d{4}[\\-\\./:\\s]\\d{2}", text); //yyyy-MM
    boolean pattern3 = Pattern.matches("\\d{4}[\\-\\./:\\s]\\d{2}[\\-\\./:\\s]\\d{2}", text); //yyyy-MM-dd
    boolean pattern4 = Pattern.matches("\\d{2}[\\-\\./:\\s]\\d{2}[\\-\\./:\\s]\\d{4}", text); //dd-MM-yyyy
    boolean pattern5 = Pattern.matches("\\d{1}[\\-\\./:\\s]\\d{1}[\\-\\./:\\s]\\d{4}", text); //d-M-yyyy
    boolean pattern6 = Pattern.matches("\\d{1}[\\-\\./:\\s]\\d{2}[\\-\\./:\\s]\\d{4}", text); //d-MM-yyyy
    boolean pattern7 = Pattern.matches("\\d{2}[\\-\\./:\\s]\\d{1}[\\-\\./:\\s]\\d{4}", text); //dd-M-yyyy
    boolean pattern8 = Pattern.matches("\\d{4}[\\-\\./:\\s]\\d{1}[\\-\\./:\\s]\\d{2}", text); //yyyy-M-dd
    boolean pattern9 = Pattern.matches("\\d{4}[\\-\\./:\\s]\\d{2}[\\-\\./:\\s]\\d{1}", text); //yyyy-MM-d
    boolean pattern0 = Pattern.matches("\\d{4}[\\-\\./:\\s]\\d{1}[\\-\\./:\\s]\\d{1}", text); //yyyy-M-d

    if (pattern4) {
        yearStandardDate = text.substring(6);
        monthStandardDate = text.substring(2, 6);
        dateStandardDate = text.substring(0, 2);
        reverseString = yearStandardDate + monthStandardDate + dateStandardDate;
        text = text.replaceAll(text, reverseString);
    }
    if (pattern1) {
        type = "y";
    } else if (pattern2) {
        monthStandardDate = text.substring(5, 7);
        if (Integer.parseInt(monthStandardDate) <= 12) {
            text = text.replaceAll("[\\./:\\s]", "-");
        }
        type = "ym";
    } else if (pattern3 || pattern4) {
        text = text.replaceAll("[\\./:\\s]", "-");
    } else if (pattern5) {
        //d-M-yyyy
        yearStandardDate = text.substring(4);
        monthStandardDate = "0" + text.substring(2, 3);
        dateStandardDate = "0" + text.substring(0, 1);
    } else if (pattern6) {
        //d-MM-yyyy
        yearStandardDate = text.substring(5);
        monthStandardDate = text.substring(2, 4);
        dateStandardDate = "0" + text.substring(0, 1);
    } else if (pattern7) {
        //dd-M-yyyy
        yearStandardDate = text.substring(5);
        monthStandardDate = "0" + text.substring(3, 4);
        dateStandardDate = text.substring(0, 2);
    } else if (pattern8) {
        //yyyy-M-dd
        yearStandardDate = text.substring(0, 4);
        monthStandardDate = "0" + text.substring(5, 6);
        dateStandardDate = text.substring(7);
    } else if (pattern9) {
        //yyyy-MM-d
        yearStandardDate = text.substring(0, 4);
        monthStandardDate = text.substring(5, 7);
        dateStandardDate = "0" + text.substring(8);
    } else if (pattern0) {
        //yyyy-M-d
        yearStandardDate = text.substring(0, 4);
        monthStandardDate = "0" + text.substring(5, 6);
        dateStandardDate = "0" + text.substring(7);
    }

    if (pattern5 || pattern6 || pattern7 || pattern8 || pattern9 || pattern0) {
        String strAux = yearStandardDate + "-" + monthStandardDate + "-" + dateStandardDate;
        text = strAux;
    }

    if (isValidDate(text, type))
        return text;
    else
        return "";

}

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

/**
* Resource groups can be updated through a simple PATCH operation to a
* group address. The format of the request is the same as that for
* creating a resource groups, though if a field is unspecified current
* value will be carried over./*  www .  j  a v a  2  s .c o m*/
*
* @param resourceGroupName Required. The name of the resource group to be
* created or updated. The name is case insensitive.
* @param parameters Required. Parameters supplied to the update state
* resource group service operation.
* @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 ResourceGroupPatchResult patch(String resourceGroupName, ResourceGroup parameters)
        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 (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("parameters", parameters);
        CloudTracing.enter(invocationId, this, "patchAsync", 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
    HttpPatch httpRequest = new HttpPatch(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 resourceGroupValue = objectMapper.createObjectNode();
    requestDoc = resourceGroupValue;

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

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

    if (parameters.getTags() != null) {
        if (parameters.getTags() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getTags()).isInitialized()) {
            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) resourceGroupValue).put("tags", tagsDictionary);
        }
    }

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

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

        // Create Result
        ResourceGroupPatchResult result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ResourceGroupPatchResult();
            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) {
                ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
                result.setResourceGroup(resourceGroupInstance);

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

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

                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();
                        resourceGroupInstance.setProvisioningState(provisioningStateInstance);
                    }
                }

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

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

                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();
                        resourceGroupInstance.getTags().put(tagsKey2, tagsValue2);
                    }
                }

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

        }
        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:jp.primecloud.auto.service.impl.LoadBalancerServiceImpl.java

/**
 * {@inheritDoc}/*from   ww  w.  ja  v a2 s  .c  o  m*/
 */
@Override
public void updateUltraMonkeyLoadBalancer(Long loadBalancerNo, String loadBalancerName, String comment,
        Long componentNo) {
    // ?
    if (loadBalancerNo == null) {
        throw new AutoApplicationException("ECOMMON-000003", "loadBalancerNo");
    }
    if (loadBalancerName == null || loadBalancerName.length() == 0) {
        throw new AutoApplicationException("ECOMMON-000003", "loadBalancerName");
    }
    if (componentNo == null) {
        throw new AutoApplicationException("ECOMMON-000003", "componentNo");
    }

    // ??
    if (!Pattern.matches("^[0-9a-z]|[0-9a-z][0-9a-z-]*[0-9a-z]$", loadBalancerName)) {
        throw new AutoApplicationException("ECOMMON-000012", "loadBalancerName");
    }

    // TODO: ??

    // ???
    LoadBalancer loadBalancer = loadBalancerDao.read(loadBalancerNo);
    if (loadBalancer == null) {
        // ??????
        throw new AutoApplicationException("ESERVICE-000603", loadBalancerNo);
    }

    // ???????
    if (LoadBalancerStatus.fromStatus(loadBalancer.getStatus()) != LoadBalancerStatus.STOPPED) {
        // ??????????????????
        if (!StringUtils.equals(loadBalancer.getLoadBalancerName(), loadBalancerName)
                || !componentNo.equals(loadBalancer.getComponentNo())) {
            throw new AutoApplicationException("ESERVICE-000604", loadBalancer.getLoadBalancerName());
        }
    }

    // ??????
    LoadBalancer checkLoadBalancer = loadBalancerDao.readByFarmNoAndLoadBalancerName(loadBalancer.getFarmNo(),
            loadBalancerName);
    if (checkLoadBalancer != null && !loadBalancerNo.equals(checkLoadBalancer.getLoadBalancerNo())) {
        // ????????
        throw new AutoApplicationException("ESERVICE-000601", loadBalancerName);
    }

    // ????
    long countComponent = componentDao.countByComponentNo(componentNo);
    if (countComponent == 0) {
        // ???????
        throw new AutoApplicationException("ESERVICE-000607", componentNo);
    }

    // ???????????
    long countListener = loadBalancerListenerDao.countByLoadBalancerNo(loadBalancerNo);
    if (countListener > 0) {
        if (!loadBalancer.getComponentNo().equals(componentNo)) {
            // ????????
            throw new AutoApplicationException("ESERVICE-000608");
        }
    }

    Farm farm = farmDao.read(loadBalancer.getFarmNo());

    // ??
    loadBalancer.setLoadBalancerName(loadBalancerName);
    loadBalancer.setComment(comment);
    loadBalancer.setFqdn(loadBalancerName + "." + farm.getDomainName());
    loadBalancer.setComponentNo(componentNo);
    loadBalancerDao.update(loadBalancer);

    // 
    eventLogger.log(EventLogLevel.INFO, farm.getFarmNo(), farm.getFarmName(), null, null, null, null,
            "LoadBalancerUpdate", null, null, new Object[] { loadBalancerName });
}

From source file:com.rapidminer.tools.Tools.java

/**
 * Replace quote chars in-quote characters by escapeChar+quotingChar
 *
 * Example: seperatorPatern = ',' , quotingChar = '"' , escapeCahr = '\\'
 *
 * line = '"Charles says://from  w  w  w .j  a  va2  s  .  c  o m
 * "Some people never go crazy, What truly horrible lives they must live"", 1968, "
 * US"' return = '"Charles says:
 * \"Some people never go crazy, What truly horrible lives they must live\"", "1968", "US"'
 */
public static String escapeQuoteCharsInQuotes(String line, Pattern separatorPattern, char quotingChar,
        char escapeChar, boolean showWarning) {
    // first remember quoteChar positions which should be escaped:
    char lastChar = '0';
    boolean openedQuote = false;

    List<Integer> rememberQuotePosition = new LinkedList<>();
    for (int i = 0; i < line.length(); i++) {
        if (lastChar == quotingChar) {
            if (openedQuote) {
                boolean matches = Pattern.matches(separatorPattern.pattern() + ".*", line.substring(i));
                if (matches) {
                    openedQuote = false;
                } else {
                    rememberQuotePosition.add(i - 1);
                }

            } else {
                openedQuote = true;
            }
        }
        lastChar = line.charAt(i);
    }
    if (openedQuote && lastChar == quotingChar) {
        openedQuote = false;
    }

    // print warning
    if (showWarning && !rememberQuotePosition.isEmpty()) {

        StringBuilder positions = new StringBuilder();
        int j = 1;
        for (int i = 0; i < rememberQuotePosition.size(); i++) {
            if (j % 10 == 0) {
                positions.append("\n");
            }
            positions.append(rememberQuotePosition.get(i));
            if (i + 1 < rememberQuotePosition.size()) {
                positions.append(", ");
            }
            j++;
        }

        String lineBeginning = line;
        if (line.length() > 20) {
            lineBeginning = line.substring(0, 20);
        }
        String warning = "While reading the line starting with \n\n\t" + lineBeginning + "   ...\n\n"
                + ",an unescaped quote character was substituted by an escaped quote at the position(s) "
                + positions.toString() + ". " + "In particular der character '" + Character.toString(lastChar)
                + "' was replaced by '" + Character.toString(escapeChar) + Character.toString(lastChar) + ".";

        LogService.getRoot().log(Level.WARNING, warning);
    }

    // then build new line:
    if (!rememberQuotePosition.isEmpty()) {
        String newLine = "";
        int pos = rememberQuotePosition.remove(0);
        int i = 0;
        for (Character c : line.toCharArray()) {
            if (i == pos) {
                newLine += Character.toString(escapeChar) + c;
                if (!rememberQuotePosition.isEmpty()) {
                    pos = rememberQuotePosition.remove(0);
                }
            } else {
                newLine += c;
            }
            i++;
        }
        line = newLine;
    }
    return line;
}

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

/**
* Gets all the management locks of a resource or any level below resource.
*
* @param resourceGroupName Required. The name of the resource group. The
* name is case insensitive.//  ww  w .ja v a  2  s  . c o  m
* @param identity Required. Resource identity.
* @param parameters Optional. Query parameters. If empty is passed returns
* all locks at or below the resource.If atScope() is passed returns all
* locks at the resource level.
* @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 List of management locks.
*/
@Override
public ManagementLockListResult listAtResourceLevel(String resourceGroupName, ResourceIdentity identity,
        ManagementLockGetQueryParameter parameters) 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);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "listAtResourceLevelAsync", 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");
    url = url + "/providers/Microsoft.Authorization/locks";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-01-01");
    ArrayList<String> odataFilter = new ArrayList<String>();
    if (parameters != null && parameters.getAtScope() != null) {
        odataFilter.add(URLEncoder.encode(parameters.getAtScope(), "UTF-8"));
    }
    if (odataFilter.size() > 0) {
        queryParameters.add("$filter=" + CollectionStringBuilder.join(odataFilter, null));
    }
    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
        ManagementLockListResult result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ManagementLockListResult();
            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)) {
                        ManagementLockObject managementLockObjectInstance = new ManagementLockObject();
                        result.getLock().add(managementLockObjectInstance);

                        JsonNode propertiesValue = valueValue.get("properties");
                        if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                            ManagementLockProperties propertiesInstance = new ManagementLockProperties();
                            managementLockObjectInstance.setProperties(propertiesInstance);

                            JsonNode levelValue = propertiesValue.get("level");
                            if (levelValue != null && levelValue instanceof NullNode == false) {
                                String levelInstance;
                                levelInstance = levelValue.getTextValue();
                                propertiesInstance.setLevel(levelInstance);
                            }

                            JsonNode notesValue = propertiesValue.get("notes");
                            if (notesValue != null && notesValue instanceof NullNode == false) {
                                String notesInstance;
                                notesInstance = notesValue.getTextValue();
                                propertiesInstance.setNotes(notesInstance);
                            }
                        }

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

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

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

                JsonNode nextLinkValue = responseDoc.get("nextLink");
                if (nextLinkValue != null && nextLinkValue instanceof NullNode == false) {
                    String nextLinkInstance;
                    nextLinkInstance = nextLinkValue.getTextValue();
                    result.setNextLink(nextLinkInstance);
                }
            }

        }
        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:uk.ac.ebi.intact.editor.controller.curate.publication.PublicationController.java

public boolean isAssignableIMEx() {
    return getImexId() == null && curationDepth != null && "IMEx".equalsIgnoreCase(curationDepth)
            && Pattern.matches(ImexCentralManager.PUBMED_REGEXP.toString(), publication.getPubmedId());
}

From source file:com.ah.be.common.NmsUtil.java

public static boolean isValidSerialNumber(String serialNumber) {
    if (serialNumber == null || serialNumber.trim().isEmpty()) {
        return false;
    }//from w  ww  . j  a v  a2  s. co m

    String regex = "\\d{14}";

    return Pattern.matches(regex, serialNumber);
}