Example usage for java.net URISyntaxException getLocalizedMessage

List of usage examples for java.net URISyntaxException getLocalizedMessage

Introduction

In this page you can find the example usage for java.net URISyntaxException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:at.bitfire.davdroid.ui.setup.LoginCredentialsFragment.java

protected LoginCredentials validateLoginData() {
    if (radioUseEmail.isChecked()) {
        URI uri = null;//from ww  w  .  j a v  a 2  s.com
        boolean valid = true;

        String email = editEmailAddress.getText().toString();
        if (!email.matches(".+@.+")) {
            editEmailAddress.setError(getString(R.string.login_email_address_error));
            valid = false;
        } else
            try {
                uri = new URI("mailto", email, null);
            } catch (URISyntaxException e) {
                editEmailAddress.setError(e.getLocalizedMessage());
                valid = false;
            }

        String password = editEmailPassword.getText().toString();
        if (password.isEmpty()) {
            editEmailPassword.setError(getString(R.string.login_password_required));
            valid = false;
        }

        return valid ? new LoginCredentials(uri, email, password) : null;

    } else if (radioUseURL.isChecked()) {
        URI uri = null;
        boolean valid = true;

        Uri baseUrl = Uri.parse(editBaseURL.getText().toString());
        String scheme = baseUrl.getScheme();
        if ("https".equalsIgnoreCase(scheme) || "http".equalsIgnoreCase(scheme)) {
            String host = baseUrl.getHost();
            if (StringUtils.isEmpty(host)) {
                editBaseURL.setError(getString(R.string.login_url_host_name_required));
                valid = false;
            } else
                try {
                    host = IDN.toASCII(host);
                } catch (IllegalArgumentException e) {
                    Constants.log.log(Level.WARNING, "Host name not conforming to RFC 3490", e);
                }

            String path = baseUrl.getEncodedPath();
            int port = baseUrl.getPort();
            try {
                uri = new URI(baseUrl.getScheme(), null, host, port, path, null, null);
            } catch (URISyntaxException e) {
                editBaseURL.setError(e.getLocalizedMessage());
                valid = false;
            }
        } else {
            editBaseURL.setError(getString(R.string.login_url_must_be_http_or_https));
            valid = false;
        }

        String userName = editUserName.getText().toString();
        if (userName.isEmpty()) {
            editUserName.setError(getString(R.string.login_user_name_required));
            valid = false;
        }

        String password = editUrlPassword.getText().toString();
        if (password.isEmpty()) {
            editUrlPassword.setError(getString(R.string.login_password_required));
            valid = false;
        }

        return valid ? new LoginCredentials(uri, userName, password) : null;
    }

    return null;
}

From source file:edu.unc.lib.dl.ingest.sip.METSPackageFileValidator.java

/**
 * Checks that there are as many files packaged as there are non-staged file references. Computes and compares the
 * MD5 digest of packaged files that have a checksum in METS. Checks access to all files referenced in staging
 * locations.//from  w w w.j  av  a 2  s  . com
 *
 * @param mets
 * @param metsPack
 * @param aip
 * @throws IngestException
 */
