Example usage for java.net MalformedURLException getMessage

List of usage examples for java.net MalformedURLException getMessage

Introduction

In this page you can find the example usage for java.net MalformedURLException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:eionet.cr.util.URLUtil.java

/**
 *
 * @param urlString//from   w w  w  .j  a  v a 2s.  c  om
 * @return
 */
public static String normalizeUrl(String urlString) {

    // if given URL string is null, return it as it is
    if (urlString == null) {
        return urlString;
    }

    // we're going to need both the URL and URI wrappers
    URL url = null;
    URI uri = null;
    try {
        url = new URL(urlString.trim());
        uri = url.toURI();
    } catch (MalformedURLException e) {
        return urlString;
    } catch (URISyntaxException e) {
        return urlString;
    }

    // get all the various parts of this URL
    String protocol = url.getProtocol();
    String userInfo = url.getUserInfo();
    String host = url.getHost();
    int port = url.getPort();
    String path = url.getPath();
    String query = url.getQuery();
    String reference = url.getRef();

    // start building the result, processing each of the above-found URL parts

    StringBuilder result = new StringBuilder();

    try {
        if (!StringUtils.isEmpty(protocol)) {
            result.append(decodeEncode(protocol.toLowerCase())).append("://");
        }

        if (!StringUtils.isEmpty(userInfo)) {
            result.append(decodeEncode(userInfo, ":")).append("@");
        }

        if (!StringUtils.isEmpty(host)) {
            result.append(decodeEncode(host.toLowerCase()));
        }

        if (port != -1 && port != 80) {
            result.append(":").append(port);
        }

        if (!StringUtils.isEmpty(path)) {
            result.append(normalizePath(path));
        }

        if (!StringUtils.isEmpty(query)) {
            String normalizedQuery = normalizeQueryString(uri);
            if (!StringUtils.isBlank(normalizedQuery)) {
                result.append("?").append(normalizedQuery);
            }
        }

        if (!StringUtils.isEmpty(reference)) {
            result.append("#").append(decodeEncode(reference));
        }
    } catch (UnsupportedEncodingException e) {
        throw new CRRuntimeException("Unsupported encoding: " + e.getMessage(), e);
    }

    return result.toString();
}

From source file:com.novartis.opensource.yada.util.QueryUtils.java

/**
 * Returns a {@link URL} built from the provided {@code urlStr}
 * // ww  w  .  jav  a 2s.c o m
 * @param urlStr
 *          the url string to convert to an object
 * @return a {@link URL} object
 */
public URL getUrl(String urlStr) {
    URL url = null;
    try {
        url = new URL(urlStr);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        l.error(e.getMessage());
    }
    return url;
}

From source file:com.eleybourn.bookcatalogue.utils.Utils.java

