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

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

Introduction

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

Prototype

public UrlValidator(long options) 

Source Link

Document

Initialize a UrlValidator with the given validation options.

Usage

From source file:ching.icecreaming.action.EditAction.java

public void validate() {
    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);
    if (StringUtils.isNotBlank(sid)) {
        if (!urlValidator.isValid(sid))
            addFieldError("sid", getText("URL.is.invalid"));
        if (StringUtils.isBlank(uid))
            addFieldError("uid", getText("Username.is.required"));
        if (StringUtils.isBlank(pid))
            addFieldError("pid", getText("Password.cannot.be.empty"));
    }//from w  ww  .j a  v a  2 s.  c om
}

From source file:eu.freme.broker.tools.NIFParameterFactory.java

public NIFParameterSet constructFromHttp(String input, String informat, String outformat, String postBody,
        String acceptHeader, String contentTypeHeader, String prefix, boolean allowEmptyInput)
        throws BadRequestException {

    String thisInput;/*w  w  w. ja v a2s  . com*/
    if (!allowEmptyInput && input == null && postBody == null) {
        throw new BadRequestException("no input found in request");
    } else if (input != null) {
        thisInput = input;
    } else {
        thisInput = postBody;
    }

    RDFSerialization thisInformat;
    if (informat == null && contentTypeHeader == null) {
        thisInformat = RDFSerialization.TURTLE;
    } else if (informat != null) {
        if (!rdfSerializationFormats.containsKey(informat)) {
            throw new BadRequestException("parameter informat has invalid value \"" + informat + "\"");
        }
        thisInformat = rdfSerializationFormats.get(informat);
    } else {
        String[] contentTypeHeaderParts = contentTypeHeader.split(";");
        if (!rdfSerializationFormats.containsKey(contentTypeHeaderParts[0])) {
            throw new BadRequestException(
                    "Content-Type header has invalid value \"" + contentTypeHeader + "\"");
        }
        thisInformat = rdfSerializationFormats.get(contentTypeHeaderParts[0]);
    }

    RDFSerialization thisOutformat;
    if (acceptHeader != null && acceptHeader.equals("*/*")) {
        acceptHeader = "text/turtle";
    }
    if (outformat == null && acceptHeader == null) {
        thisOutformat = RDFSerialization.TURTLE;
    } else if (outformat != null) {
        if (!rdfSerializationFormats.containsKey(outformat)) {
            throw new BadRequestException("Parameter outformat has invalid value \"" + outformat + "\"");
        }
        thisOutformat = rdfSerializationFormats.get(outformat);

        if (thisOutformat == RDFConstants.RDFSerialization.PLAINTEXT) {
            throw new BadRequestException("Parameter outformat has invalid value \"" + outformat + "\"");
        }
    } else {
        if (!rdfSerializationFormats.containsKey(acceptHeader)) {
            throw new BadRequestException("Parameter outformat has invalid value \"" + acceptHeader + "\"");
        }
        thisOutformat = rdfSerializationFormats.get(acceptHeader);

        if (thisOutformat == RDFConstants.RDFSerialization.PLAINTEXT) {
            throw new BadRequestException("Parameter outformat has invalid value \"" + acceptHeader + "\"");
        }
    }

    String thisPrefix;
    if (prefix == null) {
        thisPrefix = defaultPrefix;
    } else {
        thisPrefix = prefix;
    }
    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);
    if (!urlValidator.isValid(thisPrefix)) {
        throw new BadRequestException("invalid prefix");
    }

    return new NIFParameterSet(thisInput, thisInformat, thisOutformat, thisPrefix);
}

From source file:ke.co.tawi.babblesms.server.sendsms.tawismsgw.PostSMS.java

/**
 * Contains what is required to send SMS using the Tawi SMS Gateway. 
 * // www.  j a  va 2  s. c  o m
 * @param smsGateway
 * @param phoneList
 * @param smsSource
 * @param message
 * @param account
 * @param retry whether or not to keep retrying if the POST fails
 */
public PostSMS(TawiGateway smsGateway, List<Phone> phoneList, SMSSource smsSource, String message,
        Account account, boolean retry) {
    this.smsGateway = smsGateway;
    this.phoneList = phoneList;
    this.smsSource = smsSource;
    this.message = message;

    this.account = account;

    this.retry = retry;

    retryCount = RETRY_NUMBER;

    urlValidator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES + UrlValidator.ALLOW_LOCAL_URLS);

    outgoingLogDAO = OutgoingLogDAO.getInstance();

    logger = Logger.getLogger(this.getClass());
}

From source file:com.anritsu.mcrepositorymanager.utils.GenerateRSS.java

public String getRSS() {
    FileInputStream file = null;//from ww  w  .  j  a  va 2  s  .  c  o  m
    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:cl.uai.webcursos.emarking.desktop.OptionsDialog.java

/**
 * Create the dialog.//w  w  w  . ja v  a 2  s.com
 */
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.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  va 2s .co m*/

    // 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: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.");
    }//w w  w. jav a2s.com

    // 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:eu.freme.common.rest.NIFParameterFactory.java

