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:edu.vt.vbi.patric.portlets.PhylogeneticTree.java

protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    response.setContentType("text/html");

    SiteHelper.setHtmlMetaElements(request, response, "Phylogeny");

    List<Integer> phylogenyOrderIds = Arrays.asList(2037, 1385, 80840, 213849, 51291, 186802, 91347, 186826,
            118969, 356, 766, 136, 72273, 135623);

    String contextType = request.getParameter("context_type");
    String contextId = request.getParameter("context_id");

    if (contextType != null && contextId != null) {

        DataApiHandler dataApi = new DataApiHandler(request);

        List<Map<String, Object>> orderList = new ArrayList<>();
        int taxonId = 0;

        try {//from ww  w .  ja v a  2s  .  c  om
            if (contextType.equals("genome")) {

                Genome genome = dataApi.getGenome(contextId);
                taxonId = genome.getTaxonId();
            } else {
                taxonId = Integer.parseInt(contextId);
            }

            // Step1. has Order in lineage?
            Taxonomy taxonomy = dataApi.getTaxonomy(taxonId);

            List<String> lineageRanks = taxonomy.getLineageRanks();

            if (lineageRanks.contains("order")) {
                List<Integer> lineageIds = taxonomy.getLineageIds();
                List<String> lineageNames = taxonomy.getLineageNames();

                int index = lineageRanks.indexOf("order");
                int orderTaxonId = lineageIds.get(index);

                if (phylogenyOrderIds.contains(orderTaxonId)) {
                    Map order = new HashMap();
                    order.put("name", lineageNames.get(index));
                    order.put("taxonId", lineageIds.get(index));

                    orderList.add(order);
                }
            }

            if (orderList.isEmpty()) {
                // no rank Order found in lineage, then,
                // Step2. has Order rank in descendants
                SolrQuery query = new SolrQuery(
                        "lineage_ids:" + taxonId + " AND taxon_rank:order AND taxon_id:("
                                + StringUtils.join(phylogenyOrderIds, " OR ") + ")");
                query.setFields("taxon_id,taxon_name,taxon_rank");
                query.setRows(100);

                LOGGER.trace("[{}] {}", SolrCore.TAXONOMY.getSolrCoreName(), query.toString());
                String apiResponse = dataApi.solrQuery(SolrCore.TAXONOMY, query);

                Map resp = jsonReader.readValue(apiResponse);
                Map respBody = (Map) resp.get("response");

                List<Map> sdl = (List<Map>) respBody.get("docs");
                for (Map doc : sdl) {
                    if (doc.get("taxon_rank").equals("order")) {
                        Map node = new HashMap<>();
                        node.put("taxonId", doc.get("taxon_id"));
                        node.put("name", doc.get("taxon_name").toString());

                        orderList.add(node);
                    }
                }
            }
        } catch (MalformedURLException e) {
            LOGGER.error(e.getMessage(), e);
        }

        request.setAttribute("orderList", orderList);
        request.setAttribute("taxonId", taxonId);

        PortletRequestDispatcher prd = getPortletContext().getRequestDispatcher("/index.jsp");
        prd.include(request, response);
    }
}

From source file:org.jasig.cas.util.http.SimpleHttpClient.java

@Override
public boolean isValidEndPoint(final String url) {
    try {//from  w ww . j  ava 2 s  .  c o  m
        final URL u = new URL(url);
        return isValidEndPoint(u);
    } catch (final MalformedURLException e) {
        LOGGER.error(e.getMessage(), e);
        return false;
    }
}

From source file:com.goeuro.goeurotest.service.Services.java

/**
 * */*w  w  w .  j a  v a  2s.  c  o m*/
 * Query the input URL and return the result as a String, the method retry configured 
 * number of times in case of IOexception occurred 
 *
 * @param url
 * @return jsonResponse
 * @throws Exception
 */
