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.commonjava.aprox.core.ctl.ReplicationController.java

private List<EndpointView> getEndpoints(final ReplicationDTO dto) throws AproxWorkflowException {
    final String apiUrl = dto.getApiUrl();
    String url = null;/*  ww w  .j a v  a 2 s. co  m*/
    try {
        url = buildUrl(apiUrl, "/stats/all-endpoints");
    } catch (final MalformedURLException e) {
        throw new AproxWorkflowException(
                "Failed to construct endpoint-retrieval URL from api-base: {}. Reason: {}", e, apiUrl,
                e.getMessage());
    }

    //        logger.info( "\n\n\n\n\n[AutoProx] Checking URL: {} from:", new Throwable(), url );
    final HttpGet req = newGet(url, dto);
    HttpResponse response = null;
    try {
        response = http.getClient().execute(req);

        final StatusLine statusLine = response.getStatusLine();
        final int status = statusLine.getStatusCode();
        if (status == HttpStatus.SC_OK) {
            final String json = HttpResources.entityToString(response);
            final EndpointViewListing listing = serializer.readValue(json, EndpointViewListing.class);
            return listing.getItems();
        }

        throw new AproxWorkflowException(status, "Endpoint request failed: {}", statusLine);
    } catch (final ClientProtocolException e) {
        throw new AproxWorkflowException("Failed to retrieve endpoints from: {}. Reason: {}", e, url,
                e.getMessage());
    } catch (final IOException e) {
        throw new AproxWorkflowException("Failed to read endpoints from: {}. Reason: {}", e, url,
                e.getMessage());
    } finally {
        HttpResources.cleanupResources(req, response, null, http);
    }
}

From source file:com.mobiperf.measurements.PingTask.java

/** 
 * Use the HTTP Head method to emulate ping. The measurement from this method can be 
 * substantially (2x) greater than the first two methods and inaccurate. This is because, 
 * depending on the implementing of the destination web server, either a quick HTTP
 * response is replied or some actual heavy lifting will be done in preparing the response
 * *//*from   w  w w.  ja v  a 2  s.c om*/
private MeasurementResult executeHttpPingTask() throws MeasurementError {
    long pingStartTime = 0;
    long pingEndTime = 0;
    ArrayList<Double> rrts = new ArrayList<Double>();
    PingDesc pingTask = (PingDesc) this.measurementDesc;
    String errorMsg = "";
    MeasurementResult result = null;

    try {
        long totalPingDelay = 0;

        URL url = new URL("http://" + pingTask.target);

        int timeOut = (int) (3000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT);

        for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) {
            pingStartTime = System.currentTimeMillis();
            HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();
            httpClient.setRequestProperty("Connection", "close");
            httpClient.setRequestMethod("HEAD");
            httpClient.setReadTimeout(timeOut);
            httpClient.setConnectTimeout(timeOut);
            httpClient.connect();
            pingEndTime = System.currentTimeMillis();
            httpClient.disconnect();
            rrts.add((double) (pingEndTime - pingStartTime));
            this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT;
            broadcastProgressForUser(progress);
        }
        Logger.i("HTTP get ping succeeds");
        Logger.i("RTT is " + rrts.toString());
        double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT);
        result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT, PING_METHOD_HTTP);
        dataConsumed += pingTask.packetSizeByte * Config.PING_COUNT_PER_MEASUREMENT * 2;

    } catch (MalformedURLException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (IOException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    }
    if (result != null) {
        return result;
    } else {
        Logger.i("HTTP get ping fails");
        throw new MeasurementError(errorMsg);
    }
}

From source file:com.mobiperf_library.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi
 *  is not turned off *//*from   w w  w  .  ja  va  2  s .  com*/
@Override
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;
    TaskProgress taskProgress = TaskProgress.FAILED;
    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());
        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();
            if (statusCode == 200) {
                taskProgress = TaskProgress.COMPLETED;
            } else {
                taskProgress = TaskProgress.FAILED;
            }
        }

        /* 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);
                }
            }
            duration = System.currentTimeMillis() - startTime;//TODO check this
        }

        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, taskProgress,
                this.measurementDesc);

        result.addResult("code", statusCode);

        if (taskProgress == TaskProgress.COMPLETED) {
            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));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        MeasurementResult[] mrArray = new MeasurementResult[1];
        mrArray[0] = result;
        return mrArray;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("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.github.hipchat.api.HipChat.java

private URL getRequestUrl(String base, String command, String query) {
    URL url = null;/*from ww  w  .  jav a2  s .c  o m*/
    try {
        url = new URL(base + command + query);
    } catch (MalformedURLException e) {
        LogMF.error(logger, "Malformed URL Exception: {0}", new Object[] { e.getMessage() });
    }
    return url;
}

From source file:technology.tikal.accounts.dao.rest.SessionDaoRest.java

private void guardar(UserSession objeto, int intento) {
    //basic auth string
    String basicAuthString = config.getUser() + ":" + config.getPassword();
    basicAuthString = new String(Base64.encodeBase64(basicAuthString.getBytes()));
    basicAuthString = "Basic " + basicAuthString;

    //mensaje remoto
    try {//from  ww  w .  ja  v  a2s . c o m
        //config
        URL url = new URL(config.getUrl());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(config.getMethod());
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", basicAuthString);
        connection.setInstanceFollowRedirects(false);
        //write
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(mapper.writeValueAsString(objeto));
        //close
        writer.close();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            return;
        } else {
            throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable(
                    new String[] { "SessionCreationRefused.SessionDaoRest.guardar" },
                    new String[] { connection.getResponseCode() + "" }, ""));
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        if (intento <= maxRetry) {
            this.guardar(objeto, intento + 1);
        } else {
            throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable(
                    new String[] { "SessionCreationError.SessionDaoRest.guardar" },
                    new String[] { e.getMessage() }, ""));
        }
    }
}