public NIFParameterSet constructFromHttp(String input, String informat, String outformat, String postBody,
        String acceptHeader, String contentTypeHeader, String prefix, String nifVersion,
        boolean allowEmptyInput) throws BadRequestException {

    String thisInput;//ww  w.j  a  v a  2  s . c o  m
    if (!allowEmptyInput && input == null && postBody == null) {
        throw new BadRequestException("no input found in request");
    } else if (input != null) {
        thisInput = input;
    } else {
        thisInput = postBody;
    }

    String thisInformat;
    if (informat == null && contentTypeHeader == null) {
        thisInformat = TURTLE;
    } else if (informat != null) {
        thisInformat = serializationFormatMapper.get(informat);
        if (thisInformat == null) {
            throw new BadRequestException("parameter informat has invalid value \"" + informat
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    } else {
        String[] contentTypeHeaderParts = contentTypeHeader.split(";");
        thisInformat = serializationFormatMapper.get(contentTypeHeaderParts[0]);
        if (thisInformat == null) {
            throw new BadRequestException("Content-Type header has invalid value \"" + contentTypeHeader
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    }
    if (!RDFConstants.SERIALIZATION_FORMATS.contains(thisInformat)
            && !thisInformat.equals(SerializationFormatMapper.PLAINTEXT)) {
        throw new UnsupportedRDFSerializationException("Parameter informat has invalid value \"" + thisInformat
                + "\". Please use one of: "
                + SERIALIZATION_FORMATS.stream()
                        .map(v -> MapUtils.invertMap(serializationFormatMapper).get(v).toString())
                        .collect(Collectors.joining(", "))
                + " or " + SerializationFormatMapper.PLAINTEXT);
    }

    String thisOutformat;
    if (acceptHeader != null && acceptHeader.equals("*/*")) {
        acceptHeader = TURTLE;
    }
    if (outformat == null && acceptHeader == null) {
        thisOutformat = TURTLE;
    } else if (outformat != null) {
        thisOutformat = serializationFormatMapper.get(outformat);
        if (thisOutformat == null) {
            throw new BadRequestException("Parameter outformat has invalid value \"" + outformat
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    } else {
        thisOutformat = serializationFormatMapper.get(acceptHeader.split(";")[0]);
        if (thisOutformat == null) {
            throw new BadRequestException("Accept header has invalid value \"" + acceptHeader.split(";")[0]
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    }
    if (!RDFConstants.SERIALIZATION_FORMATS.contains(thisOutformat)) {
        throw new UnsupportedRDFSerializationException(
                "Parameter outformat has invalid value \"" + thisOutformat + "\". Please use one of: "
                        + SERIALIZATION_FORMATS.stream()
                                .map(v -> MapUtils.invertMap(serializationFormatMapper).get(v).toString())
                                .collect(Collectors.joining(", ")));
    }

    String thisPrefix;
    if (prefix == null) {
        thisPrefix = getDefaultPrefix();
    } else {
        thisPrefix = prefix;
    }
    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);
    if (!urlValidator.isValid(thisPrefix)) {
        throw new BadRequestException("invalid prefix");
    }

    if (nifVersion == null) {
        nifVersion = RDFConstants.nifVersion2_0;
    } else if (!(nifVersion.equals(RDFConstants.nifVersion2_0)
            || nifVersion.equals(RDFConstants.nifVersion2_1))) {
        throw new NIFVersionNotSupportedException("NIF version \"" + nifVersion + "\" is not supported");
    }

    return new NIFParameterSet(thisInput, thisInformat, thisOutformat, thisPrefix, nifVersion);
}

From source file:de.hybris.platform.b2b.punchout.services.impl.DefaultPunchOutServiceIntegrationTest.java

/**
 * Tests that sending a proper {@link PunchOutSetupRequest} in the form of a parsed from a file cXML object will
 * yield a proper cXML {@link PunchOutSetupResponse}.
 * // w  w  w . ja  v  a2 s  .co  m
 * @throws FileNotFoundException
 */
@Test
public void testPunchOutSetUpRequestHappyPath() throws FileNotFoundException {
    final CXML requestBody = PunchOutUtils.unmarshallCXMLFromFile("b2bpunchout/test/punchoutSetupRequest.xml");

    final CXML responseCXml = punchOutService.processPunchOutSetUpRequest(requestBody);

    final CXMLElementBrowser cxmlElementBrowser = new CXMLElementBrowser(responseCXml);

    final Response response = cxmlElementBrowser.findResponse();

    assertNotNull("Response must always exist in the response", response);

    assertEquals("Response code is expected to be success (200)", "200", response.getStatus().getCode());

    final PunchOutSetupResponse punchOutResponse = cxmlElementBrowser
            .findResponseByType(PunchOutSetupResponse.class);
    assertNotNull(punchOutResponse);

    final String url = punchOutResponse.getStartPage().getURL().getvalue();

    assertNotNull("StartPage URL must be part of the response", url);

    assertTrue("Must be a well formed URL", new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS).isValid(url));
}

From source file:elh.eus.absa.MicroTextNormalizer.java

/**
 *  Normalize input String (urls -> URL) 
 * /*  w ww  .ja va2  s. co m*/
 * @param input : input string to normalize
 * @returns String
 */
private static String normalizeURL(String input) {

    //URL normalization
    UrlValidator defaultValidator = new UrlValidator(UrlValidator.ALLOW_ALL_SCHEMES);

    if (defaultValidator.isValid(input)) {
        return "URLURLURL"; // valid
    } else {
        return input;
    }
}