public String getJsonResponse(String url) throws Exception {
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    String jsonResponse = "";
    String responseLine = "";
    try {
        URL servleturl = new URL(url);
        HttpURLConnection servletconnection = (HttpURLConnection) servleturl.openConnection();
        servletconnection.setRequestMethod("GET");
        servletconnection.setRequestProperty("Content-Type", "application/json");
        inputStream = servletconnection.getInputStream();
        InputStreamReader bin = new InputStreamReader(inputStream);
        bufferedReader = new BufferedReader(bin);
        while ((responseLine = bufferedReader.readLine()) != null) {
            jsonResponse = jsonResponse + responseLine;
        }

        if (jsonResponse == null || jsonResponse == "") {

            throw new Exception("Json response is empty, there is no data to write in file");
        }

    } catch (MalformedURLException ex) {
        throw new Exception(
                "MalformedURLException exception occured while trying to contect the API " + ex.getMessage());
    } catch (IOException ex) {
        if (counter < Defines.NUMBER_OF_RETRIELS) {
            counter++;
            getJsonResponse(url);
        }
        throw new Exception("IOException exception occured while trying to contact the API " + ex.getMessage());
    }

    return jsonResponse;
}

From source file:com.omertron.thetvdbapiv2.methods.AbstractMethod.java

/**
 * Create a URL to the API calls/*from   www . ja  va2  s .c  om*/
 *
 * @param methodPath
 * @param param
 * @return
 * @throws TvDbException
 */
protected URL generateUrl(final String methodPath, final Object param) throws TvDbException {
    StringBuilder builder = new StringBuilder(API_URL);
    builder.append(methodPath);

    if (param != null) {
        builder.append("/").append(param.toString());
    }
    LOG.info("URL: {}", builder.toString());

    try {
        return new URL(builder.toString());
    } catch (MalformedURLException ex) {
        LOG.warn("Failed to convert '{}' into a URL", builder.toString());
        throw new TvDbException(ApiExceptionType.INVALID_URL, ex.getMessage(), builder.toString(), ex);
    }
}

From source file:com.bittorrent.mpetazzoni.client.announce.HTTPTrackerClient.java

/**
 * Build, send and process a tracker announce request.
 *
 * <p>//from   w  w  w .j  av a2s. c om
 * This function first builds an announce request for the specified event
 * with all the required parameters. Then, the request is made to the
 * tracker and the response analyzed.
 * </p>
 *
 * <p>
 * All registered {@link AnnounceResponseListener} objects are then fired
 * with the decoded payload.
 * </p>
 *
 * @param event The announce event type (can be AnnounceEvent.NONE for
 * periodic updates).
 * @param inhibitEvents Prevent event listeners from being notified.
 */
@Override
public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents)
        throws AnnounceException {
    logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
            new Object[] { this.formatAnnounceEvent(event), this.torrent.getUploaded(),
                    this.torrent.getDownloaded(), this.torrent.getLeft() });

    URL target = null;
    try {
        HTTPAnnounceRequestMessage request = this.buildAnnounceRequest(event);
        target = request.buildAnnounceURL(this.tracker.toURL());
    } catch (MalformedURLException mue) {
        throw new AnnounceException("Invalid announce URL (" + mue.getMessage() + ")", mue);
    } catch (MessageValidationException mve) {
        throw new AnnounceException(
                "Announce request creation violated " + "expected protocol (" + mve.getMessage() + ")", mve);
    } catch (IOException ioe) {
        throw new AnnounceException("Error building announce request (" + ioe.getMessage() + ")", ioe);
    }

    HttpURLConnection conn = null;
    InputStream in = null;
    try {
        conn = (HttpURLConnection) target.openConnection();
        in = conn.getInputStream();
    } catch (IOException ioe) {
        if (conn != null) {
            in = conn.getErrorStream();
        }
    }

    // At this point if the input stream is null it means we have neither a
    // response body nor an error stream from the server. No point in going
    // any further.
    if (in == null) {
        throw new AnnounceException("No response or unreachable tracker!");
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(in);

        // Parse and handle the response
        HTTPTrackerMessage message = HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray()));
        this.handleTrackerAnnounceResponse(message, inhibitEvents);
    } catch (IOException ioe) {
        throw new AnnounceException("Error reading tracker response!", ioe);
    } catch (MessageValidationException mve) {
        throw new AnnounceException(
                "Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve);
    } finally {
        // Make sure we close everything down at the end to avoid resource
        // leaks.
        try {
            in.close();
        } catch (IOException ioe) {
            logger.warn("Problem ensuring error stream closed!", ioe);
        }

        // This means trying to close the error stream as well.
        InputStream err = conn.getErrorStream();
        if (err != null) {
            try {
                err.close();
            } catch (IOException ioe) {
                logger.warn("Problem ensuring error stream closed!", ioe);
            }
        }
    }
}

