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:com.amalto.workbench.utils.HttpClientUtil.java

public static OutputStream downloadFile(String url, String downloadFolder) {
    InputStream input = null;//w  w w.  ja v a  2  s  .c  om
    OutputStream output = null;
    try {
        URL urlFile = new URL(url);
        String filename = urlFile.getFile();
        if (filename != null) {
            int pos = filename.lastIndexOf('/');
            if (pos != -1) {
                filename = filename.substring(pos + 1);
            }
        } else {
            int pos = url.lastIndexOf('/');
            if (pos != -1) {
                filename = url.substring(pos + 1);
            }
        }
        input = urlFile.openStream();
        byte[] bytes = IOUtils.toByteArray(input);
        output = new FileOutputStream(new File(downloadFolder + "/" + filename)); //$NON-NLS-1$
        IOUtils.write(bytes, output);
        return output;
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
    }
    return null;
}

From source file:com.redhat.rcm.version.util.InputUtils.java

public static File getFile(final String location, final File downloadsDir, final boolean deleteExisting)
        throws VManException {
    if (client == null) {
        setupClient();//from  w w w  . ja v a 2 s. com
    }

    File result = null;

    if (location.startsWith("http")) {
        logger.info("Downloading: '" + location + "'...");

        try {
            final URL url = new URL(location);
            final String userpass = url.getUserInfo();
            if (!isEmpty(userpass)) {
                final AuthScope scope = new AuthScope(url.getHost(), url.getPort());
                final Credentials creds = new UsernamePasswordCredentials(userpass);

                client.getCredentialsProvider().setCredentials(scope, creds);
            }
        } catch (final MalformedURLException e) {
            logger.error("Malformed URL: '" + location + "'", e);
            throw new VManException("Failed to download: %s. Reason: %s", e, location, e.getMessage());
        }

        final File downloaded = new File(downloadsDir, new File(location).getName());
        if (deleteExisting && downloaded.exists()) {
            downloaded.delete();
        }

        if (!downloaded.exists()) {
            HttpGet get = new HttpGet(location);
            OutputStream out = null;
            try {
                HttpResponse response = null;
                // Work around for scenario where we are loading from a server
                // that does a refresh e.g. gitweb
                final int tries = 0;
                do {
                    get = new HttpGet(location);
                    response = client.execute(get);
                    if (response.containsHeader("Cache-control")) {
                        logger.info("Waiting for server to generate cache...");
                        get.abort();
                        try {
                            Thread.sleep(3000);
                        } catch (final InterruptedException e) {
                        }
                    } else {
                        break;
                    }
                } while (tries < MAX_RETRIES);

                if (response.containsHeader("Cache-control")) {
                    throw new VManException(
                            "Failed to read: %s. Cache-control header was present in final attempt.", location);
                }

                final int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    final InputStream in = response.getEntity().getContent();
                    out = new FileOutputStream(downloaded);

                    copy(in, out);
                } else {
                    logger.info("Received status: '{}' while downloading: {}", response.getStatusLine(),
                            location);

                    throw new VManException("Received status: '%s' while downloading: %s",
                            response.getStatusLine(), location);
                }
            } catch (final ClientProtocolException e) {
                throw new VManException("Failed to download: '%s'. Error: %s", e, location, e.getMessage());
            } catch (final IOException e) {
                throw new VManException("Failed to download: '%s'. Error: %s", e, location, e.getMessage());
            } finally {
                closeQuietly(out);
                get.abort();
            }
        }

        result = downloaded;
    } else {
        logger.info("Using local file: '" + location + "'...");

        result = new File(location);
    }

    return result;
}

From source file:edu.samplu.common.WebDriverUtil.java

/**
 * remote.public.driver set to chrome or firefox (null assumes firefox)
 * if remote.public.hub is set a RemoteWebDriver is created (Selenium Grid)
 * if proxy.host is set, the web driver is setup to use a proxy
 * @return WebDriver or null if unable to create
 *//*ww  w. jav  a  2s . c  o m*/
