Example usage for org.apache.commons.validator.routines UrlValidator isValid

List of usage examples for org.apache.commons.validator.routines UrlValidator isValid

Introduction

In this page you can find the example usage for org.apache.commons.validator.routines UrlValidator isValid.

Prototype

public boolean isValid(String value) 

Source Link

Document

Checks if a field has a valid url address.

Usage

From source file:com._17od.upm.gui.AccountDialog.java

/**
 * Use com.apache.commons.validator library in order to check the validity
 * (proper formating, e.x http://www.url.com) of the given URL.
 * // w  w w.  java  2s  .  c  om
 * @param urL
 * @return
 */
private boolean urlIsValid(String urL) {

    UrlValidator urlValidator = new UrlValidator();
    if (urlValidator.isValid(urL)) {
        return true;
    } else {
        return false;
    }

}

From source file:cl.uai.webcursos.emarking.desktop.OptionsDialog.java

/**
 * Create the dialog.//from   w w  w. j  a  v a 2 s  . c o  m
 */
public OptionsDialog(Moodle _moodle) {
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            cancelled = true;
        }
    });
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    setIconImage(Toolkit.getDefaultToolkit().getImage(OptionsDialog.class
            .getResource("/cl/uai/webcursos/emarking/desktop/resources/glyphicons_439_wrench.png")));
    setTitle(EmarkingDesktop.lang.getString("emarkingoptions"));
    setModal(true);
    setBounds(100, 100, 707, 444);
    this.moodle = _moodle;
    this.moodle.loadProperties();
    getContentPane().setLayout(new BorderLayout());
    {
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
        {
            okButton = new JButton(EmarkingDesktop.lang.getString("ok"));
            okButton.setEnabled(false);
            okButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
                        if (!validator.isValid(moodleurl.getText())) {
                            throw new Exception(EmarkingDesktop.lang.getString("invalidmoodleurl") + " "
                                    + moodleurl.getText());
                        }
                        File f = new File(filename.getText());
                        if (!f.exists() || f.isDirectory()
                                || (!f.getPath().endsWith(".pdf") && !f.getPath().endsWith(".zip"))) {
                            throw new Exception(EmarkingDesktop.lang.getString("invalidpdffile") + " "
                                    + filename.getText());
                        }
                        if (omrtemplate.getText().trim().length() > 0) {
                            File omrf = new File(omrtemplate.getText());
                            if (!omrf.exists() || omrf.isDirectory() || (!omrf.getPath().endsWith(".xtmpl"))) {
                                throw new Exception(EmarkingDesktop.lang.getString("invalidomrfile") + " "
                                        + omrtemplate.getText());
                            }
                        }
                        moodle.setLastfile(filename.getText());
                        moodle.getQrExtractor().setDoubleside(chckbxDoubleSide.isSelected());
                        moodle.setMaxthreads(Integer.parseInt(getMaxThreads().getSelectedItem().toString()));
                        moodle.setResolution(Integer.parseInt(getResolution().getSelectedItem().toString()));
                        moodle.setMaxzipsize(getMaxZipSize().getSelectedItem().toString());
                        moodle.setOMRTemplate(omrtemplate.getText());
                        moodle.setThreshold(Integer.parseInt(spinnerOMRthreshold.getValue().toString()));
                        moodle.setDensity(Integer.parseInt(spinnerOMRdensity.getValue().toString()));
                        moodle.setShapeSize(Integer.parseInt(spinnerOMRshapeSize.getValue().toString()));
                        moodle.setAnonymousPercentage(
                                Integer.parseInt(spinnerAnonymousPercentage.getValue().toString()));
                        moodle.setAnonymousPercentageCustomPage(
                                Integer.parseInt(spinnerAnonymousPercentageCustomPage.getValue().toString()));
                        moodle.setFakeStudents(chckbxMarkersTraining.isSelected());
                        moodle.saveProperties();
                        cancelled = false;
                        setVisible(false);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(panel,
                                EmarkingDesktop.lang.getString("invaliddatainform"));
                    }
                }
            });
            okButton.setActionCommand("OK");
            buttonPane.add(okButton);
            getRootPane().setDefaultButton(okButton);
        }
        {
            JButton cancelButton = new JButton(EmarkingDesktop.lang.getString("cancel"));
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    cancelled = true;
                    setVisible(false);
                }
            });
            cancelButton.setActionCommand("Cancel");
            buttonPane.add(cancelButton);
        }
    }

    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    getContentPane().add(tabbedPane, BorderLayout.CENTER);

    panel = new JPanel();
    tabbedPane.addTab(EmarkingDesktop.lang.getString("general"), null, panel, null);
    panel.setLayout(null);

    JPanel panel_2 = new JPanel();
    panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
    panel_2.setBounds(10, 11, 665, 131);
    panel.add(panel_2);
    panel_2.setLayout(null);

    JLabel lblPassword = new JLabel(EmarkingDesktop.lang.getString("password"));
    lblPassword.setBounds(10, 99, 109, 14);
    panel_2.add(lblPassword);
    lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);

    password = new JPasswordField();
    password.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            testConnection();
        }
    });
    password.setBounds(129, 96, 329, 20);
    panel_2.add(password);
    this.password.setText(this.moodle.getPassword());

    btnTestConnection = new JButton(EmarkingDesktop.lang.getString("connect"));
    btnTestConnection.setEnabled(false);
    btnTestConnection.setBounds(468, 93, 172, 27);
    panel_2.add(btnTestConnection);

    username = new JTextField();
    username.setBounds(129, 65, 329, 20);
    panel_2.add(username);
    username.setColumns(10);
    this.username.setText(this.moodle.getUsername());

    moodleurl = new JTextField();
    moodleurl.setBounds(129, 34, 329, 20);
    panel_2.add(moodleurl);
    moodleurl.setColumns(10);
    moodleurl.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent e) {
            warn();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            warn();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            warn();
        }

        private void warn() {
            UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
            if (!validator.isValid(moodleurl.getText()) || !moodleurl.getText().endsWith("/")) {
                moodleurl.setForeground(Color.RED);
                btnTestConnection.setEnabled(false);
            } else {
                moodleurl.setForeground(Color.BLACK);
                btnTestConnection.setEnabled(true);
            }
        }
    });

    // Initializing values from moodle configuration
    this.moodleurl.setText(this.moodle.getUrl());

    JLabel lblMoodleUrl = new JLabel(EmarkingDesktop.lang.getString("moodleurl"));
    lblMoodleUrl.setBounds(10, 37, 109, 14);
    panel_2.add(lblMoodleUrl);
    lblMoodleUrl.setHorizontalAlignment(SwingConstants.RIGHT);

    JLabel lblUsername = new JLabel(EmarkingDesktop.lang.getString("username"));
    lblUsername.setBounds(10, 68, 109, 14);
    panel_2.add(lblUsername);
    lblUsername.setHorizontalAlignment(SwingConstants.RIGHT);

    JLabel lblMoodleSettings = new JLabel(EmarkingDesktop.lang.getString("moodlesettings"));
    lblMoodleSettings.setBounds(10, 11, 230, 14);
    panel_2.add(lblMoodleSettings);
    btnTestConnection.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            testConnection();
        }
    });

    JPanel panel_3 = new JPanel();
    panel_3.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
    panel_3.setBounds(10, 159, 666, 174);
    panel.add(panel_3);
    panel_3.setLayout(null);

    JLabel lblPdfFile = new JLabel(EmarkingDesktop.lang.getString("pdffile"));
    lblPdfFile.setBounds(0, 39, 119, 14);
    panel_3.add(lblPdfFile);
    lblPdfFile.setHorizontalAlignment(SwingConstants.RIGHT);

    JLabel lblScanned = new JLabel(EmarkingDesktop.lang.getString("scanned"));
    lblScanned.setBounds(0, 64, 119, 14);
    panel_3.add(lblScanned);
    lblScanned.setHorizontalAlignment(SwingConstants.RIGHT);

    chckbxDoubleSide = new JCheckBox(EmarkingDesktop.lang.getString("doubleside"));
    chckbxDoubleSide.setEnabled(false);
    chckbxDoubleSide.setBounds(125, 60, 333, 23);
    panel_3.add(chckbxDoubleSide);
    chckbxDoubleSide.setToolTipText(EmarkingDesktop.lang.getString("doublesidetooltip"));
    this.chckbxDoubleSide.setSelected(this.moodle.getQrExtractor().isDoubleside());

    filename = new JTextField();
    filename.setEnabled(false);
    filename.setBounds(129, 36, 329, 20);
    panel_3.add(filename);
    filename.setColumns(10);
    filename.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent e) {
            warn();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            warn();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            warn();
        }

        private void warn() {
            validateFileForProcessing(!btnTestConnection.isEnabled());
        }
    });
    this.filename.setText(this.moodle.getLastfile());

    btnOpenPdfFile = new JButton(EmarkingDesktop.lang.getString("openfile"));
    btnOpenPdfFile.setEnabled(false);
    btnOpenPdfFile.setBounds(468, 33, 172, 27);
    panel_3.add(btnOpenPdfFile);

    JLabel lblPdfFileSettings = new JLabel(EmarkingDesktop.lang.getString("filesettings"));
    lblPdfFileSettings.setBounds(10, 11, 230, 14);
    panel_3.add(lblPdfFileSettings);

    JLabel lblOMRtemplate = new JLabel(EmarkingDesktop.lang.getString("omrfile"));
    lblOMRtemplate.setHorizontalAlignment(SwingConstants.RIGHT);
    lblOMRtemplate.setBounds(0, 142, 119, 14);
    panel_3.add(lblOMRtemplate);

    omrtemplate = new JTextField();
    omrtemplate.setEnabled(false);
    omrtemplate.setText((String) null);
    omrtemplate.setColumns(10);
    omrtemplate.setBounds(129, 139, 329, 20);
    panel_3.add(omrtemplate);
    omrtemplate.setText(this.moodle.getOMRTemplate());

    btnOpenOMRTemplate = new JButton(EmarkingDesktop.lang.getString("openomrfile"));
    btnOpenOMRTemplate.setEnabled(false);
    btnOpenOMRTemplate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle(EmarkingDesktop.lang.getString("openfiletitle"));
            chooser.setDialogType(JFileChooser.OPEN_DIALOG);
            chooser.setFileFilter(new FileFilter() {
                @Override
                public String getDescription() {
                    return "*.xtmpl";
                }

                @Override
                public boolean accept(File arg0) {
                    if (arg0.getName().endsWith(".xtmpl") || arg0.isDirectory())
                        return true;
                    return false;
                }
            });
            int retval = chooser.showOpenDialog(panel);
            if (retval == JFileChooser.APPROVE_OPTION) {
                omrtemplate.setText(chooser.getSelectedFile().getAbsolutePath());
            } else {
                return;
            }
        }
    });
    btnOpenOMRTemplate.setBounds(468, 136, 172, 27);
    panel_3.add(btnOpenOMRTemplate);

    lblMarkersTraining = new JLabel((String) EmarkingDesktop.lang.getString("markerstraining"));
    lblMarkersTraining.setHorizontalAlignment(SwingConstants.RIGHT);
    lblMarkersTraining.setBounds(0, 89, 119, 14);
    panel_3.add(lblMarkersTraining);

    chckbxMarkersTraining = new JCheckBox(EmarkingDesktop.lang.getString("markerstrainingfakestudents"));
    chckbxMarkersTraining.setBounds(125, 87, 333, 23);
    panel_3.add(chckbxMarkersTraining);
    btnOpenPdfFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            okButton.setEnabled(false);
            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle(EmarkingDesktop.lang.getString("openfiletitle"));
            chooser.setDialogType(JFileChooser.OPEN_DIALOG);
            chooser.setFileFilter(new FileFilter() {
                @Override
                public String getDescription() {
                    return "*.pdf, *.zip";
                }

                @Override
                public boolean accept(File arg0) {
                    if (arg0.getName().endsWith(".zip") || arg0.getName().endsWith(".pdf")
                            || arg0.isDirectory())
                        return true;
                    return false;
                }
            });
            int retval = chooser.showOpenDialog(panel);
            if (retval == JFileChooser.APPROVE_OPTION) {
                filename.setText(chooser.getSelectedFile().getAbsolutePath());
                okButton.setEnabled(true);
            } else {
                return;
            }
        }
    });

    JPanel panel_1 = new JPanel();
    tabbedPane.addTab(EmarkingDesktop.lang.getString("advanced"), null, panel_1, null);
    panel_1.setLayout(null);

    JPanel panel_4 = new JPanel();
    panel_4.setLayout(null);
    panel_4.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
    panel_4.setBounds(10, 11, 665, 131);
    panel_1.add(panel_4);

    JLabel lblAdvancedOptions = new JLabel(EmarkingDesktop.lang.getString("advancedoptions"));
    lblAdvancedOptions.setBounds(10, 11, 233, 14);
    panel_4.add(lblAdvancedOptions);

    JLabel lblThreads = new JLabel(EmarkingDesktop.lang.getString("maxthreads"));
    lblThreads.setBounds(10, 38, 130, 14);
    panel_4.add(lblThreads);
    lblThreads.setHorizontalAlignment(SwingConstants.RIGHT);

    JLabel lblSomething = new JLabel(EmarkingDesktop.lang.getString("separatezipfiles"));
    lblSomething.setBounds(10, 73, 130, 14);
    panel_4.add(lblSomething);
    lblSomething.setHorizontalAlignment(SwingConstants.RIGHT);

    JLabel label = new JLabel(EmarkingDesktop.lang.getString("resolution"));
    label.setBounds(10, 105, 130, 14);
    panel_4.add(label);
    label.setHorizontalAlignment(SwingConstants.RIGHT);

    resolution = new JComboBox<Integer>();
    resolution.setBounds(150, 99, 169, 27);
    panel_4.add(resolution);
    resolution.setModel(new DefaultComboBoxModel<Integer>(new Integer[] { 75, 100, 150, 300, 400, 500, 600 }));
    resolution.setSelectedIndex(2);
    this.resolution.setSelectedItem(this.moodle.getQrExtractor().getResolution());

    maxZipSize = new JComboBox<String>();
    maxZipSize.setBounds(150, 67, 169, 27);
    panel_4.add(maxZipSize);
    maxZipSize.setModel(new DefaultComboBoxModel<String>(new String[] { "<dynamic>", "2Mb", "4Mb", "8Mb",
            "16Mb", "32Mb", "64Mb", "128Mb", "256Mb", "512Mb", "1024Mb" }));
    maxZipSize.setSelectedIndex(6);
    this.maxZipSize.setSelectedItem(this.moodle.getMaxZipSizeString());

    maxThreads = new JComboBox<Integer>();
    maxThreads.setBounds(150, 32, 169, 27);
    panel_4.add(maxThreads);
    maxThreads.setModel(new DefaultComboBoxModel<Integer>(new Integer[] { 2, 4, 8, 16 }));
    maxThreads.setSelectedIndex(1);
    this.maxThreads.setSelectedItem(this.moodle.getQrExtractor().getMaxThreads());

    JPanel panel_5 = new JPanel();
    panel_5.setLayout(null);
    panel_5.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
    panel_5.setBounds(10, 153, 665, 131);
    panel_1.add(panel_5);

    JLabel lblOMRoptions = new JLabel(EmarkingDesktop.lang.getString("omroptions"));
    lblOMRoptions.setBounds(10, 11, 233, 14);
    panel_5.add(lblOMRoptions);

    JLabel lblOMRthreshold = new JLabel(EmarkingDesktop.lang.getString("omrthreshold"));
    lblOMRthreshold.setHorizontalAlignment(SwingConstants.RIGHT);
    lblOMRthreshold.setBounds(10, 32, 130, 14);
    panel_5.add(lblOMRthreshold);

    JLabel lblShapeSize = new JLabel(EmarkingDesktop.lang.getString("omrshapesize"));
    lblShapeSize.setHorizontalAlignment(SwingConstants.RIGHT);
    lblShapeSize.setBounds(10, 99, 130, 14);
    panel_5.add(lblShapeSize);

    JLabel lblDensity = new JLabel(EmarkingDesktop.lang.getString("omrdensity"));
    lblDensity.setHorizontalAlignment(SwingConstants.RIGHT);
    lblDensity.setBounds(10, 70, 130, 14);
    panel_5.add(lblDensity);

    spinnerOMRthreshold = new JSpinner();
    spinnerOMRthreshold.setBounds(150, 32, 169, 20);
    panel_5.add(spinnerOMRthreshold);
    spinnerOMRthreshold.setValue(this.moodle.getOMRthreshold());

    spinnerOMRdensity = new JSpinner();
    spinnerOMRdensity.setBounds(150, 67, 169, 20);
    panel_5.add(spinnerOMRdensity);
    spinnerOMRdensity.setValue(this.moodle.getOMRdensity());

    spinnerOMRshapeSize = new JSpinner();
    spinnerOMRshapeSize.setBounds(150, 99, 169, 20);
    panel_5.add(spinnerOMRshapeSize);
    spinnerOMRshapeSize.setValue(this.moodle.getOMRshapeSize());

    JLabel lblAnonymousPercentage = new JLabel(
            "<html>" + EmarkingDesktop.lang.getString("anonymouspercentage") + "</html>");
    lblAnonymousPercentage.setHorizontalAlignment(SwingConstants.RIGHT);
    lblAnonymousPercentage.setBounds(329, 32, 130, 27);
    panel_5.add(lblAnonymousPercentage);

    spinnerAnonymousPercentage = new JSpinner();
    spinnerAnonymousPercentage.setBounds(469, 32, 169, 20);
    panel_5.add(spinnerAnonymousPercentage);
    spinnerAnonymousPercentage.setValue(this.moodle.getAnonymousPercentage());

    JLabel lblAnonymousPercentageCustomPage = new JLabel(
            "<html>" + EmarkingDesktop.lang.getString("anonymouspercentagecustompage") + "</html>");
    lblAnonymousPercentageCustomPage.setHorizontalAlignment(SwingConstants.RIGHT);
    lblAnonymousPercentageCustomPage.setBounds(329, 70, 130, 27);
    panel_5.add(lblAnonymousPercentageCustomPage);

    spinnerAnonymousPercentageCustomPage = new JSpinner();
    spinnerAnonymousPercentageCustomPage.setBounds(469, 70, 169, 20);
    panel_5.add(spinnerAnonymousPercentageCustomPage);
    spinnerAnonymousPercentageCustomPage.setValue(this.moodle.getAnonymousPercentageCustomPage());

    JLabel lblCustomPage = new JLabel(
            "<html>" + EmarkingDesktop.lang.getString("anonymouscustompage") + "</html>");
    lblCustomPage.setHorizontalAlignment(SwingConstants.RIGHT);
    lblCustomPage.setBounds(329, 99, 130, 27);
    panel_5.add(lblCustomPage);

    spinnerCustomPage = new JSpinner();
    spinnerCustomPage.setBounds(469, 99, 169, 20);
    panel_5.add(spinnerCustomPage);
    spinnerCustomPage.setValue(this.moodle.getAnonymousCustomPage());
}

