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.LexGrid.LexBIG.admin.LoadManifest.java

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 {//from  w w w .j av  a2 s.  c  o  m

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

From source file:org.lenskit.data.dao.file.TextEntitySource.java

/**
 * Create a file reader./* w  w w  .  ja va 2 s .com*/
 * @param name The reader name.
 * @param object The configuring object.
 * @param base The base URI for source data.
 * @return The new entity reader.
 */
static TextEntitySource fromJSON(String name, JsonNode object, URI base, ClassLoader loader) {
    TextEntitySource source = new TextEntitySource(name);
    URI uri = base.resolve(object.get("file").asText());
    try {
        source.setURI(uri.toURL());
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Cannot resolve URI " + uri, e);
    }
    logger.info("loading text file source {} to read from {}", name, source.getURL());

    String fmt = object.path("format").asText("delimited").toLowerCase();
    String delim;
    switch (fmt) {
    case "csv":
        delim = ",";
        break;
    case "tsv":
    case "delimited":
        delim = "\t";
        break;
    default:
        throw new IllegalArgumentException("unsupported data format " + fmt);
    }
    JsonNode delimNode = object.path("delimiter");
    if (delimNode.isValueNode()) {
        delim = delimNode.asText();
    }

    DelimitedColumnEntityFormat format = new DelimitedColumnEntityFormat();
    format.setDelimiter(delim);
    logger.debug("{}: using delimiter {}", name, delim);
    JsonNode header = object.path("header");
    boolean canUseColumnMap = false;
    if (header.isBoolean() && header.asBoolean()) {
        logger.debug("{}: reading header", name);
        format.setHeader(true);
        canUseColumnMap = true;
    } else if (header.isNumber()) {
        format.setHeaderLines(header.asInt());
        logger.debug("{}: skipping {} header lines", format.getHeaderLines());
    }

    String eTypeName = object.path("entity_type").asText("rating").toLowerCase();
    EntityType etype = EntityType.forName(eTypeName);
    logger.debug("{}: reading entities of type {}", name, etype);
    EntityDefaults entityDefaults = EntityDefaults.lookup(etype);
    format.setEntityType(etype);
    format.setEntityBuilder(
            entityDefaults != null ? entityDefaults.getDefaultBuilder() : BasicEntityBuilder.class);

    JsonNode columns = object.path("columns");
    if (columns.isMissingNode() || columns.isNull()) {
        List<TypedName<?>> defColumns = entityDefaults != null ? entityDefaults.getDefaultColumns() : null;
        if (defColumns == null) {
            throw new IllegalArgumentException("no columns specified and no default columns available");
        }

        for (TypedName<?> attr : entityDefaults.getDefaultColumns()) {
            format.addColumn(attr);
        }
    } else if (columns.isObject()) {
        if (!canUseColumnMap) {
            throw new IllegalArgumentException("cannot use column map without file header");
        }
        Iterator<Map.Entry<String, JsonNode>> colIter = columns.fields();
        while (colIter.hasNext()) {
            Map.Entry<String, JsonNode> col = colIter.next();
            format.addColumn(col.getKey(), parseAttribute(entityDefaults, col.getValue()));
        }
    } else if (columns.isArray()) {
        for (JsonNode col : columns) {
            format.addColumn(parseAttribute(entityDefaults, col));
        }
    } else {
        throw new IllegalArgumentException("invalid format for columns");
    }

    JsonNode ebNode = object.path("builder");
    if (ebNode.isTextual()) {
        String ebName = ebNode.asText();
        if (ebName.equals("basic")) {
            format.setEntityBuilder(BasicEntityBuilder.class);
        } else {
            Class bld;
            try {
                bld = ClassUtils.getClass(loader, ebName);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("cannot load class " + ebName, e);
            }
            format.setEntityBuilder(bld);
        }
    }
    logger.debug("{}: using entity builder {}", format.getEntityBuilder());

    source.setFormat(format);
    return source;
}

From source file:com.igormaznitsa.sciareto.ui.UiUtils.java

public static boolean browseURI(@Nonnull final URI uri, final boolean preferInsideBrowserIfPossible) {
    try {/*w ww  .ja  v a2 s  . c  om*/
        if (preferInsideBrowserIfPossible) {
            showURL(uri.toURL());
        } else {
            showURLExternal(uri.toURL());
        }
        return true;
    } catch (MalformedURLException ex) {
        LOGGER.error("MalformedURLException", ex); //NOI18N
        return false;
    }
}

From source file:org.easyrec.utils.Web.java

/**
 * This function returns a processed HTML Page from a given XML
 * transformed with an XSL./* w  ww.  j  a v  a  2s.  c  o m*/
 *
 * @param xmlUrl String
 * @param xslUrl String
 * @return String
 * @throws Exception Exception
 */
@SuppressWarnings({ "UnusedDeclaration" })
public static String transformXML(String xmlUrl, String xslUrl) throws Exception {

    String sHTML;

    try {

        TransformerFactory factory = TransformerFactory.newInstance();

        Templates sourceTemplate = factory.newTemplates(new StreamSource(xslUrl));

        Transformer sourceTransformer = sourceTemplate.newTransformer();

        URI uri = new URI("http", xmlUrl.replace("http:", ""), null);

        Source source = new StreamSource(uri.toURL().toString());

        StringWriter writer = new StringWriter();
        Result localResult = new StreamResult(writer);

        sourceTransformer.transform(source, localResult);
        sHTML = writer.toString();

    } catch (Exception e) {
        throw new Exception();
    }
    return sHTML;
}

From source file:net.ageto.gyrex.impex.console.internal.ImpexConsoleCommands.java

/**
 * Reads properties from file//  w w  w.ja  v  a2  s . co m
 *
 * @param configSourcePath
 * @param context 
 * @return
 */
public static boolean initPropertiesFile(String configSourcePath, IRuntimeContext context) {

    String propertiesFilename = FilenameUtils.concat(configSourcePath, DEFAULT_PROPERY_FILENAME);

    File propertiesFile = new File(propertiesFilename);

    if (!propertiesFile.exists()) {
        System.err.println(propertiesFilename + " file does not exist. Aborting");
        return false;
    }

    URI propertiesUri = propertiesFile.toURI();
    URL propertiesUrl;

    try {
        propertiesUrl = propertiesUri.toURL();
    } catch (MalformedURLException e) {
        System.err.println("File could not be read." + e);
        return false;
    }

    ConfigureRepositoryPreferences.readRepositoryPreferences(propertiesUrl, CASSANDRA_REPOSITORY_ID, context);

    System.out.println(propertiesFilename + " file processed successfully.");

    return true;
}

From source file:eu.planets_project.tb.impl.services.ServiceRegistryManager.java

/**
 * Takes a given http URI and extracts the page's content which is returned as String
 * @param uri/*from  w ww  .  j  ava2  s.  c  o  m*/
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
@Deprecated
private static String readUrlContents(URI uri) throws FileNotFoundException, IOException {

    InputStream in = null;
    try {
        if (!uri.getScheme().equals("http")) {
            throw new FileNotFoundException("URI schema " + uri.getScheme() + " not supported");
        }
        in = uri.toURL().openStream();
        boolean eof = false;
        String content = "";
        StringBuffer sb = new StringBuffer();
        while (!eof) {
            int byteValue = in.read();
            if (byteValue != -1) {
                char b = (char) byteValue;
                sb.append(b);
            } else {
                eof = true;
            }
        }
        content = sb.toString();
        if (content != null) {
            //now return the services WSDL content
            return content;
        } else {
            throw new FileNotFoundException("extracted content is null");
        }
    } finally {
        in.close();
    }
}

From source file:edu.kit.dama.rest.util.RestClientUtils.java

/**
 * Encode a string to be URL conform./*from   www  .j a v  a  2s. c o m*/
 *
 * @param argument string to be encoded
 *
 * @return url encoded string
 */
private static String encode(String argument) {
    String returnValue = null;
    try {
        URI uri = new URI("http", "my.site.com", "/" + argument, null);
        returnValue = uri.toURL().getPath().substring(1);
    } catch (URISyntaxException | MalformedURLException ex) {
        LOGGER.error("Failed to encode string " + argument, ex);
    }
    return returnValue;
}

From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java

private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken)
        throws URISyntaxException, UnsupportedEncodingException {
    String host = msgRequest.getTargetHost();
    if (host == null)
        throw new URISyntaxException(host, "null URI");
    if (!host.endsWith("/"))
        host += '/';
    String address = msgRequest.getTargetAddress();
    if (address == null)
        address = "";
    if (address.startsWith("/"))
        address = address.substring(1);/* ww w .  j a v a  2s.c  om*/
    String uriString = host + address;
    try {
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (MalformedURLException e) {
        throw new URISyntaxException(uriString, e.getMessage());
    }
    if (msgRequest.getQuery() != null)
        uriString += "?" + msgRequest.getQuery();

    //      new URI(uriString);

    HttpRequestBase request = null;
    if (msgRequest.getMethod().equals(Method.POST)) {
        HttpPost post = new HttpPost(uriString);
        HttpEntity httpEntity = null;
        if (msgRequest.getRequestParams() != null) {
            // if body and requestparams are either not null there is an
            // exception
            if (msgRequest.getBody() != null && msgRequest != null) {
                throw new IllegalArgumentException("body and requestParams cannot be either populated");
            }
            httpEntity = new MultipartEntity();

            for (RequestParam param : msgRequest.getRequestParams()) {
                if (param.getParamName() == null || param.getParamName().trim().length() == 0) {
                    throw new IllegalArgumentException("paramName cannot be null or empty");
                }
                if (param instanceof FileRequestParam) {
                    FileRequestParam fileparam = (FileRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody(
                            fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename()));
                }
                if (param instanceof ObjectRequestParam) {
                    ObjectRequestParam objectparam = (ObjectRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(),
                            new StringBody(convertObject(objectparam.getVars())));
                }
            }
            // mpe.addPart("file",
            // new ByteArrayBody(msgRequest.getFileContent(), ""));
            // post.setEntity(mpe);
        }
        if (msgRequest.getBody() != null) {
            httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            ((StringEntity) httpEntity).setContentType(msgRequest.getContentType());
        }
        post.setEntity(httpEntity);
        request = post;
    } else if (msgRequest.getMethod().equals(Method.PUT)) {
        HttpPut put = new HttpPut(uriString);
        if (msgRequest.getBody() != null) {
            StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            se.setContentType(msgRequest.getContentType());
            put.setEntity(se);
        }
        request = put;
    } else if (msgRequest.getMethod().equals(Method.DELETE)) {
        request = new HttpDelete(uriString);
    } else {
        // default: GET
        request = new HttpGet(uriString);
    }

    Map<String, String> headers = new HashMap<String, String>();

    // default headers
    if (appToken != null) {
        headers.put(RequestHeader.APP_TOKEN.toString(), appToken);
    }
    if (authToken != null) {
        // is here for compatibility
        headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken);
        headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken);
    }
    headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType());

    if (msgRequest.getCustomHeaders() != null) {
        headers.putAll(msgRequest.getCustomHeaders());
    }

    for (String key : headers.keySet()) {
        request.addHeader(key, headers.get(key));
    }

    return request;
}

