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.anritsu.mcrepositorymanager.utils.GenerateRSS.java

public String getRSS() {
    FileInputStream file = null;/*from  w  w  w  .ja v  a2  s  .  c om*/
    String rssFileName = rssTemplateFileName.replaceAll("template", mcVersion);
    try {
        file = new FileInputStream(
                new File(Configuration.getInstance().getRssTemplatePath() + rssTemplateFileName));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        workbook.setSheetName(workbook.getSheetIndex("MC X.X.X"), "MC " + mcVersion);
        XSSFSheet sheet = workbook.getSheet("MC " + mcVersion);
        CreationHelper createHelper = workbook.getCreationHelper();

        Cell cell = null;

        // Update the sheet title
        cell = sheet.getRow(0).getCell(0);
        cell.setCellValue(cell.getStringCellValue().replaceAll("template", mcVersion));

        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);

        XSSFCellStyle hlinkstyle = workbook.createCellStyle();
        XSSFFont hlinkfont = workbook.createFont();
        hlinkfont.setUnderline(XSSFFont.U_SINGLE);
        hlinkfont.setColor(HSSFColor.BLUE.index);
        hlinkstyle.setFont(hlinkfont);
        hlinkstyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        hlinkstyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        hlinkstyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        hlinkstyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);

        XSSFCellStyle dateCellStyle = workbook.createCellStyle();
        dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-MMMM-yyyy"));
        dateCellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        dateCellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        dateCellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        dateCellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);

        // Populate the table
        int rowCount = 1;
        for (RecommendedMcPackage rmcp : sortedMcPackages) {
            if (rmcp.getRecommendedVersion() != null && rmcp.isShowInTable()) {
                Row row = sheet.createRow(rowCount + 1);
                rowCount++;

                cell = row.createCell(0);
                cell.setCellValue(rmcp.getTier().replaceAll("Anritsu/MasterClaw/", ""));
                cell.setCellStyle(cellStyle);

                cell = row.createCell(1);
                cell.setCellValue(rmcp.getGroup());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(2);
                cell.setCellValue(rmcp.getPackageName());

                UrlValidator defaultValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);

                if (rmcp.getRecommendedVersion().getReleaseNote() != null
                        && defaultValidator.isValid(rmcp.getRecommendedVersion().getReleaseNote())) {
                    XSSFHyperlink releaseNotelink = (XSSFHyperlink) createHelper
                            .createHyperlink(Hyperlink.LINK_URL);
                    releaseNotelink.setAddress(rmcp.getRecommendedVersion().getReleaseNote());
                    //System.out.println("Inside(if) RN: " + rmcp.getRecommendedVersion().getReleaseNote() + " Valid: " + defaultValidator.isValid(rmcp.getRecommendedVersion().getReleaseNote()));

                    cell.setHyperlink(releaseNotelink);
                }
                cell.setCellStyle(hlinkstyle);

                cell = row.createCell(3);
                cell.setCellValue(rmcp.getRecommendedVersion().getPackageVersion());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(4);
                cell.setCellValue(rmcp.getAvailability());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(5);
                String customers = Arrays.asList(rmcp.getRecommendedVersion().getCustomerList().toArray())
                        .toString();
                if (customers.equalsIgnoreCase("[All]")) {
                    customers = "";
                }
                cell.setCellValue(customers);
                cell.setCellStyle(cellStyle);

                cell = row.createCell(6);
                cell.setCellValue(rmcp.getRecommendedVersion().getRisk());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(7);
                cell.setCellValue(rmcp.getPackageName());
                XSSFHyperlink link = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_URL);
                link.setAddress(rmcp.getRecommendedVersion().getDownloadLinks().iterator().next());
                cell.setHyperlink((XSSFHyperlink) link);
                cell.setCellStyle(hlinkstyle);

                cell = row.createCell(8);
                cell.setCellValue((rmcp.getRecommendedVersion() != null
                        && rmcp.getRecommendedVersion().isLessRecommended()) ? "#" : "");
                cell.setCellStyle(cellStyle);

                cell = row.createCell(9);
                cell.setCellValue(rmcp.getRecommendedVersion().getNotes());
                cell.setCellStyle(cellStyle);

                StringBuilder newFeatures = new StringBuilder();
                for (MCPackageActivities mcpa : rmcp.getRecommendedVersion().getActivities()) {
                    if (!mcpa.getActivityType().equalsIgnoreCase("epr")) {
                        newFeatures.append(mcpa.getActivityType() + " " + mcpa.getActivityId() + "; ");
                    }
                }
                cell = row.createCell(10);
                cell.setCellValue(newFeatures.toString());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(11);
                cell.setCellValue(rmcp.getRecommendedVersion().getReleaseDate());
                cell.setCellStyle(dateCellStyle);
            }
            sheet.autoSizeColumn(0);
            sheet.autoSizeColumn(1);
            sheet.autoSizeColumn(2);
            sheet.autoSizeColumn(3);
            sheet.autoSizeColumn(4);
            sheet.autoSizeColumn(6);
            sheet.autoSizeColumn(7);
            sheet.autoSizeColumn(8);
            sheet.autoSizeColumn(11);

        }

        FileOutputStream outFile = new FileOutputStream(
                new File(Configuration.getInstance().getRssTemplatePath() + rssFileName));
        workbook.write(outFile);
        outFile.close();
        return Configuration.getInstance().getRssTemplatePath() + rssFileName;

    } catch (FileNotFoundException ex) {
        Logger.getLogger(GenerateRSS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GenerateRSS.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            file.close();
        } catch (IOException ex) {
            Logger.getLogger(GenerateRSS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return "";
}

From source file:com.hp.autonomy.searchcomponents.hod.view.HodViewServerService.java

@Override
public void viewDocument(final String reference, final ResourceIdentifier index,
        final OutputStream outputStream) throws IOException, HodErrorException {
    final GetContentRequestBuilder getContentParams = new GetContentRequestBuilder().setPrint(Print.all);
    final Documents<Document> documents = getContentService.getContent(Collections.singletonList(reference),
            index, getContentParams);// ww w  .j  a v a2s. c  om

    // This document will always exist because the GetContentService.getContent throws a HodErrorException if the
    // reference doesn't exist in the index
    final Document document = documents.getDocuments().get(0);

    final Map<String, Serializable> fields = document.getFields();
    final Object urlField = fields.get(URL_FIELD);

    final String documentUrl = urlField instanceof List ? ((List<?>) urlField).get(0).toString()
            : document.getReference();

    final UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES);
    InputStream inputStream = null;

    try {
        try {
            final URL url = new URL(documentUrl);
            final URI uri = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null);
            final String encodedUrl = uri.toASCIIString();

            if (urlValidator.isValid(encodedUrl)) {
                inputStream = viewDocumentService.viewUrl(encodedUrl, new ViewDocumentRequestBuilder());
            } else {
                throw new URISyntaxException(encodedUrl, "Invalid URL");
            }
        } catch (URISyntaxException | MalformedURLException e) {
            // URL was not valid, fall back to using the document content
            inputStream = formatRawContent(document);
        } catch (final HodErrorException e) {
            if (e.getErrorCode() == HodErrorCode.BACKEND_REQUEST_FAILED) {
                // HOD failed to read the url, fall back to using the document content
                inputStream = formatRawContent(document);
            } else {
                throw e;
            }
        }

        IOUtils.copy(inputStream, outputStream);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.github.benchdoos.weblocopener.weblocOpener.gui.EditDialog.java

private void fillTextFieldWithClipboard() {
    String data = "<empty clipboard>";
    try {/*from   w  ww .  j a v  a  2  s.c  o m*/
        data = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
        URL url = new URL(data);
        UrlValidator urlValidator = new UrlValidator();
        if (urlValidator.isValid(data)) {
            textField.setText(url.toString());
            setTextFieldFont(textField.getFont(), TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
            textField.setCaretPosition(textField.getText().length());
            textField.selectAll();
            log.debug("Got URL from clipboard: " + url);
        }
    } catch (UnsupportedFlavorException | IllegalStateException | HeadlessException | IOException e) {
        textField.setText("");
        log.warn("Can not read URL from clipboard: [" + data + "]", e);
    }
}

From source file:com.github.benchdoos.weblocopener.weblocOpener.gui.EditDialog.java

private void onOK() {
    try {//from   w w w .  j a  v  a2s .  c o  m
        URL url = new URL(textField.getText());
        UrlValidator urlValidator = new UrlValidator();
        if (urlValidator.isValid(textField.getText())) {
            UrlsProceed.createWebloc(path, url);
            dispose();
        } else {
            throw new MalformedURLException();
        }
    } catch (MalformedURLException e) {
        log.warn("Can not parse URL: [" + textField.getText() + "]", e);

        String message = incorrectUrlMessage + ": [";
        String incorrectUrl = textField.getText().substring(0, Math.min(textField.getText().length(), 10));
        //Fixes EditDialog long url message showing issue
        message += textField.getText().length() > incorrectUrl.length() ? incorrectUrl + "...]"
                : incorrectUrl + "]";

        UserUtils.showWarningMessageToUser(this, errorTitle, message);
    }

}

From source file:io.frictionlessdata.datapackage.Package.java

private JSONObject getDereferencedObject(Object obj)
        throws IOException, FileNotFoundException, MalformedURLException {
    // The JSONObject that will represent the schema.
    JSONObject dereferencedObj = null;// ww  w  .j a  v a2 s.  c o m

    // Object is already a dereferences object.
    if (obj instanceof JSONObject) {

        // Don't need to do anything, just cast and return.
        dereferencedObj = (JSONObject) obj;

    } else if (obj instanceof String) {

        // The string value of the given object value.
        String objStr = (String) obj;

        // If object value is Url.
        // Grab the JSON string content of that remote file.
        String[] schemes = { "http", "https" };
        UrlValidator urlValidator = new UrlValidator(schemes);

        if (urlValidator.isValid(objStr)) {

            // Create the dereferenced object from the remote file.
            String jsonContentString = this.getJsonStringContentFromRemoteFile(new URL(objStr));
            dereferencedObj = new JSONObject(jsonContentString);

        } else {
            // If schema is file path.
            File sourceFile = new File(objStr);
            if (sourceFile.exists()) {
                // Create the dereferenced schema object from the local file.
                String jsonContentString = this.getJsonStringContentFromLocalFile(sourceFile.getAbsolutePath());
                dereferencedObj = new JSONObject(jsonContentString);

            } else {
                throw new FileNotFoundException("Local file not found: " + sourceFile);
            }
        }
    }

    return dereferencedObj;
}

From source file:com.github.benchdoos.weblocopener.weblocOpener.gui.EditDialog.java

private void initTextField(String pathToEditingFile) {
    textField.addMouseListener(new ClickListener() {
        @Override//from   w  w w. j a  va 2s .  c  om
        public void doubleClick(MouseEvent e) {
            textField.selectAll();
        }
    });

    textField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void changedUpdate(DocumentEvent e) {
        }

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

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

        private void updateTextFont() {
            UrlValidator urlValidator = new UrlValidator();
            if (urlValidator.isValid(textField.getText())) {
                if (textField != null) {
                    setTextFieldFont(textField.getFont(), TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
                    textField.setForeground(Color.BLUE);
                }
            } else {
                if (textField != null) {
                    setTextFieldFont(textField.getFont(), TextAttribute.UNDERLINE, -1);
                    textField.setForeground(Color.BLACK);
                }
            }
        }

    });

    UndoManager undoManager = new UndoManager();
    textField.getDocument().addUndoableEditListener(new UndoableEditListener() {

        public void undoableEditHappened(UndoableEditEvent evt) {
            undoManager.addEdit(evt.getEdit());
        }

    });

    textField.getActionMap().put("Undo", new AbstractAction("Undo") {
        public void actionPerformed(ActionEvent evt) {
            try {
                if (undoManager.canUndo()) {
                    undoManager.undo();
                }
            } catch (CannotUndoException e) {
            }
        }
    });

    textField.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");

    textField.getActionMap().put("Redo", new AbstractAction("Redo") {
        public void actionPerformed(ActionEvent evt) {
            try {
                if (undoManager.canRedo()) {
                    undoManager.redo();
                }
            } catch (CannotRedoException e) {
            }
        }
    });

    textField.getInputMap().put(KeyStroke.getKeyStroke("control shift Z"), "Redo");

    fillTextField(pathToEditingFile);
}

From source file:fr.esrf.icat.manager.core.handlers.NewServerHandler.java

@Execute
public void execute(final Shell shell) {
    boolean notok = true;
    final UrlValidator validator = new UrlValidator(new String[] { "http", "https" });
    while (notok) {
        InputDialog dlg = new InputDialog(shell, "New ICAT server",
                "Enter the URL of the new ICAT server\nYou can set either the service, wsdl or server URL", "",
                new IInputValidator() {
                    @Override/*from   ww w .  j  a  va 2s. c  o  m*/
                    public String isValid(String newText) {
                        if (null == newText || newText.isEmpty()) {
                            return "Please provide an URL";
                        }
                        if (!validator.isValid(newText)) {
                            return "Invalid URL";
                        }
                        return null;
                    }
                });
        if (dlg.open() == Window.OK) {
            final String s = dlg.getValue();
            final Matcher matcher = URL_PATTERN.matcher(s);
            if (matcher.find()) {
                final String serverURL = matcher.group(1) + "/";
                if (validator.isValid(serverURL)) {
                    ICATDataService.getInstance().addServer(new ICATServer(serverURL));
                    notok = false;
                } else {
                    MessageDialog.openError(shell, "Invalid server", serverURL + " appears to be invalid");
                }
            } else {
                MessageDialog.openError(shell, "Invalid URL", s + " appears to be invalid");
            }
        } else {
            notok = false;
        }
    }
}

From source file:io.frictionlessdata.datapackage.Resource.java

public Iterator iter(boolean keyed, boolean extended, boolean cast, boolean relations) throws Exception {
    // Error for non tabular
    if (this.profile == null || !this.profile.equalsIgnoreCase(Profile.PROFILE_TABULAR_DATA_RESOURCE)) {
        throw new DataPackageException("Unsupported for non tabular data.");
    }//from  ww w. ja  v  a2s  .c  o  m

    // If the path of a data file has been set.
    if (this.getPath() != null) {

        // And if it's just a one part resource (i.e. only one file path is given).
        if (this.getPath() instanceof File) {
            // then just return the interator for the data located in that file
            File file = (File) this.getPath();
            Table table = (this.schema != null) ? new Table(file, this.schema) : new Table(file);

            return table.iterator(keyed, extended, cast, relations);

        } else if (this.getPath() instanceof URL) {
            URL url = (URL) this.getPath();
            Table table = (this.schema != null) ? new Table(url, this.schema) : new Table(url);
            return table.iterator(keyed, extended, cast, relations);

        } else if (this.getPath() instanceof JSONArray) { // If multipart resource (i.e. multiple file paths are given).

            // Create an iterator for each file, chain them, and then return them as a single iterator.
            JSONArray paths = ((JSONArray) this.getPath());
            Iterator[] tableIteratorArray = new TableIterator[paths.length()];

            // Chain the iterators.
            for (int i = 0; i < paths.length(); i++) {

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

                String thePath = paths.getString(i);

                if (urlValidator.isValid(thePath)) {
                    URL url = new URL(thePath);
                    Table table = (this.schema != null) ? new Table(url, this.schema) : new Table(url);
                    tableIteratorArray[i] = table.iterator(keyed, extended, cast, relations);

                } else {
                    File file = new File(thePath);
                    Table table = (this.schema != null) ? new Table(file, this.schema) : new Table(file);
                    tableIteratorArray[i] = table.iterator(keyed, extended, cast, relations);
                }
            }

            IteratorChain iterChain = new IteratorChain(tableIteratorArray);
            return iterChain;

        } else {
            throw new DataPackageException(
                    "Unsupported data type for Resource path. Should be String or List but was "
                            + this.getPath().getClass().getTypeName());
        }

    } else if (this.getData() != null) {

        // Data is in String, hence in CSV Format.
        if (this.getData() instanceof String && this.getFormat().equalsIgnoreCase(FORMAT_CSV)) {
            Table table = new Table((String) this.getData());
            return table.iterator();
        }
        // Data is not String, hence in JSON Array format.
        else if (this.getData() instanceof JSONArray && this.getFormat().equalsIgnoreCase(FORMAT_JSON)) {
            JSONArray dataJsonArray = (JSONArray) this.getData();
            Table table = new Table(dataJsonArray);
            return table.iterator();

        } else {
            // Data is in unexpected format. Throw exception.
            throw new DataPackageException(
                    "A resource has an invalid data format. It should be a CSV String or a JSON Array.");
        }

    } else {
        throw new DataPackageException("No data has been set.");
    }
}

From source file:com.bitplan.pdfindex.Pdfindexer.java

/**
 * get the sources to index//from w  w w.  j  a v a  2s  .  co m
 * @param pSource - the source to get the files to index from
 * @return - the list of document sournce
 * @throws MalformedURLException - if there is a wrong url
 */
public List<DocumentSource> getFilesToIndex(String pSource) throws MalformedURLException {
    List<DocumentSource> result = new ArrayList<DocumentSource>();
    if (pSource != null) {
        UrlValidator urlValidator = new UrlValidator();
        if (urlValidator.isValid(pSource)) {
            result.add(new DocumentSource(new URL(pSource)));
        } else {
            File sourceFile = new File(pSource);
            if (sourceFile.isFile()) {
                result.add(new DocumentSource(sourceFile));
            } else if (sourceFile.isDirectory()) {
                for (final File file : sourceFile.listFiles()) {
                    if (file.isDirectory()) {
                        result.addAll(getFilesToIndex(file.getAbsolutePath()));
                    }
                    if (file.isFile()) {
                        if (file.getAbsolutePath().toLowerCase().endsWith(".pdf")) {
                            result.add(new DocumentSource(file));
                        }
                    }
                }
            } else {
                throw new IllegalArgumentException("getFilesToIndex failed for '" + pSource
                        + "' it is neither an URI, nor a file nor a directory");
            }
        }
    }
    return result;
}

From source file:it.polimi.tower4clouds.manager.ManagerConfig.java

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

    try {/*from ww w .  jav a  2s  .  c o  m*/
        daPort = Integer
                .parseInt(getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_DATA_ANALYZER_ENDPOINT_PORT_PUBLIC, "8175"));
        mmPort = Integer.parseInt(getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_MANAGER_ENDPOINT_PORT, "8170"));
        rdfHistoryDbPort = Integer
                .parseInt(getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_RDF_HISTORY_DB_ENDPOINT_PORT, "31337"));
    } catch (NumberFormatException e) {
        throw new ConfigurationException("The chosen port is not a valid number");
    }

    daIP = getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_DATA_ANALYZER_ENDPOINT_IP_PUBLIC, "127.0.0.1");
    mmIP = getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_MANAGER_ENDPOINT_IP, "127.0.0.1");
    rdfHistoryDbIP = getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_RDF_HISTORY_DB_ENDPOINT_IP, null);

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

}