public static WebDriver getWebDriver() {
    String driverParam = System.getProperty(ITUtil.HUB_DRIVER_PROPERTY);
    String hubParam = System.getProperty(ITUtil.HUB_PROPERTY);
    String proxyParam = System.getProperty(PROXY_HOST_PROPERTY);

    // setup proxy if specified as VM Arg
    DesiredCapabilities capabilities = new DesiredCapabilities();
    WebDriver webDriver = null;
    if (StringUtils.isNotEmpty(proxyParam)) {
        capabilities.setCapability(CapabilityType.PROXY, new Proxy().setHttpProxy(proxyParam));
    }

    if (hubParam == null) {
        if (driverParam == null || "firefox".equalsIgnoreCase(driverParam)) {
            FirefoxProfile profile = new FirefoxProfile();
            profile.setEnableNativeEvents(false);
            capabilities.setCapability(FirefoxDriver.PROFILE, profile);
            return new FirefoxDriver(capabilities);
        } else if ("chrome".equalsIgnoreCase(driverParam)) {
            return new ChromeDriver(capabilities);
        } else if ("safari".equals(driverParam)) {
            System.out.println("SafariDriver probably won't work, if it does please contact Erik M.");
            return new SafariDriver(capabilities);
        }
    } else {
        try {
            if (driverParam == null || "firefox".equalsIgnoreCase(driverParam)) {
                return new RemoteWebDriver(new URL(ITUtil.getHubUrlString()), DesiredCapabilities.firefox());
            } else if ("chrome".equalsIgnoreCase(driverParam)) {
                return new RemoteWebDriver(new URL(ITUtil.getHubUrlString()), DesiredCapabilities.chrome());
            }
        } catch (MalformedURLException mue) {
            System.out.println(ITUtil.getHubUrlString() + " " + mue.getMessage());
            mue.printStackTrace();
        }
    }
    return null;
}

From source file:de.jlo.talendcomp.jasperrepo.RepositoryClient.java

