Example usage for java.net URI isAbsolute

List of usage examples for java.net URI isAbsolute

Introduction

In this page you can find the example usage for java.net URI isAbsolute.

Prototype

public boolean isAbsolute() 

Source Link

Document

Tells whether or not this URI is absolute.

Usage

From source file:org.mapfish.print.PDFUtils.java

private static Image loadImageFromUrl(final RenderingContext context, final URI uri,
        final boolean alwaysThrowExceptionOnError) throws IOException, DocumentException {
    if (!uri.isAbsolute()) {
        //Assumption is that the file is on the local file system
        return Image.getInstance(uri.toString());
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        String path;/* w ww.  j a va2  s .  co m*/
        if (uri.getHost() != null && uri.getPath() != null) {
            path = uri.getHost() + uri.getPath();
        } else if (uri.getHost() == null && uri.getPath() != null) {
            path = uri.getPath();
        } else {
            path = uri.toString().substring("file:".length()).replaceAll("/+", "/");
        }
        path = path.replace("/", File.separator);
        return Image.getInstance(new File(path).toURI().toURL());
    } else {

        final String contentType;
        final int statusCode;
        final String statusText;
        byte[] data = null;
        try {
            //read the whole image content in memory, then give that to iText
            if ((uri.getScheme().equals("http") || uri.getScheme().equals("https"))
                    && context.getConfig().localHostForwardIsFrom(uri.getHost())) {
                String scheme = uri.getScheme();
                final String host = uri.getHost();
                if (uri.getScheme().equals("https") && context.getConfig().localHostForwardIsHttps2http()) {
                    scheme = "http";
                }
                URL url = new URL(scheme, "localhost", uri.getPort(), uri.getPath() + "?" + uri.getQuery());

                HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
                connexion.setRequestProperty("Host", host);
                for (Map.Entry<String, String> entry : context.getHeaders().entrySet()) {
                    connexion.setRequestProperty(entry.getKey(), entry.getValue());
                }
                InputStream is = null;
                try {
                    try {
                        is = connexion.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = is.read(buffer)) != -1) {
                            baos.write(buffer, 0, length);
                        }
                        baos.flush();
                        data = baos.toByteArray();
                    } catch (IOException e) {
                        LOGGER.warn(e);
                    }
                    statusCode = connexion.getResponseCode();
                    statusText = connexion.getResponseMessage();
                    contentType = connexion.getContentType();
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            } else {
                GetMethod getMethod = null;
                try {
                    getMethod = new GetMethod(uri.toString());
                    for (Map.Entry<String, String> entry : context.getHeaders().entrySet()) {
                        getMethod.setRequestHeader(entry.getKey(), entry.getValue());
                    }
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("loading image: " + uri);
                    context.getConfig().getHttpClient(uri).executeMethod(getMethod);
                    statusCode = getMethod.getStatusCode();
                    statusText = getMethod.getStatusText();

                    Header contentTypeHeader = getMethod.getResponseHeader("Content-Type");
                    if (contentTypeHeader == null) {
                        contentType = "";
                    } else {
                        contentType = contentTypeHeader.getValue();
                    }
                    data = getMethod.getResponseBody();
                } finally {
                    if (getMethod != null) {
                        getMethod.releaseConnection();
                    }
                }
            }

            if (statusCode == 204) {
                // returns a transparent image
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("creating a transparent image for: " + uri);
                try {
                    final byte[] maskr = { (byte) 255 };
                    Image mask = Image.getInstance(1, 1, 1, 1, maskr);
                    mask.makeMask();
                    data = new byte[1 * 1 * 3];
                    Image image = Image.getInstance(1, 1, 3, 8, data);
                    image.setImageMask(mask);
                    return image;
                } catch (DocumentException e) {
                    LOGGER.warn("Couldn't generate a transparent image");

                    if (alwaysThrowExceptionOnError) {
                        throw e;
                    }

                    Image image = handleImageLoadError(context, e.getMessage());

                    LOGGER.warn("The status code was not a valid code, a default image is being returned.");

                    return image;
                }
            } else if (statusCode < 200 || statusCode >= 300 || contentType.startsWith("text/")
                    || contentType.equals("application/vnd" + ".ogc.se_xml")) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Server returned an error for " + uri + ": " + new String(data));
                String errorMessage;
                if (statusCode < 200 || statusCode >= 300) {
                    errorMessage = "Error (status=" + statusCode + ") while reading the image from " + uri
                            + ": " + statusText;
                } else {
                    errorMessage = "Didn't receive an image while reading: " + uri;
                }

                if (alwaysThrowExceptionOnError) {
                    throw new IOException(errorMessage);
                }

                Image image = handleImageLoadError(context, errorMessage);

                LOGGER.warn("The status code was not a valid code, a default image is being returned.");

                return image;
            } else {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("loaded image: " + uri);
                return Image.getInstance(data);
            }
        } catch (IOException e) {
            LOGGER.error("Server returned an error for " + uri + ": " + e.getMessage());

            if (alwaysThrowExceptionOnError) {
                throw e;
            }

            return handleImageLoadError(context, e.getMessage());
        }
    }
}

