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.github.e2point718.har2jmx.HAR.java

public static HAR build(String source) {
    HAR h = new HAR();
    JSONObject har = new JSONObject(source);
    JSONObject log = har.getJSONObject("log");
    JSONArray jPages = getOptionalArray(log, "pages");
    Map<String, Page> pages = new HashMap<>();
    if (jPages != null) {
        h.pages = new Page[jPages.length()];
        for (int i = 0; i < jPages.length(); i++) {
            JSONObject jPage = jPages.getJSONObject(i);
            Page page = new Page();
            h.pages[i] = page;/*from   w  w w . j  ava2s.  c  om*/
            page.id = jPage.getString("id");
            page.title = jPage.getString("title");
            pages.put(page.id, page);
        }

    }
    JSONArray jEntries = getOptionalArray(log, "entries");
    if (jEntries != null) {
        h.entries = new Entry[jEntries.length()];
        for (int i = 0; i < jEntries.length(); i++) {
            JSONObject jEntry = jEntries.getJSONObject(i);
            Entry entry = new Entry();
            h.entries[i] = entry;
            entry.pageref = pages.get(getOptionalProperty(jEntry, "pageref"));
            JSONObject jRequest = jEntry.getJSONObject("request");
            Request request = new Request();
            entry.request = request;
            request.httpVersion = jRequest.getString("httpVersion");
            request.method = Method.valueOf(jRequest.getString("method"));
            try {
                request.url = new URL(jRequest.getString("url"));
            } catch (MalformedURLException e) {
                throw new JSONException(e.getMessage());
            }
            JSONArray jHeaders = getOptionalArray(jRequest, "headers");
            if (jHeaders != null) {
                request.headers = new HashMap<>();
                for (int j = 0; j < jHeaders.length(); j++) {
                    JSONObject jHeader = jHeaders.getJSONObject(j);
                    request.headers.put(jHeader.getString("name"), jHeader.getString("value"));
                }
            }
            JSONArray jQueryString = getOptionalArray(jRequest, "queryString");
            if (jQueryString != null) {
                request.queryString = new HashMap<>();
                for (int j = 0; j < jQueryString.length(); j++) {
                    JSONObject jQueryStringO = jQueryString.getJSONObject(j);
                    request.queryString.put(jQueryStringO.getString("name"), jQueryStringO.getString("value"));
                }
            }
            JSONArray jCookies = getOptionalArray(jRequest, "cookies");
            if (jCookies != null) {
                request.cookies = new Cookie[jCookies.length()];
                for (int j = 0; j < jCookies.length(); j++) {
                    JSONObject jCookie = jCookies.getJSONObject(j);
                    Cookie cookie = new Cookie();
                    request.cookies[j] = cookie;
                    cookie.name = jCookie.getString("name");
                    cookie.value = jCookie.getString("value");
                }
            }

            JSONObject jPostData = getOptionalObject(jRequest, ("postData"));
            if (jPostData != null) {
                PostData pd = new PostData();
                request.postData = pd;
                pd.mimeType = jPostData.getString("mimeType");
                pd.text = getOptionalProperty(jPostData, "text");

                JSONArray jPostParams = getOptionalArray(jPostData, "params");
                if (jPostParams != null) {
                    pd.params = new PostDataParam[jPostParams.length()];
                    for (int j = 0; j < jPostParams.length(); j++) {
                        PostDataParam pdp = new PostDataParam();
                        JSONObject jPostDataParam = jPostParams.getJSONObject(j);
                        pd.params[j] = pdp;
                        pdp.name = getOptionalProperty(jPostDataParam, "name");
                        pdp.value = getOptionalProperty(jPostDataParam, "value");
                        pdp.contentType = getOptionalProperty(jPostDataParam, "contentType");
                        pdp.fileName = getOptionalProperty(jPostDataParam, "fileName");
                    }
                }
            }
            JSONObject jResponse = jEntry.getJSONObject("response");
            Response response = new Response();
            entry.response = response;
            response.httpVersion = jResponse.getString("httpVersion");
            response.status = jResponse.getInt("status");
            response.statusText = jResponse.getString("statusText");
            jHeaders = getOptionalArray(jResponse, "headers");
            if (jHeaders != null) {
                response.headers = new HashMap<>();
                for (int j = 0; j < jHeaders.length(); j++) {
                    JSONObject jHeader = jHeaders.getJSONObject(j);
                    response.headers.put(jHeader.getString("name"), jHeader.getString("value"));
                }
            }
            jCookies = getOptionalArray(jResponse, "cookies");
            if (jCookies != null) {
                response.cookies = new Cookie[jCookies.length()];
                for (int j = 0; j < jCookies.length(); j++) {
                    JSONObject jCookie = jCookies.getJSONObject(j);
                    Cookie cookie = new Cookie();
                    response.cookies[j] = cookie;
                    cookie.name = jCookie.getString("name");
                    cookie.value = jCookie.getString("value");
                }
            }
            JSONObject jContent = getOptionalObject(jResponse, ("content"));
            if (jContent != null) {
                ResponseContent content = new ResponseContent();
                response.content = content;
                content.size = jContent.getLong("size");
                content.mimeType = jContent.getString("mimeType");
                content.text = getOptionalProperty(jContent, ("text"));
            }
        }

    }
    return h;
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.Crawl.java

final private static void addDiscoverLink(UrlManager urlManager, PatternManager inclusionManager,
        PatternManager exclusionManager, String href, Origin origin, String parentUrl, URL currentURL,
        UrlFilterItem[] urlFilterList, List<LinkItem> newUrlList) {
    if (href == null)
        return;//from   w  w w  .  j av a2s  .  c  o m
    try {
        URL url = currentURL != null ? LinkUtils.getLink(currentURL, href, urlFilterList, false)
                : LinkUtils.newEncodedURL(href);

        if (exclusionManager != null)
            if (exclusionManager.matchPattern(url))
                return;
        if (inclusionManager != null)
            if (!inclusionManager.matchPattern(url))
                return;
        newUrlList.add(new LinkItem(url.toExternalForm(), origin, parentUrl));
    } catch (MalformedURLException e) {
        Logging.warn(href + " " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        Logging.warn(href + " " + e.getMessage(), e);
    }
}

From source file:com.meterware.httpunit.HttpUnitUtils.java

/**
 * parse the given inputSource with a new Parser
 * @param inputSource//from  w  w w . ja v a2  s  . c  o  m
 * @return the document parsed from the input Source
 */
public static Document parse(InputSource inputSource) throws SAXException, IOException {
    DocumentBuilder db = newParser();
    try {
        Document doc = db.parse(inputSource);
        return doc;
    } catch (java.net.MalformedURLException mue) {
        if (EXCEPTION_DEBUG) {
            String msg = mue.getMessage();
            if (msg != null) {
                System.err.println(msg);
            }
            InputStream is = inputSource.getByteStream();
            is.reset();
            String content = parseISToString(is);
            System.err.println(content);
        }
        throw mue;
    }
}

From source file:com.meterware.httpunit.HttpUnitUtils.java

/**
 * parse the given inputStream with a new Parser
 * @param inputStream/*from ww w  .  ja v  a  2  s  . c  om*/
 * @return the document parsed from the input Stream
 */
public static Document parse(InputStream inputStream) throws SAXException, IOException {
    DocumentBuilder db = newParser();
    try {
        Document doc = db.parse(inputStream);
        return doc;
    } catch (java.net.MalformedURLException mue) {
        if (EXCEPTION_DEBUG) {
            String msg = mue.getMessage();
            if (msg != null) {
                System.err.println(msg);
            }
            InputStream is = inputStream;
            is.reset();
            String content = parseISToString(is);
            System.err.println(content);
        }
        throw mue;
    }
}

From source file:cdr.forms.SwordDepositHandler.java

/**
 * Generates a limited authentication scope for the supplied URL, so that an HTTP client will not send username and
 * passwords to other URLs./* ww  w .  ja v a  2  s  . com*/
 * 
 * @param queryURL
 *           the URL for the query.
 * @return an authentication scope tuned to the requested URL.
 * @throws IllegalArgumentException
 *            if <code>queryURL</code> is not a well-formed URL.
 */
public static AuthScope getAuthenticationScope(String queryURL) {
    if (queryURL == null) {
        throw new NullPointerException("Cannot derive authentication scope for null URL");
    }
    try {
        URL url = new URL(queryURL);
        // port defaults to 80 unless the scheme is https
        // or the port is explicitly set in the URL.
        int port = 80;
        if (url.getPort() == -1) {
            if ("https".equals(url.getProtocol())) {
                port = 443;
            }
        } else {
            port = url.getPort();
        }
        return new AuthScope(url.getHost(), port);
    } catch (MalformedURLException mue) {
        throw new IllegalArgumentException("supplied URL <" + queryURL + "> is ill-formed:" + mue.getMessage());
    }
}

From source file:edu.ucsb.nceas.metacat.util.RequestUtil.java

public static String get(String urlString, Hashtable<String, String[]> params) throws MetacatUtilException {
    try {/*from   w w  w . jav a 2s .c o  m*/
        URL url = new URL(urlString);
        URLConnection urlConn = url.openConnection();

        urlConn.setDoOutput(true);

        PrintWriter pw = new PrintWriter(urlConn.getOutputStream());
        String queryString = paramsToQuery(params);
        logMetacat.debug("Sending get request: " + urlString + "?" + queryString);
        pw.print(queryString);
        pw.close();

        // get the input from the request
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();

        return sb.toString();
    } catch (MalformedURLException mue) {
        throw new MetacatUtilException("URL error when contacting: " + urlString + " : " + mue.getMessage());
    } catch (IOException ioe) {
        throw new MetacatUtilException("I/O error when contacting: " + urlString + " : " + ioe.getMessage());
    }
}

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 DOM
 * to XML converter/*from ww w  . ja va2  s.  c  o m*/
 *
 * @param pluggableDatasouce
 * @param datasource
 * @return
 */
static String prepareDatasourceResponse(HttpServletResponse response, Integer templateID,
        IPluggableDatasource pluggableDatasouce, Map<String, Object> description, Object datasource) {
    // otherwise prepare an XML result
    DownloadUtil.prepareResponse(ServletActionContext.getRequest(), response, "TrackReport.xml", "text/xml");
    try {
        final OutputStream outputStream = response.getOutputStream();
        final String xslt = (String) description.get("xslt");
        if ((datasource != null) && (xslt != null) && (templateID != null)) {
            final File template = ReportBL.getDirTemplate(templateID);
            URL baseURL = null;
            try {
                baseURL = template.toURL();
            } catch (final MalformedURLException e) {
                LOGGER.error("Wrong template URL for " + template.getName() + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
            if (baseURL != null) {
                final String absolutePathXslt = baseURL.getFile() + xslt;
                try {
                    datasource = XsltTransformer.getInstance().transform((Document) datasource,
                            absolutePathXslt);
                } catch (final Exception e) {
                    LOGGER.warn("Tranforming the datasource with " + absolutePathXslt + " failed with "
                            + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
        if (pluggableDatasouce == null) {
            // the default datasource (ReportBeans from last executed query)
            // serialize the DOM object into an XML stream
            ReportBeansToXML.convertToXml(outputStream, (Document) datasource);
        } else {
            // datasource specific serialization
            pluggableDatasouce.serializeDatasource(outputStream, datasource);
        }
    } catch (final Exception e) {
        LOGGER.error("Serializing the datasource to output stream failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));

    }
    return null;
}

From source file:io.cloudslang.content.xml.utils.XmlUtils.java

/**
 * Transforms a String or File provided by path to a Document object.
 *
 * @param xml      xml the xml as String
 * @param filePath the path/remote path to the file
 * @param features parsing features to set on the document builder
 * @return a  Document representation of the String or file
 * @throws Exception in case something goes wrong
 *///from w  w  w.  j a  v a 2  s.c  om
public static Document createDocument(String xml, String filePath, String features) throws Exception {
    try {
        return parseXmlInputStream(getStream(xml, filePath), features);
    } catch (MalformedURLException e) {
        throw new Exception((new StringBuilder("Unable to open remote file requested, file path["))
                .append(filePath).append("], error[").append(e.getMessage()).append("]").toString(), e);
    } catch (IOException e) {
        throw new Exception((new StringBuilder("Unable to open file requested, filename[")).append(filePath)
                .append("], error[").append(e.getMessage()).append("]").toString(), e);
    }
}

From source file:com.dynamobi.db.conn.couchdb.CouchUdx.java

/**
 * Creates a CouchDB view//from  ww w.  ja v a 2s .c o  m
 */
public static void makeView(String user, String pw, String url, String viewDef) throws SQLException {
    try {
        URL u = new URL(url);
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();
        uc.setDoOutput(true);
        if (user != null && user.length() > 0) {
            uc.setRequestProperty("Authorization", "Basic " + buildAuthHeader(user, pw));
        }
        uc.setRequestProperty("Content-Type", "application/json");
        uc.setRequestMethod("PUT");
        OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
        wr.write(viewDef);
        wr.close();

        String s = readStringFromConnection(uc);
    } catch (MalformedURLException e) {
        throw new SQLException("Bad URL.");
    } catch (IOException e) {
        throw new SQLException(e.getMessage());
    }
}

From source file:net.sf.firemox.tools.Picture.java

/**
 * Download a file from the specified URL to the specified local file.
 * /*  w w w.j a v a 2  s .c o  m*/
 * @param localFile
 *          is the new card's picture to try first
 * @param remoteFile
 *          is the URL where this picture will be downloaded in case of the
 *          specified card name has not been found locally.
 * @param listener
 *          the component waiting for this picture.
 * @since 0.83 Empty file are deleted to force file to be downloaded.
 */
public static synchronized void download(String localFile, URL remoteFile, MonitoredCheckContent listener) {
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    File toDownload = new File(localFile);
    if (toDownload.exists() && toDownload.length() == 0 && toDownload.canWrite()) {
        toDownload.delete();
    }
    if (!toDownload.exists() || (toDownload.length() == 0 && toDownload.canWrite())) {
        // the file has to be downloaded
        try {
            if ("file".equals(remoteFile.getProtocol())) {
                File localRemoteFile = MToolKit
                        .getFile(remoteFile.toString().substring(7).replaceAll("%20", " "), false);
                int contentLength = (int) localRemoteFile.length();
                Log.info("Copying from " + localRemoteFile.getAbsolutePath());
                LoaderConsole.beginTask(
                        LanguageManager.getString("downloading") + " " + localRemoteFile.getAbsolutePath() + "("
                                + FileUtils.byteCountToDisplaySize(contentLength) + ")");

                // Copy file
                in = new BufferedInputStream(new FileInputStream(localRemoteFile));
                byte[] buf = new byte[2048];
                int currentLength = 0;
                boolean succeed = false;
                for (int bufferLen = in.read(buf); bufferLen >= 0; bufferLen = in.read(buf)) {
                    if (!succeed) {
                        toDownload.getParentFile().mkdirs();
                        out = new BufferedOutputStream(new FileOutputStream(localFile));
                        succeed = true;
                    }
                    currentLength += bufferLen;
                    if (out != null) {
                        out.write(buf, 0, bufferLen);
                    }
                    if (listener != null) {
                        listener.updateProgress(contentLength, currentLength);
                    }
                }

                // Step 3: close streams
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
                in = null;
                out = null;
                return;
            }

            // Testing mode?
            if (!MagicUIComponents.isUILoaded()) {
                return;
            }

            // Step 1: open streams
            final URLConnection connection = MToolKit.getHttpConnection(remoteFile);
            int contentLength = connection.getContentLength();
            in = new BufferedInputStream(connection.getInputStream());
            Log.info("Download from " + remoteFile + "(" + FileUtils.byteCountToDisplaySize(contentLength)
                    + ")");
            LoaderConsole.beginTask(LanguageManager.getString("downloading") + " " + remoteFile + "("
                    + FileUtils.byteCountToDisplaySize(contentLength) + ")");

            // Step 2: read and write until done
            byte[] buf = new byte[2048];
            int currentLength = 0;
            boolean succeed = false;
            for (int bufferLen = in.read(buf); bufferLen >= 0; bufferLen = in.read(buf)) {
                if (!succeed) {
                    toDownload.getParentFile().mkdirs();
                    out = new BufferedOutputStream(new FileOutputStream(localFile));
                    succeed = true;
                }
                currentLength += bufferLen;
                if (out != null) {
                    out.write(buf, 0, bufferLen);
                }
                if (listener != null) {
                    listener.updateProgress(contentLength, currentLength);
                }
            }

            // Step 3: close streams
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
            in = null;
            out = null;
            return;
        } catch (IOException e1) {
            if (MToolKit.getFile(localFile) != null) {
                MToolKit.getFile(localFile).delete();
            }
            if (remoteFile.getFile().equals(remoteFile.getFile().toLowerCase())) {
                Log.fatal("could not load picture " + localFile + " from URL " + remoteFile + ", "
                        + e1.getMessage());
            }
            String tmpRemote = remoteFile.toString().toLowerCase();
            try {
                download(localFile, new URL(tmpRemote), listener);
            } catch (MalformedURLException e) {
                Log.fatal("could not load picture " + localFile + " from URL " + tmpRemote + ", "
                        + e.getMessage());
            }
        }
    }
}