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.depgraph.rest.RepositoryController.java

public String getDownloadLog(final WebOperationConfigDTO dto, final String baseUri,
        final UriFormatter uriFormatter) throws AproxWorkflowException {
    final Set<String> downLog = new HashSet<String>();
    try {/*from w ww  .  ja  va  2s.  c om*/
        final Map<ProjectVersionRef, Map<ArtifactRef, ConcreteResource>> contents = resolveContents(dto);

        final List<ProjectVersionRef> refs = new ArrayList<ProjectVersionRef>(contents.keySet());
        Collections.sort(refs);

        for (final ProjectVersionRef ref : refs) {
            final Map<ArtifactRef, ConcreteResource> items = contents.get(ref);
            for (final ConcreteResource item : items.values()) {
                logger.info("Adding: '{}'", item);
                downLog.add(formatDownlogEntry(item, dto.getLocalUrls(), baseUri, uriFormatter));
            }
        }
    } catch (final MalformedURLException e) {
        throw new AproxWorkflowException("Failed to generate runtime repository. Reason: {}", e,
                e.getMessage());
    }

    final List<String> sorted = new ArrayList<String>(downLog);
    Collections.sort(sorted);

    return join(sorted, "\n");
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.Location.java

/**
 * Returns the location URL./*from  ww  w  .  j  av a 2 s.c  om*/
 * @return the location URL
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms533867.aspx">MSDN Documentation</a>
 */
@JsxGetter
public String getHref() {
    final Page page = window_.getWebWindow().getEnclosedPage();
    if (page == null) {
        return UNKNOWN;
    }
    try {
        URL url = page.getUrl();
        final boolean encodeHash = getBrowserVersion().hasFeature(JS_LOCATION_HASH_IS_ENCODED);
        final String hash = getHash(encodeHash);
        if (hash != null) {
            url = UrlUtils.getUrlWithNewRef(url, hash);
        }
        String s = url.toExternalForm();
        if (s.startsWith("file:/") && !s.startsWith("file:///")) {
            // Java (sometimes?) returns file URLs with a single slash; however, browsers return
            // three slashes. See http://www.cyanwerks.com/file-url-formats.html for more info.
            s = "file:///" + s.substring("file:/".length());
        }
        return s;
    } catch (final MalformedURLException e) {
        LOG.error(e.getMessage(), e);
        return page.getUrl().toExternalForm();
    }
}

From source file:de.fraunhofer.iosb.ilt.sta.service.Service.java

private ServiceResponse executeGetCapabilities(ServiceRequest request) {
    ServiceResponse response = new ServiceResponse();
    Map<String, List<Map<String, String>>> result = new HashMap<>();
    List<Map<String, String>> capList = new ArrayList<>();
    result.put("value", capList);
    try {// w w w.  ja  v a2s .  com
        for (EntityType entityType : EntityType.values()) {
            capList.add(createCapability(entityType.plural,
                    URI.create(settings.getServiceRootUrl() + "/" + entityType.plural).normalize().toURL()));
        }
        response.setCode(200);
        response.setResult(result);
        response.setResultFormatted(
                request.getFormatter().format(null, null, result, settings.isUseAbsoluteNavigationLinks()));
    } catch (MalformedURLException ex) {
        LOGGER.error("Failed to build url.", ex);
        return response.setStatus(500, ex.getMessage());
    }
    return response;
}

From source file:TickTockPicking.java

public void init() {
    if (texImage == null) {
        // the path to the image for an applet
        try {// w  ww.j  a  va 2s  .c o m
            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();

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

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph(c);
    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:ch.entwine.weblounge.kernel.fop.FopEndpoint.java

/**
 * Downloads both XML and XSL document and transforms them to PDF.
 * /*from w ww.  j a  va2 s .co  m*/
 * @param xmlURL
 *          the URL to the XML document
 * @param xslURL
 *          the URL to the XSL document
 * @return the generated PDF
 * @throws WebApplicationException
 *           if the XML document cannot be downloaded
 * @throws WebApplicationException
 *           if the XSL document cannot be downloaded
 * @throws WebApplicationException
 *           if the PDF creation fails
 */
@POST
@Path("/pdf")
public Response transformToPdf(@FormParam("xml") String xmlURL, @FormParam("xsl") String xslURL,
        @FormParam("parameters") String params) {

    // Make sure we have a service
    if (fopService == null)
        throw new WebApplicationException(Status.SERVICE_UNAVAILABLE);

    final Document xml;
    final Document xsl;

    // Load the xml document
    InputStream xmlInputStream = null;
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        xmlInputStream = new URL(xmlURL).openStream();
        xml = documentBuilder.parse(xmlInputStream);
    } catch (MalformedURLException e) {
        logger.warn("Error creating xml url from '{}'", xmlURL);
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (IOException e) {
        logger.warn("Error accessing xml document at '{}': {}", xmlURL, e.getMessage());
        throw new WebApplicationException(Status.NOT_FOUND);
    } catch (ParserConfigurationException e) {
        logger.warn("Error setting up xml parser: {}", e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (SAXException e) {
        logger.warn("Error parsing xml document from {}: {}", xmlURL, e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } finally {
        IOUtils.closeQuietly(xmlInputStream);
    }

    // Load the XLST stylesheet
    InputStream xslInputStream = null;
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        xslInputStream = new URL(xslURL).openStream();
        xsl = documentBuilder.parse(xslInputStream);
    } catch (MalformedURLException e) {
        logger.warn("Error creating xsl url from '{}'", xslURL);
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (IOException e) {
        logger.warn("Error accessing xsl stylesheet at '{}': {}", xslURL, e.getMessage());
        throw new WebApplicationException(Status.NOT_FOUND);
    } catch (ParserConfigurationException e) {
        logger.warn("Error setting up xml parser: {}", e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (SAXException e) {
        logger.warn("Error parsing xml document from {}: {}", xslURL, e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } finally {
        IOUtils.closeQuietly(xslInputStream);
    }

    // Create the filename
    String name = FilenameUtils.getBaseName(xmlURL) + ".pdf";

    // Process the parameters
    final List<String[]> parameters = new ArrayList<String[]>();
    if (StringUtils.isNotBlank(params)) {
        for (String param : StringUtils.split(params, ";")) {
            String[] parameterValue = StringUtils.split(param, "=");
            if (parameterValue.length != 2) {
                logger.warn("Parameter for PDF generation is malformed: {}", param);
                throw new WebApplicationException(Status.BAD_REQUEST);
            }
            parameters.add(
                    new String[] { StringUtils.trim(parameterValue[0]), StringUtils.trim(parameterValue[1]) });
        }
    }

    // Write the file contents back
    ResponseBuilder response = Response.ok(new StreamingOutput() {
        public void write(OutputStream os) throws IOException, WebApplicationException {
            try {
                fopService.xml2pdf(xml, xsl, parameters.toArray(new String[parameters.size()][2]), os);
            } catch (IOException e) {
                Throwable cause = e.getCause();
                if (cause == null || !"Broken pipe".equals(cause.getMessage()))
                    logger.warn("Error writing file contents to response", e);
            } catch (TransformerConfigurationException e) {
                logger.error("Error setting up the XSL transfomer: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (FOPException e) {
                logger.error("Error creating PDF document: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (TransformerException e) {
                logger.error("Error transforming to PDF: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } finally {
                IOUtils.closeQuietly(os);
            }
        }
    });

    // Set response information
    response.type("application/pdf");
    response.header("Content-Disposition", "inline; filename=" + name);
    response.lastModified(new Date());

    return response.build();
}

From source file:edu.indiana.d2i.htrc.dataapi.DataAPIWrapper.java

private long retrieveContents(String requestURL, Map<String, Map<String, String>> volPageContents) {
    long totalTime = 0;
    long startTime = 0;
    long endTime = 0;

    InputStream inputStream = null;

    try {//from   w  w w  . j  a  v a 2s . c  o m

        if (isSecureConn)
            initSSL(isSelfSigned);

        startTime = System.currentTimeMillis();
        URL url = new URL(requestURL);
        URLConnection connection = url.openConnection();

        connection.addRequestProperty("Authorization", "Bearer " + oauth2Token);

        if (isSecureConn)
            assert connection instanceof HttpsURLConnection;
        else
            assert connection instanceof HttpURLConnection;

        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
        httpURLConnection.setRequestMethod("GET");

        if (httpURLConnection.getResponseCode() == 200) {
            inputStream = httpURLConnection.getInputStream();
            openZipStream(inputStream, volPageContents, isConcat);

            endTime = System.currentTimeMillis();
            totalTime = endTime - startTime;

        } else {
            int responseCode = httpURLConnection.getResponseCode();
            log.error("Server response code : " + responseCode);
            inputStream = httpURLConnection.getInputStream();
            String responseBody = OAuthUtils.saveStreamAsString(inputStream);

            log.error(responseBody);

            /**
             * Currently server doesn't provide a way to renew the token, or
             * there is no response code particularly for the token
             * expiration, 500 will be returned in this case, but it can
             * also indicate other sorts of errors. In the following code we
             * just renew the token anyway
             * 
             */
            if (responseCode == 500)
                authenticate();

        }

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        log.error("MalformedURLException : " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.error("IOException : " + e.getMessage());
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        log.error("KeyManagementException : " + e.getMessage());
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        log.error("NoSuchAlgorithmException : " + e.getMessage());
        e.printStackTrace();
    } catch (OAuthSystemException e) {
        // TODO Auto-generated catch block
        log.error("OAuthSystemException : " + e.getMessage());
        e.printStackTrace();
    } catch (OAuthProblemException e) {
        // TODO Auto-generated catch block
        log.error("OAuthProblemException : " + e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error("Failed to close zip inputstream");
            log.error("IOException : " + e.getMessage());
            e.printStackTrace();
        }
    }

    return totalTime;
}

From source file:com.dtolabs.rundeck.core.common.impl.URLFileUpdater.java

private void updateHTTPUrl(final File destinationFile) throws FileUpdaterException {
    if (null == interaction) {
        interaction = new normalInteraction();
    }// w w  w. j av a2 s  .com
    final Properties cacheProperties;
    if (useCaching) {
        cacheProperties = loadCacheData(cacheMetadata);
        contentTypeFromCache(cacheProperties);
    } else {
        cacheProperties = null;
    }

    final HttpClientParams params = new HttpClientParams();
    if (timeout > 0) {
        params.setConnectionManagerTimeout(timeout * 1000);
        params.setSoTimeout(timeout * 1000);
    }

    final HttpClient client = new HttpClient(params);
    AuthScope authscope = null;
    UsernamePasswordCredentials cred = null;
    boolean doauth = false;
    String cleanUrl = url.toExternalForm().replaceAll("^(https?://)([^:@/]+):[^@/]*@", "$1$2:****@");
    String urlToUse = url.toExternalForm();
    try {
        if (null != url.getUserInfo()) {
            doauth = true;
            authscope = new AuthScope(url.getHost(), url.getPort() > 0 ? url.getPort() : url.getDefaultPort(),
                    AuthScope.ANY_REALM, "BASIC");
            cred = new UsernamePasswordCredentials(url.getUserInfo());
            urlToUse = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()).toExternalForm();
        } else if (null != username && null != password) {
            doauth = true;
            authscope = new AuthScope(url.getHost(), url.getPort() > 0 ? url.getPort() : url.getDefaultPort(),
                    AuthScope.ANY_REALM, "BASIC");
            cred = new UsernamePasswordCredentials(username + ":" + password);
            urlToUse = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()).toExternalForm();
        }
    } catch (MalformedURLException e) {
        throw new FileUpdaterException("Failed to configure base URL for authentication: " + e.getMessage(), e);
    }
    if (doauth) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(authscope, cred);
    }
    interaction.setClient(client);
    interaction.setMethod(new GetMethod(urlToUse));
    interaction.setFollowRedirects(true);
    if (null != acceptHeader) {
        interaction.setRequestHeader("Accept", acceptHeader);
    } else {
        interaction.setRequestHeader("Accept", "*/*");
    }

    if (useCaching) {
        applyCacheHeaders(cacheProperties, interaction);
    }

    logger.debug("Making remote request: " + cleanUrl);
    try {
        resultCode = interaction.executeMethod();
        reasonCode = interaction.getStatusText();
        if (useCaching && HttpStatus.SC_NOT_MODIFIED == resultCode) {
            logger.debug("Content NOT MODIFIED: file up to date");
        } else if (HttpStatus.SC_OK == resultCode) {
            determineContentType(interaction);

            //write to file
            FileOutputStream output = new FileOutputStream(destinationFile);
            try {
                Streams.copyStream(interaction.getResponseBodyAsStream(), output);
            } finally {
                output.close();
            }
            if (destinationFile.length() < 1) {
                //file was empty!
                if (!destinationFile.delete()) {
                    logger.warn("Failed to remove empty file: " + destinationFile.getAbsolutePath());
                }
            }
            if (useCaching) {
                cacheResponseInfo(interaction, cacheMetadata);
            }
        } else {
            throw new FileUpdaterException(
                    "Unable to retrieve content: result code: " + resultCode + " " + reasonCode);
        }
    } catch (HttpException e) {
        throw new FileUpdaterException(e);
    } catch (IOException e) {
        throw new FileUpdaterException(e);
    } finally {
        interaction.releaseConnection();
    }
}

From source file:org.commonjava.aprox.depgraph.rest.RepositoryController.java

private String getUrlMap(final WebOperationConfigDTO dto, final String baseUri, final UriFormatter uriFormatter)
        throws AproxWorkflowException {
    final Map<ProjectVersionRef, Map<String, Object>> result = new LinkedHashMap<ProjectVersionRef, Map<String, Object>>();

    try {//w w  w.  ja va 2s  . com

        final Map<ProjectVersionRef, Map<ArtifactRef, ConcreteResource>> contents = resolveContents(dto);

        final List<ProjectVersionRef> topKeys = new ArrayList<ProjectVersionRef>(contents.keySet());
        Collections.sort(topKeys, new ProjectVersionRefComparator());

        for (final ProjectVersionRef gav : topKeys) {
            final Map<ArtifactRef, ConcreteResource> items = contents.get(gav);

            final Map<String, Object> data = new HashMap<String, Object>();
            result.put(gav, data);

            final Set<String> files = new HashSet<String>();
            KeyedLocation kl = null;

            for (final ConcreteResource item : items.values()) {
                final KeyedLocation loc = (KeyedLocation) item.getLocation();

                // FIXME: we're squashing some potential variation in the locations here!
                // if we're not looking for local urls, allow any cache-only location to be overridden...
                if (kl == null || (!dto.getLocalUrls() && (kl instanceof CacheOnlyLocation))) {
                    kl = loc;
                }

                logger.info("Adding {} (keyLocation: {})", item, kl);
                files.add(new File(item.getPath()).getName());
            }

            final List<String> sortedFiles = new ArrayList<String>(files);
            Collections.sort(sortedFiles);
            data.put(URLMAP_DATA_REPO_URL,
                    formatUrlMapRepositoryUrl(kl, dto.getLocalUrls(), baseUri, uriFormatter));
            data.put(URLMAP_DATA_FILES, sortedFiles);
        }
    } catch (final MalformedURLException e) {
        throw new AproxWorkflowException("Failed to generate runtime repository. Reason: {}", e,
                e.getMessage());
    }

    try {
        return serializer.writeValueAsString(result);
    } catch (final JsonProcessingException e) {
        throw new AproxWorkflowException("Failed to serialize to JSON: %s", e, e.getMessage());
    }
}

From source file:ImageComponentByReferenceTest.java

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

    Canvas3D c = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
    BranchGroup scene = createSceneGraph();
    u = new SimpleUniverse(c);
    u.getViewingPlatform().setNominalViewingTransform();
    u.addBranchGraph(scene);
    Container contentPane = getContentPane();
    JPanel p = new JPanel();
    BoxLayout boxlayout = new BoxLayout(p, BoxLayout.Y_AXIS);
    p.setLayout(boxlayout);
    contentPane.add("Center", c);

    contentPane.add("South", p);

    p.add(createImagePanel());

}

From source file:ws.argo.BrowserWeb.BrowserWebController.java

private String restGetCall(String url) {
    String response = "";

    try {/* w  ww. j a  v  a 2s . c o m*/

        HttpGet getRequest = new HttpGet(url);

        CloseableHttpResponse httpResponse = getHttpClient().execute(getRequest);

        try {
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode > 300) {
                throw new RuntimeException(
                        "Failed : HTTP error code : " + httpResponse.getStatusLine().getStatusCode());
            }

            if (statusCode != 204) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((httpResponse.getEntity().getContent())));

                StringBuffer buf = new StringBuffer();

                String output;
                //System.out.println("Output from Listener .... \n");
                while ((output = br.readLine()) != null) {
                    buf.append(output);
                }

                response = buf.toString();
            }
        } finally {
            httpClient.close();
        }

        //         System.out.println("Response payload sent successfully to respondTo address.");

    } catch (MalformedURLException e) {
        System.out.println(
                "MalformedURLException occured\nThe respondTo URL was a no good.  respondTo URL is: " + url);
        //         e.printStackTrace();
    } catch (IOException e) {
        System.out.println("An IOException occured: the error message is - " + e.getMessage());
        //         e.printStackTrace();
    } catch (Exception e) {
        System.out.println("Some error occured: the error message is - " + e.getMessage());
        //         e.printStackTrace();
    }

    return response;
}