Example usage for java.net URI toURL

List of usage examples for java.net URI toURL

Introduction

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

Prototype

public URL toURL() throws MalformedURLException 

Source Link

Document

Constructs a URL from this URI.

Usage

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

public static Image createImageFromSVG(RenderingContext context, String iconItem, double maxIconWidth,
        double maxIconHeight, double scale) throws IOException {
    Image image = null;//from w w  w.j  a  v  a 2  s .  co m
    try {
        PdfContentByte dc = context.getDirectContent();
        URI uri = URI.create(iconItem);
        URL url = uri.toURL();
        SVGDocumentFactory factory = new SAXSVGDocumentFactory(XMLResourceDescriptor.getXMLParserClassName());
        UserAgent userAgent = new UserAgentAdapter();
        DocumentLoader loader = new DocumentLoader(userAgent);
        BridgeContext ctx = new BridgeContext(userAgent, loader);
        ctx.setDynamicState(BridgeContext.DYNAMIC);
        SVGDocument svgDoc = factory.createSVGDocument(null, url.openStream());
        GVTBuilder builder = new GVTBuilder();
        GraphicsNode graphics = builder.build(ctx, svgDoc);
        String svgWidthString = svgDoc.getDocumentElement().getAttribute("width");
        String svgHeightString = svgDoc.getDocumentElement().getAttribute("height");
        float svgWidth = Float.valueOf(svgWidthString.substring(0, svgWidthString.length() - 2));
        float svgHeight = Float.valueOf(svgHeightString.substring(0, svgHeightString.length() - 2));
        /**
         * svgFactor needs to be calculated depending on the screen DPI by the PDF DPI
         * This is 96 / 72 = 4 / 3 ~= 1.3333333 on Windows, but might be different on *nix.
         */
        final float svgFactor = 25.4f / userAgent.getPixelUnitToMillimeter() / 72f; // 25.4 mm = 1 inch TODO: Might need to get 72 from somewhere else?
        //float svgFactor = (float) Toolkit.getDefaultToolkit().getScreenResolution() / 72f; // this only works with AWT, i.e. when a window environment is running
        PdfTemplate map = dc.createTemplate(svgWidth * svgFactor, svgHeight * svgFactor);
        Graphics2D g2d = map.createGraphics(svgWidth * svgFactor, svgHeight * svgFactor);
        graphics.paint(g2d);
        g2d.dispose();
        image = Image.getInstance(map);
        image.scalePercent((float) (scale * 100));
        if (image.getWidth() * scale > maxIconWidth || image.getHeight() * scale > maxIconHeight) {
            image.scaleToFit((float) maxIconWidth, (float) maxIconHeight);
        }
    } catch (BadElementException bee) {
        LOGGER.warn("Bad Element " + iconItem + " with " + bee.getMessage());
    } catch (MalformedURLException mue) {
        LOGGER.warn("Malformed URL " + iconItem + " with " + mue.getMessage());
    } catch (IOException ioe) {
        throw ioe;
    }
    return image;
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UMLSHistoryFileToSQL.java

/**
 * Method returns a BufferedReader for the passes URI.
 * /*from w  w w  .j a va2  s. c o  m*/
 * @param filePath
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
private static BufferedReader getReader(URI filePath) throws MalformedURLException, IOException {
    BufferedReader reader = null;
    if (filePath.getScheme().equals("file")) {

        reader = new BufferedReader(new FileReader(new File(filePath)));
    } else {

        reader = new BufferedReader(new InputStreamReader(filePath.toURL().openConnection().getInputStream()));
    }
    return reader;
}

From source file:com.occamlab.te.parsers.ImageParser.java

/**
 * Determines the width of the first image in an image file in pixels.
 * //from w  w w.  j  av  a  2 s. c  o  m
 * @param imageLoc
 *            the string location of the image (uri syntax expected)
 * @return int the image width in pixels, or -1 if unable.
 * @author Paul Daisey added 2011-05-13 to support WMTS ETS
 */
public static int getImageWidth(String imageLoc) {

    // Get the image as an InputStream
    InputStream is = null;
    try {
        URI imageUri = new URI(imageLoc);
        URL imageUrl = imageUri.toURL();
        is = imageUrl.openStream();
    } catch (Exception e) {
        jlogger.log(Level.SEVERE, "getImageWidth", e);

        return -1;
    }
    // Determine the image width
    try {
        // Create an image input stream on the image
        ImageInputStream iis = ImageIO.createImageInputStream(is);

        // Find all image readers that recognize the image format
        Iterator iter = ImageIO.getImageReaders(iis);

        // No readers found
        if (!iter.hasNext()) {
            return -1;
        }

        // Use the first reader
        ImageReader reader = (ImageReader) iter.next();
        reader.setInput(iis, true);
        int width = reader.getWidth(0);
        iis.close();

        return width;
    } catch (IOException e) {
        jlogger.log(Level.SEVERE, "getImageWidth", e);
        // The image could not be read
    }
    return -1;
}

From source file:com.occamlab.te.parsers.ImageParser.java

/**
 * Determines the height of the first image in an image file in pixels.
 * /*from  w  w w.  j av  a2 s  . c om*/
 * @param imageLoc
 *            the string location of the image (uri syntax expected)
 * @return int the image width in pixels, or -1 if unable.
 * @author Paul Daisey added 2011-05-13 to support WMTS ETS
 */
public static int getImageHeight(String imageLoc) {

    // Get the image as an InputStream
    InputStream is = null;
    try {
        URI imageUri = new URI(imageLoc);
        URL imageUrl = imageUri.toURL();
        is = imageUrl.openStream();
    } catch (Exception e) {
        jlogger.log(Level.SEVERE, "getImageWidth", e);

        return -1;
    }
    // Determine the image width
    try {
        // Create an image input stream on the image
        ImageInputStream iis = ImageIO.createImageInputStream(is);

        // Find all image readers that recognize the image format
        Iterator iter = ImageIO.getImageReaders(iis);

        // No readers found
        if (!iter.hasNext()) {
            return -1;
        }

        // Use the first reader
        ImageReader reader = (ImageReader) iter.next();
        reader.setInput(iis, true);
        int height = reader.getHeight(0);
        iis.close();

        return height;
    } catch (IOException e) {
        jlogger.log(Level.SEVERE, "getImageWidth", e);
        // The image could not be read
    }
    return -1;
}

From source file:com.occamlab.te.parsers.ImageParser.java

/**
 * Determines the type of image, or null if not a valid image type
 * //from  w  ww. ja  v  a  2  s.co m
 * @param imageLoc
 *            the string location of the image (uri syntax expected)
 * @return String the name of the image type/format, or null if not valid
 */
public static String getImageType(String imageLoc) {

    // Get the image as an InputStream
    InputStream is = null;
    try {
        URI imageUri = new URI(imageLoc);
        URL imageUrl = imageUri.toURL();
        is = imageUrl.openStream();
    } catch (Exception e) {
        jlogger.log(Level.SEVERE, "getImageType", e);

        return null;
    }

    // Determine the image type and return it if valid
    try {
        // Create an image input stream on the image
        ImageInputStream iis = ImageIO.createImageInputStream(is);

        // Find all image readers that recognize the image format
        Iterator iter = ImageIO.getImageReaders(iis);

        // No readers found
        if (!iter.hasNext()) {
            return null;
        }

        // Use the first reader
        ImageReader reader = (ImageReader) iter.next();
        iis.close();

        // Return the format name
        return reader.getFormatName();
    } catch (IOException e) {
        jlogger.log(Level.SEVERE, "getImageType", e);

    }

    // The image could not be read
    return null;
}

From source file:de.fuberlin.agcsw.heraclitus.graph.GraphAnalyse.java

public static void initSailRepository(URI physicalURI, URI namespace) {
    try {//www.  j  a v a 2 s  .c o m
        rep = new SailRepository(new MemoryStore());
        rep.initialize();
        RepositoryConnection con = rep.getConnection();
        ValueFactory f = rep.getValueFactory();
        con.add(physicalURI.toURL(), namespace.toString(), RDFFormat.RDFXML, f.createURI("http://graph.com"));
    } catch (RepositoryException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (RDFParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.microsoft.tfs.core.util.URIUtils.java

/**
 * <p>//  w  w w  .j av  a  2s  .c o m
 * If a {@link URI} is successfully constructed but contains invalid
 * characters in the hostname (notably, underscores), the
 * {@link URI#getHost()} method returns {@link <code>null</code>}. This
 * method first gets the host using that method. If <code>null</code> is
 * returned, a best effort to get the original host (if any) is made by
 * converting the {@link URI} to a {@link URL} and calling
 * {@link URL#getHost()}.
 * </p>
 *
 * <p>
 * This method should only be used in the specific case when you want to try
 * to detect and handle the above condition. For most cases, underscores in
 * hostnames should correctly be treated as errors, and this method should
 * not be used.
 * </p>
 *
 * @param uri
 *        the {@link URI} to get the host name for (must not be
 *        <code>null</code>)
 * @return the host name of the {@link URI}, or <code>null</code> if the
 *         host name was not defined
 */
public static String safeGetHost(final URI uri) {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    String host = uri.getHost();

    if (host == null) {
        try {
            host = uri.toURL().getHost();
        } catch (final MalformedURLException e) {
            // ignore
        }
    }

    return host;
}

From source file:edu.ku.brc.specify.config.init.secwiz.DatabasePanel.java

/**
 * @param bgColor/* ww w  .j a v  a2s  . c o m*/
 * @param htmlFileName
 * @return
 */
public static JComponent createHelpPanel(final Color bgColor, final String htmlFileName) {
    Locale currLocale = Locale.getDefault();

    String helpMasterPath = (new File(".")).getAbsolutePath() + File.separator + "../" + "help/securitywiz/"
            + htmlFileName;
    String fullHelpMasterPath = UIHelper.createLocaleName(currLocale, helpMasterPath, "html");

    JEditorPane htmlPane = null;
    try {
        File file = new File(fullHelpMasterPath);
        if (!file.exists()) // for testing
        {
            helpMasterPath = (new File(".")).getAbsolutePath() + File.separator + "help/securitywiz/"
                    + htmlFileName;
            fullHelpMasterPath = UIHelper.createLocaleName(currLocale, helpMasterPath, "html");
            file = new File(fullHelpMasterPath);
            System.out.println(file.getCanonicalPath());
        }
        URI url = file.toURI();

        htmlPane = new JEditorPane(url.toURL()); //$NON-NLS-1$
        htmlPane.setEditable(false);
        htmlPane.setBackground(bgColor);

    } catch (IOException ex) {
        File file = new File(fullHelpMasterPath);
        String htmlDesc = "";
        try {
            htmlDesc = "Error loading help: " + file.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        htmlPane = new JEditorPane("text/plain", htmlDesc); //$NON-NLS-1$
    }

    JScrollPane scrollPane = UIHelper.createScrollPane(htmlPane, true);
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    scrollPane.getViewport().setPreferredSize(new Dimension(400, 400));

    return scrollPane;
}

From source file:eu.asterics.mw.services.ResourceRegistry.java

/**
 * Checks whether the given URI is a URL or not.
 * @param uriToCheck true: URI is a URL, false: URI is not a URL but probably a file (relative or absolute)
 * @return/*  w ww. j a va  2 s . c  o  m*/
 */
public static boolean isURL(URI uriToCheck) {
    try {
        uriToCheck.toURL();
        return true;
    } catch (MalformedURLException e) {
        return false;
    }
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpLoader.java

public static synchronized void loadPolicy(Properties properties, StdPDPStatus status, String id,
        boolean isRoot) throws PAPException {
    PolicyDef policy = null;//from   www.  j  a  v a  2  s .c o m
    String location = null;
    URI locationURI = null;
    boolean isFile = false;
    try {
        location = properties.getProperty(id + ".file");
        if (location == null) {
            location = properties.getProperty(id + ".url");
            if (location != null) {
                //
                // Construct the URL
                //
                locationURI = URI.create(location);
                URL url = locationURI.toURL();
                URLConnection urlConnection = url.openConnection();
                urlConnection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID,
                        XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID));
                //
                // Now construct the output file name
                //
                Path outFile = Paths.get(getPDPConfig().toAbsolutePath().toString(), id);
                //
                // Copy it to disk
                //
                try (FileOutputStream fos = new FileOutputStream(outFile.toFile())) {
                    IOUtils.copy(urlConnection.getInputStream(), fos);
                }
                //
                // Now try to load
                //
                isFile = true;
                try (InputStream fis = Files.newInputStream(outFile)) {
                    policy = DOMPolicyDef.load(fis);
                }
                //
                // Save it
                //
                properties.setProperty(id + ".file", outFile.toAbsolutePath().toString());
            }
        } else {
            isFile = true;
            locationURI = Paths.get(location).toUri();
            try (InputStream is = Files.newInputStream(Paths.get(location))) {
                policy = DOMPolicyDef.load(is);
            }
        }
        if (policy != null) {
            status.addLoadedPolicy(new StdPDPPolicy(id, isRoot, locationURI, properties));
            logger.info("Loaded policy: " + policy.getIdentifier() + " version: "
                    + policy.getVersion().stringValue());
        } else {
            String error = "Failed to load policy " + location;
            logger.error(error);
            status.setStatus(PDPStatus.Status.LOAD_ERRORS);
            status.addLoadError(error);
            status.addFailedPolicy(new StdPDPPolicy(id, isRoot));
        }
    } catch (Exception e) {
        logger.error("Failed to load policy '" + id + "' from location '" + location + "'", e);
        status.setStatus(PDPStatus.Status.LOAD_ERRORS);
        status.addFailedPolicy(new StdPDPPolicy(id, isRoot));
        //
        // Is it a file?
        //
        if (isFile) {
            //
            // Let's remove it
            //
            try {
                logger.error("Corrupted policy file, deleting: " + location);
                Files.delete(Paths.get(location));
            } catch (IOException e1) {
                logger.error(e1);
            }
        }
        throw new PAPException("Failed to load policy '" + id + "' from location '" + location + "'");
    }
}