public static String checkRepositoryUrl(String urlStr) {
    if (urlStr == null || urlStr.isEmpty()) {
        throw new IllegalArgumentException("url cannot be null or empty");
    }/*from   ww w. j a va  2 s  . c om*/
    if (urlStr.endsWith(repositoryUrlPath)) {
        // everything is fine
        return urlStr;
    } else {
        // extract url parts
        try {
            URL url = new URL(urlStr);
            String host = url.getHost();
            String prot = url.getProtocol();
            int port = url.getPort();
            String path = url.getPath();
            if (path.length() > 1) {
                int pos = path.indexOf('/', 1);
                if (pos > 0) {
                    path = path.substring(0, pos);
                }
                path = path + repositoryUrlPath;
            } else {
                path = repositoryUrlPath;
            }
            StringBuilder newUrl = new StringBuilder();
            newUrl.append(prot);
            newUrl.append("://");
            newUrl.append(host);
            if (port > 0) {
                newUrl.append(":");
                newUrl.append(port);
            }
            newUrl.append(path);
            System.out.println("Given URL:" + urlStr + " changed to a repository URL:" + newUrl.toString());
            return newUrl.toString();
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("URL: " + urlStr + " is not valied:" + e.getMessage(), e);
        }
    }
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportExecuteBL.java

/**
 * Serializes the data source into the response's output stream using a
 * ReportExporter//from ww  w .j  a  va  2  s . co  m
 *
 * @param templateID
 * @param datasource
 * @return
 */
static String prepareReportResponse(HttpServletResponse response, Integer templateID,
        Map<String, Object> contextMap, Map<String, Object> description, Object datasource,
        Map<String, Object> parameters, ServletContext servletContext, TPersonBean personBean, Locale locale) {
    URL baseURL = null;
    String logoFolder = null;
    URL completeURL = null;
    String baseFileName = null;
    if (templateID == null) {
        final String baseFolder = "/design/silver/";
        // direct pdf/xls from report overview
        try {
            // set the baseURL to take some standard icons from
            // "/design/silver/icons"
            // which ale already used by the report overview anyway
            baseURL = servletContext.getResource(baseFolder + "16x16");
            LOGGER.debug("baseURL: " + baseURL.toString());
        } catch (final MalformedURLException e) {
            LOGGER.error("Getting the baseURL for " + baseFolder + "16x16 failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        // set the baseURL to take some standard icons from
        // "/design/silver/icons"
        // which ale already used by the report overview anyway
        logoFolder = HandleHome.getTrackplus_Home() + File.separator + HandleHome.LOGOS_DIR + File.separator;
    } else {
        // template exists
        final File template = ReportBL.getDirTemplate(templateID);
        final ILabelBean templateBean = ReportFacade.getInstance().getByKey(templateID);
        if (templateBean != null) {
            baseFileName = templateBean.getLabel();
        }
        try {
            baseURL = template.toURL();
            LOGGER.debug("baseURL: " + baseURL.toString());
        } catch (final MalformedURLException e) {
            LOGGER.error("Wrong template URL for " + template.getName() + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
            return null;
        }
        try {
            completeURL = new URL(baseURL.toExternalForm() /*
                                                           * +
                                                           * "/"File.separator
                                                           */
                    + description.get(IDescriptionAttributes.MASTERFILE));
            completeURL.openStream();
            LOGGER.debug("completeURL: " + completeURL.toString());
        } catch (final Exception me) {
            LOGGER.error(LocalizeUtil.getParametrizedString(
                    "report.reportExportManager.err.masterFileTemplateNotFound",
                    new String[] { me.getMessage() }, locale) + me);
            return null;
        }
    }
    if (parameters == null) {
        parameters = new HashMap<String, Object>();
    }
    parameters.put(JasperReportExporter.REPORT_PARAMETERS.BASE_URL, baseURL);
    if (logoFolder != null) {
        parameters.put(JasperReportExporter.REPORT_PARAMETERS.LOGO_FOLDER_URL, logoFolder);
    }
    if (completeURL != null) {
        parameters.put(JasperReportExporter.REPORT_PARAMETERS.COMPLETE_URL, completeURL);
    }
    if (baseFileName == null) {
        baseFileName = "TrackReport";
    }
    baseFileName += DateTimeUtils.getInstance().formatISODateTime(new Date());
    response.reset();
    final String format = (String) description.get(IDescriptionAttributes.FORMAT);
    if (ReportExporter.FORMAT_PDF.equals(format)) {
        response.setHeader("Content-Type", "application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".pdf\"");
    } else if (ReportExporter.FORMAT_RTF.equals(format)) {
        response.setHeader("Content-Type", "application/rtf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".rtf\"");
    } else if (ReportExporter.FORMAT_XML.equals(format)) {
        response.setHeader("Content-Type", "text/xml");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".xml\"");
    } else if (ReportExporter.FORMAT_HTML.equals(format)) {
        response.setHeader("Content-Type", "text/html");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".html\"");
    } else if (ReportExporter.FORMAT_ZIP.equals(format)) {
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".zip\"");
    } else if (ReportExporter.FORMAT_XLS.equals(format)) {
        response.setHeader("Content-Type", "application/xls");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".xls\"");
    } else if (ReportExporter.FORMAT_CSV.equals(format)) {
        final String csvEncoding = personBean.getCsvEncoding();
        LOGGER.debug("csvEncoding is " + csvEncoding);
        if (csvEncoding != null) {
            response.setContentType("text/plain; " + csvEncoding);
        } else {
            response.setContentType("text/plain; charset=UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".csv\"");
    } else if (ReportExporter.FORMAT_DOCX.equals(format)) {
        response.setHeader("Content-Type",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".docx\"");
    }
    DownloadUtil.prepareCacheControlHeader(ServletActionContext.getRequest(), response);
    OutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
    } catch (final IOException e) {
        LOGGER.error("Getting the output stream failed with " + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    try {
        LOGGER.debug("Exporter type is " + description.get(IDescriptionAttributes.TYPE) + " exporter format is "
                + description.get(IDescriptionAttributes.FORMAT));
        final ReportExporter exporter = ReportExecuteBL
                .getExporter((String) description.get(IDescriptionAttributes.TYPE));
        exporter.exportReport((Document) datasource, personBean, locale, parameters, outputStream, contextMap,
                description);
        LOGGER.debug("Export done...");
    } catch (final ReportExportException e) {
        LOGGER.error("Exporting the report failed with " + e.getMessage());
        String actionMessage = "";
        if (e.getCause() != null) {
            actionMessage = LocalizeUtil.getParametrizedString(e.getMessage(),
                    new String[] { e.getCause().getMessage() }, locale);
        } else {
            actionMessage = LocalizeUtil.getLocalizedTextFromApplicationResources(e.getMessage(), locale);
        }
        LOGGER.error(actionMessage);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    } catch (final Exception e) {
        LOGGER.error("Exporting the report failed with throwable " + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return null;
}

From source file:fll.xml.XMLUtils.java

/**
 * Get all challenge descriptors build into the software.
 *//*  www .j av  a 2  s  . c  om*/
public static Collection<URL> getAllKnownChallengeDescriptorURLs() {
    final String baseDir = "fll/resources/challenge-descriptors/";

    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    final URL directory = classLoader.getResource(baseDir);
    if (null == directory) {
        LOGGER.warn("base dir for challenge descriptors not found");
        return Collections.emptyList();
    }

    final Collection<URL> urls = new LinkedList<URL>();
    if ("file".equals(directory.getProtocol())) {
        try {
            final URI uri = directory.toURI();
            final File fileDir = new File(uri);
            final File[] files = fileDir.listFiles();
            if (null != files) {
                for (final File file : files) {
                    if (file.getName().endsWith(".xml")) {
                        try {
                            final URL fileUrl = file.toURI().toURL();
                            urls.add(fileUrl);
                        } catch (final MalformedURLException e) {
                            LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e);
                        }
                    }
                }
            }
        } catch (final URISyntaxException e) {
            LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e);
        }
    } else if (directory.getProtocol().equals("jar")) {
        final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource();
        if (null != src) {
            final URL jar = src.getLocation();

            JarInputStream zip = null;
            try {
                zip = new JarInputStream(jar.openStream());

                JarEntry ze = null;
                while ((ze = zip.getNextJarEntry()) != null) {
                    final String entryName = ze.getName();
                    if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) {
                        // add 1 to baseDir to skip past the path separator
                        final String challengeName = entryName.substring(baseDir.length());

                        // check that the file really exists and turn it into a URL
                        final URL challengeUrl = classLoader.getResource(baseDir + challengeName);
                        if (null != challengeUrl) {
                            urls.add(challengeUrl);
                        } else {
                            // TODO could write the resource out to a temporary file if
                            // needed
                            // then mark the file as delete on exit
                            LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: "
                                    + entryName);
                        }
                    }
                }

                zip.close();
            } catch (final IOException e) {
                LOGGER.error("Error reading jar file at: " + jar.toString(), e);
            } finally {
                IOUtils.closeQuietly(zip);
            }

        } else {
            LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors");
        }
    } else {
        throw new UnsupportedOperationException("Cannot list files for URL " + directory);

    }

    return urls;

}