From source file:org.apache.sentry.binding.solr.authz.SentrySolrPluginImpl.java

/**
 * This method provides the path(s) of various Hadoop configuration files required
 * by the Sentry/Solr plugin.// w w w  .  j ava  2  s.c om
 * @param confDir Location of a folder (on local file-system) storing Sentry Hadoop
 *                configuration files
 * @return A list of URLs containing the Sentry Hadoop
 *                configuration files
 */
private List<URL> getHadoopConfigFiles(String confDir) {
    List<URL> result = new ArrayList<>();

    if (confDir != null && !confDir.isEmpty()) {
        File confDirFile = new File(confDir);
        if (!confDirFile.exists()) {
            throw new SolrException(ErrorCode.SERVER_ERROR,
                    "Specified Sentry hadoop config directory does not exist: "
                            + confDirFile.getAbsolutePath());
        }
        if (!confDirFile.isDirectory()) {
            throw new SolrException(ErrorCode.SERVER_ERROR,
                    "Specified Sentry hadoop config directory path is not a directory: "
                            + confDirFile.getAbsolutePath());
        }
        if (!confDirFile.canRead()) {
            throw new SolrException(ErrorCode.SERVER_ERROR,
                    "Specified Sentry hadoop config directory must be readable by the Solr process: "
                            + confDirFile.getAbsolutePath());
        }

        for (String file : Arrays.asList("core-site.xml", "hdfs-site.xml", "ssl-client.xml")) {
            File f = new File(confDirFile, file);
            if (f.exists()) {
                try {
                    result.add(f.toURI().toURL());
                } catch (MalformedURLException e) {
                    throw new SolrException(ErrorCode.SERVER_ERROR, e.getMessage(), e);
                }
            }
        }
    }

    return result;
}

From source file:AppearanceMixed.java

public void init() {
    if (bgImage == null) {
        // the path to the image for an applet
        try {/*from  w  w  w  .j av a 2  s  .  co m*/
            bgImage = new java.net.URL(getCodeBase().toString() + "bg.jpg");
        } catch (java.net.MalformedURLException ex) {
            System.out.println(ex.getMessage());
            System.exit(1);
        }
    }

    if (texImage == null) {
        // the path to the image for an applet
        try {
            texImage = new java.net.URL(getCodeBase().toString() + "apimage.jpg");
        } catch (java.net.MalformedURLException ex) {
            System.out.println(ex.getMessage());
            System.exit(1);
        }
    }
    setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    MyCanvas3D c = new MyCanvas3D(config);
    add("Center", c);

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();
    u = new SimpleUniverse(c);

    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    u.getViewingPlatform().setNominalViewingTransform();

    u.addBranchGraph(scene);
}

From source file:argendata.service.impl.AppServiceImpl.java

@Override
public List<FacetCount> getIndexAllAppKeywords() {
    List<Count> resp = new ArrayList<Count>();

    QueryResponse rsp = null;//from   w  w w.ja v  a 2 s.  c o  m

    String appQuery = "type:app";

    List<String> myFacetFields = new ArrayList<String>();
    List<String> myFiltersQuery = new ArrayList<String>();

    myFacetFields.add("appkeyword");

    try {
        rsp = solrDao.simpleFacetQuery(appQuery, 1, null, myFacetFields, myFiltersQuery, "title",
                SolrQuery.ORDER.asc);
    } catch (MalformedURLException e) {
        logger.fatal("No se puede conectar a solr");
    } catch (SolrServerException e) {
        logger.error(e.getMessage(), e);
    }

    if (rsp.getFacetField("appkeyword") != null) {
        List<Count> lc = rsp.getFacetField("appkeyword").getValues();
        if (lc != null)
            resp.addAll(lc);
    }
    return getFacetCount(resp);
}

From source file:com.mobiperf.speedometer.measurements.PingTask.java

/**
 * Use the HTTP Head method to emulate ping. The measurement from this method can be substantially
 * (2x) greater than the first two methods and inaccurate. This is because, depending on the
 * implementing of the destination web server, either a quick HTTP response is replied or some
 * actual heavy lifting will be done in preparing the response
 * *//*www  .  ja  v a2  s .  co  m*/
private MeasurementResult executeHttpPingTask() throws MeasurementError {
    long pingStartTime = 0;
    long pingEndTime = 0;
    ArrayList<Double> rrts = new ArrayList<Double>();
    PingDesc pingTask = (PingDesc) this.measurementDesc;
    String errorMsg = "";
    MeasurementResult result = null;

    try {
        long totalPingDelay = 0;

        HttpClient client = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent));
        HttpHead headMethod;

        headMethod = new HttpHead("http://" + targetIp);

        headMethod.addHeader(new BasicHeader("Connection", "close"));
        headMethod.setParams(new BasicHttpParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000));

        int timeOut = (int) (1000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT);
        HttpConnectionParams.setConnectionTimeout(headMethod.getParams(), timeOut);

        for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) {
            pingStartTime = System.currentTimeMillis();
            HttpResponse response = client.execute(headMethod);
            pingEndTime = System.currentTimeMillis();
            rrts.add((double) (pingEndTime - pingStartTime));
            this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT;
            broadcastProgressForUser(progress);
        }
        Logger.i("HTTP get ping succeeds");
        double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT);
        result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT);
        // close the client to avoid memory leak
        ((AndroidHttpClient) client).close();
    } catch (MalformedURLException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (IOException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    }
    if (result != null) {
        return result;
    } else {
        Logger.i("HTTP get ping fails");
        throw new MeasurementError(errorMsg);
    }
}