static public void parseUrlOutput(String path, SAXParserFactory factory, DefaultHandler handler) {
    SAXParser parser;/*from w  w  w .  jav a2 s.  com*/
    URL url;

    try {
        url = new URL(path);
        parser = factory.newSAXParser();
        parser.parse(Utils.getInputStream(url), handler);
        // Dont bother catching general exceptions, they will be caught by the caller.
    } catch (MalformedURLException e) {
        String s = "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    } catch (ParserConfigurationException e) {
        String s = "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    } catch (SAXException e) {
        String s = e.getMessage(); // "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    } catch (java.io.IOException e) {
        String s = "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    }
}

From source file:com.impetus.kundera.classreading.ClasspathReader.java

/**
 * Scan class resource in the provided urls with the additional Class-Path
 * of each jar checking// ww  w.j a v  a  2 s.c o  m
 * 
 * @param classRelativePath
 *            relative path to a class resource
 * @param urls
 *            urls to be checked
 * @return list of class path included in the base package
 */
private URL[] findResourcesInUrls(String classRelativePath, URL[] urls) {
    List<URL> list = new ArrayList<URL>();
    for (URL url : urls) {
        if (AllowedProtocol.isValidProtocol(url.getProtocol().toUpperCase())
                && url.getPath().endsWith(".jar")) {
            try {
                JarFile jarFile = new JarFile(URLDecoder.decode(url.getFile(), Constants.CHARSET_UTF8));

                // Checking the dependencies of this jar file
                Manifest manifest = jarFile.getManifest();
                if (manifest != null) {
                    String classPath = manifest.getMainAttributes().getValue("Class-Path");
                    // Scan all entries in the classpath if they are
                    // specified in the jar
                    if (!StringUtils.isEmpty(classPath)) {
                        List<URL> subList = new ArrayList<URL>();
                        for (String cpEntry : classPath.split(" ")) {
                            try {
                                subList.add(new URL(cpEntry));
                            } catch (MalformedURLException e) {
                                URL subResources = ClasspathReader.class.getClassLoader().getResource(cpEntry);
                                if (subResources != null) {
                                    subList.add(subResources);
                                }
                                // logger.warn("Incorrect URL in the classpath of a jar file ["
                                // + url.toString()
                                // + "]: " + cpEntry);
                            }
                        }
                        list.addAll(Arrays.asList(findResourcesInUrls(classRelativePath,
                                subList.toArray(new URL[subList.size()]))));
                    }
                }
                JarEntry present = jarFile.getJarEntry(classRelativePath + ".class");
                if (present != null) {
                    list.add(url);
                }
            } catch (IOException e) {
                logger.warn("Error during loading from context , Caused by:" + e.getMessage());
            }

        } else if (url.getPath().endsWith("/")) {
            File file = new File(url.getPath() + classRelativePath + ".class");
            if (file.exists()) {
                try {
                    list.add(file.toURL());
                } catch (MalformedURLException e) {
                    throw new ResourceReadingException(e);
                }
            }
        }

    }
    return list.toArray(new URL[list.size()]);
}

From source file:org.apache.manifoldcf.agents.output.solr.HttpPoster.java

/** Initialize the SolrCloud http poster.
*///from w ww.  j av a2 s.c  o  m
public HttpPoster(String zookeeperHosts, String collection, int zkClientTimeout, int zkConnectTimeout,
        String updatePath, String removePath, String statusPath, String allowAttributeName,
        String denyAttributeName, String idAttributeName, String modifiedDateAttributeName,
        String createdDateAttributeName, String indexedDateAttributeName, String fileNameAttributeName,
        String mimeTypeAttributeName, String contentAttributeName, Long maxDocumentLength, String commitWithin,
        boolean useExtractUpdateHandler) throws ManifoldCFException {
    // These are the paths to the handlers in Solr that deal with the actions we need to do
    this.postUpdateAction = updatePath;
    this.postRemoveAction = removePath;
    this.postStatusAction = statusPath;

    this.commitWithin = commitWithin;

    this.allowAttributeName = allowAttributeName;
    this.denyAttributeName = denyAttributeName;
    this.idAttributeName = idAttributeName;
    this.modifiedDateAttributeName = modifiedDateAttributeName;
    this.createdDateAttributeName = createdDateAttributeName;
    this.indexedDateAttributeName = indexedDateAttributeName;
    this.fileNameAttributeName = fileNameAttributeName;
    this.mimeTypeAttributeName = mimeTypeAttributeName;
    this.contentAttributeName = contentAttributeName;
    this.useExtractUpdateHandler = useExtractUpdateHandler;

    this.maxDocumentLength = maxDocumentLength;

    try {
        CloudSolrServer cloudSolrServer = new CloudSolrServer(zookeeperHosts,
                new ModifiedLBHttpSolrServer(HttpClientUtil.createClient(null)));
        cloudSolrServer.setZkClientTimeout(zkClientTimeout);
        cloudSolrServer.setZkConnectTimeout(zkConnectTimeout);
        cloudSolrServer.setDefaultCollection(collection);
        // Set the solrj instance we want to use
        solrServer = cloudSolrServer;
    } catch (MalformedURLException e) {
        throw new ManifoldCFException(e.getMessage(), e);
    }
}

From source file:org.jahia.tools.maven.plugins.LegalArtifactAggregator.java

private void processPOM(boolean lookForNotice, boolean lookForLicense, String jarFilePath,
        JarMetadata contextJarMetadata, Set<JarMetadata> embeddedJarNames, int level,
        InputStream pomInputStream, boolean processingSources) throws IOException {
    MavenXpp3Reader reader = new MavenXpp3Reader();
    final String indent = getIndent(level);
    try {//w w  w .j a v a  2 s . co m
        final Model model = reader.read(pomInputStream);
        final Parent parent = model.getParent();
        String parentGroupId = null;
        String parentVersion = null;
        if (parent != null) {
            parentGroupId = parent.getGroupId();
            parentVersion = parent.getVersion();
        }

        if (model.getInceptionYear() != null) {
            contextJarMetadata.setInceptionYear(model.getInceptionYear());
        }

        if (model.getOrganization() != null) {
            if (model.getOrganization().getName() != null) {
                contextJarMetadata.setOrganizationName(model.getOrganization().getName());
            }
            if (model.getOrganization().getUrl() != null) {
                contextJarMetadata.setOrganizationUrl(model.getOrganization().getUrl());
            }
        }

        if (model.getUrl() != null) {
            contextJarMetadata.setProjectUrl(model.getUrl());
        }

        if (model.getLicenses() != null && model.getLicenses().size() > 0) {
            for (License license : model.getLicenses()) {
                output(indent, "Found license in POM for " + model.getId());
                String licenseName = license.getName();
                // let's try to resolve the license by name
                KnownLicense knownLicense = getKnowLicenseByName(licenseName);
                if (knownLicense != null) {
                    SortedSet<LicenseFile> licenseFiles = knownLicensesFound.get(knownLicense);
                    if (licenseFiles == null) {
                        licenseFiles = new TreeSet<>();
                    }
                    LicenseFile licenseFile = new LicenseFile(jarFilePath,
                            FilenameUtils.getBaseName(jarFilePath), jarFilePath, knownLicense.getTextToUse());
                    licenseFile.getKnownLicenses().add(knownLicense);
                    licenseFile.getKnownLicenseKeys().add(knownLicense.getId());
                    licenseFiles.add(licenseFile);
                    knownLicensesFound.put(knownLicense, licenseFiles);
                    // found a license for this project, let's see if we can resolve it
                    Map<String, LicenseFile> projectLicenseFiles = contextJarMetadata.getLicenseFiles();
                    if (projectLicenseFiles == null) {
                        projectLicenseFiles = new TreeMap<>();
                    }
                    projectLicenseFiles.put("pom.xml", licenseFile);
                } else if (license.getUrl() != null) {
                    try {
                        URL licenseURL = new URL(license.getUrl());
                        String licenseText = IOUtils.toString(licenseURL);
                        if (StringUtils.isNotBlank(licenseText)) {
                            // found a license for this project, let's see if we can resolve it
                            Map<String, LicenseFile> licenseFiles = contextJarMetadata.getLicenseFiles();
                            if (licenseFiles == null) {
                                licenseFiles = new TreeMap<>();
                            }
                            LicenseFile newLicenseFile = new LicenseFile(jarFilePath,
                                    FilenameUtils.getBaseName(jarFilePath), jarFilePath, licenseText);
                            if (licenseFiles.containsValue(newLicenseFile)) {
                                for (LicenseFile licenseFile : licenseFiles.values()) {
                                    if (licenseFile.equals(newLicenseFile)) {
                                        newLicenseFile = licenseFile;
                                        break;
                                    }
                                }
                            }
                            resolveKnownLicensesByText(newLicenseFile);
                            licenseFiles.put("pom.xml", newLicenseFile);
                        }
                    } catch (MalformedURLException mue) {
                        output(indent, "Invalid license URL : " + license.getUrl() + ": " + mue.getMessage());
                    }
                } else {
                    // couldn't resolve the license
                }
            }
        } else {
            if (parent != null) {
                Artifact parentArtifact = new DefaultArtifact(parent.getGroupId(), parent.getArtifactId(),
                        "pom", parent.getVersion());
                Artifact resolvedParentArtifact = resolveArtifact(parentArtifact, level);
                if (resolvedParentArtifact != null) {
                    output(indent, "Processing parent POM " + parentArtifact + "...");
                    processPOM(lookForNotice, lookForLicense, jarFilePath, contextJarMetadata, embeddedJarNames,
                            level + 1, new FileInputStream(resolvedParentArtifact.getFile()),
                            processingSources);
                } else {
                    output(indent, "Couldn't resolve parent POM " + parentArtifact + " !");
                }
            }
        }

        String scmConnection = null;
        if (model.getScm() != null) {
            scmConnection = model.getScm().getDeveloperConnection();
            if (scmConnection == null) {
                model.getScm().getConnection();
            }
            if (scmConnection == null) {
                // @todo let's try to resolve in the parent hierarcy
            }
        }

        /*
        if (scmManager != null && scmConnection != null) {
        ScmProvider scmProvider;
        File checkoutDir = new File(outputDirectory, "source-checkouts");
        checkoutDir.mkdirs();
        File wcDir = new File(checkoutDir, model.getArtifactId());
        wcDir.mkdirs();
        try {
            scmProvider = scmManager.getProviderByUrl(scmConnection);
            ScmRepository scmRepository = scmManager.makeScmRepository(scmConnection);
            CheckOutScmResult scmResult = scmProvider.checkOut(scmRepository, new ScmFileSet(wcDir));
            if (!scmResult.isSuccess()) {
            }
        } catch (ScmRepositoryException e) {
            e.printStackTrace();
        } catch (NoSuchScmProviderException e) {
            e.printStackTrace();
        } catch (ScmException e) {
            e.printStackTrace();
        }
        }
        */
        if (!embeddedJarNames.isEmpty()) {
            final List<Dependency> dependencies = model.getDependencies();
            Map<String, Dependency> artifactToDep = new HashMap<String, Dependency>(dependencies.size());
            for (Dependency dependency : dependencies) {
                artifactToDep.put(dependency.getArtifactId(), dependency);
            }

            for (JarMetadata jarName : embeddedJarNames) {
                final Dependency dependency = artifactToDep.get(jarName.name);
                if (dependency != null) {
                    File jarFile = getArtifactFile(new DefaultArtifact(dependency.getGroupId(),
                            dependency.getArtifactId(), null, "jar", jarName.version), level);
                    if (jarFile != null && jarFile.exists()) {
                        FileInputStream jarInputStream = new FileInputStream(jarFile);
                        processJarFile(jarInputStream, jarFile.getPath(), null, true, level, true, true,
                                processingSources);
                        IOUtils.closeQuietly(jarInputStream);
                    } else {
                        output(indent, "Couldn't find dependency for embedded JAR " + jarName, true, false);
                    }
                }
            }
        }

        if (!processingSources && (lookForLicense || lookForNotice)) {
            final String groupId = model.getGroupId() != null ? model.getGroupId() : parentGroupId;
            final String version = model.getVersion() != null ? model.getVersion() : parentVersion;
            final Artifact artifact = new DefaultArtifact(groupId, model.getArtifactId(), "sources", "jar",
                    version);

            File sourceJar = getArtifactFile(artifact, level);
            if (sourceJar != null && sourceJar.exists()) {
                FileInputStream sourceJarInputStream = new FileInputStream(sourceJar);
                processJarFile(sourceJarInputStream, sourceJar.getPath(), contextJarMetadata, false, level,
                        lookForNotice, lookForLicense, true);
                IOUtils.closeQuietly(sourceJarInputStream);
            }
        }
    } catch (XmlPullParserException e) {
        throw new IOException(e);
    }
}

From source file:EnvironmentExplorer.java

void setupSounds() {
    soundSwitch = new Switch(Switch.CHILD_NONE);
    soundSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE);

    // Set up the sound media container
    java.net.URL soundURL = null;
    String soundFile = "techno_machine.au";
    try {/*  w  w  w  . j  a  va 2  s  . c o m*/
        soundURL = new java.net.URL(codeBaseString + soundFile);
    } catch (java.net.MalformedURLException ex) {
        System.out.println(ex.getMessage());
        System.exit(1);
    }
    if (soundURL == null) { // application, try file URL
        try {
            soundURL = new java.net.URL("file:./" + soundFile);
        } catch (java.net.MalformedURLException ex) {
            System.out.println(ex.getMessage());
            System.exit(1);
        }
    }
    //System.out.println("soundURL = " + soundURL);
    MediaContainer soundMC = new MediaContainer(soundURL);

    // set up the Background Sound
    soundBackground = new BackgroundSound();
    soundBackground.setCapability(Sound.ALLOW_ENABLE_WRITE);
    soundBackground.setSoundData(soundMC);
    soundBackground.setSchedulingBounds(infiniteBounds);
    soundBackground.setEnable(false);
    soundBackground.setLoop(Sound.INFINITE_LOOPS);
    soundSwitch.addChild(soundBackground);

    // set up the point sound
    soundPoint = new PointSound();
    soundPoint.setCapability(Sound.ALLOW_ENABLE_WRITE);
    soundPoint.setSoundData(soundMC);
    soundPoint.setSchedulingBounds(infiniteBounds);
    soundPoint.setEnable(false);
    soundPoint.setLoop(Sound.INFINITE_LOOPS);
    soundPoint.setPosition(-5.0f, 5.0f, 0.0f);
    Point2f[] distGain = new Point2f[2];
    // set the attenuation to linearly decrease volume from max at
    // source to 0 at a distance of 15m
    distGain[0] = new Point2f(0.0f, 1.0f);
    distGain[1] = new Point2f(15.0f, 0.0f);
    soundPoint.setDistanceGain(distGain);
    soundSwitch.addChild(soundPoint);

    // Create the chooser GUI
    String[] soundNames = { "None", "Background", "Point", };

    soundChooser = new IntChooser("Sound:", soundNames);
    soundChooser.addIntListener(new IntListener() {
        public void intChanged(IntEvent event) {
            int value = event.getValue();
            // Should just be able to use setWhichChild on
            // soundSwitch, have to explictly enable/disable due to
            // bug.
            switch (value) {
            case 0:
                soundSwitch.setWhichChild(Switch.CHILD_NONE);
                soundBackground.setEnable(false);
                soundPoint.setEnable(false);
                break;
            case 1:
                soundSwitch.setWhichChild(0);
                soundBackground.setEnable(true);
                soundPoint.setEnable(false);
                break;
            case 2:
                soundSwitch.setWhichChild(1);
                soundBackground.setEnable(false);
                soundPoint.setEnable(true);
                break;
            }
        }
    });
    soundChooser.setValue(Switch.CHILD_NONE);

}