From source file:MessageSend_p.java

public static serverObjects respond(@SuppressWarnings("unused") final RequestHeader header,
        final serverObjects post, final serverSwitch env) {
    final Switchboard sb = (Switchboard) env;
    final serverObjects prop = new serverObjects();

    if ((post == null) || (post.get("hash", "").isEmpty())) {
        prop.put("mode", "3");
        return prop;
    }//ww w . j  a  va 2s  .c o  m

    final String hash = post.get("hash", "");
    String subject = post.get("subject", "");
    String message = post.get("message", "");

    if ((message.isEmpty()) || (post.containsKey("preview"))) {
        if (post.containsKey("preview")) {
            prop.put("mode", "1");
        } else {
            prop.put("mode", "0");
        }

        // open an editor page for the message
        // first ask if the other peer is online, and also what kind of document it accepts
        Seed seed = sb.peers.getConnected(ASCII.getBytes(hash));
        if (seed != null) {
            for (final String ip : seed.getIPs()) {
                Map<String, String> result = null;
                MultiProtocolURL targetBaseURL = null;
                final String targetBaseURLStr = seed.getPublicURL(ip,
                        sb.getConfigBool(SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED,
                                SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED_DEFAULT));
                try {
                    targetBaseURL = new MultiProtocolURL(targetBaseURLStr);
                    result = Protocol.permissionMessage(targetBaseURL, seed, sb);
                } catch (final MalformedURLException e) {
                    Network.log.warn(
                            "yacyClient.permissionMessage malformed target peer URL :" + targetBaseURLStr);
                } catch (final Exception e) {
                    // most probably a network time-out exception
                    Network.log.warn("yacyClient.permissionMessage error:" + e.getMessage());
                    if (targetBaseURL.isHTTPS()) {
                        try {
                            /* Request made over https : retry using http on the same IP as a fallback */
                            targetBaseURL = seed.getPublicMultiprotocolURL(ip, false);
                            result = Protocol.permissionMessage(targetBaseURL, seed, sb);
                            if (result != null) {
                                /* Got a successfull result with http : mark now SSl as not available ont the target peer */
                                seed.setFlagSSLAvailable(false);
                                sb.peers.updateConnected(seed);
                            }
                        } catch (final IOException e2) {
                            Network.log.warn("yacyClient.postMessage error:" + e2.getMessage());
                        }
                    }
                }
                //System.out.println("DEBUG: permission request result = " + result.toString());
                String peerName;
                Seed targetPeer = null;
                if (hash.equals(sb.peers.mySeed().hash)) {
                    peerName = sb.peers.mySeed().get(Seed.NAME, "nameless");
                } else {
                    targetPeer = sb.peers.getConnected(hash);
                    if (targetPeer == null) {
                        peerName = "nameless";
                    } else {
                        peerName = targetPeer.get(Seed.NAME, "nameless");
                    }
                }

                prop.putXML("mode_permission_peerName", peerName);
                final String response = (result == null) ? null : result.get("response");
                if (response == null || result == null) {
                    // we don't have permission or other peer does not exist
                    prop.put("mode_permission", "0");
                    if (targetPeer != null) {
                        sb.peers.peerActions.interfaceDeparture(targetPeer, ip);
                    }
                } else {

                    prop.put("mode_permission", "1");

                    // write input form
                    try {
                        final int messagesize = Integer.parseInt(result.get("messagesize"));
                        final int attachmentsize = Integer.parseInt(result.get("attachmentsize"));

                        prop.putXML("mode_permission_response", response);
                        prop.put("mode_permission_messagesize", messagesize);
                        prop.put("mode_permission_attachmentsize", attachmentsize);
                        prop.putXML("mode_permission_subject", subject);
                        prop.putXML("mode_permission_message", message);
                        prop.putHTML("mode_permission_hash", hash);
                        if (post.containsKey("preview")) {
                            prop.putWiki("mode_permission_previewmessage", message);
                        }

                    } catch (final NumberFormatException e) {
                        // "unresolved pattern", the remote peer is alive but had an exception
                        prop.put("mode_permission", "2");
                    }
                }
            }
        } else { // seed == null
            prop.put("mode_permission", "0");
            prop.putXML("mode_permission_peerName", "a passive peer");
        }
    } else {
        prop.put("mode", "2");
        // send written message to peer
        try {
            prop.put("mode_status", "0");
            int messagesize = post.getInt("messagesize", 0);
            //int attachmentsize = Integer.parseInt(post.get("attachmentsize", "0"));

            if (messagesize < 1000)
                messagesize = 1000; // debug
            if (subject.length() > 100)
                subject = subject.substring(0, 100);
            if (message.length() > messagesize)
                message = message.substring(0, messagesize);
            final byte[] mb = UTF8.getBytes(message);
            SeedDB seedDB = sb.peers;
            // prepare request
            final String salt = crypt.randomSalt();

            // send request
            final Map<String, ContentBody> parts = Protocol.basicRequestParts(sb, hash, salt);
            parts.put("process", UTF8.StringBody("post"));
            parts.put("myseed", UTF8.StringBody(seedDB.mySeed().genSeedStr(salt)));
            parts.put("subject", UTF8.StringBody(subject));
            parts.put("message", UTF8.StringBody(mb));
            final Seed seed = seedDB.getConnected(ASCII.getBytes(hash));
            boolean preferHttps = sb.getConfigBool(SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED,
                    SwitchboardConstants.NETWORK_PROTOCOL_HTTPS_PREFERRED_DEFAULT);
            Post post1 = null;
            for (final String ip : seed.getIPs()) {
                MultiProtocolURL targetBaseURL = null;
                try {
                    targetBaseURL = seed.getPublicMultiprotocolURL(ip, preferHttps);
                    post1 = new Post(targetBaseURL, seed.hash, "/yacy/message.html", parts, 20000);
                } catch (final MalformedURLException e) {
                    Network.log.warn("yacyClient.postMessage malformed target peer URL when using ip " + ip);
                } catch (final IOException e) {
                    Network.log.warn("yacyClient.postMessage error:" + e.getMessage());
                    if (targetBaseURL.isHTTPS()) {
                        try {
                            /* Request made over https : retry using http on the same IP as a fallback */
                            targetBaseURL = seed.getPublicMultiprotocolURL(ip, false);
                            post1 = new Post(targetBaseURL, seed.hash, "/yacy/message.html", parts, 20000);
                            if (post1 != null) {
                                /* Got a successfull result with http : mark now SSl as not available ont the target peer */
                                seed.setFlagSSLAvailable(false);
                            }
                        } catch (final IOException e2) {
                            Network.log.warn("yacyClient.postMessage error:" + e2.getMessage());
                        }
                    }
                }

                if (post1 != null) {
                    break;
                }
                seedDB.peerActions.interfaceDeparture(seed, ip);
            }
            final Map<String, String> result1 = post1 == null ? null : FileUtils.table(post1.getResult());
            final Map<String, String> result = result1;

            if (result != null) {
                // message has been sent
                prop.put("mode_status_response", result.get("response"));
            } else {
                prop.put("mode_status", "1");

                // "unresolved pattern", the remote peer is alive but had an exception
                prop.putXML("mode_status_message", message);
            }

        } catch (final NumberFormatException e) {
            prop.put("mode_status", "1");

            // "unresolved pattern", the remote peer is alive but had an exception
            prop.putXML("mode_status_message", message);
        }
    }
    return prop;
}