@SuppressWarnings("unchecked")
public void validateFiles(Document mets, METSPackageSIP metsPack) throws IngestException {
    StringBuffer errors = new StringBuffer();
    List<File> manifestFiles = new ArrayList<File>();
    List<String> missingFiles = new ArrayList<String>();
    List<String> badChecksumFiles = new ArrayList<String>();

    // find missing or corrupt files listed in manifest
    try {
        for (Element fileEl : (List<Element>) allFilesXpath.selectNodes(mets)) {
            String href = null;
            try {
                href = fileEl.getChild("FLocat", JDOMNamespaceUtil.METS_NS).getAttributeValue("href",
                        JDOMNamespaceUtil.XLINK_NS);
                URI uri = new URI(href);
                if (uri.getScheme() != null && !uri.getScheme().contains("file")) {
                    continue;
                }
            } catch (URISyntaxException e) {
                errors.append("Cannot parse file location: " + e.getLocalizedMessage() + " (" + href + ")");
                missingFiles.add(href);
                continue;
            } catch (NullPointerException e) {
                errors.append("A file location is missing for file ID: " + fileEl.getAttributeValue("ID"));
                continue;
            }
            File file = null;
            // locate the file and check that it exists
            try {
                log.debug("Looking in SIP");
                file = metsPack.getFileForLocator(href);
                file.equals(file);
                manifestFiles.add(file);
                log.debug("FILE IS IN METSPackage: " + file.getPath());
                if (file == null || !file.exists()) {
                    missingFiles.add(href);
                    continue;
                }
            } catch (IOException e) {
                log.debug(e);
                missingFiles.add(href);
                errors.append(e.getMessage());
            }

            String checksum = fileEl.getAttributeValue("CHECKSUM");
            if (checksum != null) {
                log.debug("found a checksum in METS");
                Checksum checker = new Checksum();
                try {
                    String sum = checker.getChecksum(file);
                    if (!sum.equals(checksum.toLowerCase())) {
                        log.debug("Checksum failed for file: " + href + " (METS says " + checksum
                                + ", but we got " + sum + ")");
                        badChecksumFiles.add(href);
                    }
                    log.debug("METS manifest checksum was verified for file: " + href);
                } catch (IOException e) {
                    throw new IngestException("Checksum failed to find file: " + href);
                }
            }
        }
    } catch (JDOMException e1) {
        throw new Error("Unexpected JDOM Exception", e1);
    }

    // TODO: account for local (not inline xmlData) MODS files
    // see if there are extra files in the SIP
    List<String> extraFiles = new ArrayList<String>();

    if (metsPack.getSIPDataDir() != null) {
        int zipPathLength = 0;
        try {
            zipPathLength = metsPack.getSIPDataDir().getCanonicalPath().length();

            for (File received : metsPack.getDataFiles()) {
                if (!manifestFiles.contains(received) && received.compareTo(metsPack.getMetsFile()) != 0) {
                    extraFiles.add("file://" + received.getCanonicalPath().substring(zipPathLength));
                }
            }
        } catch (IOException e) {
            throw new Error("Unexpected IO Exception trying to get path of a known file.", e);
        }
    }
    if (missingFiles.size() > 0 || badChecksumFiles.size() > 0 || extraFiles.size() > 0) {
        // We have an error here...
        String msg = "The files submitted do not match those listed in the METS manifest.";
        FilesDoNotMatchManifestException e = new FilesDoNotMatchManifestException(msg);
        e.setBadChecksumFiles(badChecksumFiles);
        e.setExtraFiles(extraFiles);
        e.setMissingFiles(missingFiles);
        throw e;
    }
}

From source file:com.keedio.nifi.processors.azure.blob.PutAzureBlobObjectTest.java

protected Path getResourcePath(String resourceName) {
    Path path = null;//from   w w w.ja  va  2s .c  o m

    try {
        path = Paths.get(getClass().getResource(resourceName).toURI());
    } catch (URISyntaxException e) {
        Assert.fail("Resource: " + resourceName + " does not exist" + e.getLocalizedMessage());
    }

    return path;
}

From source file:com.microsoft.tfs.core.TFSConfigurationServer.java

/**
 * Gets the {@link TFSTeamProjectCollection} for the specified ID.
 *
 * @param collectionID//from  w  ww . j  a va  2 s . c  om
 *        the collection's ID (must not be <code>null</code>)
 * @return the {@link TFSTeamProjectCollection} that matches the ID, or
 *         <code>null</code> if no matching collection was found
 */
public TFSTeamProjectCollection getTeamProjectCollection(final GUID collectionID) {
    checkNotClosed();

    Check.notNull(collectionID, "collectionID"); //$NON-NLS-1$

    final String collectionLocation = getServerDataProvider().findServerLocation(collectionID);

    TFSTeamProjectCollection ret = null;

    synchronized (collectionsLock) {
        if (collectionLocation != null) {
            if (collections.containsKey(collectionLocation)) {
                ret = collections.get(collectionLocation);
            } else {
                /*
                 * Collection location comes from the server data provider
                 * as a properly formed (escaped) URI. Do not use helper
                 * methods that would re-escape.
                 */
                final URI collectionLocationURI;

                try {
                    collectionLocationURI = new URI(collectionLocation);
                } catch (final URISyntaxException e) {
                    throw new IllegalArgumentException(e.getLocalizedMessage(), e);
                }

                ret = new TFSTeamProjectCollection(collectionLocationURI, getCredentialsHolder(),
                        getConnectionAdvisor());
                ret.setHTTPClientReference(getHTTPClientReference());

                collections.put(collectionLocation, ret);
            }
        }
    }

    return ret;
}