From source file:org.apache.manifoldcf.crawler.connectors.generic.GenericConnector.java

protected DefaultHttpClient getClient() throws ManifoldCFException {
    DefaultHttpClient cl = new DefaultHttpClient();
    if (genericLogin != null && !genericLogin.isEmpty()) {
        try {/*  w  w  w.  j a  va 2 s  . c om*/
            URL url = new URL(genericEntryPoint);
            Credentials credentials = new UsernamePasswordCredentials(genericLogin, genericPassword);
            cl.getCredentialsProvider().setCredentials(
                    new AuthScope(url.getHost(), url.getPort() > 0 ? url.getPort() : 80, AuthScope.ANY_REALM),
                    credentials);
            cl.addRequestInterceptor(new PreemptiveAuth(credentials), 0);
        } catch (MalformedURLException ex) {
            throw new ManifoldCFException("getClient exception: " + ex.getMessage(), ex);
        }
    }
    HttpConnectionParams.setConnectionTimeout(cl.getParams(), connectionTimeoutMillis);
    HttpConnectionParams.setSoTimeout(cl.getParams(), socketTimeoutMillis);
    return cl;
}

From source file:com.quartercode.quarterbukkit.api.query.ServerModsAPIQuery.java

/**
 * Executes the stored query and returns the result as a {@link JSONArray}.
 * The query string ({@link #getQuery()}) is attached to {@code https://api.curseforge.com/servermods/}.
 * The GET response of that {@link URL} is then parsed to a {@link JSONArray}.
 * /* w ww.  j  a  va2 s .  c o m*/
 * @return The response of the server mods api.
 * @throws QueryException Something goes wrong while querying the server mods api.
 */