From source file:net.sourceforge.czt.gnast.Gnast.java

private static URL toURL(File file) {
    if (file == null) {
        return null;
    }/*  w w  w  .  jav  a  2  s  .  com*/

    try {
        return file.toURI().toURL();
    } catch (MalformedURLException e) {
        throw new GnastException("File " + file + " cannot be converted to URL: " + e.getMessage(), e);
    }
}

From source file:com.serli.maven.plugin.quality.mojo.LicenseMojo.java

/**
 * @param project/*from   w w w . ja va  2 s  . c  o  m*/
 *          not null
 * @param url
 *          not null
 * @return a valid URL object from the url string
 * @throws IOException
 *           if any
 */
protected static URL getLicenseURL(MavenProject project, String url) throws IOException {
    URL licenseUrl = null;
    UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_ALL_SCHEMES);
    // UrlValidator does not accept file URLs because the file
    // URLs do not contain a valid authority (no hostname).
    // As a workaround accept license URLs that start with the
    // file scheme.
    if (urlValidator.isValid(url) || StringUtils.defaultString(url).startsWith("file://")) {
        try {
            licenseUrl = new URL(url);
        } catch (MalformedURLException e) {
            throw new MalformedURLException(
                    "The license url '" + url + "' seems to be invalid: " + e.getMessage());
        }
    } else {
        File licenseFile = new File(project.getBasedir(), url);
        if (!licenseFile.exists()) {
            // Workaround to allow absolute path names while
            // staying compatible with the way it was...
            licenseFile = new File(url);
        }
        if (!licenseFile.exists()) {
            throw new IOException("Maven can't find the file '" + licenseFile + "' on the system.");
        }
        try {
            licenseUrl = licenseFile.toURI().toURL();
        } catch (MalformedURLException e) {
            throw new MalformedURLException(
                    "The license url '" + url + "' seems to be invalid: " + e.getMessage());
        }
    }

    return licenseUrl;
}

