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:net.spfbl.spf.SPF.java

/**
 * Verifica se o whois  um modificador explanation vlido.
 *
 * @param token o whois a ser verificado.
 * @return verdadeiro se o whois  um modificador explanation vlido.
 *///from w w w. java 2 s .  c o m
private static boolean isModifierExplanation(String token) {
    token = expand(token, "127.0.0.1", "sender@domain.tld", "host.domain.tld");
    return Pattern.matches("^exp="
            + "((?=.{1,255}$)[0-9A-Za-z_](?:(?:[0-9A-Za-z_]|-){0,61}[0-9A-Za-z_])?(?:\\.[0-9A-Za-z_](?:(?:[0-9A-Za-z_]|-){0,61}[0-9A-Za-z_])?)*\\.?)"
            + "$", token.toLowerCase());
}

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

/**
 * {@inheritDoc}// w  w  w  . j a v a2s.com
 */
@Override
public Long createUltraMonkeyLoadBalancer(Long farmNo, String loadBalancerName, String comment, Long platformNo,
        Long componentNo) {
    // ?
    if (farmNo == null) {
        throw new AutoApplicationException("ECOMMON-000003", "farmNo");
    }
    if (loadBalancerName == null || loadBalancerName.length() == 0) {
        throw new AutoApplicationException("ECOMMON-000003", "loadBalancerName");
    }
    if (platformNo == null) {
        throw new AutoApplicationException("ECOMMON-000003", "platformNo");
    }
    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: ??

    // ??
    Image image = null;
    List<Image> images = imageDao.readAll();
    for (Image image2 : images) {
        if (image2.getPlatformNo().equals(platformNo.longValue())
                && PCCConstant.IMAGE_NAME_ULTRAMONKEY.equals(image2.getImageName())) {
            image = image2;
            break;
        }
    }
    if (image == null) {
        // UltraMonkey?????
        throw new AutoApplicationException("ESERVICE-000625", platformNo);
    }

    // ??????
    LoadBalancer checkLoadBalancer = loadBalancerDao.readByFarmNoAndLoadBalancerName(farmNo, loadBalancerName);
    if (checkLoadBalancer != null) {
        // ????????
        throw new AutoApplicationException("ESERVICE-000601", loadBalancerName);
    }

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

    // ??
    Farm farm = farmDao.read(farmNo);
    if (farm == null) {
        throw new AutoApplicationException("ESERVICE-000602", farmNo);
    }

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

    // UltraMonkey??
    //String lbInstanceName = "lb-" + loadBalancerNo;
    String lbInstanceName = loadBalancerName;
    Long lbInstanceNo = null;
    Platform platform = platformDao.read(platformNo);
    // TODO CLOUD BRANCHING
    if (PCCConstant.PLATFORM_TYPE_AWS.equals(platform.getPlatformType())) {
        ImageAws imageAws = imageAwsDao.read(image.getImageNo());
        String[] instanceTypes = StringUtils.split(imageAws.getInstanceTypes(), ",");
        lbInstanceNo = instanceService.createIaasInstance(farmNo, lbInstanceName, platformNo, null,
                image.getImageNo(), instanceTypes[0].trim());
    } else if (PCCConstant.PLATFORM_TYPE_VMWARE.equals(platform.getPlatformType())) {
        ImageVmware imageVmware = imageVmwareDao.read(image.getImageNo());
        String[] instanceTypes = StringUtils.split(imageVmware.getInstanceTypes(), ",");
        lbInstanceNo = instanceService.createVmwareInstance(farmNo, lbInstanceName, platformNo, null,
                image.getImageNo(), instanceTypes[0].trim());
    } else if (PCCConstant.PLATFORM_TYPE_NIFTY.equals(platform.getPlatformType())) {
        ImageNifty imageNifty = imageNiftyDao.read(image.getImageNo());
        String[] instanceTypes = StringUtils.split(imageNifty.getInstanceTypes(), ",");
        lbInstanceNo = instanceService.createNiftyInstance(farmNo, lbInstanceName, platformNo, null,
                image.getImageNo(), instanceTypes[0].trim());
    } else if (PCCConstant.PLATFORM_TYPE_CLOUDSTACK.equals(platform.getPlatformType())) {
        ImageCloudstack imageCloudstack = imageCloudstackDao.read(image.getImageNo());
        String[] instanceTypes = StringUtils.split(imageCloudstack.getInstanceTypes(), ",");
        lbInstanceNo = instanceService.createIaasInstance(farmNo, lbInstanceName, platformNo, null,
                image.getImageNo(), instanceTypes[0].trim());
    } else if (PCCConstant.PLATFORM_TYPE_VCLOUD.equals(platform.getPlatformType())) {
        ImageVcloud imageVcloud = imageVcloudDao.read(image.getImageNo());
        String[] instanceTypes = StringUtils.split(imageVcloud.getInstanceTypes(), ",");
        lbInstanceNo = instanceService.createIaasInstance(farmNo, lbInstanceName, platformNo, null,
                image.getImageNo(), instanceTypes[0].trim());
    } else if (PCCConstant.PLATFORM_TYPE_AZURE.equals(platform.getPlatformType())) {
        ImageAzure imageAzure = imageAzureDao.read(image.getImageNo());
        String[] instanceTypes = StringUtils.split(imageAzure.getInstanceTypes(), ",");
        lbInstanceNo = instanceService.createIaasInstance(farmNo, lbInstanceName, platformNo, null,
                image.getImageNo(), instanceTypes[0].trim());
    } else if (PCCConstant.PLATFORM_TYPE_OPENSTACK.equals(platform.getPlatformType())) {
        ImageOpenstack imageOpenstack = imageOpenstackDao.read(image.getImageNo());
        String[] instanceTypes = StringUtils.split(imageOpenstack.getInstanceTypes(), ",");
        lbInstanceNo = instanceService.createIaasInstance(farmNo, lbInstanceName, platformNo, null,
                image.getImageNo(), instanceTypes[0].trim());
    }
    // UltraMonkey???
    Instance lbInstance = instanceDao.read(lbInstanceNo);
    lbInstance.setLoadBalancer(true);
    instanceDao.update(lbInstance);

    // ???
    LoadBalancer loadBalancer = new LoadBalancer();
    loadBalancer.setFarmNo(farmNo);
    loadBalancer.setLoadBalancerName(loadBalancerName);
    loadBalancer.setComment(comment);
    loadBalancer.setFqdn(loadBalancerName + "." + farm.getDomainName());
    loadBalancer.setPlatformNo(platformNo);
    loadBalancer.setType(PCCConstant.LOAD_BALANCER_ULTRAMONKEY);
    loadBalancer.setEnabled(false);
    loadBalancer.setStatus(LoadBalancerStatus.STOPPED.toString());
    loadBalancer.setComponentNo(componentNo);
    loadBalancerDao.create(loadBalancer);

    Long loadBalancerNo = loadBalancer.getLoadBalancerNo();

    // UltraMonkey????
    String lbComponentName = "lb-" + loadBalancerNo;
    Long lbComponentTypeNo = Long.valueOf(image.getComponentTypeNos());
    Long lbComponentNo = componentService.createComponent(farmNo, lbComponentName, lbComponentTypeNo, null,
            null);

    // UltraMonkey?????
    Component lbComponent = componentDao.read(lbComponentNo);
    lbComponent.setLoadBalancer(true);
    componentDao.update(lbComponent);

    // ?????
    componentService.associateInstances(lbComponentNo, Arrays.asList(lbInstanceNo));

    // ?????
    ComponentLoadBalancer componentLoadBalancer = new ComponentLoadBalancer();
    componentLoadBalancer.setLoadBalancerNo(loadBalancerNo);
    componentLoadBalancer.setComponentNo(lbComponentNo);
    componentLoadBalancerDao.create(componentLoadBalancer);

    // ???
    createDefaultHealthCheck(loadBalancer);

    // ??
    createDefaultAutoScalingConf(loadBalancer);

    // ??
    registerInstances(loadBalancer);

    // 
    eventLogger.log(EventLogLevel.INFO, farmNo, farm.getFarmName(), null, null, null, null,
            "LoadBalancerCreate", null, null, new Object[] { loadBalancerName, platform.getPlatformName(),
                    PCCConstant.LOAD_BALANCER_ULTRAMONKEY });

    return loadBalancerNo;
}

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * Create a blog post from the content and the attachments retrieved from a
 * mail message.//  w  w  w  .j  a  v a  2  s . c o m
 * There are only two parameters, the other necessary parameters are global
 * variables.
 *
 * @param space The space where to publish the blog post.
 * @param m The message which to publish as a blog post.
 * @throws MessagingException Throws a MessagingException if something goes wrong when getting attributes from the message.
 */