From source file:com._17od.upm.gui.MainWindow.java

private boolean urlIsValid(String urL) {

    UrlValidator urlValidator = new UrlValidator();
    if (urlValidator.isValid(urL)) {
        return true;
    } else {/*from ww  w .  ja  v  a  2s .  co m*/
        return false;
    }

}

From source file:com.nwn.NwnUpdaterHomeView.java

/**
 * Add server and save it to config//from  w  w w  .  ja  v  a2  s. c  om
 * Ensure the server name and url are valid and follow the same pattern 
 * that we expect to read from the config
 * @param evt 
 */
private void btnAddServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddServerActionPerformed
    //Regex validation is here to make sure we can read the config later. 
    //this should be changed both here and on the config object
    //todo: enum for regex values
    String newServerName, newServerFileUrl = null;
    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);
    String nameMessage = "Server Name:\n";
    String urlMessage = "Server File URL:\n";
    do {
        newServerName = (String) JOptionPane.showInputDialog(null, nameMessage, "Add Server",
                JOptionPane.PLAIN_MESSAGE);
        if (newServerName == null) {
            break;
        }
        if (newServerName.contains(",")) {
            nameMessage = "Name cannot have commas:\n";
            newServerName = "";
        }
    } while ((newServerName.length() == 0));
    do {
        if (newServerName == null) {
            break;
        }
        newServerFileUrl = (String) JOptionPane.showInputDialog(null, urlMessage, "Add Server",
                JOptionPane.PLAIN_MESSAGE);
        if (newServerFileUrl == null) {
            break;
        }
        if (!urlValidator.isValid(newServerFileUrl)) {
            urlMessage = "Please Enter Valid Url:\n";
            newServerFileUrl = "";
        }
    } while ((newServerFileUrl.length() == 0));
    if (newServerName != null && newServerFileUrl != null) {
        try {
            ServerInfo newServer = new ServerInfo(newServerName, new URL(newServerFileUrl));
            config.getServerList().add(newServer);
            cmbServerList.addItem(newServer);
            nwnUpdaterConfig.getInstance().save();
        } catch (Exception ex) {
            //            ex.printStackTrace();
            appendOutputText("\nERROR: Unknown error occured, cannot add server: " + newServerName);
        }
    }
}