From source file:com.eucalyptus.webui.server.ConfigurationWebBackend.java

private static String getExternalIpAddress() {
    String ipAddr = null;//from  w w w. jav a  2  s  . co  m
    HttpClient httpClient = new HttpClient();

    //set User-Agent
    String clientVersion = (String) httpClient.getParams().getDefaults()
            .getParameter(HttpMethodParams.USER_AGENT);
    String javaVersion = System.getProperty("java.version");
    String osName = System.getProperty("os.name");
    String osArch = System.getProperty("os.arch");
    String eucaVersion = System.getProperty("euca.version");
    String extraVersion = System.getProperty("euca.extra_version");

    // Jakarta Commons-HttpClient/3.1 (java 1.6.0_24; Linux amd64) Eucalyptus/3.1.0-1.el6
    String userAgent = clientVersion + " (java " + javaVersion + "; " + osName + " " + osArch + ") Eucalyptus/"
            + eucaVersion;
    if (extraVersion != null) {
        userAgent = userAgent + "-" + extraVersion;
    }

    httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);

    //support for http proxy
    if (HttpServerBootstrapper.httpProxyHost != null && (HttpServerBootstrapper.httpProxyHost.length() > 0)) {
        String proxyHost = HttpServerBootstrapper.httpProxyHost;
        if (HttpServerBootstrapper.httpProxyPort != null
                && (HttpServerBootstrapper.httpProxyPort.length() > 0)) {
            int proxyPort = Integer.parseInt(HttpServerBootstrapper.httpProxyPort);
            httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
        } else {
            httpClient.getHostConfiguration().setProxyHost(new ProxyHost(proxyHost));
        }
    }
    // Use Rightscale's "whoami" service
    String whoamiUrl = WebProperties.getProperty(WebProperties.RIGHTSCALE_WHOAMI_URL,
            WebProperties.RIGHTSCALE_WHOAMI_URL_DEFAULT);
    GetMethod method = new GetMethod(whoamiUrl);
    Integer timeoutMs = new Integer(3 * 1000); // TODO: is this working?
    method.getParams().setSoTimeout(timeoutMs);

    try {
        httpClient.executeMethod(method);
        String str = "";
        InputStream in = method.getResponseBodyAsStream();
        byte[] readBytes = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = in.read(readBytes)) > 0) {
            str += new String(readBytes, 0, bytesRead);
        }
        Matcher matcher = Pattern.compile(".*your ip is (.*)").matcher(str);
        if (matcher.find()) {
            ipAddr = matcher.group(1);
        }

    } catch (MalformedURLException e) {
        LOG.warn("Malformed URL exception: " + e.getMessage());
        LOG.debug(e, e);
    } catch (IOException e) {
        LOG.warn("I/O exception: " + e.getMessage());
        LOG.debug(e, e);
    } finally {
        method.releaseConnection();
    }

    return ipAddr;
}