Example usage for java.util.regex Pattern matches

List of usage examples for java.util.regex Pattern matches

Introduction

In this page you can find the example usage for java.util.regex Pattern matches.

Prototype

public static boolean matches(String regex, CharSequence input) 

Source Link

Document

Compiles the given regular expression and attempts to match the given input against it.

Usage

From source file:com.google.gerrit.server.project.RefControl.java

private boolean appliesToRef(AccessSection section) {
    String refPattern = section.getRefPattern();

    if (isTemplate(refPattern)) {
        ParamertizedString template = new ParamertizedString(refPattern);
        HashMap<String, String> p = new HashMap<String, String>();

        if (getCurrentUser() instanceof IdentifiedUser) {
            p.put("username", ((IdentifiedUser) getCurrentUser()).getUserName());
        } else {/*w  ww .  j  a va 2 s .c o  m*/
            // Right now we only template the username. If not available
            // this rule cannot be matched at all.
            //
            return false;
        }

        if (isRE(refPattern)) {
            for (Map.Entry<String, String> ent : p.entrySet()) {
                ent.setValue(escape(ent.getValue()));
            }
        }

        refPattern = template.replace(p);
    }

    if (isRE(refPattern)) {
        return Pattern.matches(refPattern, getRefName());

    } else if (refPattern.endsWith("/*")) {
        String prefix = refPattern.substring(0, refPattern.length() - 1);
        return getRefName().startsWith(prefix);

    } else {
        return getRefName().equals(refPattern);
    }
}

From source file:edu.harvard.iq.dataverse.HarvestingSetsPage.java

public void validateSetSpec(FacesContext context, UIComponent toValidate, Object rawValue) {
    String value = (String) rawValue;
    UIInput input = (UIInput) toValidate;
    input.setValid(true); // Optimistic approach

    if (context.getExternalContext().getRequestParameterMap().get("DO_VALIDATION") != null) {

        if (!StringUtils.isEmpty(value)) {
            if (!Pattern.matches("^[a-zA-Z0-9\\_\\-]+$", value)) {
                input.setValid(false);/*  ww w . ja  v a  2  s .  com*/
                context.addMessage(toValidate.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "",
                        JH.localize("harvestserver.newSetDialog.setspec.invalid")));
                return;

                // If it passes the regex test, check 
            } else if (oaiSetService.findBySpec(value) != null) {
                input.setValid(false);
                context.addMessage(toValidate.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "",
                        JH.localize("harvestserver.newSetDialog.setspec.alreadyused")));
                return;
            }

            // set spec looks legit!
            return;
        }

        // the field can't be left empty either: 
        input.setValid(false);
        context.addMessage(toValidate.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "",
                JH.localize("harvestserver.newSetDialog.setspec.required")));

    }

    // no validation requested - so we're cool!
}

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

/**
 * Verifica se o endereo  um TLD vlido./*  www.j  a v a  2s . c  o  m*/
 * @param address o endereo a ser verificado.
 * @return verdadeiro se o endereo  um TLD vlido.
 */
public static boolean isValidTLD(String address) {
    address = address.trim();
    address = address.toLowerCase();
    return Pattern.matches("^(\\.([a-z0-9]|[a-z0-9][a-z0-9-]+[a-z0-9])+)+$", address);
}

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

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

    return withSession(workspaceName, session -> {
        try {/* w ww. ja v  a2s  .  com*/
            final Node node = session.getNodeByIdentifier(id);
            return found.doInSessionWithNode(session, node);
        } catch (final PathNotFoundException e) {
            return notFound.doInSessionWithException(session, e);
        } catch (final RepositoryException e) {
            return error.doInSessionWithException(session, e);
        }
    });
}

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