From source file:it.polimi.modaclouds.monitoring.monitoring_manager.configuration.ManagerConfig.java

private ManagerConfig() throws ConfigurationException {
    UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);

    try {//from  ww  w . j  av  a 2 s . c  om
        ddaPort = Integer.parseInt(getEnvVar(Env.MODACLOUDS_MONITORING_DDA_ENDPOINT_PORT, "8175"));
        kbPort = Integer.parseInt(getEnvVar(Env.MODACLOUDS_KNOWLEDGEBASE_ENDPOINT_PORT, "3030"));
        mmPort = Integer.parseInt(getEnvVar(Env.MODACLOUDS_MONITORING_MANAGER_PORT, "8170"));
        mmPrivatePort = Integer.parseInt(getEnvVar(Env.MODACLOUDS_MONITORING_MANAGER_PRIVATE_PORT, "8070"));
    } catch (NumberFormatException e) {
        throw new ConfigurationException("The chosen port is not a valid number");
    }

    monitoringMetricsFileName = getEnvVar(Env.MODACLOUDS_MONITORING_MONITORING_METRICS_FILE, null);

    ddaIP = getEnvVar(Env.MODACLOUDS_MONITORING_DDA_ENDPOINT_IP, "127.0.0.1");
    kbIP = getEnvVar(Env.MODACLOUDS_KNOWLEDGEBASE_ENDPOINT_IP, "127.0.0.1");
    mmPrivateIP = getEnvVar(Env.MODACLOUDS_MONITORING_MANAGER_PRIVATE_IP, "127.0.0.1");
    kbPath = getEnvVar(Env.MODACLOUDS_KNOWLEDGEBASE_DATASET_PATH, "/modaclouds/kb");

    ddaUrl = "http://" + ddaIP + ":" + ddaPort;
    kbUrl = "http://" + kbIP + ":" + kbPort + kbPath;
    actionsExecutorUrl = "http://" + mmPrivateIP + ":" + mmPrivatePort + actionsExecutorPath;

    if (!validator.isValid(ddaUrl))
        throw new ConfigurationException(ddaUrl + " is not a valid URL");
    if (!validator.isValid(kbUrl))
        throw new ConfigurationException(kbUrl + " is not a valid URL");

}