From source file:org.commonjava.maven.galley.transport.htcli.HttpClientTransport.java

@Override
public boolean handles(final Location location) {
    final String uri = location.getUri();
    try {//from w  ww  . ja v  a 2 s . co m
        return uri != null && uri.startsWith("http") && new URL(location.getUri()) != null; // hack, but just verify that the URL parses.
    } catch (final MalformedURLException e) {
        logger.warn(String.format("HTTP transport cannot handle: %s. Error parsing URL: %s", location,
                e.getMessage()), e);
    }

    return false;
}

From source file:fyp.project.uploadFile.UploadFile.java

public int upLoad2Server(String sourceFileUri) {
    String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp";
    // String [] string = sourceFileUri;
    String fileName = sourceFileUri;
    int serverResponseCode = 0;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;// w ww .  j a v  a  2 s. c  o m
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {

        return 0;
    }
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                + fileName.substring(fileName.lastIndexOf("/")) + "\"" + lineEnd);

        m_log.log(Level.INFO, "Content-Disposition: form-data; name=\"file\";filename=\"{0}\"{1}",
                new Object[] { fileName.substring(fileName.lastIndexOf("/")), lineEnd });
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        m_log.log(Level.INFO, "Upload file to server" + "HTTP Response is : {0}: {1}",
                new Object[] { serverResponseMessage, serverResponseCode });

        // close streams
        m_log.log(Level.INFO, "Upload file to server{0} File is written", fileName);
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        m_log.log(Level.ALL, "Upload file to server" + "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //this block will give the response of upload link

    return serverResponseCode; // like 200 (Ok)

}

From source file:com.cyc.corpus.nlmpaper.AIMedOpenAccessPaper.java

private Optional<Path> getZipArchive(boolean cached) {
    try {//from  w ww.j  a v a 2  s. c o  m
        Path cachedFilePath = cachedArchivePath();
        Path parentDirectoryPath = cachedFilePath.getParent();

        // create the parent directory it doesn't already exist
        if (Files.notExists(parentDirectoryPath, LinkOption.NOFOLLOW_LINKS)) {
            Files.createDirectory(parentDirectoryPath);
        }

        // if cached file already exist - return it, no download necessary
        if (cached && Files.exists(cachedFilePath, LinkOption.NOFOLLOW_LINKS)) {
            return Optional.of(cachedFilePath.toAbsolutePath());
        }

        // otherwise, download the file
        URL url = new URL(PROTEINS_URL);
        Files.copy(url.openStream(), cachedFilePath, StandardCopyOption.REPLACE_EXISTING);
        return Optional.of(cachedFilePath.toAbsolutePath());

    } catch (MalformedURLException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }

    return Optional.empty();
}

From source file:api.v2.LabdooClient.java

public LabdooClient(String url) throws APIException {
    this.url = url;

    try {//from  ww w  .  ja  v a  2  s.c o  m
        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
        if (!url.startsWith("mock:")) {
            config.setServerURL(new URL(url));
            client = new XmlRpcClient();
            client.setConfig(config);
        } else {
            client = new MockXmlRpcClient();
        }
    } catch (MalformedURLException e) {
        log.error(e.getMessage());
        APIException apiException = new APIException();
        apiException.initCause(e.getCause());
        throw apiException;
    }

}

From source file:org.openmrs.module.referenceapplication.page.controller.LoginPageController.java

private String getRedirectUrlFromReferer(PageRequest pageRequest) {
    String referer = pageRequest.getRequest().getHeader("Referer");
    String redirectUrl = "";
    if (referer != null) {
        if (referer.contains("http://") || referer.contains("https://")) {
            try {
                URL refererUrl = new URL(referer);
                String refererPath = refererUrl.getPath();
                String refererContextPath = refererPath.substring(0, refererPath.indexOf('/', 1));
                if (StringUtils.equals(pageRequest.getRequest().getContextPath(), refererContextPath)) {
                    redirectUrl = refererPath;
                }/*from   w  w  w.j a  v a2  s. c  o m*/
            } catch (MalformedURLException e) {
                log.error(e.getMessage());
            }
        } else {
            redirectUrl = pageRequest.getRequest().getHeader("Referer");
        }
    }
    return StringEscapeUtils.escapeHtml(redirectUrl);
}