/**
* Cancel a currently running template deployment.
*
* @param resourceGroupName Required. The name of the resource group. The
* name is case insensitive./*from   www .ja  v  a  2 s. c  om*/
* @param deploymentName Required. The name of the deployment.
* @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 A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse cancel(String resourceGroupName, String deploymentName)
        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 (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("resourceGroupName", resourceGroupName);
        tracingParameters.put("deploymentName", deploymentName);
        CloudTracing.enter(invocationId, this, "cancelAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourcegroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/cancel";
    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
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers

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

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        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.openkm.module.db.DbDocumentModule.java

public static Document createByMigration(String token, Document doc, InputStream is, long size)
        throws UnsupportedMimeTypeException, FileSizeExceededException, UserQuotaExceededException,
        VirusDetectedException, ItemExistsException, PathNotFoundException, AccessDeniedException,
        RepositoryException, IOException, DatabaseException, ExtensionException, AutomationException {

    System.out.println("Begin of createdByMigration");
    long begin = System.currentTimeMillis();
    Document newDocument = null;/*from   ww  w.  ja va2  s  . c  o  m*/
    Authentication auth = null, oldAuth = null;

    if (Config.SYSTEM_READONLY) {
        throw new AccessDeniedException("System is in read-only mode");
    }

    if (!PathUtils.checkPath(doc.getPath())) {
        throw new RepositoryException("Invalid path: " + doc.getPath());
    }

    String parentPath = PathUtils.getParent(doc.getPath());
    String name = PathUtils.getName(doc.getPath());

    // Add to KEA - must have the same extension
    int idx = name.lastIndexOf('.');
    String fileExtension = idx > 0 ? name.substring(idx) : ".tmp";
    File tmp = File.createTempFile("okm", fileExtension);

    try {
        if (token == null) {
            auth = PrincipalUtils.getAuthentication();
        } else {
            oldAuth = PrincipalUtils.getAuthentication();
            auth = PrincipalUtils.getAuthenticationByToken(token);
        }

        // Escape dangerous chars in name
        name = PathUtils.escape(name);

        if (!name.isEmpty()) {
            doc.setPath(parentPath + "/" + name);

            // Check file restrictions
            String mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
            doc.setMimeType(mimeType);

            if (Config.RESTRICT_FILE_MIME && MimeTypeDAO.findByName(mimeType) == null) {
                String usr = doc.getAuthor();
                UserActivity.log(usr, "ERROR_UNSUPPORTED_MIME_TYPE", null, doc.getPath(), mimeType);
                throw new UnsupportedMimeTypeException(mimeType);
            }

            // Restrict for extension
            if (!Config.RESTRICT_FILE_NAME.isEmpty()) {
                StringTokenizer st = new StringTokenizer(Config.RESTRICT_FILE_NAME, Config.LIST_SEPARATOR);

                while (st.hasMoreTokens()) {
                    String wc = st.nextToken().trim();
                    String re = ConfigUtils.wildcard2regexp(wc);

                    if (Pattern.matches(re, name)) {
                        String usr = doc.getAuthor();
                        UserActivity.log(usr, "ERROR_UNSUPPORTED_MIME_TYPE", null, doc.getPath(), mimeType);
                        throw new UnsupportedMimeTypeException(mimeType);
                    }
                }
            }

            // Manage temporary files
            byte[] buff = new byte[4 * 1024];
            FileOutputStream fos = new FileOutputStream(tmp);
            int read;

            while ((read = is.read(buff)) != -1) {
                fos.write(buff, 0, read);
            }

            fos.flush();
            fos.close();
            is.close();
            is = new FileInputStream(tmp);

            if (!Config.SYSTEM_ANTIVIR.equals("")) {
                String info = VirusDetection.detect(tmp);

                if (info != null) {
                    String usr = doc.getAuthor();
                    UserActivity.log(usr, "ERROR_VIRUS_DETECTED", null, doc.getPath(), info);
                    throw new VirusDetectedException(info);
                }
            }

            String parentUuid = NodeBaseDAO.getInstance().getUuidFromPath(parentPath);
            NodeBase parentNode = NodeBaseDAO.getInstance().findByPk(parentUuid);

            // AUTOMATION - PRE
            // INSIDE BaseDocumentModule.create

            // Create node
            Set<String> keywords = doc.getKeywords() != null ? doc.getKeywords() : new HashSet<String>();
            NodeDocument docNode = BaseDocumentModule.createByMigration(doc.getAuthor(), parentPath, parentNode,
                    name, doc.getTitle(), doc.getCreated(), mimeType, is, size, keywords, new HashSet<String>(),
                    new HashSet<NodeProperty>(), new ArrayList<NodeNote>());

            // AUTOMATION - POST
            // INSIDE BaseDocumentModule.create

            // Set returned folder properties
            newDocument = BaseDocumentModule.getProperties(auth.getName(), docNode);

            if (doc.getAuthor() == null) {
                // Check subscriptions
                BaseNotificationModule.checkSubscriptions(docNode, auth.getName(), "CREATE_DOCUMENT", null);

                // Activity log
                UserActivity.log(auth.getName(), "CREATE_DOCUMENT", docNode.getUuid(), doc.getPath(),
                        mimeType + ", " + size);
            } else {
                // Check subscriptions
                BaseNotificationModule.checkSubscriptions(docNode, doc.getAuthor(), "CREATE_MAIL_ATTACHMENT",
                        null);

                // Activity log
                UserActivity.log(doc.getAuthor(), "CREATE_MAIL_ATTACHMENT", docNode.getUuid(), doc.getPath(),
                        mimeType + ", " + size);
            }
        } else {
            throw new RepositoryException("Invalid document name");
        }
    } finally {
        IOUtils.closeQuietly(is);
        org.apache.commons.io.FileUtils.deleteQuietly(tmp);

        if (token != null) {
            PrincipalUtils.setAuthentication(oldAuth);
        }
    }

    log.trace("create.Time: {}", System.currentTimeMillis() - begin);
    log.debug("create: {}", newDocument);
    return newDocument;
}

From source file:cn.edu.hfut.dmic.contentextractor.ContentExtractor.java

/**
 * metaTitle?metaTitle,metaTitle??????title
 *
 * @param contentElement//from   w  w  w  .  j a  v a 2s. c om
 * @return
 * @throws Exception
 */
protected String getTitle(final Element contentElement) throws Exception {
    final ArrayList<Element> titleList = new ArrayList<Element>();
    final ArrayList<Double> titleSim = new ArrayList<Double>();
    final String metaTitle = getText(doc.title().trim());
    if (!metaTitle.isEmpty()) {
        doc.body().traverse(new NodeVisitor() {
            @Override
            public void head(Node node, int i) {
                if (node instanceof Element) {
                    Element tag = (Element) node;
                    String tagName = tag.tagName();
                    if (Pattern.matches("h[1-6]", tagName)) {
                        String title = tag.text().trim();
                        double sim = strSim(title, metaTitle);
                        titleSim.add(sim);
                        titleList.add(tag);
                    }
                }
            }

            @Override
            public void tail(Node node, int i) {
            }
        });
        int index = titleSim.size();
        if (index >= 0) {
            double maxScore = 0;
            int maxIndex = -1;
            for (int i = 0; i < index; i++) {
                double score = (i + 1) * titleSim.get(i);
                if (score > maxScore) {
                    maxScore = score;
                    maxIndex = i;
                }
            }

            if (maxIndex == -1 || titleSim.get(maxIndex) < 0.3) {
                String title = getText(metaTitle);
                if (!title.endsWith("") && title.length() > 7) {
                    return title;
                }
                Collections.sort(titleList, new Comparator<Element>() {
                    @Override
                    public int compare(Element o1, Element o2) {
                        int len1 = 1;
                        int len2 = 1;
                        if (o1.text().replaceAll("[^\\u4e00-\\u9fa5]", "").length() > 26
                                || o1.text().replaceAll("[^\\u4e00-\\u9fa5]", "").length() < 7) {
                            len1 = 0;
                        }
                        if (o2.text().replaceAll("[^\\u4e00-\\u9fa5]", "").length() > 26
                                || o2.text().replaceAll("[^\\u4e00-\\u9fa5]", "").length() < 7) {
                            len2 = 0;
                        }
                        if (len1 == len2) {
                            return o1.tagName().charAt(1) - o2.tagName().charAt(1);
                        }
                        return len2 - len1;
                    }
                });
                return getText(titleList.get(0).text());
            }
            return titleList.get(maxIndex).text();
        }
    }

    /**
     * ?
     */
    Elements titles = doc.body().select("*[id^=title],*[id$=title],*[class^=title],*[class$=title]");
    if (titles.size() > 0) {
        String title = titles.first().text();
        if (title.length() > 5 && title.length() < 40) {
            return titles.first().text();
        }
    }
    try {
        return getTitleByEditDistance(contentElement);
    } catch (Exception ex) {
        throw new Exception("title not found");
    }

}

From source file:com.ning.maven.plugins.dependencyversionscheck.AbstractDependencyVersionsMojo.java

/**
 * Locate the version strategy for a given version resolution. This will try
 * to locate a direct match and also do wildcard match on "group only" and "group and artifact".
 *//*from   w  w  w  . j ava2s.co  m*/
private Strategy findStrategy(final VersionResolution resolution) {
    final String dependencyName = resolution.getDependencyName();
    Strategy strategy = (Strategy) resolverMap.get(dependencyName);
    if (strategy != null) {
        LOG.debug("Found direct match: {}", strategy.getName());
        return strategy;
    }

    // No direct hit. Try just the group
    final String[] elements = StringUtils.split(dependencyName, ":");

    if (elements.length == 2) {
        strategy = (Strategy) resolverMap.get(elements[0]);

        if (strategy != null) {
            LOG.debug("Found group ({}) match: {}", elements[0], strategy.getName());

            resolverMap.put(dependencyName, strategy);
            return strategy;
        }

        // Try the wildcards
        for (Iterator it = resolverPatternMap.entrySet().iterator(); it.hasNext();) {
            final Map.Entry entry = (Map.Entry) it.next();
            final String pattern = (String) entry.getKey();
            final String patternElements[] = StringUtils.split(pattern, ":");

            if (Pattern.matches(patternElements[0], elements[0])) {
                // group wildcard match.
                if (patternElements.length == 1) {
                    strategy = (Strategy) entry.getValue();
                    LOG.debug("Found pattern match ({}) on group ({}) match: {}",
                            new Object[] { patternElements[0], elements[0], strategy.getName() });

                    resolverMap.put(dependencyName, strategy);
                    return strategy;
                }
                // group and artifact wildcard match.
                else if (Pattern.matches(patternElements[1], elements[1])) {
                    strategy = (Strategy) entry.getValue();
                    LOG.debug("Found regexp match ({}) on ({}) match: {}",
                            new Object[] { pattern, dependencyName, strategy.getName() });

                    resolverMap.put(dependencyName, strategy);
                    return strategy;
                }
            }
        }
    }

    strategy = defaultStrategyType;
    resolverMap.put(dependencyName, strategy);
    LOG.debug("Using default strategy for {} match: {}", dependencyName, strategy.getName());
    return strategy;
}

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

/**
 * {@inheritDoc}/*from  ww w .j av  a  2 s .c o  m*/
 */
@Override
public Long createComponent(Long farmNo, String componentName, Long componentTypeNo, String comment,
        Integer diskSize) {
    // ?
    if (farmNo == null) {
        throw new AutoApplicationException("ECOMMON-000003", "farmNo");
    }
    if (componentName == null || componentName.length() == 0) {
        throw new AutoApplicationException("ECOMMON-000003", "componentName");
    }
    if (componentTypeNo == null) {
        throw new AutoApplicationException("ECOMMON-000003", "componentTypeNo");
    }

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

    // TODO: ??

    // ???????
    Component checkComponent = componentDao.readByFarmNoAndComponentName(farmNo, componentName);
    if (checkComponent != null) {
        // ?????????
        throw new AutoApplicationException("ESERVICE-000301", componentName);
    }

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

    // ????
    Component component = new Component();
    component.setFarmNo(farmNo);
    component.setComponentName(componentName);
    component.setComponentTypeNo(componentTypeNo);
    component.setComment(comment);
    componentDao.create(component);

    // ?????
    if (diskSize != null) {
        // ?
        ComponentConfig componentConfig = new ComponentConfig();
        componentConfig.setComponentNo(component.getComponentNo());
        componentConfig.setConfigName(ComponentConstants.CONFIG_NAME_DISK_SIZE);
        componentConfig.setConfigValue(diskSize.toString());
        componentConfigDao.create(componentConfig);
    }

    ComponentType componentType = componentTypeDao.read(componentTypeNo);

    // TODO: ??phpMyAdmin???
    // MySQL??????phpMyAdmin??
    if (MySQLConstants.COMPONENT_TYPE_NAME.equals(componentType.getComponentTypeName())) {
        ComponentConfig componentConfig = new ComponentConfig();
        componentConfig.setComponentNo(component.getComponentNo());
        componentConfig.setConfigName(MySQLConstants.CONFIG_NAME_PHP_MY_ADMIN);
        componentConfig.setConfigValue("true");
        componentConfigDao.create(componentConfig);
    }

    // ??
    Boolean useZabbix = BooleanUtils.toBooleanObject(Config.getProperty("zabbix.useZabbix"));
    if (BooleanUtils.isTrue(useZabbix)) {
        zabbixHostProcess.createComponentHostgroup(component.getComponentNo());
    }

    // 
    eventLogger.log(EventLogLevel.INFO, farmNo, farm.getFarmName(), component.getComponentNo(), componentName,
            null, null, "ComponentCreate", null, null, new Object[] { componentType.getComponentTypeName() });

    return component.getComponentNo();
}

From source file:com.vgi.mafscaling.MafCompare.java

/**
 * Initialize the contents of the frame.
 */// www  .  j a v  a2s .  com
private void initialize() {
    try {
        ImageIcon tableImage = new ImageIcon(getClass().getResource("/table.jpg"));
        setTitle(Title);
        setIconImage(tableImage.getImage());
        setBounds(100, 100, 621, 372);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        setSize(Config.getCompWindowSize());
        setLocation(Config.getCompWindowLocation());
        setLocationRelativeTo(null);
        setVisible(false);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                Utils.clearTable(origMafTable);
                Utils.clearTable(newMafTable);
                Utils.clearTable(compMafTable);
                Config.setCompWindowSize(getSize());
                Config.setCompWindowLocation(getLocation());
                origMafData.clear();
                newMafData.clear();
            }
        });

        JPanel dataPanel = new JPanel();
        GridBagLayout gbl_dataPanel = new GridBagLayout();
        gbl_dataPanel.columnWidths = new int[] { 0, 0, 0 };
        gbl_dataPanel.rowHeights = new int[] { RowHeight, RowHeight, RowHeight, RowHeight, RowHeight, 0 };
        gbl_dataPanel.columnWeights = new double[] { 0.0, 0.0, 0.0 };
        gbl_dataPanel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 };
        dataPanel.setLayout(gbl_dataPanel);
        getContentPane().add(dataPanel);

        JLabel origLabel = new JLabel(origMaf);
        GridBagConstraints gbc_origLabel = new GridBagConstraints();
        gbc_origLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_origLabel.insets = new Insets(1, 1, 1, 5);
        gbc_origLabel.weightx = 0;
        gbc_origLabel.weighty = 0;
        gbc_origLabel.gridx = 0;
        gbc_origLabel.gridy = 0;
        gbc_origLabel.gridheight = 2;
        dataPanel.add(origLabel, gbc_origLabel);

        JLabel newLabel = new JLabel(newMaf);
        GridBagConstraints gbc_newLabel = new GridBagConstraints();
        gbc_newLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_newLabel.insets = new Insets(1, 1, 1, 5);
        gbc_newLabel.weightx = 0;
        gbc_newLabel.weighty = 0;
        gbc_newLabel.gridx = 0;
        gbc_newLabel.gridy = 2;
        gbc_newLabel.gridheight = 2;
        dataPanel.add(newLabel, gbc_newLabel);

        JLabel compLabel = new JLabel("Change");
        GridBagConstraints gbc_compLabel = new GridBagConstraints();
        gbc_compLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_compLabel.insets = new Insets(1, 1, 1, 5);
        gbc_compLabel.weightx = 0;
        gbc_compLabel.weighty = 0;
        gbc_compLabel.gridx = 0;
        gbc_compLabel.gridy = 4;
        dataPanel.add(compLabel, gbc_compLabel);

        JLabel origVoltLabel = new JLabel("volt");
        GridBagConstraints gbc_origVoltLabel = new GridBagConstraints();
        gbc_origVoltLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_origVoltLabel.insets = new Insets(1, 1, 1, 5);
        gbc_origVoltLabel.weightx = 0;
        gbc_origVoltLabel.weighty = 0;
        gbc_origVoltLabel.gridx = 1;
        gbc_origVoltLabel.gridy = 0;
        dataPanel.add(origVoltLabel, gbc_origVoltLabel);

        JLabel origGsLabel = new JLabel(" g/s");
        GridBagConstraints gbc_origGsLabel = new GridBagConstraints();
        gbc_origGsLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_origGsLabel.insets = new Insets(1, 1, 1, 5);
        gbc_origGsLabel.weightx = 0;
        gbc_origGsLabel.weighty = 0;
        gbc_origGsLabel.gridx = 1;
        gbc_origGsLabel.gridy = 1;
        dataPanel.add(origGsLabel, gbc_origGsLabel);

        JLabel newVoltLabel = new JLabel("volt");
        GridBagConstraints gbc_newVoltLabel = new GridBagConstraints();
        gbc_newVoltLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_newVoltLabel.insets = new Insets(1, 1, 1, 5);
        gbc_newVoltLabel.weightx = 0;
        gbc_newVoltLabel.weighty = 0;
        gbc_newVoltLabel.gridx = 1;
        gbc_newVoltLabel.gridy = 2;
        dataPanel.add(newVoltLabel, gbc_newVoltLabel);

        JLabel newGsLabel = new JLabel(" g/s");
        GridBagConstraints gbc_newGsLabel = new GridBagConstraints();
        gbc_newGsLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_newGsLabel.insets = new Insets(1, 1, 1, 5);
        gbc_newGsLabel.weightx = 0;
        gbc_newGsLabel.weighty = 0;
        gbc_newGsLabel.gridx = 1;
        gbc_newGsLabel.gridy = 3;
        dataPanel.add(newGsLabel, gbc_newGsLabel);

        JLabel compPctLabel = new JLabel(" %  ");
        GridBagConstraints gbc_compPctLabel = new GridBagConstraints();
        gbc_compPctLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_compPctLabel.insets = new Insets(1, 1, 1, 5);
        gbc_compPctLabel.weightx = 0;
        gbc_compPctLabel.weighty = 0;
        gbc_compPctLabel.gridx = 1;
        gbc_compPctLabel.gridy = 4;
        dataPanel.add(compPctLabel, gbc_compPctLabel);

        JPanel tablesPanel = new JPanel();
        GridBagLayout gbl_tablesPanel = new GridBagLayout();
        gbl_tablesPanel.columnWidths = new int[] { 0 };
        gbl_tablesPanel.rowHeights = new int[] { 0, 0, 0 };
        gbl_tablesPanel.columnWeights = new double[] { 0.0 };
        gbl_tablesPanel.rowWeights = new double[] { 0.0, 0.0, 1.0 };
        tablesPanel.setLayout(gbl_tablesPanel);

        JScrollPane mafScrollPane = new JScrollPane(tablesPanel);
        mafScrollPane.setMinimumSize(new Dimension(1600, 107));
        mafScrollPane.getHorizontalScrollBar().setMaximumSize(new Dimension(20, 20));
        mafScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        mafScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        GridBagConstraints gbc_mafScrollPane = new GridBagConstraints();
        gbc_mafScrollPane.weightx = 1.0;
        gbc_mafScrollPane.anchor = GridBagConstraints.PAGE_START;
        gbc_mafScrollPane.fill = GridBagConstraints.HORIZONTAL;
        gbc_mafScrollPane.gridx = 2;
        gbc_mafScrollPane.gridy = 0;
        gbc_mafScrollPane.gridheight = 5;
        dataPanel.add(mafScrollPane, gbc_mafScrollPane);

        origMafTable = new JTable();
        origMafTable.setColumnSelectionAllowed(true);
        origMafTable.setCellSelectionEnabled(true);
        origMafTable.setBorder(new LineBorder(new Color(0, 0, 0)));
        origMafTable.setRowHeight(RowHeight);
        origMafTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        origMafTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        origMafTable.setModel(new DefaultTableModel(2, MafTableColumnCount));
        origMafTable.setTableHeader(null);
        Utils.initializeTable(origMafTable, ColumnWidth);
        GridBagConstraints gbc_origMafTable = new GridBagConstraints();
        gbc_origMafTable.anchor = GridBagConstraints.PAGE_START;
        gbc_origMafTable.insets = new Insets(0, 0, 0, 0);
        gbc_origMafTable.fill = GridBagConstraints.HORIZONTAL;
        gbc_origMafTable.weightx = 1.0;
        gbc_origMafTable.weighty = 0;
        gbc_origMafTable.gridx = 0;
        gbc_origMafTable.gridy = 0;
        tablesPanel.add(origMafTable, gbc_origMafTable);
        excelAdapter.addTable(origMafTable, false, false, false, false, true, false, true, false, true);

        newMafTable = new JTable();
        newMafTable.setColumnSelectionAllowed(true);
        newMafTable.setCellSelectionEnabled(true);
        newMafTable.setBorder(new LineBorder(new Color(0, 0, 0)));
        newMafTable.setRowHeight(RowHeight);
        newMafTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        newMafTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        newMafTable.setModel(new DefaultTableModel(2, MafTableColumnCount));
        newMafTable.setTableHeader(null);
        Utils.initializeTable(newMafTable, ColumnWidth);
        GridBagConstraints gbc_newMafTable = new GridBagConstraints();
        gbc_newMafTable.anchor = GridBagConstraints.PAGE_START;
        gbc_newMafTable.insets = new Insets(0, 0, 0, 0);
        gbc_newMafTable.fill = GridBagConstraints.HORIZONTAL;
        gbc_newMafTable.weightx = 1.0;
        gbc_newMafTable.weighty = 0;
        gbc_newMafTable.gridx = 0;
        gbc_newMafTable.gridy = 1;
        tablesPanel.add(newMafTable, gbc_newMafTable);
        excelAdapter.addTable(newMafTable, false, false, false, false, false, false, false, false, true);

        compMafTable = new JTable();
        compMafTable.setColumnSelectionAllowed(true);
        compMafTable.setCellSelectionEnabled(true);
        compMafTable.setBorder(new LineBorder(new Color(0, 0, 0)));
        compMafTable.setRowHeight(RowHeight);
        compMafTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        compMafTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        compMafTable.setModel(new DefaultTableModel(1, MafTableColumnCount));
        compMafTable.setTableHeader(null);
        Utils.initializeTable(compMafTable, ColumnWidth);
        NumberFormatRenderer numericRenderer = new NumberFormatRenderer();
        numericRenderer.setFormatter(new DecimalFormat("0.000"));
        compMafTable.setDefaultRenderer(Object.class, numericRenderer);
        GridBagConstraints gbc_compMafTable = new GridBagConstraints();
        gbc_compMafTable.anchor = GridBagConstraints.PAGE_START;
        gbc_compMafTable.insets = new Insets(0, 0, 0, 0);
        gbc_compMafTable.fill = GridBagConstraints.HORIZONTAL;
        gbc_compMafTable.weightx = 1.0;
        gbc_compMafTable.weighty = 0;
        gbc_compMafTable.gridx = 0;
        gbc_compMafTable.gridy = 2;
        tablesPanel.add(compMafTable, gbc_compMafTable);
        compExcelAdapter.addTable(compMafTable, false, true, false, false, false, true, true, false, true);

        TableModelListener origTableListener = new TableModelListener() {
            public void tableChanged(TableModelEvent tme) {
                if (tme.getType() == TableModelEvent.UPDATE) {
                    int colCount = origMafTable.getColumnCount();
                    Utils.ensureColumnCount(colCount, newMafTable);
                    Utils.ensureColumnCount(colCount, compMafTable);
                    origMafData.clear();
                    String origY, origX, newY;
                    for (int i = 0; i < colCount; ++i) {
                        origY = origMafTable.getValueAt(1, i).toString();
                        if (Pattern.matches(Utils.fpRegex, origY)) {
                            origX = origMafTable.getValueAt(0, i).toString();
                            if (Pattern.matches(Utils.fpRegex, origX))
                                origMafData.add(Double.valueOf(origX), Double.valueOf(origY), false);
                            newY = newMafTable.getValueAt(1, i).toString();
                            if (Pattern.matches(Utils.fpRegex, newY))
                                compMafTable.setValueAt(
                                        ((Double.valueOf(newY) / Double.valueOf(origY)) - 1.0) * 100.0, 0, i);
                        } else
                            break;
                    }
                    origMafData.fireSeriesChanged();
                }
            }
        };

        TableModelListener newTableListener = new TableModelListener() {
            public void tableChanged(TableModelEvent tme) {
                if (tme.getType() == TableModelEvent.UPDATE) {
                    int colCount = newMafTable.getColumnCount();
                    Utils.ensureColumnCount(colCount, origMafTable);
                    Utils.ensureColumnCount(colCount, compMafTable);
                    newMafData.clear();
                    String newY, newX, origY;
                    for (int i = 0; i < colCount; ++i) {
                        newY = newMafTable.getValueAt(1, i).toString();
                        if (Pattern.matches(Utils.fpRegex, newY)) {
                            newX = newMafTable.getValueAt(0, i).toString();
                            if (Pattern.matches(Utils.fpRegex, newX))
                                newMafData.add(Double.valueOf(newX), Double.valueOf(newY), false);
                            origY = origMafTable.getValueAt(1, i).toString();
                            if (Pattern.matches(Utils.fpRegex, origY))
                                compMafTable.setValueAt(
                                        ((Double.valueOf(newY) / Double.valueOf(origY)) - 1.0) * 100.0, 0, i);
                        } else
                            break;
                    }
                    newMafData.fireSeriesChanged();
                }
            }
        };

        origMafTable.getModel().addTableModelListener(origTableListener);
        newMafTable.getModel().addTableModelListener(newTableListener);

        Action action = new AbstractAction() {
            private static final long serialVersionUID = 8148393537657380215L;

            public void actionPerformed(ActionEvent e) {
                TableCellListener tcl = (TableCellListener) e.getSource();
                if (Pattern.matches(Utils.fpRegex, compMafTable.getValueAt(0, tcl.getColumn()).toString())) {
                    if (Pattern.matches(Utils.fpRegex,
                            origMafTable.getValueAt(1, tcl.getColumn()).toString())) {
                        double corr = Double.valueOf(compMafTable.getValueAt(0, tcl.getColumn()).toString())
                                / 100.0 + 1.0;
                        newMafTable.setValueAt(
                                Double.valueOf(origMafTable.getValueAt(1, tcl.getColumn()).toString()) * corr,
                                1, tcl.getColumn());
                    }
                } else
                    compMafTable.setValueAt(tcl.getOldValue(), 0, tcl.getColumn());
            }
        };

        setCompMafCellListener(new TableCellListener(compMafTable, action));

        // CHART

        JFreeChart chart = ChartFactory.createXYLineChart(null, null, null, null, PlotOrientation.VERTICAL,
                false, true, false);
        chart.setBorderVisible(true);
        chartPanel = new ChartPanel(chart, true, true, true, true, true);
        chartPanel.setAutoscrolls(true);

        GridBagConstraints gbl_chartPanel = new GridBagConstraints();
        gbl_chartPanel.anchor = GridBagConstraints.PAGE_START;
        gbl_chartPanel.fill = GridBagConstraints.BOTH;
        gbl_chartPanel.insets = new Insets(1, 1, 1, 1);
        gbl_chartPanel.weightx = 1.0;
        gbl_chartPanel.weighty = 1.0;
        gbl_chartPanel.gridx = 0;
        gbl_chartPanel.gridy = 5;
        gbl_chartPanel.gridheight = 1;
        gbl_chartPanel.gridwidth = 3;
        dataPanel.add(chartPanel, gbl_chartPanel);

        XYSplineRenderer lineRenderer = new XYSplineRenderer(3);
        lineRenderer.setUseFillPaint(true);
        lineRenderer.setBaseToolTipGenerator(
                new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                        new DecimalFormat("0.00"), new DecimalFormat("0.00")));

        Stroke stroke = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, null, 0.0f);
        lineRenderer.setSeriesStroke(0, stroke);
        lineRenderer.setSeriesStroke(1, stroke);
        lineRenderer.setSeriesPaint(0, new Color(201, 0, 0));
        lineRenderer.setSeriesPaint(1, new Color(0, 0, 255));
        lineRenderer.setSeriesShape(0, ShapeUtilities.createDiamond((float) 2.5));
        lineRenderer.setSeriesShape(1, ShapeUtilities.createDownTriangle((float) 2.5));
        lineRenderer.setLegendItemLabelGenerator(new StandardXYSeriesLabelGenerator() {
            private static final long serialVersionUID = -4045338273187150888L;

            public String generateLabel(XYDataset dataset, int series) {
                XYSeries xys = ((XYSeriesCollection) dataset).getSeries(series);
                return xys.getDescription();
            }
        });

        NumberAxis mafvDomain = new NumberAxis(XAxisName);
        mafvDomain.setAutoRangeIncludesZero(false);
        mafvDomain.setAutoRange(true);
        mafvDomain.setAutoRangeStickyZero(false);
        NumberAxis mafgsRange = new NumberAxis(YAxisName);
        mafgsRange.setAutoRangeIncludesZero(false);
        mafgsRange.setAutoRange(true);
        mafgsRange.setAutoRangeStickyZero(false);

        XYSeriesCollection lineDataset = new XYSeriesCollection();
        origMafData.setDescription(origMaf);
        newMafData.setDescription(newMaf);
        lineDataset.addSeries(origMafData);
        lineDataset.addSeries(newMafData);

        XYPlot plot = chart.getXYPlot();
        plot.setRangePannable(true);
        plot.setDomainPannable(true);
        plot.setDomainGridlinePaint(Color.DARK_GRAY);
        plot.setRangeGridlinePaint(Color.DARK_GRAY);
        plot.setBackgroundPaint(new Color(224, 224, 224));

        plot.setDataset(0, lineDataset);
        plot.setRenderer(0, lineRenderer);
        plot.setDomainAxis(0, mafvDomain);
        plot.setRangeAxis(0, mafgsRange);
        plot.mapDatasetToDomainAxis(0, 0);
        plot.mapDatasetToRangeAxis(0, 0);

        LegendTitle legend = new LegendTitle(plot.getRenderer());
        legend.setItemFont(new Font("Arial", 0, 10));
        legend.setPosition(RectangleEdge.TOP);
        chart.addLegend(legend);

    } catch (Exception e) {
        logger.error(e);
    }
}