From source file:com.dmsl.anyplace.utils.NetworkUtils.java

public static String encodeURL(String urlStr) throws URISyntaxException, MalformedURLException {
    URL url = new URL(urlStr);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());
    url = uri.toURL();
    return url.toString();
}

From source file:org.easyrec.util.core.Web.java

/**
 * This function returns a processed HTML Page from a given XML
 * transformed with an XSL./*w ww . j  a v  a  2 s  .  c  o  m*/
 *
 * @param xmlUrl String
 * @param xslUrl String
 * @return String
 * @throws Exception Exception
 */
@SuppressWarnings({ "UnusedDeclaration" })
public static String transformXML(String xmlUrl, String xslUrl) throws Exception {

    String sHTML;

    try {

        TransformerFactory factory = TransformerFactory.newInstance();

        Templates sourceTemplate = factory.newTemplates(new StreamSource(xslUrl));

        Transformer sourceTransformer = sourceTemplate.newTransformer();

        URI uri = new URI("http", xmlUrl.replace("http:", ""), null);

        Source source = new StreamSource(uri.toURL().toString());

        StringWriter writer = new StringWriter();
        Result localResult = new StreamResult(writer);

        sourceTransformer.transform(source, localResult);
        sHTML = writer.toString();

    } catch (Exception e) {
        logger.warn("An error occurred!", e);
        throw new Exception();
    }
    return sHTML;
}