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.streamreduce.util.WebHDFSClient.java

private void validateUrl() throws IllegalArgumentException {
    try {/*from  w w  w .j a  va  2  s  .  co  m*/
        URL target = new URL(url);
        if (!target.getPath().contains("webhdfs/v1")) {
            throw new IllegalStateException(
                    "The destination URL was invalid: It must contain the path 'webhdfs/v1'.");
        }
    } catch (MalformedURLException e) {
        throw new IllegalStateException(String.format("The destination URL was invalid: %s", e.getMessage()));
    }
}

From source file:eumetsat.pn.elasticsearch.webapp.ElasticsearchApp.java

@Override
protected Map<String, Object> search(String searchTerms, String filterString, int from, int size) {
    Map<String, Object> data = new HashMap<>();
    // put "session" parameters here rightaway so it can be used in template even when empty result
    data.put("search_terms", searchTerms);
    data.put("filter_terms", filterString);

    URL url;/*from   w ww  . j  ava2s  . c  o m*/
    try {
        url = new URL(searchEndpointUrlString);
    } catch (MalformedURLException e) {
        log.error("Search enpoint URL malformed: {}", e.getMessage());
        addMessage(data, MessageLevel.danger, "Search endpoint URL is malformed: " + e.getMessage());
        return data;
    }

    List<Map<String, String>> resHits = new ArrayList<>();
    Map<String, String> resHit = null;

    Multimap<String, String> filterTermsMap = parseFiltersTerms(filterString);
    Set<String> hiddenFacets = new HashSet<>(); // to create the list of filters to hide

    String filterConstruct = "";
    if (filterTermsMap.size() > 0) {
        int i = 0;
        String filterTerms = "";
        for (String key : filterTermsMap.keySet()) {
            for (String term : filterTermsMap.get(key)) {
                if (i == 0) {
                    filterTerms += "{ \"term\" : { \"" + FACETS2HIERACHYNAMES.get(key) + "\":\"" + term
                            + "\"}}";
                } else {
                    filterTerms += ",{ \"term\" : { \"" + FACETS2HIERACHYNAMES.get(key) + "\":\"" + term
                            + "\"}}";
                }

                // hide the facets that are used for filtering
                hiddenFacets.add(key + ":" + term);

                i++;
            }
        }

        filterConstruct = " \"bool\" : { \"must\" : [" + filterTerms + "] }";
    }

    int lengthOfTitle = 300;
    int lengthOfAbstract = 5000;
    int boostFactorTitle = 10;

    String body = "{ " + // pagination information
            "\"from\" : " + from + ", \"size\" : " + size + "," + // request highlighted info
            "\"highlight\" : { \"pre_tags\" : [\"<em><strong>\"], \"post_tags\" : [\"</strong></em>\"], "
            + "                  \"fields\" : { \"identificationInfo.title\": {\"fragment_size\" : "
            + lengthOfTitle + ", \"number_of_fragments\" : 1}, "
            + "                                 \"identificationInfo.abstract\": {\"fragment_size\" : "
            + lengthOfAbstract + ", \"number_of_fragments\" : 1} } } , " + // request facets to refine search (here the maximum number of facets can be configured)
            " \"facets\" :   { \"satellites\": { \"terms\" : { \"field\" : \"hierarchyNames.satellite\", \"size\":5 } }, "
            + "                  \"instruments\": { \"terms\" : { \"field\" : \"hierarchyNames.instrument\", \"size\":5  } }, "
            + "                  \"categories\": { \"terms\" : { \"field\" : \"hierarchyNames.category\", \"size\": 5 } }, "
            + "                  \"societal Benefit Area\": { \"terms\" : { \"field\" : \"hierarchyNames.societalBenefitArea\", \"size\":5 } }, "
            + "                  \"distribution\": { \"terms\" : { \"field\" : \"hierarchyNames.distribution\", \"size\":5 } } "
            + "                }," + // add query info
            "\"query\" : { \"filtered\": { \"query\": "
            + "              { \"simple_query_string\" : { \"fields\" : [\"identificationInfo.title^"
            + boostFactorTitle + "\", \"identificationInfo.abstract\"], " + "\"query\" : \"" + searchTerms
            + "\" } " + "}" + ",\"filter\": {" + filterConstruct + "}" + " }}}";

    log.trace("elastic-search request: {}", body);

    //measure elapsed time
    Stopwatch stopwatch = Stopwatch.createStarted();

    WebResponse response = rClient.doGetRequest(url, new HashMap<String, String>(),
            new HashMap<String, String>(), body, log.isDebugEnabled());

    if (response == null) {
        log.error("Response from {} is null!", this.name);
        data.put("total_hits", 0);
        data = addMessage(data, MessageLevel.danger, "Response is null from " + this.name);
    } else {
        log.trace("Got response: {}", response);

        if (response.status == 200) {
            JSONParser parser = new JSONParser();
            JSONObject jsObj;
            try {
                jsObj = (JSONObject) parser.parse(response.body);
            } catch (ParseException e) {
                log.error("Could not parse search server response: {}", e);
                addMessage(data, MessageLevel.danger, "Could not parse server response: " + e.getMessage());
                return data;
            }

            Long hitcount = (Long) ((Map<?, ?>) jsObj.get("hits")).get("total");
            data.put("total_hits", hitcount);
            if (hitcount < 1)
                addMessage(data, MessageLevel.info, "No results found!");

            // compute the pagination information to create the pagination bar
            Map<String, Object> pagination = computePaginationParams(hitcount.intValue(), from);
            data.put("pagination", pagination);

            @SuppressWarnings("unchecked")
            List<Map<String, Object>> hits = (List<Map<String, Object>>) ((Map<?, ?>) jsObj.get("hits"))
                    .get("hits");

            //to get the highlight
            Map<?, ?> highlight = null;
            for (Map<String, Object> hit : hits) {
                resHit = new HashMap<>();

                resHit.put("id", (String) hit.get("_id"));
                resHit.put("score", String.format("%.4g%n", ((Double) hit.get("_score"))));

                // can have or not title or abstract
                // strategy. If it doesn't have an abstract or a title match then take it from the _source
                highlight = (Map<?, ?>) hit.get("highlight");

                if (highlight.containsKey("identificationInfo.title")) {
                    resHit.put("title",
                            (String) ((JSONArray) highlight.get("identificationInfo.title")).get(0));
                } else {
                    resHit.put("title", ((String) (((Map<?, ?>) (((Map<?, ?>) hit.get("_source"))
                            .get("identificationInfo"))).get("title"))));
                }

                if (highlight.containsKey("identificationInfo.abstract")) {
                    resHit.put("abstract",
                            (String) ((JSONArray) highlight.get("identificationInfo.abstract")).get(0));
                } else {
                    resHit.put("abstract", ((String) (((Map<?, ?>) (((Map<?, ?>) hit.get("_source"))
                            .get("identificationInfo"))).get("abstract"))));
                }

                JSONObject info = (JSONObject) ((JSONObject) hit.get("_source")).get("identificationInfo");
                JSONArray keywords = (JSONArray) info.get("keywords");
                resHit.put("keywords", Joiner.on(", ").join(keywords.iterator()));

                resHit.put("thumbnail", info.get("thumbnail").toString());
                resHit.put("status", info.get("status").toString());

                resHits.add(resHit);
            }

            data.put("hits", resHits);

            data.put("facets", jsObj.get("facets"));

            data.put("tohide", hiddenFacets);

        } else { // non-200 resonse
            log.error("Received non-200 response: {}", response);
            data = addMessage(data, MessageLevel.danger, "Non 200 response: " + response.toString());
        }
    }

    stopwatch.stop();

    data.put("elapsed", (double) (stopwatch.elapsed(TimeUnit.MILLISECONDS)) / (double) 1000);

    return data;
}