From source file:com.ut.healthelink.service.impl.transactionInManagerImpl.java

@Override
public boolean isValidURL(String url) {
    UrlValidator urlValidator = new UrlValidator();
    if (urlValidator.isValid(url)) {
        return true;
    } else {//from w  w w .j  a  v  a  2 s .com
        return false;
    }
}

From source file:com.svi.uzabase.logic.ValidationProcess.java

private List<XMLHolder> validateData(List<XMLHolder> xmlBatchHolder) {
    try {/* ww  w .  j  a v  a 2  s  .co  m*/
        int totalCounter = 0;
        //Initialize dictionary
        String dictFileName = "file://./dic/english.jar";
        String configFile = "file://./classes/spellCheck.config";
        BasicDictionary dictionary = new BasicDictionary(dictFileName);
        SpellCheckConfiguration configuration = new SpellCheckConfiguration(configFile);
        BasicSuggester suggester = new BasicSuggester(configuration);
        suggester.attach(dictionary);

        // create SpellCheck object based on configuration and specify Suggester
        SpellCheck spellCheck = new SpellCheck(configuration);
        spellCheck.setSuggester(suggester);
        //set for jprogress bar
        for (XMLHolder h : xmlBatchHolder) {
            totalCounter += h.size();

        }
        progress = new AtomicInteger(0);
        total = new AtomicInteger(totalCounter);
        mf.setJprogressValues(total, progress);
        //validation process begins here
        String[] invalidWords = { "corporation", "inc.", "city", "corp.", "st.", "co.", "ltd." };
        String[] invalidBoardWords = { "other", "oth" };
        String[] validWords = { "loc", "to", "ext", "local" };
        String[] invalidCharacters = { ",", "/", "\\", "[", "]", "\"", ":", "^", "{", "}", "%", "+", "#", "(",
                ")" };
        String[] splitter;
        String tempURL;
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY/MM/DD");
        SimpleDateFormat fiscalYear = new SimpleDateFormat("MM/DD");
        sdf.setLenient(false);
        Set<String> officerList = new HashSet<>();
        List<Double> percentOwnership = new ArrayList<>();
        UrlValidator urlValidator = new UrlValidator();
        Date date = null;
        for (XMLHolder h : xmlBatchHolder) {
            for (Field f : h) {
                mf.loader("Validating fields: ", false);
                if (!f.getType().equals("none") && !f.getValue().equals("*N/A")) {
                    switch (f.getType()) {
                    case "city":
                        if (f.getValue().isEmpty() || f.getValue().equals("")) {
                            f.add("Address is empty");
                        } else {
                            if (hasWhiteSpaceTrailing(f.getValue())) {
                                f.add("has trailing white space ");
                            }
                            if (cityList.indexOf(f.getValue()) < 0) {
                                f.add("City not found on list!");
                            }
                        }

                        break;
                    case "province":
                        if (f.getValue().isEmpty() || f.getValue().equals("")) {
                            f.add("Address is empty");
                        } else {
                            if (hasWhiteSpaceTrailing(f.getValue())) {
                                f.add("has trailing white space ");
                            }
                            if (provinceList.indexOf(f.getValue()) < 0) {
                                f.add("Province not found on list!");
                            }
                        }

                        break;
                    case "tel":
                        if (!f.getValue().isEmpty() || !f.getValue().equals("")) {
                            //                                    if (f.getValue().matches("[a-z A-Z]+")) {
                            if (f.getValue().matches(".*[a-zA-Z]+.*")) {
                                for (String s : validWords) {
                                    if (!f.getValue().contains(s)) {
                                        f.add("Invalid telephone number");
                                    }
                                }
                            }

                            if (f.getValue().replace(" ", "").replace("-", "").length() < 7
                                    || f.getValue().replace(" ", "").replace("-", "").length() > 8) {
                                f.add("Invalid telephone number length");
                            }

                            if (hasWhiteSpaceTrailing(f.getValue())) {
                                f.add("has trailing white space ");
                            }
                            if (StringUtils.countMatches(f.getValue(), "-") > 2) {
                                f.add("Invalid telephone number");
                            }

                            for (String c : invalidCharacters) {
                                if (f.getValue().contains(c)) {
                                    f.add("Contains invalid character [ " + c + " ]");
                                    break;
                                }
                            }
                        }
                        break;
                    case "fax":
                        if (!f.getValue().isEmpty() || !f.getValue().equals("")) {
                            //                                    if (f.getValue().matches("[a-z A-Z]+")) {
                            if (f.getValue().matches(".*[a-zA-Z]+.*")) {
                                for (String s : validWords) {
                                    if (!f.getValue().contains(s)) {
                                        f.add("Invalid fax number");
                                    }
                                }
                            }
                            if (f.getValue().replace(" ", "").length() < 6) {
                                f.add("Invalid fax number");
                            }
                            if (StringUtils.countMatches(f.getValue(), "-") > 1) {
                                f.add("Invalid fax number");
                            }
                            if (hasWhiteSpaceTrailing(f.getValue())) {
                                f.add("has trailing white space ");
                            }
                            for (String c : invalidCharacters) {
                                if (f.getValue().contains(c)) {
                                    f.add("Contains invalid character [ " + c + " ]");
                                    break;
                                }
                            }
                        }
                        break;
                    case "person":
                        if (!f.getValue().isEmpty() || !f.getValue().equals("")) {
                            if (!f.getValue().matches("[a-zA-Z\\.,\\- ()]+")) {
                                f.add("Invalid name");
                            }
                            if (f.getValue().matches("[a-z ]+")) {
                                f.add("All small caps");
                            }
                            if (f.getValue().matches("\\w+")) {
                                f.add("Only one word");
                            }
                            if (f.getValue().replace(" ", "").length() > 30) {
                                f.add("More than 30 characters.");
                            }
                            if (f.getValue().replace(" ", "").length() < 2) {
                                f.add("Invalid name.");
                            }
                            if (hasWhiteSpaceTrailing(f.getValue())) {
                                f.add("has trailing white space ");
                            }
                        }
                        break;
                    case "email":
                        if (!f.getValue().isEmpty() || !f.getValue().equals("")) {
                            if (!EmailValidator.getInstance(true).isValid(f.getValue())) {
                                f.add("Invalid email");
                            }
                        }
                        break;
                    case "website":
                        if (!f.getValue().isEmpty() || !f.getValue().equals("")) {
                            if (!f.getValue().contains("http")) {
                                tempURL = "http://" + f.getValue();
                            } else {
                                tempURL = f.getValue();
                            }
                            if (!urlValidator.isValid(tempURL)) {
                                f.add("Invalid website");
                            }
                            if (hasWhiteSpaceTrailing(f.getValue())) {
                                f.add("has trailing white space ");
                            }
                        }
                        break;
                    case "name":
                        officerList.add(f.getValue());
                        if (!f.getValue().isEmpty() || !f.getValue().equals("")) {
                            if (!f.getValue().matches("[a-zA-Z\\.,\\-() ]+")) {
                                f.add("Invalid name");
                            }
                            if (f.getValue().replace(" ", "").length() > 30) {
                                f.add("More than 50 characters.");
                            }
                            if (f.getValue().matches("[a-z ]+")) {
                                f.add("All small caps");
                            }
                            if (f.getValue().matches("\\w+")) {
                                f.add("Only one word");
                            }
                            if (f.getValue().replace(" ", "").length() < 2) {
                                f.add("Invalid name.");
                            }
                            if (hasWhiteSpaceTrailing(f.getValue())) {
                                f.add("has trailing white space ");
                            }
                            for (String s : invalidWords) {
                                if (f.getValue().contains(s)) {
                                    f.add("Contains invalid word: " + s);
                                    break;
                                }
                            }
                        }
                        break;
                    case "stockholder":
                        officerList.add(f.getValue());
                        if (!f.getValue().isEmpty() || !f.getValue().equals("")) {
                            if (!f.getValue().matches("[a-zA-Z\\.,\\-() ]+")) {
                                f.add("Invalid name");
                            }
                            if (f.getValue().replace(" ", "").length() > 30) {
                                f.add("More than 50 characters.");
                            }
                            if (f.getValue().matches("[a-z ]+")) {
                                f.add("All small caps");
                            }
                            if (f.getValue().matches("\\w+")) {
                                f.add("Only one word");
                            }
                            if (f.getValue().replace(" ", "").length() < 2) {
                                f.add("Invalid name.");
                            }
                            if (hasWhiteSpaceTrailing(f.getValue())) {
                                f.add("has trailing white space ");
                            }
                            for (String s : invalidWords) {
                                if (f.getValue().contains(s)) {
                                    f.add("Contains invalid word: " + s);
                                    break;
                                }
                            }
                        }
                        break;
                    case "board":
                        if (!f.getValue().isEmpty() || !f.getValue().equals("")) {
                            if (!f.getValue().matches("[a-zA-Z\\.,\\-() ]+")) {
                                f.add("Invalid position");
                            }
                            for (String c : invalidCharacters) {
                                if (f.getValue().contains(c)) {
                                    f.add("Contains invalid character [ " + c + " ]");
                                    break;
                                }
                            }
                            for (String c : invalidBoardWords) {
                                if (f.getValue().contains(c)) {
                                    f.add("Contains invalid word [ " + c + " ]");
                                    break;
                                }
                            }

                            if (f.getValue().equalsIgnoreCase("N") || f.getValue().equalsIgnoreCase("Y")) {
                                f.add("is letter " + f.getValue() + " only");
                            }
                            if (Character.isLowerCase(f.getValue().charAt(0))) {
                                f.add("starts with a lower case letter");
                            }

                            spellCheck.setText(f.getValue(), Constants.DOC_TYPE_TEXT, "en");
                            spellCheck.check();
                            if (spellCheck.hasMisspelt()) {
                                f.add("word is misspelled.");
                            }

                        }
                        break;
                    case "corporation":
                        if (companyList.indexOf(f.getValue().toUpperCase()) < 0) {
                            f.add("Company name not found on table.");
                        }
                        break;
                    case "sec":
                        if (StringUtils.countMatches(f.getValue(), "-") > 1) {
                            f.add("Invalid SEC number");
                        }
                        if (f.getValue().replace(" ", "").length() > 9) {
                            f.add("SEC number more than 9 digits.");
                        }
                        if (hasWhiteSpaceTrailing(f.getValue())) {
                            f.add("SEC has trailing white space.");
                        }
                        for (String c : invalidCharacters) {
                            if (f.getValue().contains(c)) {
                                f.add("Contains invalid character [ " + c + " ]");
                                break;
                            }
                        }
                        break;
                    case "tin":
                        if (f.getValue().isEmpty() || f.getValue().equals("")) {
                            f.add("TIN is empty");
                        }
                        if (hasWhiteSpaceTrailing(f.getValue())) {
                            f.add("TIN has trailing white space.");
                        }
                        if (!f.getValue().matches("[0-9]+")) {
                            f.add("invalid TIN number");
                        }
                        if (f.getValue().replace(" ", "").replace("-", "").length() > 12
                                || f.getValue().replace(" ", "").replace("-", "").length() < 9) {
                            f.add("TIN number invalid length.");
                        }
                        if (StringUtils.countMatches(f.getValue(), "-") > 1) {
                            f.add("Invalid TIN number");
                        }
                        for (String c : invalidCharacters) {
                            if (f.getValue().contains(c)) {
                                f.add("Contains invalid character [ " + c + " ]");
                                break;
                            }
                        }
                        break;
                    case "nationality":
                        if (!f.getValue().isEmpty() || !f.getValue().equals("")) {
                            if (nationalityList.indexOf(f.getValue()) < 0) {
                                f.add("nationality is misspelled.");
                            }
                        }
                        break;
                    case "purpose":
                        splitter = f.getValue().split(" ");
                        for (int i = 0; i < splitter.length; i++) {
                            spellCheck.setText(splitter[i], Constants.DOC_TYPE_TEXT, "en");
                            spellCheck.check();
                            if (spellCheck.hasMisspelt()) {
                                f.add("word is misspelled. ( " + spellCheck.getMisspelt() + " )");
                            }
                        }
                        break;
                    case "periodCovered":
                        try {
                            date = sdf.parse(f.getValue());
                            if (!f.getValue().equals(sdf.format(date))) {
                                f.add("Invalid date format");
                            }
                        } catch (ParseException ex) {
                            f.add("Invalid date format");
                        }
                        break;
                    case "fiscalYear":
                        try {
                            date = fiscalYear.parse(f.getValue());
                            if (!f.getValue().equals(sdf.format(date))) {
                                f.add("Invalid date format");
                            }
                        } catch (ParseException ex) {
                            f.add("Invalid date format");
                        }
                        break;
                    case "position":
                        if (f.getValue().contains("\\d+")) {
                            f.add("Invalid position/designation");
                        }
                        if (f.getValue().replace(" ", "").length() > 10
                                || f.getValue().replace(" ", "").length() < 3) {
                            f.add("More than 30 characters.");
                        }
                        break;
                    case "shareType":
                        if (f.getValue().toLowerCase().contains("total")) {
                            f.add("Share type contains total.");
                        }

                        if (f.getValue().replace(" ", "").length() > 20) {
                            f.add("Share type More than 20 characters.");
                        }
                        break;
                    case "ownership":
                        percentOwnership.add(Double.parseDouble(f.getValue()));
                        if (Double.parseDouble(f.getValue()) > 100) {
                            f.add("Percent ownership more than 100%");
                        }
                        break;
                    default:
                        break;
                    }
                } else if (f.getType().equals("tin") && f.getValue().equals("*N/A")) {
                    f.add("TIN is N/A");
                }
            }
        }

    } catch (EncryptedDocumentException | SuggesterException ex) {
        Logger.getLogger(ValidationProcess.class.getName()).log(Level.SEVERE, null, ex);
    }
    return xmlBatchHolder;
}