private void createBlogPost(Space space, Message m) throws MessagingException {
    /* create the blogPost and add values */
    BlogPost blogPost = new BlogPost();
    /* set the creation date of the blog post to the current date */
    blogPost.setCreationDate(new Date());
    /* set the space where to save the blog post */
    blogPost.setSpace(space);
    /* if the gallery macro is set and the post contains an image add the macro */
    MailConfiguration config = configurationManager.getMailConfiguration();
    if (config.getGallerymacro()) {
        /* gallery macro is set */
        if (containsImage) {
            /* post contains an image */
            /* add the macro */
            blogEntryContent = blogEntryContent.concat("{gallery}");
        }
    }
    /* set the blog post content */
    if (blogEntryContent != null) {
        blogPost.setContent(blogEntryContent);
    } else {
        blogPost.setContent("");
    }
    /* set the title of the blog post */
    String title = m.getSubject();
    /* check for illegal characters in the title and replace them with a space */
    /* could be replaced with a regex */
    /* Only needed for Confluence < 4.1 */
    String version = GeneralUtil.getVersionNumber();
    if (!Pattern.matches("^4\\.[1-9]+.*$", version)) {
        char[] illegalCharacters = { ':', '@', '/', '%', '\\', '&', '!', '|', '#', '$', '*', ';', '~', '[', ']',
                '(', ')', '{', '}', '<', '>', '.' };
        for (int i = 0; i < illegalCharacters.length; i++) {
            if (title.indexOf(illegalCharacters[i]) != -1) {
                title = title.replace(illegalCharacters[i], ' ');
            }
        }
    }
    blogPost.setTitle(title);

    /* set creating user */
    String creatorEmail = getEmailAddressFromMessage(m);

    String creatorName = "Anonymous";
    User creator = null;
    if (creatorEmail != "") {
        SearchResult sr = userAccessor.getUsersByEmail(creatorEmail);

        Pager p = sr.pager();
        List l = p.getCurrentPage();

        if (l.size() == 1) {
            /* found a matching user for the email address of the sender */
            creator = (User) l.get(0);
            creatorName = creator.getName();
        }

    }
    //this.log.info("creatorName: " + creatorName);
    //this.log.info("creator: " + creator);

    blogPost.setCreatorName(creatorName);

    if (creator != null) {
        AuthenticatedUserThreadLocal.setUser(creator);
    } else {
        //this.log.info("Resetting authenticated user.");
        AuthenticatedUserThreadLocal.setUser(null);
    }

    /* save the blog post */
    pageManager.saveContentEntity(blogPost, null);

    /* set attachments of this blog post */
    /* we have to save the blog post before we can add the
     * attachments, because attachments need to be attached to
     * a content. */
    Attachment[] a = new Attachment[attachments.size()];
    a = (Attachment[]) attachments.toArray(a);
    for (int j = 0; j < a.length; j++) {
        InputStream is = (InputStream) attachmentsInputStreams.get(j);

        /* save the attachment */
        try {
            /* set the creator of the attachment */
            a[j].setCreatorName(creatorName);
            /* set the content of this attachment to the newly saved blog post */
            a[j].setContent(blogPost);
            attachmentManager.saveAttachment(a[j], null, is);
        } catch (Exception e) {
            this.log.error("Could not save attachment: " + e.getMessage(), e);
            /* skip this attachment */
            continue;
        }

        /* add the attachment to the blog post */
        blogPost.addAttachment(a[j]);
    }
}

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

public void validasiNumberofNearest(KeyEvent evt, JTextField txtNumberOfK, JLabel labelPesanError,
        JTable tableDataSetModel) {
    String numberValidate = txtNumberOfK.getText();
    int modelRow = tableDataSetModel.getRowCount();
    if (Pattern.matches("[0-9]+", numberValidate) == false && numberValidate.length() > 0) {
        evt.consume();/*  w ww . j a  v a  2  s. co  m*/
        labelPesanError.setText("Number of Nearest Neighbor tidak valid");
    } else if (numberValidate.length() == 9) {
        evt.consume();
        labelPesanError.setText("Number of Nearest Neighbor terlalu panjang");
    } else {
        labelPesanError.setText("");
    }
}