From source file:org.clazzes.odtransform.ZipFileURIResolver.java

public Source resolve(String href, String base) throws TransformerException {
    try {// w  ww .j  a  v a  2  s  .co  m
        URI uri = new URI(href);

        if (uri.isAbsolute())
            return null;

        log.debug("Resolving relative URI [" + href + "].");

        return new StreamSource(this.zipFile.getInputStream(new ZipEntry(href)));

    } catch (URISyntaxException e) {
        throw new TransformerException("Invalid URI", e);
    } catch (IOException e) {
        throw new TransformerException("Unexpected I/O error", e);
    }
}

From source file:cz.cvut.portal.kos.utils.UriBuilder.java

public URI build() {
    URI path = builder.buildAndExpand(variables).toUri();
    return path.isAbsolute() ? path : URI.create(base + path);
}

From source file:org.codice.ddf.ui.searchui.filter.RedirectServlet.java

@Override
public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    if (StringUtils.isNotBlank(redirectConfiguration.getDefaultUri())) {
        URI uri = URI.create(redirectConfiguration.getDefaultUri());
        if (uri.isAbsolute()) {
            LOGGER.warn("Redirecting /search to an absolute URI: {}", redirectConfiguration.getDefaultUri());
        } else {/*from   ww w  . jav  a2  s  .co  m*/
            LOGGER.info("Redirecting /search to a relative URI: {}", redirectConfiguration.getDefaultUri());
        }
        servletResponse.sendRedirect(redirectConfiguration.getDefaultUri());
    } else {
        LOGGER.warn("Search page redirection has not been configured.");
        servletResponse.sendError(404);
    }
}

From source file:org.eurekastreams.server.service.actions.strategies.activity.plugins.StandardFeedBookmarkMapper.java

/**
 * Gets the base object./* www . ja va2 s  . c  o  m*/
 *
 * @param inFeed
 *            Feed the entry was taken from.
 * @param entry
 *            the entry.
 * @return the object.
 */
protected HashMap<String, String> getBaseObject(final Feed inFeed, final SyndEntry entry) {
    HashMap<String, String> object = new HashMap<String, String>();
    // TODO: Strip markup
    object.put("title", InputCleaner.stripHtml(entry.getTitle(), MAXLENGTH));
    if (entry.getDescription() != null) {
        object.put("description", InputCleaner.stripHtml(entry.getDescription().getValue(), MAXLENGTH));
    } else {
        object.put("description", "");
    }

    // fix URLs missing hostnames
    String url = InputCleaner.stripHtml(entry.getLink(), MAXLENGTH);
    try {
        URI uri = new URI(url);
        if (!uri.isAbsolute()) {
            URI feedUri = new URI(inFeed.getUrl());
            url = feedUri.resolve(uri).toString();
        }
        object.put("targetUrl", url);
    } catch (Exception ex) {
        log.warn("Omitting invalid target URL '" + url + "' from bookmark activity generated from feed.", ex);
    }

    object.put("targetTitle", InputCleaner.stripHtml(entry.getTitle(), MAXLENGTH));

    MediaModule media = (MediaModuleImpl) entry.getModule(MediaModule.URI);
    if (media != null && media.getMetadata().getThumbnail().length > 0) {
        object.put("thumbnail",
                InputCleaner.stripHtml(media.getMetadata().getThumbnail()[0].getUrl().toString(), MAXLENGTH));
    }

    return object;
}