From source file:com.bah.applefox.main.plugins.webcrawler.utilities.WebPageCrawl.java

/**
 * Gets all allowed child links from the Web Page
 * /*from   www  .j  a  va 2 s  . c  om*/
 * @return - allLinks (excluding non-child links and parent link)
 */
public Set<String> getChildLinks() {
    // temp is used to eliminate duplicate links
    HashSet<String> temp = new HashSet<String>();

    // Ensure a link is a child link, then add it to temp
    for (String u : allLinks) {
        try {
            if (new URL(u).getHost().equals(parentURL.getHost())) {
                temp.add(u);
            }
        } catch (MalformedURLException e) {
            // This catch statement should never be reached because the URLs
            // were already confirmed, but if it is write to the error log
            log.error(e.getMessage());
        }
    }
    return temp;
}

From source file:com.google.wireless.speed.speedometer.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off */
@Override//w  w  w .  j a  v a 2s .c  o  m
public MeasurementResult call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    boolean success = false;
    String errorMsg = "";
    InputStream inputStream = null;

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent));
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            success = (statusCode == 200);
        }

        /* For HttpClient to work properly, we still want to consume the entire response even if
         * the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
                this.progress = (int) (100 * totalBodyLen / expectedResponseLen);
                this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress);
                broadcastProgressForUser(this.progress);
            }
            duration = System.currentTimeMillis() - startTime;
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success,
                this.measurementDesc);

        result.addResult("code", statusCode);

        if (success) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Log.i(SpeedometerApp.TAG, MeasurementJsonConvertor.toJsonString(result));
        return result;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Log.e(SpeedometerApp.TAG, e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Log.e(SpeedometerApp.TAG, e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e(SpeedometerApp.TAG, "Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:com.bah.applefox.main.plugins.webcrawler.utilities.WebPageCrawl.java

/**
 * Gets all child images from the Web Page
 * //from  w  ww.  jav a2  s .c o m
 * @return - allLinks (excluding non-child images)
 */
