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:com.aptana.editor.css.validator.CSSValidator.java

/**
 * Gets the validation report from the validator.
 * //from  w w w .  j  a v  a 2  s.  c om
 * @param source
 *            the source text
 * @param path
 *            the source path
 * @return the report
 */
private static String getReport(String source, URI path) {
    StyleSheetParser parser = new StyleSheetParser();
    ApplContext ac = new ApplContext("en"); //$NON-NLS-1$
    ac.setProfile(APTANA_PROFILE);
    try {
        parser.parseStyleElement(ac, new ByteArrayInputStream(source.getBytes(IOUtil.UTF_8)), null, null,
                path.toURL(), 0);
    } catch (MalformedURLException e) {
        IdeLog.logError(CSSPlugin.getDefault(),
                MessageFormat.format(Messages.CSSValidator_ERR_InvalidPath, path), e);
    } catch (UnsupportedEncodingException e) {
        IdeLog.logError(CSSPlugin.getDefault(), e);
    }

    StyleSheet stylesheet = parser.getStyleSheet();
    stylesheet.findConflicts(ac);
    StyleReport report = StyleReportFactory.getStyleReport(ac, "Title", stylesheet, "soap12", 2); //$NON-NLS-1$ //$NON-NLS-2$
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    report.print(new PrintWriter(out));
    return out.toString().replaceAll("m:", ""); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:com.aptana.css.core.internal.build.CSSValidator.java

/**
 * Gets the validation report from the validator.
 * /*  ww  w .  ja va2s . c  om*/
 * @param source
 *            the source text
 * @param path
 *            the source path
 * @return the report
 */
private static String getReport(String source, URI path) {
    StyleSheetParser parser = new StyleSheetParser();
    ApplContext ac = new ApplContext("en"); //$NON-NLS-1$
    ac.setProfile(APTANA_PROFILE);
    try {
        parser.parseStyleElement(ac, new ByteArrayInputStream(source.getBytes(IOUtil.UTF_8)), null, null,
                path.toURL(), 0);
    } catch (MalformedURLException e) {
        IdeLog.logError(CSSCorePlugin.getDefault(),
                MessageFormat.format(Messages.CSSValidator_ERR_InvalidPath, path), e);
    } catch (UnsupportedEncodingException e) {
        IdeLog.logError(CSSCorePlugin.getDefault(), e);
    }

    StyleSheet stylesheet = parser.getStyleSheet();
    stylesheet.findConflicts(ac);
    StyleReport report = StyleReportFactory.getStyleReport(ac, "Title", stylesheet, "soap12", 2); //$NON-NLS-1$ //$NON-NLS-2$
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    report.print(new PrintWriter(out));
    return out.toString().replaceAll("m:", ""); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:com.aol.advertising.qiao.util.CommonUtils.java

/**
 * Extends scheme to include 'classpath'.
 *
 * @param uriString/*from w w w. j  a va2 s.  com*/
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
public static URL uriToURL(String uriString) throws URISyntaxException, IOException {
    URI uri = new URI(uriString);
    String scheme = uri.getScheme();
    if (scheme == null)
        throw new URISyntaxException(uriString, "Invalid URI syntax: missing scheme => " + uriString);

    if (scheme.equals("classpath")) {
        ClassPathResource res = new ClassPathResource(uri.getSchemeSpecificPart());
        return res.getURL();
    } else {
        return uri.toURL();
    }
}

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

private static boolean verifyTableExists(URI tableURI) {
    // if its a file, check if it exists
    if (tableURI.getScheme().equals("file")) {
        return new File(tableURI).exists();
    }/*from   w w w .  j  a va 2 s . c  o  m*/
    // otherwise, just try to connect..
    // TODO: find a better way to check this instead of catching an
    // exception.
    else {
        try {
            tableURI.toURL().openConnection();
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}

From source file:sce.RESTAppMetricJob.java

public static URL convertToURLEscapingIllegalCharacters(String string) {
    try {/*from   ww  w . ja v a2  s . co  m*/
        String decodedURL = URLDecoder.decode(string, "UTF-8");
        URL url = new URL(decodedURL);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return uri.toURL();
    } catch (MalformedURLException | URISyntaxException | UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:fr.free.movierenamer.utils.URIRequest.java

private static URLConnection openConnection(URI uri, RequestProperty... properties) throws IOException {
    boolean isHttpRequest = Proxy.Type.HTTP.name().equalsIgnoreCase(uri.getScheme());
    URLConnection connection;/*from   w  w  w . j a  va  2s. c o  m*/
    if (isHttpRequest && Settings.getInstance().isProxyIsOn()) {
        Settings settings = Settings.getInstance();
        Proxy proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(settings.getProxyUrl(), settings.getProxyPort()));
        connection = uri.toURL().openConnection(proxy);
    } else {
        connection = uri.toURL().openConnection();
    }

    if (isHttpRequest) {
        Settings settings = Settings.getInstance();
        connection.setReadTimeout(settings.getHttpRequestTimeOut() * 1000); // in ms
        //fake user agent ;)
        connection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
        connection.addRequestProperty("From", "googlebot(at)googlebot.com");
        connection.addRequestProperty("Accept", "*/*");
        String customUserAgent = settings.getHttpCustomUserAgent();
        if (customUserAgent != null && customUserAgent.length() > 0) {
            connection.addRequestProperty("User-Agent", customUserAgent);
        }
    }

    connection.addRequestProperty("Accept-Encoding", "gzip,deflate");
    connection.addRequestProperty("Accept-Charset", UTF + "," + ISO); // important for accents !

    if (properties != null) {
        for (RequestProperty property : properties) {
            connection.addRequestProperty(property.getKey(), property.getValue());
        }
    }

    return connection;
}

From source file:com.marklogic.xcc.ContentFactory.java

/**
 * Create a new {@link Content} object from a URI, buffering so that it's rewindable and only
 * accesses the URL one time.//from   w ww.  jav a 2s.  c o m
 * 
 * @param uri
 *            The URI (name) with which the document will be inserted into the content store. If
 *            the URI already exists in the store, it will be replaced with the new content.
 * @param documentUri
 *            A {@link URI} object that represents the location from which the content can be
 *            fetched. Unlike {@link URL}s, {@link URI} objects are not validated when they are
 *            created. This method converts the {@link URI} to a {@link URL}. If this parameter
 *            does not represent a valid URL, an exception will be thrown.
 * @param createOptions
 *            Creation meta-information to be applied when the content is inserted into the
 *            contentbase. These options control the document format (json, xml, text, binary) and
 *            access permissions.
 * @return A {@link Content} object suitable for passing to
 *         {@link Session#insertContent(Content)}
 * @throws IOException
 *             If there is a problem creating a {@link URL} or reading the data from the stream.
 * @throws IllegalArgumentException
 *             If the URI is not absolute.
 */
public static Content newContent(String uri, URI documentUri, ContentCreateOptions createOptions)
        throws IOException {
    return newContent(uri, documentUri.toURL(), createOptions);
}

From source file:com.marklogic.xcc.ContentFactory.java

/**
 * Create a new, non-rewindable {@link Content} object from a {@link URI}.
 * //from  ww w.j a  va2 s.c  om
 * @param uri
 *            The {@link URI} (name) with which the document will be inserted into the content
 *            store. If the URI already exists in the store, it will be replaced with the new
 *            content.
 * @param documentUri
 *            A URI object that represents the location from which the content can be fetched.
 * @param createOptions
 *            Creation meta-information to be applied when the content is inserted into the
 *            contentbase. These options control the document format (json, xml, text, binary) and
 *            access permissions.
 * @return A {@link Content} object suitable for passing to
 *         {@link Session#insertContent(Content)}
 * @throws IOException
 *             If there is a problem creating a {@link URL} or opening a data stream.
 */
public static Content newUnBufferedContent(String uri, URI documentUri, ContentCreateOptions createOptions)
        throws IOException {
    return newUnBufferedContent(uri, documentUri.toURL(), createOptions);
}

From source file:Main.java

/** Obtiene el flujo de entrada de un fichero (para su lectura) a partir de su URI.
 * @param uri URI del fichero a leer//from   w  w w  .j a va  2  s. com
 * @return Flujo de entrada hacia el contenido del fichero
 * @throws IOException Cuando no se ha podido abrir el fichero de datos. */
public static InputStream loadFile(final URI uri) throws IOException {

    if (uri == null) {
        throw new IllegalArgumentException("Se ha pedido el contenido de una URI nula"); //$NON-NLS-1$
    }

    if (uri.getScheme().equals("file")) { //$NON-NLS-1$
        // Es un fichero en disco. Las URL de Java no soportan file://, con
        // lo que hay que diferenciarlo a mano

        // Retiramos el "file://" de la uri
        String path = uri.getSchemeSpecificPart();
        if (path.startsWith("//")) { //$NON-NLS-1$
            path = path.substring(2);
        }
        return new FileInputStream(new File(path));
    }

    // Es una URL
    final InputStream tmpStream = new BufferedInputStream(uri.toURL().openStream());

    // Las firmas via URL fallan en la descarga por temas de Sun, asi que
    // descargamos primero
    // y devolvemos un Stream contra un array de bytes
    final byte[] tmpBuffer = getDataFromInputStream(tmpStream);

    return new java.io.ByteArrayInputStream(tmpBuffer);
}

From source file:org.audiveris.omr.log.LogUtil.java

/**
 * Check for (BackLog) logging configuration, and if not found,
 * define a minimal configuration.//from w  w  w  . j a  va  2 s  . co  m
 * This method should be called at the very beginning of the program before
 * any logging request is sent.
 *
 * @param CONFIG_FOLDER Config folder which may contain a logback.xml file
 * @param RES_URI       uri to 'res' folder (within .jar or development hierarchy)
 */
public static void initialize(Path CONFIG_FOLDER, URI RES_URI) {
    // 1/ Check if system property is set and points to a real file
    final String loggingProp = System.getProperty(LOGBACK_LOGGING_KEY);

    if (loggingProp != null) {
        Path configPath = Paths.get(loggingProp).toAbsolutePath();

        if (Files.exists(configPath)) {
            // Everything seems OK, let LogBack use the config file
            initMessage("LogUtil. Configuration found " + configPath);

            return;
        } else {
            initMessage("LogUtil. File " + configPath + " does not exist.");
        }
    } else {
        initMessage("LogUtil. Property " + LOGBACK_LOGGING_KEY + " not defined, skipped.");
    }

    // 2/ Look for well-known location (user Audiveris config folder)
    Path configPath = CONFIG_FOLDER.resolve(LOGBACK_FILE_NAME).toAbsolutePath();

    if (Files.exists(configPath)) {
        initMessage("LogUtil. Configuration found " + configPath);
        System.setProperty(LOGBACK_LOGGING_KEY, configPath.toString());

        return;
    } else {
        initMessage("LogUtil. No " + configPath + ", skipped.");
    }

    // 3/ Look for suitable file within 'res' folder or resource
    try {
        final URI configUri = UriUtil.toURI(RES_URI, LOGBACK_FILE_NAME);
        final Path localPath;

        if (configUri.toString().startsWith("jar:")) {
            // Make a temporary copy off .jar archive
            File tmpFile = File.createTempFile("logback-", ".xml");
            tmpFile.deleteOnExit();

            try (InputStream is = configUri.toURL().openStream()) {
                FileUtils.copyInputStreamToFile(is, tmpFile);
            }

            localPath = tmpFile.toPath();
        } else {
            localPath = Paths.get(configUri);
        }

        if (Files.exists(localPath)) {
            initMessage("LogUtil. Configuration found " + configUri);
            System.setProperty(LOGBACK_LOGGING_KEY, localPath.toString());

            return;
        } else {
            initMessage("LogUtil. No " + localPath + ", skipped.");
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    // 4/ We need a default configuration
    initMessage("LogUtil. Building a minimal Logging configuration");

    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

    // CONSOLE
    ConsoleAppender consoleAppender = new ConsoleAppender();
    PatternLayoutEncoder consoleEncoder = new PatternLayoutEncoder();
    consoleAppender.setName("CONSOLE");
    consoleAppender.setContext(loggerContext);
    consoleEncoder.setContext(loggerContext);
    consoleEncoder.setPattern("%-5level %caller{1} [%X{BOOK}%X{SHEET}] %msg%n%ex");
    consoleEncoder.start();
    consoleAppender.setEncoder(consoleEncoder);
    consoleAppender.start();
    root.addAppender(consoleAppender);

    // Levels
    root.setLevel(Level.INFO);

    // OPTIONAL: print logback internal status messages
    StatusPrinter.print(loggerContext);
}