From source file:com.sinosoft.one.mvc.scanning.MvcScanner.java

/**
 * ????(WEB-INF/classestarget/classes?)/*from  w w  w  . j  av a  2 s  . co m*/
 * 
 * @return
 * @throws IOException
 * @throws URISyntaxException
 */
public List<ResourceRef> getClassesFolderResources() throws IOException {
    if (classesFolderResources == null) {
        if (logger.isInfoEnabled()) {
            logger.info("[classesFolder] start to found available classes folders ...");
        }
        List<ResourceRef> classesFolderResources = new ArrayList<ResourceRef>();
        Enumeration<URL> founds = resourcePatternResolver.getClassLoader().getResources("");
        while (founds.hasMoreElements()) {
            URL urlObject = founds.nextElement();
            if (!"file".equals(urlObject.getProtocol())) {
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] Ignored classes folder because " + "not a file protocol url: "
                            + urlObject);
                }
                continue;
            }
            String path = urlObject.getPath();
            Assert.isTrue(path.endsWith("/"));
            if (!path.endsWith("/classes/") && !path.endsWith("/test-classes/") && !path.endsWith("/bin/")) {
                if (logger.isInfoEnabled()) {
                    logger.info("[classesFolder] Ignored classes folder because "
                            + "not ends with '/classes/' or '/bin/': " + urlObject);
                }
                continue;
            }
            File file;
            try {
                file = new File(urlObject.toURI());
            } catch (URISyntaxException e) {
                throw new IOException(e.getLocalizedMessage());
            }
            if (file.isFile()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] Ignored because not a directory: " + urlObject);
                }
                continue;
            }
            Resource resource = new FileSystemResource(file);
            ResourceRef resourceRef = ResourceRef.toResourceRef(resource);
            if (classesFolderResources.contains(resourceRef)) {
                // ???
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] remove replicated classes folder: " + resourceRef);
                }
            } else {
                classesFolderResources.add(resourceRef);
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] add classes folder: " + resourceRef);
                }
            }
        }
        // ?????
        Collections.sort(classesFolderResources);
        List<ResourceRef> toRemove = new LinkedList<ResourceRef>();
        for (int i = 0; i < classesFolderResources.size(); i++) {
            ResourceRef ref = classesFolderResources.get(i);
            String refURI = ref.getResource().getURI().toString();
            for (int j = i + 1; j < classesFolderResources.size(); j++) {
                ResourceRef refj = classesFolderResources.get(j);
                String refjURI = refj.getResource().getURI().toString();
                if (refURI.startsWith(refjURI)) {
                    toRemove.add(refj);
                    if (logger.isInfoEnabled()) {
                        logger.info("[classesFolder] remove wrapper classes folder: " //
                                + refj);
                    }
                } else if (refjURI.startsWith(refURI) && refURI.length() != refjURI.length()) {
                    toRemove.add(ref);
                    if (logger.isInfoEnabled()) {
                        logger.info("[classesFolder] remove wrapper classes folder: " //
                                + ref);
                    }
                }
            }
        }
        classesFolderResources.removeAll(toRemove);
        //
        this.classesFolderResources = new ArrayList<ResourceRef>(classesFolderResources);
        if (logger.isInfoEnabled()) {
            logger.info("[classesFolder] found " + classesFolderResources.size() + " classes folders: "
                    + classesFolderResources);
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("[classesFolder] found cached " + classesFolderResources.size() + " classes folders: "
                    + classesFolderResources);
        }
    }
    return Collections.unmodifiableList(classesFolderResources);
}

From source file:org.sonar.plugins.scm.perforce.PerforceExecutor.java