public Set<String> getChildImages() {

    // temp is used to eliminate duplicate links
    HashSet<String> temp = new HashSet<String>();

    // Ensure a link is a child link, then add it to temp
    for (String u : allImages) {
        try {
            if (new URL(u).getHost().equals(parentURL.getHost())) {
                temp.add(u);
            }
        } catch (MalformedURLException e) {
            // This catch statement should never be reached because the URLs
            // were already confirmed, but if it is write to the error log
            log.error(e.getMessage());
        }
    }
    return temp;
}

From source file:es.tekniker.framework.ktek.questionnaire.mng.server.EventServiceClient.java

public String queryContext(String codUser) {
    String strJSON = null;// w  ww  .ja  va  2 s.c o  m
    HttpURLConnection conn = null;
    StringBuffer strBOutput = new StringBuffer();
    boolean boolOK = true;
    String input = null;
    StringBuffer stbInput = new StringBuffer();

    try {
        log.debug("queryContext Start ");

        conn = getEventServiceSEConnection(methodQueryContext, endpointEventService, headerContentTypeJSON);

        stbInput.append("{\"entities\": [ {\"type\": \"" + typeContextValue
                + "\", \"isPattern\": \"false\", \"id\": \"" + codUser + "\"}]}");

        input = stbInput.toString();
        log.debug(input);

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() == 200) {
            log.debug("queryContext Response code " + conn.getResponseCode());
        } else {
            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }
        }

        log.debug("queryContext OutputStream wrote");

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        log.debug("queryContext Waiting server response ");

        String output;
        log.debug("queryContext Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            strBOutput.append(output);
            log.debug(output);
        }

        conn.disconnect();

        strJSON = strBOutput.toString();

        boolOK = true;

    } catch (MalformedURLException e) {
        log.error("queryContext MalformedURLException " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        log.error("queryContext IOException " + e.getMessage());
        e.printStackTrace();
    }

    return strJSON;
}

From source file:es.tekniker.framework.ktek.questionnaire.mng.server.EventServiceClient.java

public boolean getAccessToken() {
    HttpURLConnection conn = null;
    StringBuffer strBOutput = new StringBuffer();
    boolean boolOK = true;
    String input = null;//from  ww w.j a va 2  s .c  om
    StringBuffer stbInput = new StringBuffer();

    try {
        log.debug("getAccessToken Start ");

        conn = getEventServiceSEConnection(methodAccessToken, endpointOauth, headerContentTypeFormUrlencoded);

        stbInput.append(
                "client_id=522a3819dc268f33c983&client_secret=169d587f10e75316501483280d0c4843c3333144&grant_type=password&username=ktekQuser&password=F20st67R&scope=write");

        input = stbInput.toString();
        log.debug(input);

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() == 200) {
            log.debug("getAccessToken Response code " + conn.getResponseCode());
        } else {
            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException(
                        "getAccessToken Failed : HTTP error code : " + conn.getResponseCode());
            }
        }

        log.debug("getAccessToken OutputStream wrote");

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        log.debug("getAccessToken Waiting server response ");

        String output;
        log.debug("getAccessToken Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            strBOutput.append(output);
            log.debug(output);
        }

        conn.disconnect();

        boolOK = true;

    } catch (MalformedURLException e) {
        log.error("getAccessToken MalformedURLException " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        log.error("getAccessToken IOException " + e.getMessage());
        e.printStackTrace();
    }

    return boolOK;
}

From source file:org.esupportail.portlet.filemanager.services.cifs.CifsAccessImpl.java

private SmbFile cd(String path, SharedUserPortletParameters userParameters) {
    try {//w  w w.j  a v  a  2  s.c om
        this.open(userParameters);
        if (path == null || path.length() == 0)
            return root;
        return new SmbFile(this.getUri() + path, userAuthenticator);
    } catch (MalformedURLException me) {
        log.error(me.getMessage());
        throw new EsupStockException(me);
    }
}

From source file:com.sfs.dao.bugreport.JiraBugReportHandler.java