From source file:com.safi.asterisk.handler.SafletEngine.java

public List<String> getLocalIPAddresses() {
    List<String> iplist = new ArrayList<String>();
    NetworkInterface iface = null;
    try {//from  w  ww . j  a  v  a 2s  .com
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
                .hasMoreElements();) {
            iface = ifaces.nextElement();
            System.out.println("Interface:" + iface.getDisplayName());
            InetAddress ia = null;
            for (Enumeration<InetAddress> ips = iface.getInetAddresses(); ips.hasMoreElements();) {
                ia = ips.nextElement();
                if (Pattern.matches(AbstractConnectionManager.PATTERN_IP, ia.getHostAddress())) {
                    iplist.add(ia.getHostAddress());
                }
            }
        }
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return iplist;
}

From source file:com.gemstone.gemfire.management.internal.cli.GfshParser.java

private boolean hasOptionSpecified(String userInput) {
    userInput = userInput.trim();
    return Pattern.matches("^(.*)(-+)(\\w+)(.*)$", userInput);
}

From source file:fr.paris.lutece.plugins.calendar.web.CalendarJspBean.java

/**
 * Process Event creation/*from  w  w  w.j a  va2  s . c  o m*/
 * 
 * @param request The Http request
 * @return URL
 */
public String doCreateEvent(HttpServletRequest request) {
    String strJspReturn = StringUtils.EMPTY;
    String strCalendarId = request.getParameter(Constants.PARAMETER_CALENDAR_ID);
    String strPeriodicity = request.getParameter(Constants.PARAMETER_PERIODICITY);
    if (StringUtils.isNotBlank(strCalendarId) && StringUtils.isNumeric(strCalendarId)
            && StringUtils.isNotBlank(strPeriodicity) && StringUtils.isNumeric(strPeriodicity)) {
        //Retrieving parameters from form
        int nCalendarId = Integer.parseInt(strCalendarId);
        int nPeriodicity = Integer.parseInt(strPeriodicity);
        String strEventDateEnd = request.getParameter(Constants.PARAMETER_EVENT_DATE_END);
        String strTimeStart = request.getParameter(Constants.PARAMETER_EVENT_TIME_START);
        String strTimeEnd = request.getParameter(Constants.PARAMETER_EVENT_TIME_END);
        String strOccurrence = request.getParameter(Constants.PARAMETER_OCCURRENCE);
        String strEventTitle = request.getParameter(Constants.PARAMETER_EVENT_TITLE);
        String strDate = request.getParameter(Constants.PARAMETER_EVENT_DATE);
        String strNotify = request.getParameter(Constants.PARAMETER_NOTIFY);

        //Retrieve the features of an event from form
        String strDescription = request.getParameter(Constants.PARAMETER_DESCRIPTION);
        String strEventTags = request.getParameter(Constants.PARAMETER_EVENT_TAGS).trim();
        String strLocationAddress = request.getParameter(Constants.PARAMETER_EVENT_LOCATION_ADDRESS).trim();
        String strLocationTown = request.getParameter(Constants.PARAMETER_LOCATION_TOWN).trim();
        String strLocation = request.getParameter(Constants.PARAMETER_LOCATION).trim();
        String strLocationZip = request.getParameter(Constants.PARAMETER_LOCATION_ZIP).trim();
        String strLinkUrl = request.getParameter(Constants.PARAMETER_EVENT_LINK_URL).trim();
        String strDocumentId = request.getParameter(Constants.PARAMETER_EVENT_DOCUMENT_ID).trim();
        String strPageUrl = request.getParameter(Constants.PARAMETER_EVENT_PAGE_URL).trim();
        String strTopEvent = request.getParameter(Constants.PARAMETER_EVENT_TOP_EVENT).trim();
        String strMapUrl = request.getParameter(Constants.PARAMETER_EVENT_MAP_URL).trim();

        //Retrieving the excluded days
        String[] arrayExcludedDays = request.getParameterValues(Constants.PARAMETER_EXCLUDED_DAYS);

        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        FileItem item = mRequest.getFile(Constants.PARAMETER_EVENT_IMAGE);

        String[] arrayCategory = request.getParameterValues(Constants.PARAMETER_CATEGORY);

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

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

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

        String[] strTabEventTags = null;

        // Mandatory field
        if (StringUtils.isBlank(strDate) || StringUtils.isBlank(strEventTitle)
                || StringUtils.isBlank(strDescription)) {
            return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS,
                    AdminMessage.TYPE_STOP);
        }

        if (StringUtils.isNotBlank(strEventTags) && strEventTags.length() > 0) {
            //Test if there aren't special characters in tag list
            boolean isAllowedExp = Pattern.matches(PROPERTY_TAGS_REGEXP, strEventTags);

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

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

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

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

        Date dateEndEvent = null;

        if (StringUtils.isNotBlank(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;

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

        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);
            }
        }

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

        //If a date end is chosen
        if ((Integer.parseInt(request.getParameter(Constants.PARAMETER_RADIO_PERIODICITY)) == 1)
                && StringUtils.isNotBlank(strEventDateEnd)) {
            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);
        } else if ((Integer.parseInt(request.getParameter(Constants.PARAMETER_RADIO_PERIODICITY)) == 1)
                && StringUtils.isBlank(strEventDateEnd)) {
            return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATEFORMAT,
                    AdminMessage.TYPE_STOP);
        }

        //If a date end is not chosen
        if ((Integer.parseInt(request.getParameter(Constants.PARAMETER_RADIO_PERIODICITY)) == 0)
                && StringUtils.isBlank(strEventDateEnd)) {
            dateEndEvent = Utils.getDateForward(dateEvent, nPeriodicity, nOccurrence, arrayExcludedDays);
            if (dateEndEvent.before(dateEvent)) {
                nOccurrence = 0;
                dateEndEvent = dateEvent;
            }
        }

        SimpleEvent event = new SimpleEvent();
        event.setDate(dateEvent);
        event.setDateEnd(dateEndEvent);
        event.setDateTimeStart(strTimeStart);
        event.setDateTimeEnd(strTimeEnd);
        event.setTitle(strEventTitle);
        event.setOccurrence(nOccurrence);
        event.setPeriodicity(nPeriodicity);
        event.setDescription(strDescription);

        if (item.getSize() == 0) {
            HttpSession session = request.getSession(true);
            if (session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_CONTENT_FILE) != null
                    && session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_MIME_TYPE_FILE) != null) {
                ImageResource imageResource = new ImageResource();
                imageResource.setImage(
                        (byte[]) session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_CONTENT_FILE));
                imageResource.setMimeType(
                        (String) session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_MIME_TYPE_FILE));
                event.setImageResource(imageResource);
                session.removeAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_CONTENT_FILE);
                session.removeAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_MIME_TYPE_FILE);
            }
        }

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

        event.setTags(strTabEventTags);
        event.setLocationAddress(strLocationAddress);
        event.setLocation(strLocation);
        event.setLocationTown(strLocationTown);
        event.setLocationZip(strLocationZip);
        event.setLinkUrl(strLinkUrl);
        event.setPageUrl(strPageUrl);
        event.setTopEvent(Integer.parseInt(strTopEvent));
        event.setMapUrl(strMapUrl);
        event.setDocumentId(nDocumentId);
        event.setListCategories(listCategories);
        event.setExcludedDays(arrayExcludedDays);
        event.setIdCalendar(nCalendarId);

        _eventListService.doAddEvent(event, null, getPlugin());

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

        for (OccurrenceEvent occ : listOccurencesEvent) {
            IndexationService.addIndexerAction(Integer.toString(occ.getId()),
                    AppPropertiesService.getProperty(CalendarIndexer.PROPERTY_INDEXER_NAME),
                    IndexerAction.TASK_CREATE);
            CalendarIndexerUtils.addIndexerAction(occ.getId(), IndexerAction.TASK_CREATE);
        }

        /*
         * IndexationService.addIndexerAction( Constants.EMPTY_STRING +
         * nCalendarId
         * ,AppPropertiesService.getProperty(
         * CalendarIndexer.PROPERTY_INDEXER_NAME ),
         * IndexerAction.TASK_CREATE );
         */
        boolean isNotify = Boolean.parseBoolean(strNotify);

        if (isNotify) {
            int nSubscriber = _agendaSubscriberService.getSubscriberNumber(nCalendarId, getPlugin());

            if (nSubscriber > 0) {
                Collection<CalendarSubscriber> calendarSubscribers = _agendaSubscriberService
                        .getSubscribers(nCalendarId, getPlugin());
                _agendaSubscriberService.sendSubscriberMail(request, calendarSubscribers, event, nCalendarId);
            }
        }

        strJspReturn = AppPathService.getBaseUrl(request) + JSP_EVENT_LIST2 + nCalendarId;
    } else {
        strJspReturn = AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_NUMBER_FORMAT,
                AdminMessage.TYPE_STOP);
    }
    return strJspReturn;

}

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

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

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("resourceGroupName", resourceGroupName);
        tracingParameters.put("identity", identity);
        CloudTracing.enter(invocationId, this, "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 + "/providers/";
    url = url + URLEncoder.encode(identity.getResourceProviderNamespace(), "UTF-8");
    url = url + "/";
    if (identity.getParentResourcePath() != null) {
        url = url + identity.getParentResourcePath();
    }
    url = url + "/";
    url = url + identity.getResourceType();
    url = url + "/";
    url = url + URLEncoder.encode(identity.getResourceName(), "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + URLEncoder.encode(identity.getResourceProviderApiVersion(), "UTF-8"));
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

        // Create Result
        ResourceGetResult result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ResourceGetResult();
            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) {
                GenericResourceExtended resourceInstance = new GenericResourceExtended();
                result.setResource(resourceInstance);

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

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

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

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

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

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

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

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

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

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

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

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

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

        }
        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.rinke.solutions.pinball.PinDmdEditor.java

/**
 * Create contents of the window.//  ww  w. ja v  a 2s .c o m
 */
void createContents(Shell shell) {
    shell.setSize(1238, 657);
    shell.setText("Pin2dmd - Editor");
    shell.setLayout(new GridLayout(4, false));

    createMenu(shell);

    recentProjectsMenuManager = new RecentMenuManager("recentProject", 4, menuPopRecentProjects,
            e -> loadProject((String) e.widget.getData()));
    recentProjectsMenuManager.loadRecent();

    recentPalettesMenuManager = new RecentMenuManager("recentPalettes", 4, mntmRecentPalettes,
            e -> paletteHandler.loadPalette((String) e.widget.getData()));
    recentPalettesMenuManager.loadRecent();

    recentAnimationsMenuManager = new RecentMenuManager("recentAnimations", 4, mntmRecentAnimations,
            e -> aniAction.loadAni(((String) e.widget.getData()), true, false));
    recentAnimationsMenuManager.loadRecent();

    resManager = new LocalResourceManager(JFaceResources.getResources(), shell);

    Label lblAnimations = new Label(shell, SWT.NONE);
    lblAnimations.setText("Animations");

    Label lblKeyframes = new Label(shell, SWT.NONE);
    lblKeyframes.setText("KeyFrames");

    Label lblPreview = new Label(shell, SWT.NONE);
    lblPreview.setText("Preview");
    new Label(shell, SWT.NONE);

    aniListViewer = new TableViewer(shell, SWT.BORDER | SWT.V_SCROLL);
    Table aniList = aniListViewer.getTable();
    GridData gd_aniList = new GridData(SWT.LEFT, SWT.FILL, false, false, 1, 1);
    gd_aniList.widthHint = 189;
    aniList.setLayoutData(gd_aniList);
    aniList.setLinesVisible(true);
    aniList.addKeyListener(new EscUnselect(aniListViewer));
    aniListViewer.setContentProvider(ArrayContentProvider.getInstance());
    aniListViewer.setLabelProvider(new LabelProviderAdapter(o -> ((Animation) o).getDesc()));
    aniListViewer.setInput(animations.values());
    aniListViewer.addSelectionChangedListener(event -> {
        IStructuredSelection selection = (IStructuredSelection) event.getSelection();
        onAnimationSelectionChanged(selection.size() > 0 ? (Animation) selection.getFirstElement() : null);
    });
    TableViewerColumn viewerCol1 = new TableViewerColumn(aniListViewer, SWT.LEFT);
    viewerCol1.setEditingSupport(
            new GenericTextCellEditor(aniListViewer, e -> ((Animation) e).getDesc(), (e, v) -> {
                Animation ani = (Animation) e;
                updateAnimationMapKey(ani.getDesc(), v);
                ani.setDesc(v);
                frameSeqViewer.refresh();
            }));

    viewerCol1.getColumn().setWidth(220);
    viewerCol1.setLabelProvider(new ColumnLabelProviderAdapter(o -> ((Animation) o).getDesc()));

    keyframeTableViewer = new TableViewer(shell, SWT.SINGLE | SWT.V_SCROLL);
    Table keyframeList = keyframeTableViewer.getTable();
    GridData gd_keyframeList = new GridData(SWT.LEFT, SWT.FILL, false, false, 1, 1);
    gd_keyframeList.widthHint = 137;
    keyframeList.setLinesVisible(true);
    keyframeList.setLayoutData(gd_keyframeList);
    keyframeList.addKeyListener(new EscUnselect(keyframeTableViewer));

    //keyframeTableViewer.setLabelProvider(new KeyframeLabelProvider(shell));
    keyframeTableViewer.setContentProvider(ArrayContentProvider.getInstance());
    keyframeTableViewer.setInput(project.palMappings);
    keyframeTableViewer.addSelectionChangedListener(event -> keyFrameChanged(event));

    TableViewerColumn viewerColumn = new TableViewerColumn(keyframeTableViewer, SWT.LEFT);
    viewerColumn.setEditingSupport(
            new GenericTextCellEditor(keyframeTableViewer, e -> ((PalMapping) e).name, (e, v) -> {
                ((PalMapping) e).name = v;
            }));

    viewerColumn.getColumn().setWidth(200);
    viewerColumn.setLabelProvider(new KeyframeLabelProvider(shell));

    dmdWidget = new DMDWidget(shell, SWT.DOUBLE_BUFFERED, this.dmd, true);
    // dmdWidget.setBounds(0, 0, 700, 240);
    GridData gd_dmdWidget = new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1);
    gd_dmdWidget.heightHint = 231;
    gd_dmdWidget.widthHint = 826;
    dmdWidget.setLayoutData(gd_dmdWidget);
    dmdWidget.setPalette(activePalette);
    dmdWidget.addListeners(l -> frameChanged(l));

    Composite composite_1 = new Composite(shell, SWT.NONE);
    composite_1.setLayout(new GridLayout(2, false));
    GridData gd_composite_1 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
    gd_composite_1.heightHint = 35;
    gd_composite_1.widthHint = 206;
    composite_1.setLayoutData(gd_composite_1);

    btnRemoveAni = new Button(composite_1, SWT.NONE);
    btnRemoveAni.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
    btnRemoveAni.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
        }
    });
    btnRemoveAni.setText("Remove");
    btnRemoveAni.setEnabled(false);
    btnRemoveAni.addListener(SWT.Selection, e -> {
        if (selectedAnimation.isPresent()) {
            String key = selectedAnimation.get().getDesc();
            animations.remove(key);
            playingAnis.clear();
            animationHandler.setAnimations(playingAnis);
            animationHandler.setClockActive(true);
        }
    });

    btnSortAni = new Button(composite_1, SWT.NONE);
    btnSortAni.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
    btnSortAni.setText("Sort");
    btnSortAni.addListener(SWT.Selection, e -> sortAnimations());

    Composite composite_2 = new Composite(shell, SWT.NONE);
    composite_2.setLayout(new GridLayout(3, false));
    GridData gd_composite_2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
    gd_composite_2.heightHint = 35;
    gd_composite_2.widthHint = 157;
    composite_2.setLayoutData(gd_composite_2);

    btnDeleteKeyframe = new Button(composite_2, SWT.NONE);
    GridData gd_btnDeleteKeyframe = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
    gd_btnDeleteKeyframe.widthHint = 88;
    btnDeleteKeyframe.setLayoutData(gd_btnDeleteKeyframe);
    btnDeleteKeyframe.setText("Remove");
    btnDeleteKeyframe.setEnabled(false);
    btnDeleteKeyframe.addListener(SWT.Selection, e -> {
        if (selectedPalMapping != null) {
            project.palMappings.remove(selectedPalMapping);
            keyframeTableViewer.refresh();
            checkReleaseMask();
        }
    });

    Button btnSortKeyFrames = new Button(composite_2, SWT.NONE);
    btnSortKeyFrames.setText("Sort");
    btnSortKeyFrames.addListener(SWT.Selection, e -> sortKeyFrames());
    new Label(composite_2, SWT.NONE);

    scale = new Scale(shell, SWT.NONE);
    scale.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
    scale.addListener(SWT.Selection, e -> animationHandler.setPos(scale.getSelection()));

    Group grpKeyframe = new Group(shell, SWT.NONE);
    grpKeyframe.setLayout(new GridLayout(3, false));
    GridData gd_grpKeyframe = new GridData(SWT.FILL, SWT.TOP, false, false, 2, 4);
    gd_grpKeyframe.heightHint = 191;
    gd_grpKeyframe.widthHint = 350;
    grpKeyframe.setLayoutData(gd_grpKeyframe);
    grpKeyframe.setText("KeyFrames");

    Composite composite_hash = new Composite(grpKeyframe, SWT.NONE);
    //gd_composite_hash.widthHint = 105;
    GridData gd_composite_hash = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1);
    gd_composite_hash.widthHint = 148;
    composite_hash.setLayoutData(gd_composite_hash);
    createHashButtons(composite_hash, 10, 0);

    previewDmd = new DMDWidget(grpKeyframe, SWT.DOUBLE_BUFFERED, dmd, false);
    GridData gd_dmdPreWidget = new GridData(SWT.CENTER, SWT.TOP, false, false, 1, 1);
    gd_dmdPreWidget.heightHint = 40;
    gd_dmdPreWidget.widthHint = 132;
    previewDmd.setLayoutData(gd_dmdPreWidget);
    previewDmd.setDrawingEnabled(false);
    previewDmd.setPalette(previewPalettes.get(0));

    new Label(grpKeyframe, SWT.NONE);

    btnAddColormaskKeyFrame = new Button(grpKeyframe, SWT.NONE);
    btnAddColormaskKeyFrame
            .setToolTipText("Adds a key frame that trigger a color masking scene to be overlayed");
    btnAddColormaskKeyFrame.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
    btnAddColormaskKeyFrame.setText("Add ColorMask");
    btnAddColormaskKeyFrame.setEnabled(false);
    btnAddColormaskKeyFrame.addListener(SWT.Selection, e -> addFrameSeq(SwitchMode.ADD));

    btnAddKeyframe = new Button(grpKeyframe, SWT.NONE);
    btnAddKeyframe.setToolTipText("Adds a key frame that switches palette");
    btnAddKeyframe.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, false, false, 1, 1));
    btnAddKeyframe.setText("Add PalSwitch");
    btnAddKeyframe.setEnabled(false);
    btnAddKeyframe.addListener(SWT.Selection, e -> addKeyFrame(SwitchMode.PALETTE));

    Label lblDuration = new Label(grpKeyframe, SWT.NONE);
    lblDuration.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblDuration.setText("Duration:");

    txtDuration = new Text(grpKeyframe, SWT.BORDER);
    GridData gd_txtDuration = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
    gd_txtDuration.widthHint = 93;
    txtDuration.setLayoutData(gd_txtDuration);
    txtDuration.setText("0");
    txtDuration.addListener(SWT.Verify, e -> e.doit = Pattern.matches("^[0-9]*$", e.text));
    txtDuration.addListener(SWT.Modify, e -> {
        if (selectedPalMapping != null) {
            selectedPalMapping.durationInMillis = Integer.parseInt(txtDuration.getText());
            selectedPalMapping.durationInFrames = (int) selectedPalMapping.durationInMillis / 40;
        }
    });

    btnFetchDuration = new Button(grpKeyframe, SWT.NONE);
    btnFetchDuration.setToolTipText(
            "Fetches duration for palette switches by calculating the difference between actual timestamp and keyframe timestamp");
    btnFetchDuration.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
    btnFetchDuration.setText("Fetch Duration");
    btnFetchDuration.setEnabled(false);
    btnFetchDuration.addListener(SWT.Selection, e -> {
        if (selectedPalMapping != null) {
            selectedPalMapping.durationInMillis = lastTimeCode - saveTimeCode;
            selectedPalMapping.durationInFrames = (int) selectedPalMapping.durationInMillis / FRAME_RATE;
            txtDuration.setText(selectedPalMapping.durationInMillis + "");
        }
    });

    Label lblNewLabel = new Label(grpKeyframe, SWT.NONE);
    lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblNewLabel.setText("FrameSeq:");

    frameSeqViewer = new ComboViewer(grpKeyframe, SWT.NONE);
    Combo frameSeqCombo = frameSeqViewer.getCombo();
    frameSeqCombo.setToolTipText("Choose frame sequence to use with key frame");
    GridData gd_frameSeqCombo = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
    gd_frameSeqCombo.widthHint = 100;
    frameSeqCombo.setLayoutData(gd_frameSeqCombo);
    frameSeqViewer.setLabelProvider(new LabelProviderAdapter(o -> ((Animation) o).getDesc()));
    frameSeqViewer.setContentProvider(ArrayContentProvider.getInstance());
    frameSeqViewer.setInput(frameSeqList);
    frameSeqViewer.addSelectionChangedListener(event -> frameSeqChanged(event));

    btnAddFrameSeq = new Button(grpKeyframe, SWT.NONE);
    btnAddFrameSeq.setToolTipText("Adds a keyframe that triggers playback of a replacement scene");
    btnAddFrameSeq.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
    btnAddFrameSeq.setText("Add FrameSeq");
    btnAddFrameSeq.addListener(SWT.Selection, e -> addFrameSeq(SwitchMode.REPLACE));
    btnAddFrameSeq.setEnabled(false);

    Group grpDetails = new Group(shell, SWT.NONE);
    grpDetails.setLayout(new GridLayout(10, false));
    GridData gd_grpDetails = new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1);
    gd_grpDetails.heightHint = 21;
    gd_grpDetails.widthHint = 776;
    grpDetails.setLayoutData(gd_grpDetails);
    grpDetails.setText("Details");

    Label lblFrame = new Label(grpDetails, SWT.NONE);
    lblFrame.setText("Frame:");

    lblFrameNo = new Label(grpDetails, SWT.NONE);
    GridData gd_lblFrameNo = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
    gd_lblFrameNo.widthHint = 66;
    gd_lblFrameNo.minimumWidth = 60;
    lblFrameNo.setLayoutData(gd_lblFrameNo);
    lblFrameNo.setText("---");

    Label lblTimecode = new Label(grpDetails, SWT.NONE);
    lblTimecode.setText("Timecode:");

    lblTcval = new Label(grpDetails, SWT.NONE);
    GridData gd_lblTcval = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
    gd_lblTcval.widthHint = 62;
    gd_lblTcval.minimumWidth = 80;
    lblTcval.setLayoutData(gd_lblTcval);
    lblTcval.setText("---");

    Label lblDelay = new Label(grpDetails, SWT.NONE);
    lblDelay.setText("Delay:");

    lblDelayVal = new Label(grpDetails, SWT.NONE);
    GridData gd_lblDelayVal = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
    gd_lblDelayVal.widthHint = 53;
    lblDelayVal.setLayoutData(gd_lblDelayVal);
    lblDelayVal.setText("---");

    Label lblPlanes = new Label(grpDetails, SWT.NONE);
    lblPlanes.setText("Planes:");

    lblPlanesVal = new Label(grpDetails, SWT.NONE);
    lblPlanesVal.setText("---");
    new Label(grpDetails, SWT.NONE);

    btnLivePreview = new Button(grpDetails, SWT.CHECK);
    btnLivePreview.setToolTipText("controls live preview to real display device");
    btnLivePreview.setText("Live Preview");
    btnLivePreview.addListener(SWT.Selection, e -> switchLivePreview(e));

    Composite composite = new Composite(shell, SWT.NONE);
    composite.setLayout(new GridLayout(9, false));
    composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));

    btnStartStop = new Button(composite, SWT.NONE);
    btnStartStop.setText("Start");
    btnStartStop.addListener(SWT.Selection, e -> startStop(animationHandler.isStopped()));

    btnPrev = new Button(composite, SWT.NONE);
    btnPrev.setText("<");
    btnPrev.addListener(SWT.Selection, e -> prevFrame());

    btnNext = new Button(composite, SWT.NONE);
    btnNext.setText(">");
    btnNext.addListener(SWT.Selection, e -> nextFrame());

    btnMarkStart = new Button(composite, SWT.NONE);
    btnMarkStart.setToolTipText("Marks start of scene for cutting");
    btnMarkEnd = new Button(composite, SWT.NONE);
    btnCut = new Button(composite, SWT.NONE);
    btnCut.setToolTipText("Cuts out a new scene for editing and use a replacement or color mask");

    btnMarkStart.setText("Mark Start");
    btnMarkStart.addListener(SWT.Selection, e -> {
        cutInfo.setStart(selectedAnimation.get().actFrame);
    });

    btnMarkEnd.setText("Mark End");
    btnMarkEnd.addListener(SWT.Selection, e -> {
        cutInfo.setEnd(selectedAnimation.get().actFrame);
    });

    btnCut.setText("Cut");
    btnCut.addListener(SWT.Selection, e -> {
        // respect number of planes while cutting / copying
        Animation ani = cutScene(selectedAnimation.get(), cutInfo.getStart(), cutInfo.getEnd(),
                "Scene " + animations.size());
        log.info("cutting out scene from {} to {}", cutInfo);
        cutInfo.reset();

        // TODO mark such a scene somehow, to copy it to the
        // projects frames sequence for later export
        // alternatively introduce a dedicated flag for scenes that
        // should be exported
        // also define a way that a keyframe triggers a replacement
        // sequence instead of switching
        // the palette only
        // TODO NEED TO ADD a reference to the animation in the list
        // / map
        project.scenes.add(new Scene(ani.getDesc(), ani.start, ani.end, activePalette.index));
    });

    new Label(composite, SWT.NONE);

    Button btnIncPitch = new Button(composite, SWT.NONE);
    btnIncPitch.setText("+");
    btnIncPitch.addListener(SWT.Selection, e -> dmdWidget.incPitch());

    Button btnDecPitch = new Button(composite, SWT.NONE);
    btnDecPitch.setText("-");
    btnDecPitch.addListener(SWT.Selection, e -> dmdWidget.decPitch());

    Group grpPalettes = new Group(shell, SWT.NONE);
    grpPalettes.setLayout(new GridLayout(4, false));
    GridData gd_grpPalettes = new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1);
    gd_grpPalettes.widthHint = 479;
    gd_grpPalettes.heightHint = 71;
    grpPalettes.setLayoutData(gd_grpPalettes);
    grpPalettes.setText("Palettes");

    paletteComboViewer = new ComboViewer(grpPalettes, SWT.NONE);
    Combo combo = paletteComboViewer.getCombo();
    GridData gd_combo = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
    gd_combo.widthHint = 166;
    combo.setLayoutData(gd_combo);
    paletteComboViewer.setContentProvider(ArrayContentProvider.getInstance());
    paletteComboViewer
            .setLabelProvider(new LabelProviderAdapter(o -> ((Palette) o).index + " - " + ((Palette) o).name));
    paletteComboViewer.setInput(project.palettes);
    paletteComboViewer.addSelectionChangedListener(event -> {
        IStructuredSelection selection = (IStructuredSelection) event.getSelection();
        if (selection.size() > 0) {
            paletteChanged((Palette) selection.getFirstElement());
        }
    });

    paletteTypeComboViewer = new ComboViewer(grpPalettes, SWT.READ_ONLY);
    Combo combo_1 = paletteTypeComboViewer.getCombo();
    combo_1.setToolTipText(
            "Type of palette. Default palette is choosen at start and after timed switch is expired");
    GridData gd_combo_1 = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
    gd_combo_1.widthHint = 85;
    combo_1.setLayoutData(gd_combo_1);
    paletteTypeComboViewer.setContentProvider(ArrayContentProvider.getInstance());
    paletteTypeComboViewer.setInput(PaletteType.values());
    paletteTypeComboViewer.setSelection(new StructuredSelection(activePalette.type));
    paletteTypeComboViewer.addSelectionChangedListener(e -> paletteTypeChanged(e));

    btnNewPalette = new Button(grpPalettes, SWT.NONE);
    btnNewPalette.setToolTipText("Creates a new palette by copying the actual colors");
    btnNewPalette.setText("New");
    btnNewPalette.addListener(SWT.Selection, e -> paletteHandler.newPalette());

    btnRenamePalette = new Button(grpPalettes, SWT.NONE);
    btnRenamePalette.setToolTipText("Confirms the new palette name");
    btnRenamePalette.setText("Rename");
    btnRenamePalette.addListener(SWT.Selection, e -> {
        String newName = paletteComboViewer.getCombo().getText();
        if (newName.contains(" - ")) {
            activePalette.name = newName.split(" - ")[1];
            paletteComboViewer.setSelection(new StructuredSelection(activePalette));
            paletteComboViewer.refresh();
        } else {
            warn("Illegal palette name",
                    "Palette names must consist of palette index and name.\nName format therefore must be '<idx> - <name>'");
            paletteComboViewer.getCombo().setText(activePalette.index + " - " + activePalette.name);
        }

    });

    Composite grpPal = new Composite(grpPalettes, SWT.NONE);
    grpPal.setLayout(new GridLayout(1, false));
    GridData gd_grpPal = new GridData(SWT.LEFT, SWT.TOP, false, false, 2, 1);
    gd_grpPal.widthHint = 313;
    gd_grpPal.heightHint = 22;
    grpPal.setLayoutData(gd_grpPal);
    // GridData gd_grpPal = new GridData(SWT.LEFT, SWT.CENTER, false, false,
    // 1, 1);
    // gd_grpPal.widthHint = 223;
    // gd_grpPal.heightHint = 61;
    // grpPal.setLayoutData(gd_grpPal);
    //
    paletteTool = new PaletteTool(shell, grpPal, SWT.FLAT | SWT.RIGHT, activePalette);

    paletteTool.addListener(dmdWidget);

    Label lblCtrlclickToEdit = new Label(grpPalettes, SWT.NONE);
    GridData gd_lblCtrlclickToEdit = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1);
    gd_lblCtrlclickToEdit.widthHint = 139;
    lblCtrlclickToEdit.setLayoutData(gd_lblCtrlclickToEdit);
    lblCtrlclickToEdit.setText("Ctrl-Click to edit color");

    Composite composite_3 = new Composite(shell, SWT.NONE);
    GridLayout gl_composite_3 = new GridLayout(1, false);
    gl_composite_3.marginWidth = 0;
    gl_composite_3.marginHeight = 0;
    composite_3.setLayout(gl_composite_3);
    GridData gd_composite_3 = new GridData(SWT.LEFT, SWT.FILL, false, false, 1, 2);
    gd_composite_3.heightHint = 190;
    gd_composite_3.widthHint = 338;
    composite_3.setLayoutData(gd_composite_3);
    goDmdGroup = new GoDmdGroup(composite_3);

    Group grpDrawing = new Group(shell, SWT.NONE);
    grpDrawing.setLayout(new GridLayout(6, false));
    GridData gd_grpDrawing = new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1);
    gd_grpDrawing.heightHint = 63;
    gd_grpDrawing.widthHint = 479;
    grpDrawing.setLayoutData(gd_grpDrawing);
    grpDrawing.setText("Drawing");

    drawToolBar = new ToolBar(grpDrawing, SWT.FLAT | SWT.RIGHT);
    drawToolBar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));

    ToolItem tltmPen = new ToolItem(drawToolBar, SWT.RADIO);
    tltmPen.setImage(
            resManager.createImage(ImageDescriptor.createFromFile(PinDmdEditor.class, "/icons/pencil.png")));
    tltmPen.addListener(SWT.Selection, e -> dmdWidget.setDrawTool(drawTools.get("pencil")));

    ToolItem tltmFill = new ToolItem(drawToolBar, SWT.RADIO);
    tltmFill.setImage(resManager
            .createImage(ImageDescriptor.createFromFile(PinDmdEditor.class, "/icons/color-fill.png")));
    tltmFill.addListener(SWT.Selection, e -> dmdWidget.setDrawTool(drawTools.get("fill")));

    ToolItem tltmRect = new ToolItem(drawToolBar, SWT.RADIO);
    tltmRect.setImage(
            resManager.createImage(ImageDescriptor.createFromFile(PinDmdEditor.class, "/icons/rect.png")));
    tltmRect.addListener(SWT.Selection, e -> dmdWidget.setDrawTool(drawTools.get("rect")));

    ToolItem tltmLine = new ToolItem(drawToolBar, SWT.RADIO);
    tltmLine.setImage(
            resManager.createImage(ImageDescriptor.createFromFile(PinDmdEditor.class, "/icons/line.png")));
    tltmLine.addListener(SWT.Selection, e -> dmdWidget.setDrawTool(drawTools.get("line")));

    ToolItem tltmCircle = new ToolItem(drawToolBar, SWT.RADIO);
    tltmCircle.setImage(
            resManager.createImage(ImageDescriptor.createFromFile(PinDmdEditor.class, "/icons/oval.png")));
    tltmCircle.addListener(SWT.Selection, e -> dmdWidget.setDrawTool(drawTools.get("circle")));

    ToolItem tltmColorize = new ToolItem(drawToolBar, SWT.RADIO);
    tltmColorize.setImage(
            resManager.createImage(ImageDescriptor.createFromFile(PinDmdEditor.class, "/icons/colorize.png")));
    tltmColorize.addListener(SWT.Selection, e -> dmdWidget.setDrawTool(drawTools.get("colorize")));
    drawTools.put("pencil", new SetPixelTool(paletteTool.getSelectedColor()));
    drawTools.put("fill", new FloodFillTool(paletteTool.getSelectedColor()));
    drawTools.put("rect", new RectTool(paletteTool.getSelectedColor()));
    drawTools.put("line", new LineTool(paletteTool.getSelectedColor()));
    drawTools.put("circle", new CircleTool(paletteTool.getSelectedColor()));
    drawTools.put("colorize", new ColorizeTool(paletteTool.getSelectedColor()));
    drawTools.values().forEach(d -> paletteTool.addIndexListener(d));
    paletteTool.addListener(palette -> {
        if (livePreviewActive) {
            connector.upload(activePalette, handle);
        }
    });
    new Label(grpDrawing, SWT.NONE);

    btnColorMask = new Button(grpDrawing, SWT.CHECK);
    btnColorMask.setToolTipText("limits drawing to upper planes, so that this will just add coloring layers");
    btnColorMask.setText("ColMask");
    btnColorMask.addListener(SWT.Selection, e -> switchColorMask(btnColorMask.getSelection()));

    Label lblMaskNo = new Label(grpDrawing, SWT.NONE);
    lblMaskNo.setText("Mask No:");

    maskSpinner = new Spinner(grpDrawing, SWT.BORDER);
    maskSpinner.setToolTipText("select the mask to use");
    maskSpinner.setMinimum(0);
    maskSpinner.setMaximum(9);
    maskSpinner.addListener(SWT.Selection, e -> maskNumberChanged(e));

    btnMask = new Button(grpDrawing, SWT.CHECK);
    btnMask.setText("Show Mask");
    btnMask.addListener(SWT.Selection, e -> switchMask(btnMask.getSelection()));

    btnCopyToPrev = new Button(grpDrawing, SWT.NONE);
    btnCopyToPrev.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    btnCopyToPrev.setText("CopyToPrev");
    btnCopyToPrev.addListener(SWT.Selection, e -> copyAndMoveToPrevFrame());

    new Label(grpDrawing, SWT.NONE);

    btnCopyToNext = new Button(grpDrawing, SWT.NONE);
    btnCopyToNext.setToolTipText("copy the actual scene / color mask to next frame and move forward");
    btnCopyToNext.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
    btnCopyToNext.setText("CopyToNext");
    btnCopyToNext.addListener(SWT.Selection, e -> copyAndMoveToNextFrame());

    btnUndo = new Button(grpDrawing, SWT.NONE);
    btnUndo.setText("&Undo");
    btnUndo.addListener(SWT.Selection, e -> undo());

    btnRedo = new Button(grpDrawing, SWT.NONE);
    btnRedo.setText("&Redo");
    btnRedo.addListener(SWT.Selection, e -> redo());

    ObserverManager.bind(maskDmdObserver, e -> btnUndo.setEnabled(e), () -> maskDmdObserver.canUndo());
    ObserverManager.bind(maskDmdObserver, e -> btnRedo.setEnabled(e), () -> maskDmdObserver.canRedo());

}

From source file:net.spfbl.data.White.java

private static boolean matches(String regex, String token) {
    try {// w  w  w .ja  v a  2s .com
        return Pattern.matches(regex, token);
    } catch (Exception ex) {
        return false;
    }
}