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:org.jason.mapmaker.server.service.FeatureServiceImpl.java

@Override
public void importFromUrl(String url, FeaturesMetadata fm) throws ServiceException {

    URL u;/*  ww  w .  ja va 2  s .  c  o  m*/
    try {
        u = new URL(url);
    } catch (MalformedURLException ex) {
        log.debug("Exception thrown:", ex.getMessage());
        throw new ServiceException(ex);
    }

    List<File> fileList;
    try {
        fileList = ZipUtil.decompress(u);
    } catch (Exception e) {
        log.debug("Exception thrown:", e.getMessage());
        throw new ServiceException(e);
    }

    if (fileList == null || fileList.size() == 0) {
        log.debug("File list is null or zero!");
        throw new ServiceException("File List contains no files!");
    }

    File file = fileList.get(0); // get the txt file handler
    try {

        BufferedReader reader = new BufferedReader(new FileReader(file));
        reader.readLine(); // ignore header line

        String line = reader.readLine();
        List<Feature> featureList = new ArrayList<Feature>(); // arraylist may not be the best choice since I don't know how many features I'm importing
        int counter = 1;
        while (line != null) {
            String[] splitLine = split(line, "|"); // static import of StringUtils because I don't like regex's
            if (!NumberUtils.isNumber(splitLine[0]) || !NumberUtils.isNumber(splitLine[9])
                    || !NumberUtils.isNumber(splitLine[10])) {
                System.out.println("Feature ID#" + splitLine[0] + " fails isNumeric() test. Skipping.");
                line = reader.readLine();
                continue; // "silently" die
            }

            // only import the manmade features
            if (FeatureUtil.isManmadeFeature(splitLine[2])) {
                // setting this to variables and using the non-default Feature constructor means this is
                // easier to debug. Yay.

                // sometimes the USGS state file isn't limited to a single state... god only knows what the problem is
                String stateGeoId = splitLine[4];
                if (fm.getStateGeoId().equals(stateGeoId)) {

                    int id = Integer.parseInt(splitLine[0]);
                    String featureName = StringUtils.left(splitLine[1], 99);
                    String featureClass = StringUtils.left(splitLine[2], 99);
                    double lat = Double.parseDouble(splitLine[9]);
                    double lng = Double.parseDouble(splitLine[10]);

                    Feature feature = new Feature(id, featureName, featureClass, lat, lng, fm);
                    feature.setFeatureSource("usgs");

                    featureList.add(feature);

                    counter++;
                }
            }

            if (counter % 100000 == 0) {
                System.out.println("Processed " + counter + " items");
                try {
                    saveList(featureList);
                    featureList.clear();
                } catch (ServiceException e) {
                    log.debug("Exception thrown: ", e.getMessage());
                    break;
                }
            }
            line = reader.readLine();
        }

        saveList(featureList);

        reader.close();

    } catch (IOException e) {
        log.debug("Exception thrown:", e);
        throw new ServiceException(e);
    }

    file.delete();
}

From source file:com.tune.reporting.base.service.TuneServiceProxy.java

/**
 * Post request to TUNE Service API Service
 *
 * @return Boolean True if successful posting request, else False.
 * @throws TuneSdkException If error within SDK.
 *//*from   w w w .  j a va2 s  .  c  om*/