From source file:noThreads.ParseLevel2.java

/**
 * @param theUrl/*from   w ww.  j  a  v a  2 s. c o  m*/
 * @param conAttempts
 * @return
 * @throws IOException
 */
public boolean validUrl(String theUrl, int conAttempts) throws IOException {
    long total_time = 0, endTime = 0;
    long startTime = System.currentTimeMillis();
    URL link = new URL(theUrl);
    int CONNECT_TIMEOUT = 5000, READ_TIMEOUT = 2000;

    HttpURLConnection huc = (HttpURLConnection) link.openConnection();
    huc.setRequestProperty("User-Agent", userAgent);
    huc.setConnectTimeout(CONNECT_TIMEOUT);
    huc.setReadTimeout(READ_TIMEOUT);
    try {
        huc.connect();

    } catch (java.net.ConnectException e) {
        print(e.getMessage() + "\n");
        if (e.getMessage().equalsIgnoreCase("Connection timed out")) {
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        } else {
            return false;
        }

    } catch (java.net.SocketTimeoutException e) {
        print(e.getMessage() + "\n");
        if (e.getMessage().equalsIgnoreCase("connect timed out")) {
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        } else {
            return false;
        }

    } catch (IOException e) {
        print(e.getMessage() + "\n");
        return false;
    }
    UrlValidator urlValidator = new UrlValidator();
    if (urlValidator.isValid(theUrl) == true) {
        print("valid url form");
        if (huc.getContentType() != null) {
            print("Content: " + huc.getContentType());
            if (huc.getContentType().equals("text/html") || huc.getContentType().equals("unknown/unknown")) {
                if (getResposeCode(theUrl, 0) >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
                    print("Server Response Code: " + getResposeCode(theUrl, 0));
                    return false;
                }
            }
            print(huc.getContentType());
            endTime = System.currentTimeMillis();
            total_time = total_time + (endTime - startTime);
            print("Total elapsed time is :" + total_time + "\n");
            return true;
        } else {//edw erxetai an den prolavei na diavasei h an einai null to content
            endTime = System.currentTimeMillis();
            total_time = total_time + (endTime - startTime);
            print("Total elapsed time is :" + total_time + "\n");
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        }
    } else {
        endTime = System.currentTimeMillis();
        total_time = total_time + (endTime - startTime);
        print("Total elapsed time is :" + total_time + "\n");
        return false;
    }
}