/**
 * Initialize an instance of the Perforce server from the factory using the
 * specified protocol, server port, protocol specific properties and usage
 * options. Register callback on the server. Connect to server; set the user
 * (if present) to server and login to the server with the user's password
 * (if present).//from w ww.j a  va 2s.co m
 *
 */
private void initServer() {

    try {
        createServer();
        // Connect to the server.
        server.connect();
        // Set the Perforce charset.
        String charset = config.charset();
        if (charset != null && server.isConnected() && server.supportsUnicode()) {
            server.setCharsetName(charset);
        }
        // Set server user.
        String username = config.username();
        if (username != null) {
            server.setUserName(username);
            // Check if user is already logged (reuse previous ticket)
            if (!isLogin(server)) {
                // Login to the server with a password.
                // Password can be null if it is not needed (i.e. SSO logins).
                server.login(config.password(), null);
            }
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e.getLocalizedMessage(), e);
    } catch (P4JavaException e) {
        throw new IllegalStateException(e.getLocalizedMessage(), e);
    }
}

From source file:it.geosolutions.geoserver.jms.impl.JMSActiveMQFactory.java

/**
 * @return true if brokerURI is modified
 *///  w ww .  ja v a 2  s  . co m
private boolean checkBrokerURI(final String _brokerURI) {
    if (brokerURI == null) {
        if (_brokerURI == null || _brokerURI.length() == 0) {
            brokerURI = getDefaultURI();
            return true;
        } else {
            // initialize to the new configuration
            brokerURI = _brokerURI;

            // check the URI syntax
            try {
                new URI(brokerURI);
            } catch (URISyntaxException e) {
                if (LOGGER.isLoggable(Level.SEVERE)) {
                    LOGGER.severe(e.getLocalizedMessage());
                }
                brokerURI = getDefaultURI();
            }
            return true;
        }
    } else {
        if (_brokerURI == null || _brokerURI.length() == 0) {
            // use the default
            return checkBrokerURI(getDefaultURI());

        } else if (brokerURI.equalsIgnoreCase(_brokerURI)) {
            return false;
        } else {
            // something is changed: reset
            brokerURI = null;
            return checkBrokerURI(_brokerURI);
        }
    }
}

From source file:org.zaizi.alfresco.publishing.marklogic.MarkLogicChannelType.java

@Override
public void unpublish(final NodeRef nodeToUnpublish, final Map<QName, Serializable> channelProperties) {

    LOG.info("unpublish() invoked...");

    final HttpClient httpclient = new DefaultHttpClient();
    try {//  ww w.jav  a2  s .c  o  m
        if (LOG.isDebugEnabled()) {
            LOG.debug("Unpublishing node: " + nodeToUnpublish);
        }

        final URI uriDelete = publishingHelper.getDeleteURIFromNodeRefAndChannelProperties(nodeToUnpublish,
                channelProperties);
        final HttpDelete httpDelete = new HttpDelete(uriDelete);
        final HttpResponse response = httpclient.execute(httpDelete,
                publishingHelper.getHttpContextFromChannelProperties(channelProperties));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Response Status: " + response.getStatusLine().getStatusCode() + " - Message: "
                    + response.getStatusLine().getReasonPhrase() + " - NodeRef: " + nodeToUnpublish.toString());
        }

        if (response.getStatusLine().getStatusCode() != STATUS_DOCUMENT_DELETED) {
            throw new AlfrescoRuntimeException(response.getStatusLine().getReasonPhrase());
        }
    } catch (IllegalStateException illegalEx) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Exception in Unpublish(): ", illegalEx);
        }
        throw new AlfrescoRuntimeException(illegalEx.getLocalizedMessage());
    } catch (IOException ioex) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Exception in Unpublish(): ", ioex);
        }
        throw new AlfrescoRuntimeException(ioex.getLocalizedMessage());
    } catch (URISyntaxException uriSynEx) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Exception in Unpublish(): ", uriSynEx);
        }
        throw new AlfrescoRuntimeException(uriSynEx.getLocalizedMessage());
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.zaizi.alfresco.publishing.marklogic.MarkLogicChannelType.java