public JSONArray execute() throws QueryException {

    // Build request url using the query
    URL requestUrl = null;
    try {
        requestUrl = new URL(HOST + query);
    } catch (MalformedURLException e) {
        throw new QueryException(QueryExceptionType.MALFORMED_URL, this, HOST + query, e);
    }

    // Open connection to request url
    URLConnection request = null;
    try {
        request = requestUrl.openConnection();
    } catch (IOException e) {
        throw new QueryException(QueryExceptionType.CANNOT_OPEN_CONNECTION, this, requestUrl.toExternalForm(),
                e);
    }

    // Set connection timeout
    request.setConnectTimeout(CONNECTION_TIMEOUT);

    // Set user agent
    request.addRequestProperty("User-Agent", USER_AGENT);

    // Set api key (if provided)
    String apiKey = QuarterBukkit.getPlugin().getConfig().getString("server-mods-api-key");
    if (apiKey != null && !apiKey.isEmpty()) {
        request.addRequestProperty("X-API-Key", apiKey);
    }

    // We want to read the results
    request.setDoOutput(true);

    // Read first line from the response
    BufferedReader reader = null;
    String response = null;
    try {
        reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        response = reader.readLine();
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            throw new QueryException(QueryExceptionType.INVALID_API_KEY, this, requestUrl.toExternalForm(), e);
        } else {
            throw new QueryException(QueryExceptionType.CANNOT_READ_RESPONSE, this, requestUrl.toExternalForm(),
                    e);
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                throw new QueryException(QueryExceptionType.CANNOT_CLOSE_RESPONSE_STREAM, this,
                        requestUrl.toExternalForm(), e);
            }
        }
    }

    // Parse the response
    Object jsonResponse = JSONValue.parse(response);

    if (jsonResponse instanceof JSONArray) {
        return (JSONArray) jsonResponse;
    } else {
        throw new QueryException(QueryExceptionType.INVALID_RESPONSE, this, requestUrl.toExternalForm());
    }
}