From source file:org.ambraproject.action.article.MediaCoverageAction.java

/**
 * Validate the input from the form/*from   w w w. j ava 2  s.  c  o m*/
 * @return true if everything is ok
 */
private boolean validateInput() {
    // TODO handle data better

    boolean isValid = true;

    if (StringUtils.isBlank(uri)) {
        isValid = false;
    }

    UrlValidator urlValidator = new UrlValidator();

    if (StringUtils.isBlank(link)) {
        addFieldError("link", "This field is required.");
        isValid = false;
    } else if (!urlValidator.isValid(link)) {
        addFieldError("link", "Invalid Media link URL");
        isValid = false;
    }

    if (StringUtils.isBlank(name)) {
        addFieldError("name", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(email)) {
        addFieldError("email", "This field is required.");
        isValid = false;
    } else if (!EmailValidator.getInstance().isValid(email)) {
        addFieldError("email", "Invalid e-mail address");
        isValid = false;
    }

    HttpServletRequest request = ServletActionContext.getRequest();

    if (!captchaService.validateCaptcha(request.getRemoteAddr(), captchaChallenge, captchaResponse)) {
        addFieldError("captcha", "Verification is incorrect. Please try again.");
        isValid = false;
    }

    if (isValid) {
        this.link = this.link.substring(0, Math.min(this.link.length(), MAX_LENGTH));
        this.name = this.name.substring(0, Math.min(this.name.length(), MAX_LENGTH));
        this.email = this.email.substring(0, Math.min(this.email.length(), MAX_LENGTH));

        if (!StringUtils.isBlank(comment)) {
            this.comment = this.comment.substring(0, Math.min(this.comment.length(), MAX_LENGTH));
        }
    }

    return isValid;
}

From source file:org.ambraproject.wombat.controller.MediaCurationController.java

/**
 * Validate the input from the form/*from   w w w  . j a v  a  2  s. com*/
 *
 * @param model data passed in from the view
 * @param link  link pointing to media content relating to the article
 * @param name  name of the user submitting the media curation request
 * @param email email of the user submitting the media curation request
 * @return true if everything is ok
 */

private boolean validateMediaCurationInput(Model model, String link, String name, String email, String title,
        String publishedOn, String consent) throws IOException {

    boolean isValid = true;

    UrlValidator urlValidator = new UrlValidator(new String[] { "http", "https" });

    if (consent == null || !"true".equals(consent)) {
        model.addAttribute("consentError", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(link)) {
        model.addAttribute("linkError", "This field is required.");
        isValid = false;
    } else if (!urlValidator.isValid(link)) {
        model.addAttribute("linkError", "Invalid Media link URL");
        isValid = false;
    }

    if (StringUtils.isBlank(name)) {
        model.addAttribute("nameError", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(title)) {
        model.addAttribute("titleError", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(publishedOn)) {
        model.addAttribute("publishedOnError", "This field is required.");
        isValid = false;
    } else {
        try {
            LocalDate.parse(publishedOn);
        } catch (DateTimeParseException e) {
            model.addAttribute("publishedOnError", "Invalid Date Format, should be YYYY-MM-DD");
            isValid = false;
        }
    }

    if (StringUtils.isBlank(email)) {
        model.addAttribute("emailError", "This field is required.");
        isValid = false;
    } else if (!EmailValidator.getInstance().isValid(email)) {
        model.addAttribute("emailError", "Invalid e-mail address");
        isValid = false;
    }

    model.addAttribute("isValid", isValid);
    return isValid;
}