@Override
public void publish(final NodeRef nodeToPublish, final Map<QName, Serializable> channelProperties) {
    LOG.info("publish() invoked...");
    final ContentReader reader = contentService.getReader(nodeToPublish, ContentModel.PROP_CONTENT);
    if (reader.exists()) {
        File contentFile;/*from w ww . jav  a2  s .c o  m*/
        boolean deleteContentFileOnCompletion = false;
        if (FileContentReader.class.isAssignableFrom(reader.getClass())) {
            // Grab the content straight from the content store if we can...
            contentFile = ((FileContentReader) reader).getFile();
        } else {
            // ...otherwise copy it to a temp file and use the copy...
            final File tempDir = TempFileProvider.getLongLifeTempDir("marklogic");
            contentFile = TempFileProvider.createTempFile("marklogic", "", tempDir);
            reader.getContent(contentFile);
            deleteContentFileOnCompletion = true;
        }

        HttpClient httpclient = new DefaultHttpClient();
        try {
            final String mimeType = reader.getMimetype();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Publishing node: " + nodeToPublish);
                LOG.debug("ContentFile_MIMETYPE: " + mimeType);
            }

            URI uriPut = publishingHelper.getPutURIFromNodeRefAndChannelProperties(nodeToPublish,
                    channelProperties);

            final HttpPut httpput = new HttpPut(uriPut);
            final FileEntity filenEntity = new FileEntity(contentFile, mimeType);
            httpput.setEntity(filenEntity);

            final HttpResponse response = httpclient.execute(httpput,
                    publishingHelper.getHttpContextFromChannelProperties(channelProperties));

            if (LOG.isDebugEnabled()) {
                LOG.debug("Response Status: " + response.getStatusLine().getStatusCode() + " - Message: "
                        + response.getStatusLine().getReasonPhrase() + " - NodeRef: "
                        + nodeToPublish.toString());
            }
            if (response.getStatusLine().getStatusCode() != STATUS_DOCUMENT_INSERTED) {
                throw new AlfrescoRuntimeException(response.getStatusLine().getReasonPhrase());
            }
        } catch (IllegalStateException illegalEx) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Exception in publish(): ", illegalEx);
            }
            throw new AlfrescoRuntimeException(illegalEx.getLocalizedMessage());
        } catch (IOException ioex) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Exception in publish(): ", ioex);
            }
            throw new AlfrescoRuntimeException(ioex.getLocalizedMessage());
        } catch (URISyntaxException uriSynEx) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Exception in publish(): ", uriSynEx);
            }
            throw new AlfrescoRuntimeException(uriSynEx.getLocalizedMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
            if (deleteContentFileOnCompletion) {
                contentFile.delete();
            }
        }
    }
}

From source file:jfs.sync.vfs.JFSVFSFile.java

/**
 * Creates a new external root file and reads the structure from server.
 * //from   w  ww  .ja va 2s  .  c o m
 * @param fileProducer
 *            The assigned file producer.
 */
public JFSVFSFile(JFSVFSFileProducer fileProducer) {
    super(fileProducer, "");
    try {
        FileSystemOptions opts = new FileSystemOptions();

        // Avoid using known hosts file if SFTP is used:
        if (fileProducer.getScheme().equals("sftp")) {
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
        }

        // Get user name and password, if not specified:
        try {
            URI uriObject = new URI(fileProducer.getUri());
            String userInfo = uriObject.getUserInfo();
            if (userInfo == null || !userInfo.contains(":")) {
                JFSUserAuthentication userAuth = JFSUserAuthentication.getInstance();
                userAuth.setResource(fileProducer.getUri());
                JFSUserAuthenticationInterface userInterface = userAuth.getUserInterface();

                StaticUserAuthenticator auth = new StaticUserAuthenticator(null, userInterface.getUserName(),
                        userInterface.getPassword());
                DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
            }
        } catch (URISyntaxException e) {
            JFSLog.getErr().getStream().println(e.getLocalizedMessage());
        }

        file = VFS.getManager().resolveFile(fileProducer.getUri(), opts);
    } catch (FileSystemException e) {
        JFSLog.getErr().getStream().println(e.getLocalizedMessage());
    }
}