/**
 * Submit the bug report.//from ww  w. j  a  va  2s .  c om
 *
 * @param bugReport the bug report to submit
 *
 * @throws SFSDaoException the sfs dao exception
 */
public final void submitReport(final BugReportBean bugReport) throws SFSDaoException {
    if (bugReport == null) {
        throw new SFSDaoException("BugReportBean cannot be null");
    }
    if (jiraBaseUrl == null) {
        throw new SFSDaoException("The Jira base url cannot be null");
    }
    if (jiraUsername == null) {
        throw new SFSDaoException("The Jira username cannot be null");
    }
    if (jiraPassword == null) {
        throw new SFSDaoException("The Jira password cannot be null");
    }
    if (bugReport.getUser() == null) {
        throw new SFSDaoException("Submission of a bug report requires a valid user object");
    }
    if (bugReport.getReportClass() == null) {
        throw new SFSDaoException("The bug report class cannot be null");
    }

    final String jiraReportUrl = buildUrl(XMLRPC_ENDPOINT);

    Hashtable<String, String> issue = new Hashtable<String, String>();

    /** Set the bug report type url parameters **/
    String bugTypeParameters = "";
    try {
        ObjectTypeBean objectType = this.objectTypeDAO.load("Bug Report Type", bugReport.getReportType(),
                bugReport.getReportClass());
        bugTypeParameters = StringUtils.replace(objectType.getAbbreviation(), "&amp;", "&");
    } catch (SFSDaoException sde) {
        throw new SFSDaoException("Error submitting Jira report: " + sde.getMessage());
    }
    // Convert this string of bug report parameters to the array
    if (StringUtils.isNotBlank(bugTypeParameters)) {
        StringTokenizer st = new StringTokenizer(bugTypeParameters, "&");

        while (st.hasMoreElements()) {
            final String option = st.nextToken();
            final String parameter = option.substring(0, option.indexOf("="));
            final String value = option.substring(option.indexOf("=") + 1, option.length());

            logger.debug("Parameter: " + parameter + ", value: " + value);
            issue.put(parameter, value);
        }
    }

    /** Set the bug priority url parameters **/
    String priority = "";
    try {
        ObjectTypeBean objectType = this.objectTypeDAO.load("Bug Report Priority", "", bugReport.getPriority());
        priority = StringUtils.replace(objectType.getAbbreviation(), "&amp;", "&");
    } catch (SFSDaoException sde) {
        throw new SFSDaoException("Error submitting Jira report: " + sde.getMessage());
    }
    issue.put("priority", priority);

    /** Set the summary **/
    if (StringUtils.isBlank(bugReport.getTitle())) {
        bugReport.setTitle("Untitled issue");
    }
    issue.put("summary", bugReport.getTitle());

    /** Set the description **/
    issue.put("description", bugReport.getDescription());

    /** The username of the reporter **/
    issue.put("reporter", bugReport.getUser().getUserName().toLowerCase());

    /** Set the assignee - if none default set to automatic **/
    if (StringUtils.isNotBlank(this.jiraAssignee)) {
        issue.put("assignee", this.jiraAssignee);
    } else {
        // Set to automatic (-1 in Jira)
        issue.put("assignee", "-1");
    }

    if (!debugMode) {
        /** Post the bug report to Jira **/
        try {
            logger.info("Jira Report - submitting");
            logger.info("Jira URL: " + jiraReportUrl.toString());
            logger.info("Jira Parameters: " + issue.toString());

            final String response = this.performRestRequest(jiraReportUrl.toString(), issue);

            logger.info("Jira response: " + response);

        } catch (XmlRpcException xre) {
            throw new SFSDaoException("Error submitting Jira report via XMLRPC: " + xre.getMessage());
        } catch (MalformedURLException mue) {
            throw new SFSDaoException("Error with the Jira XMLRPC URL: " + mue.getMessage());
        }
    } else {
        logger.debug("Jira Report - debug mode");
        logger.debug("Jira URL: " + jiraReportUrl.toString());
        logger.debug("Jira Parameters: " + issue.toString());
    }
}

From source file:fr.aliasource.index.solr.SolrClientFactory.java

private SelfOptimizingServer initSrv(String serverUrl, String type) {
    SelfOptimizingServer sos = null;/*from  w  w  w  .j av  a 2  s .  co m*/

    try {
        sos = new SelfOptimizingServer(serverUrl);
    } catch (MalformedURLException e) {
        logger.error("Cannot init solr server ", e);
    }

    try {
        SolrPingResponse ping = sos.ping();
        logger.info("Got ping reply in " + ping.getElapsedTime() + "ms. Solr is alive.");
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Ping failed on solr server " + e.getMessage());
        }
    }

    return sos;
}