protected boolean postRequest() throws TuneSdkException {
    URL url = null;
    HttpsURLConnection conn = null;

    try {
        url = new URL(this.uri);
    } catch (MalformedURLException ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: %s: '%s'", this.uri,
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    try {
        // connect to the server over HTTPS and submit the payload
        conn = (HttpsURLConnection) url.openConnection();

        // Create the SSL connection
        SSLContext sc;
        sc = SSLContext.getInstance("TLS");
        sc.init(null, null, new java.security.SecureRandom());
        conn.setSSLSocketFactory(sc.getSocketFactory());

        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.connect();

        // Gets the status code from an HTTP response message.
        final int responseHttpCode = conn.getResponseCode();

        // Returns an unmodifiable Map of the header fields.
        // The Map keys are Strings that represent the response-header
        // field names. Each Map value is an unmodifiable List of Strings
        // that represents the corresponding field values.
        final Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        final String requestUrl = url.toString();

        // Gets the HTTP response message, if any, returned along
        // with the response code from a server.
        String responseRaw = conn.getResponseMessage();

        // Pull entire JSON raw response
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        responseRaw = sb.toString();

        // decode to JSON
        JSONObject responseJson = new JSONObject(responseRaw);

        this.response = new TuneServiceResponse(responseRaw, responseJson, responseHttpCode, responseHeaders,
                requestUrl.toString());
    } catch (Exception ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: '%s'",
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    return true;
}

From source file:edu.du.penrose.systems.fedoraApp.batchIngest.data.BatchIngestXMLhandlerImpl.java

/**
 * @throws JDOMException /* ww  w . j  av a  2 s .com*/
 * @throws Exception 
 * @see BatchIngestXMLhandler#getCurrentXMLdocument(boolean, boolean)
 */
public Document getCurrentXMLdocument(boolean validate, boolean schemaCheck) throws JDOMException {

    Document xmlDoc = null; // validate=false schemaCheck=false

    try {
        xmlDoc = this.buildDocumentCheckValid(this.currentXmlFile, validate, schemaCheck,
                new URL(FedoraAppConstants.METS_SCHEMA_URL));
    } catch (MalformedURLException e) {

        new JDOMException(e.getMessage()); // really shouldn't happen
    }

    return xmlDoc;

}

From source file:org.openqa.grid.internal.utils.SelfRegisteringRemote.java

public URL getRemoteURL() {
    String host = (String) nodeConfig.getConfiguration().get(RegistrationRequest.HOST);
    String port = (String) nodeConfig.getConfiguration().get(RegistrationRequest.PORT);
    String url = "http://" + host + ":" + port;

    try {/*  w  ww .  j a  va  2s  .  c o m*/
        return new URL(url);
    } catch (MalformedURLException e) {
        throw new GridConfigurationException("error building the node url " + e.getMessage(), e);
    }
}

From source file:org.xmatthew.spy2servers.component.spy.jmx.JmxSpySupportComponent.java

public void startup() {

    bean = new MBeanServerConnectionFactoryBean();
    try {//from   w ww . j a v  a  2s.  c o  m
        bean.setServiceUrl(getServerUrl());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    runing = true;
    setStatusRun();
    startJmxConnection();

    ObjectInstance objInstance;
    while (runing) {
        try {
            // begin to get MBeans
            Set mbeans = mbsc.queryMBeans(null, null);
            if (mbeans != null && mbeans.size() > 0) {
                Iterator iter = mbeans.iterator();
                while (iter.hasNext()) {
                    objInstance = (ObjectInstance) iter.next();
                    if (!getNameFilterQueryExp().apply(objInstance.getObjectName())) {
                        continue;
                    }
                    inspectMBean(objInstance, mbsc);
                }
            }

            //every repeat will call back MBeanServerConnection
            mscOnInterval(mbsc);

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            if (e instanceof IOException) {
                try {
                    bean.destroy();
                } catch (Exception e1) {
                    LOGGER.error(e1.getMessage(), e1);
                } finally {
                    bean = new MBeanServerConnectionFactoryBean();
                    try {
                        bean.setServiceUrl(getServerUrl());
                    } catch (MalformedURLException e1) {
                    }
                    isConnectionEstablished = false;
                    reStartJmxConnection();
                }
            }
        }

        try {
            Thread.sleep(detectInterval);
        } catch (InterruptedException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}

From source file:de.codecentric.jira.jenkins.plugin.servlet.RecentBuildsServlet.java

/**
* Gets BuldRss if authorization is required
* @return BuildRss//from  w  w  w. jav a 2 s .  c  o m
*/
private Document getBuildRssAuth(String urlJenkinsServer, String view, String job)
        throws MalformedURLException, DocumentException {
    String url;
    // was there a certain job specified?
    if (StringUtils.isNotEmpty(job)) {
        url = (urlJenkinsServer + "job/" + URLEncoder.encodeForURL(job) + RSS_ALL);
    } else if (StringUtils.isNotEmpty(view)) {
        url = (urlJenkinsServer + "view/" + URLEncoder.encodeForURL(view) + RSS_ALL);
    } else {
        url = (urlJenkinsServer + RSS_ALL);
    }

    PostMethod post = new PostMethod(url);
    Document buildRss = null;
    post.setDoAuthentication(true);

    try {
        client.executeMethod(post);
        buildRss = new SAXReader().read(post.getResponseBodyAsStream());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (SSLException e) {
        if (e.getMessage().equals("Unrecognized SSL message, plaintext connection?")) {
            urlJenkinsServer = urlJenkinsServer.replaceFirst("s", "");
            this.getBuildRssAuth(urlJenkinsServer, view, job);
        } else {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
    }

    return buildRss;
}

From source file:com.moviejukebox.tools.WebBrowser.java

/**
 * Get URL - allow to know if there is some redirect
 *
 * @param urlString// www.  j a v  a 2  s. c  om
 * @return
 */
public String getUrl(final String urlString) {
    URL url;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException ex) {
        LOG.warn("Unable to convert URL: {} - Error: {}", urlString, ex.getMessage());
        return Movie.UNKNOWN;
    }

    ThreadExecutor.enterIO(url);

    try {
        URLConnection cnx = openProxiedConnection(url);
        sendHeader(cnx);
        readHeader(cnx);
        return cnx.getURL().toString();
    } catch (IOException ex) {
        LOG.warn("Unable to retrieve URL: {} - Error: {}", urlString, ex.getMessage());
        return Movie.UNKNOWN;
    } finally {
        ThreadExecutor.leaveIO();
    }
}

From source file:org.geowebcache.layer.wms.WMSHttpHelper.java

/**
 * Loops over the different backends, tries the request
 * //from   w  w  w. ja v a  2s .  c om
 * @param tileRespRecv
 * @param profile
 * @param wmsparams
 * @return
 * @throws GeoWebCacheException
 */
@Override
protected void makeRequest(TileResponseReceiver tileRespRecv, WMSLayer layer, Map<String, String> wmsParams,
        String expectedMimeType, Resource target) throws GeoWebCacheException {
    Assert.notNull(target, "Target resource can't be null");
    Assert.isTrue(target.getSize() == 0, "Target resource is not empty");

    URL wmsBackendUrl = null;

    final Integer backendTimeout = layer.getBackendTimeout();
    int backendTries = 0; // keep track of how many backends we have tried
    GeoWebCacheException fetchException = null;
    while (target.getSize() == 0 && backendTries < layer.getWMSurl().length) {
        String requestUrl = layer.nextWmsURL();

        try {
            wmsBackendUrl = new URL(requestUrl);
        } catch (MalformedURLException maue) {
            throw new GeoWebCacheException("Malformed URL: " + requestUrl + " " + maue.getMessage());
        }
        try {
            connectAndCheckHeaders(tileRespRecv, wmsBackendUrl, wmsParams, expectedMimeType, backendTimeout,
                    target);
        } catch (GeoWebCacheException e) {
            fetchException = e;
        }

        backendTries++;
    }

    if (target.getSize() == 0) {
        String msg = "All backends (" + backendTries + ") failed.";
        if (fetchException != null) {
            msg += " Reason: " + fetchException.getMessage() + ". ";
        }
        msg += " Last request: '" + wmsBackendUrl.toString() + "'. "
                + (tileRespRecv.getErrorMessage() == null ? "" : tileRespRecv.getErrorMessage());

        tileRespRecv.setError();
        tileRespRecv.setErrorMessage(msg);
        throw new GeoWebCacheException(msg);
    }
}

From source file:com.cisco.gerrit.plugins.slack.client.WebhookClient.java

/**
 * Opens a connection to the provided Webhook URL.
 *
 * @param webhookUrl The Webhook URL to open a connection to.
 * @return The open connection to the provided Webhook URL.
 *///from  w  ww  . ja  v a2  s .  com
private HttpURLConnection openConnection(String webhookUrl) {
    try {
        HttpURLConnection connection;
        if (StringUtils.isNotBlank(config.getProxyHost())) {
            LOGGER.info("Connecting via proxy");
            if (StringUtils.isNotBlank(config.getProxyUsername())) {
                Authenticator authenticator;
                authenticator = new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return (new PasswordAuthentication(config.getProxyUsername(),
                                config.getProxyPassword().toCharArray()));
                    }
                };
                Authenticator.setDefault(authenticator);
            }

            Proxy proxy;
            proxy = new Proxy(Proxy.Type.HTTP,
                    new InetSocketAddress(config.getProxyHost(), config.getProxyPort()));

            connection = (HttpURLConnection) new URL(webhookUrl).openConnection(proxy);
        } else {
            LOGGER.info("Connecting directly");
            connection = (HttpURLConnection) new URL(webhookUrl).openConnection();
        }
        return connection;
    } catch (MalformedURLException e) {
        throw new RuntimeException("Unable to create webhook URL: " + webhookUrl, e);
    } catch (IOException e) {
        throw new RuntimeException("Error opening connection to Slack URL: [" + e.getMessage() + "].", e);
    }
}

From source file:com.krawler.esp.utils.ConfigReader.java

/** Returns the URL for the named resource. */
public URL getResource(String name) {
    URL configUrl = null;//from  w w w.  ja  va2  s .  com
    String configDir = System.getProperty(CONFIG_FILE_LOCATION);

    boolean useConfigRoot = false;
    if (configDir != null && configDir.length() > 0) {
        File dir = new File(configDir);
        if (dir.exists() && dir.isDirectory()) {
            useConfigRoot = true;
        }
    }

    if (useConfigRoot) {
        try {
            configUrl = new URL(configDir + (configDir.endsWith("/") ? "" : "/") + CONFIG_FILE_NAME);
        } catch (MalformedURLException e) {
            LOG.error(e.getMessage(), e);
        }
    } else {
        configUrl = classLoader.getResource(name);
    }

    return configUrl;
}