From source file:org.apache.ode.axis2.util.Axis2WSDLLocator.java

public InputStream openResource(URI uri) throws IOException {
    if (uri.isAbsolute() && uri.getScheme().equals("file")) {
        try {//from   w  w  w .  ja v a 2s.c om
            return uri.toURL().openStream();
        } catch (Exception except) {
            LOG.error("openResource: unable to open file URL " + uri + "; " + except.toString());
            return null;
        }
    }

    // Note that if we get an absolute URI, the relativize operation will simply
    // return the absolute URI.
    URI relative = _baseUri.relativize(uri);
    if (relative.isAbsolute() && !relative.getScheme().equals("urn")) {
        LOG.error("openResource: invalid scheme (should be urn:)  " + uri);
        return null;
    }

    File f = new File(_baseUri.getPath(), relative.getPath());
    if (!f.exists()) {
        LOG.error("openResource: file not found " + f);
        return null;
    }
    return new FileInputStream(f);
}

From source file:org.apache.ode.bpel.compiler.DefaultResourceFinder.java

private URI relativize(URI u) {
    if (u.isAbsolute()) {
        return _absoluteDir.toURI().relativize(u);
    } else//from ww  w  .jav  a  2  s .  c  o  m
        return u;
}

From source file:org.lenskit.config.LenskitConfigDSL.java

@Override
public void include(URI uri) throws IOException, RecommenderConfigurationException {
    URI realURI = uri;
    if (!realURI.isAbsolute()) {
        realURI = getBaseURI().resolve(realURI);
    }/*from w ww  . j  a v  a2s  .co  m*/
    LenskitConfigScript script = getConfigLoader().loadScript(realURI.toURL());
    script.configure(getConfig());
}

From source file:org.codehaus.httpcache4j.auth.digest.Digest.java

private List<URI> parseDomain(String domain) {
    if (StringUtils.isNotBlank(domain) && !"*".equals(domain)) {
        String[] strings = domain.split(" ");
        if (strings.length > 0) {
            ImmutableList.Builder<URI> builder = ImmutableList.builder();
            for (String string : strings) {
                if (string.startsWith("/")) {
                    string = host.toURI().resolve(string).toString();
                }//from w w w  .ja va  2s  .  c  o  m
                URI uri = URI.create(string);
                if (!uri.isAbsolute() && uri.getHost() == null) {
                    uri = host.toURI().resolve(uri);
                }
                builder.add(uri);
            }
            return builder.build();
        }
    }
    return Collections.emptyList();
}

From source file:org.wso2.carbon.bpel.core.ode.integration.axis2.Axis2WSDLLocator.java

public InputStream openResource(URI uri) throws IOException {
    if (uri.isAbsolute() && uri.getScheme().equals("file")) {
        try {//from  w w  w  .  j  a va  2s . c o  m
            return uri.toURL().openStream();
        } catch (Exception except) {
            log.error("openResource: unable to open file URL " + uri + "; " + except.toString());
            return null;
        }
    }

    // Note that if we get an absolute URI, the relativize operation will simply
    // return the absolute URI.
    URI relative = baseUri.relativize(uri);

    if (relative.isAbsolute() && relative.getScheme().equals("http")) {
        try {
            return relative.toURL().openStream();
        } catch (Exception except) {
            log.error("openResource: unable to open http URL " + uri + "; " + except.toString());
            return null;
        }
    }

    if (relative.isAbsolute() && !relative.getScheme().equals("urn")) {
        log.error("openResource: invalid scheme (should be urn:)  " + uri);
        return null;
    }

    File f = new File(baseUri.getPath(), relative.getPath());
    if (!f.exists()) {
        log.error("openResource: file not found " + f);
        return null;
    }
    return new FileInputStream(f);
}