Java Code Examples for java.net.URLConnection#getContentType()

The following examples show how to use java.net.URLConnection#getContentType() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: java-swing-tips   File: MainPanel.java    License: MIT License 6 votes vote down vote up
private static Charset getCharset(URLConnection urlConnection) {
  Charset cs = StandardCharsets.UTF_8;
  String encoding = urlConnection.getContentEncoding();
  if (Objects.nonNull(encoding)) {
    cs = Charset.forName(encoding);
  } else {
    String contentType = urlConnection.getContentType();
    Stream.of(contentType.split(";"))
        .map(String::trim)
        .filter(s -> !s.isEmpty() && s.toLowerCase(Locale.ENGLISH).startsWith("charset="))
        .map(s -> s.substring("charset=".length()))
        .findFirst()
        .ifPresent(Charset::forName);
  }
  System.out.println(cs);
  return cs;
}
 
Example 2
/**
 * Initialise response
 * 
 * @param urlConnection  url connection
 */
protected void initialiseResponse(URLConnection urlConnection)
{
    String type = urlConnection.getContentType();
    if (type != null)
    {
        int encodingIdx = type.lastIndexOf("charset=");
        if (encodingIdx == -1)
        {
            String encoding = urlConnection.getContentEncoding();
            if (encoding != null && encoding.length() > 0)
            {
                type += ";charset=" + encoding;
            }
        }
        
        response.setContentType(type);
    }
}
 
Example 3
public static String getCharset(URLConnection connection) {
  String contentType = connection == null ? null : connection.getContentType();
  if (contentType != null) {
    StringTokenizer tok = new StringTokenizer(contentType, ";");
    if (tok.hasMoreTokens()) {
      tok.nextToken();
      while (tok.hasMoreTokens()) {
        String assignment = tok.nextToken().trim();
        int eqIdx = assignment.indexOf('=');
        if (eqIdx != -1) {
          String varName = assignment.substring(0, eqIdx).trim();
          if ("charset".equalsIgnoreCase(varName)) {
            String varValue = assignment.substring(eqIdx + 1);
            return unquote(varValue.trim());
          }
        }
      }
    }
  }
  return null;
}
 
Example 4
Source Project: ontopia   File: RemoteTopicIndex.java    License: Apache License 2.0 6 votes vote down vote up
protected InputSource getInputSource(String method, String params,
                                     boolean compress)
  throws IOException {
  
  String baseuri = viewBaseuri == null ? editBaseuri : viewBaseuri;
  String url = baseuri + method + "?" + params;
  URLConnection conn = this.getConnection(url, 0);
  InputSource src = new InputSource(url);

  if (!compress) {
    src.setByteStream(conn.getInputStream());
  
    String ctype = conn.getContentType();
    if (ctype != null && ctype.startsWith("text/xml")) {
      int pos = ctype.indexOf("charset=");
      if (pos != -1) src.setEncoding(ctype.substring(pos + 8));
    }
  } else
    src.setByteStream(new java.util.zip.GZIPInputStream(conn.getInputStream()));
  
  return src;
}
 
Example 5
private static String getCharacterEncoding(URLConnection urlConnection) {
    final ParsedContentType pct = new ParsedContentType(
            urlConnection.getContentType());
    final String encoding = pct.getEncoding();
    if(encoding != null) {
        return encoding;
    }
    final String contentType = pct.getContentType();
    if(contentType != null && contentType.startsWith("text/")) {
        return "8859_1";
    }
    else {
        return "utf-8";
    }
}
 
Example 6
public UrlWebResource(final URL url, final String path, final String contentType, final boolean cacheable) {
  this.url = checkNotNull(url);
  this.path = checkNotNull(path);
  this.cacheable = cacheable;

  // open connection to get details about the resource
  try {
    final URLConnection connection = this.url.openConnection();
    try (final InputStream ignore = connection.getInputStream()) {
      if (Strings.isNullOrEmpty(contentType)) {
        this.contentType = connection.getContentType();
      }
      else {
        this.contentType = contentType;
      }

      // support for legacy int and modern long content-length
      long detectedSize = connection.getContentLengthLong();
      if (detectedSize == -1) {
        detectedSize = connection.getContentLength();
      }
      this.size = detectedSize;

      this.lastModified = connection.getLastModified();
    }
  }
  catch (IOException e) {
    throw new IllegalArgumentException("Resource inaccessible: " + url, e);
  }
}
 
Example 7
Source Project: nyzoVerifier   File: RelayEndpoint.java    License: The Unlicense 5 votes vote down vote up
public void refresh() {
    // Only refresh web endpoints that are out of date.
    if (!isFileEndpoint && lastRefreshTimestamp < System.currentTimeMillis() - interval) {
        LogUtil.println("refreshing endpoint: " + sourceEndpoint);
        try {
            URLConnection connection = new URL(sourceEndpoint).openConnection();
            connection.setConnectTimeout(2000);  // 2 seconds
            connection.setReadTimeout(10000);    // 10 seconds
            if (connection.getContentLength() <= maximumSize) {
                byte[] result = new byte[connection.getContentLength()];
                ByteBuffer buffer = ByteBuffer.wrap(result);
                ReadableByteChannel channel = Channels.newChannel(connection.getInputStream());
                int bytesRead;
                int totalBytesRead = 0;
                while ((bytesRead = channel.read(buffer)) > 0) {
                    totalBytesRead += bytesRead;
                }
                channel.close();

                // Build the response and set the last-modified header.
                long refreshTimestamp = System.currentTimeMillis();
                cachedWebResponse = new EndpointResponse(result, connection.getContentType());
                cachedWebResponse.setHeader("Last-Modified", WebUtil.imfFixdateString(refreshTimestamp));
                cachedWebResponse.setHeader("Access-Control-Allow-Origin", "*");

                // Set the refresh timestamp.
                lastRefreshTimestamp = refreshTimestamp;
            }
        } catch (Exception ignored) { }
    }
}
 
Example 8
private synchronized void load(URL url, URLConnection urlCon, IRI context, ParserConfig config)
		throws RepositoryException, RDFParseException, IOException {
	long modified = urlCon.getLastModified();
	if (lastModified.containsKey(url) && lastModified.get(url) >= modified) {
		return;
	}

	// Try to determine the data's MIME type
	String mimeType = urlCon.getContentType();
	int semiColonIdx = mimeType.indexOf(';');
	if (semiColonIdx >= 0) {
		mimeType = mimeType.substring(0, semiColonIdx);
	}
	RDFFormat format = Rio.getParserFormatForMIMEType(mimeType)
			.orElse(Rio.getParserFormatForFileName(url.getPath()).orElseThrow(Rio.unsupportedFormat(mimeType)));

	try (InputStream stream = urlCon.getInputStream()) {
		try (RepositoryConnection repCon = super.getConnection()) {

			repCon.setParserConfig(config);
			repCon.begin();
			repCon.clear(context);
			repCon.add(stream, url.toExternalForm(), format, context);
			repCon.commit();
			lastModified.put(url, modified);
		}
	}
}
 
Example 9
Source Project: netbeans   File: NbClassLoaderTest.java    License: Apache License 2.0 5 votes vote down vote up
public User() throws Exception {
    URLClassLoader ncl = (URLClassLoader)getClass().getClassLoader();
    URL[] urls = ncl.getURLs();
    if (urls.length != 1) throw new IllegalStateException("Weird URLs: " + Arrays.asList(urls));
    URL manual = new URL(urls[0], "org/openide/execution/data/foo.xml");
    URLConnection uc = manual.openConnection();
    uc.connect();
    String ct = uc.getContentType();
    /* May now be a file: URL, in which case content type is hard to control:
    if (!"text/xml".equals(ct)) throw new IllegalStateException("Wrong content type (manual): " + ct);
     */
    URL auto = getClass().getResource("data/foo.xml");
    if (auto == null) throw new IllegalStateException("Could not load data/foo.xml; try uncommenting se.printStackTrace() in MySecurityManager.checkPermission");
    uc = auto.openConnection();
    uc.connect();
    ct = uc.getContentType();
    /* Ditto:
    if (!"text/xml".equals(ct)) throw new IllegalStateException("Wrong content type (auto): " + ct);
     */
    // Ensure this class does *not* have free access to random permissions:
    try {
        System.getProperty("foo");
        throw new IllegalStateException("Was permitted to access sys prop foo");
    } catch (SecurityException se) {
        // good
    }
}
 
Example 10
Source Project: find   File: MapController.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("OverlyBroadCatchBlock")
@RequestMapping(value = PROXY_PATH, method = RequestMethod.GET)
@ResponseBody
public String getMapData(
        @RequestParam(URL_PARAM) final String url,
        @RequestParam(CALLBACK_PARAM) final String callback
) {
    if (!CALLBACK_FUNCTION_NAME_PATTERN.matcher(callback).matches()) {
        throw new IllegalArgumentException("Invalid callback function name");
    }

    try {
        final String tileUrlTemplate = configService.getConfig().getMap().getTileUrlTemplate();

        final URL targetURL = new URL(url);
        final URL validationURL = new URL(tileUrlTemplate);

        if (!validationURL.getProtocol().equals(targetURL.getProtocol()) || !validationURL.getHost().equals(targetURL.getHost()) || validationURL.getPort() != targetURL.getPort()) {
            throw new IllegalArgumentException("We only allow proxying to the tile server");
        }

        final URLConnection urlConnection = targetURL.openConnection();
        final String contentType = urlConnection.getContentType();
        return getMapData(callback, urlConnection, contentType);
    } catch (final IOException e) {
        log.error("Error retrieving map data", e);
        return callback + "(\"error:Application error\")";
    }
}
 
Example 11
@Override
public void init(MCRFile file) throws MCRPersistenceException {
    super.init(file);

    String prefix = "MCR.IFS.AVExtender." + file.getStoreID() + ".";

    baseMetadata = MCRConfiguration2.getStringOrThrow(prefix + "ViewSourceBaseURL");

    try {
        String data = getMetadata(baseMetadata + file.getStorageID());

        String sSize = getBetween("File Size:</strong>", "Bytes", data, "0");
        String sBitRate = getBetween("Bit Rate:</strong>", "Kbps", data, "0.0");
        String sFrameRate = getBetween("Frame Rate: </strong>", "fps", data, "0.0");
        String sDuration = getBetween("Duration:</strong>", "<br>", data, "0:0.0");
        String sType = getBetween("Stream:</strong>", "<br>", data, "");

        bitRate = Math.round(1024 * Float.valueOf(sBitRate));

        StringTokenizer st1 = new StringTokenizer(sFrameRate, " ,");

        while (st1.hasMoreTokens()) {
            double value = Double.valueOf(st1.nextToken());
            frameRate = Math.max(frameRate, value);
        }

        hasVideo = frameRate > 0;

        StringTokenizer st2 = new StringTokenizer(sDuration, ":.");
        durationMinutes = Integer.parseInt(st2.nextToken());
        durationSeconds = Integer.parseInt(st2.nextToken());

        if (Integer.parseInt(st2.nextToken()) > 499) {
            durationSeconds += 1;

            if (durationSeconds > 59) {
                durationMinutes += 1;
                durationSeconds = 0;
            }
        }

        StringTokenizer st3 = new StringTokenizer(sSize, ",");
        StringBuilder sb = new StringBuilder();

        while (st3.hasMoreTokens()) {
            sb.append(st3.nextToken());
        }

        size = Long.parseLong(sb.toString());

        durationHours = durationMinutes / 60;
        durationMinutes = durationMinutes - durationHours * 60;

        if (sType.contains("MPEG Layer 3")) {
            contentTypeID = "mp3";
            hasVideo = false;
        } else if (sType.contains("3GPP")) {
            contentTypeID = "3gp";
            hasVideo = true;
        } else if (sType.contains("MPEG4")) {
            contentTypeID = "mpeg4";
            hasVideo = true;
        } else if (sType.contains("MPEG")) {
            contentTypeID = "mpegvid";
            hasVideo = true;
        } else if (sType.contains("RealVideo")) {
            contentTypeID = "realvid";
        } else if (sType.contains("RealAudio")) {
            contentTypeID = "realaud";
        } else if (sType.contains("Wave File")) {
            contentTypeID = "wav";
            hasVideo = false;
        } else {
            // should be one of "wma" "wmv" "asf"
            contentTypeID = file.getContentTypeID();

            hasVideo = !contentTypeID.equals("wma");
        }

        if (" wma wmv asf asx ".contains(" " + contentTypeID + " ")) {
            basePlayerStarter = MCRConfiguration2.getStringOrThrow(prefix + "AsxGenBaseURL");
            playerDownloadURL = MCRConfiguration2.getStringOrThrow(prefix + "MediaPlayerURL");
        } else {
            basePlayerStarter = MCRConfiguration2.getStringOrThrow(prefix + "RamGenBaseURL");
            playerDownloadURL = MCRConfiguration2.getStringOrThrow(prefix + "RealPlayerURL");
        }

        URLConnection con = getConnection(basePlayerStarter + file.getStorageID());
        playerStarterCT = con.getContentType();
    } catch (Exception exc) {
        String msg = "Error parsing metadata from Real Server ViewSource: " + file.getStorageID();
        LOGGER.warn(msg, exc);
    }
}
 
Example 12
Source Project: jdk8u60   File: Resolver.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Query an external RFC2483 resolver.
 *
 * @param resolver The URL of the RFC2483 resolver.
 * @param command The command to send the resolver.
 * @param arg1 The first argument to the resolver.
 * @param arg2 The second argument to the resolver, usually null.
 *
 * @return The Resolver constructed.
 */
protected Resolver queryResolver(String resolver,
                                 String command,
                                 String arg1,
                                 String arg2) {
    InputStream iStream = null;
    String RFC2483 = resolver + "?command=" + command
        + "&format=tr9401&uri=" + arg1
        + "&uri2=" + arg2;
    String line = null;

    try {
        URL url = new URL(RFC2483);

        URLConnection urlCon = url.openConnection();

        urlCon.setUseCaches(false);

        Resolver r = (Resolver) newCatalog();

        String cType = urlCon.getContentType();

        // I don't care about the character set or subtype
        if (cType.indexOf(";") > 0) {
            cType = cType.substring(0, cType.indexOf(";"));
        }

        r.parseCatalog(cType, urlCon.getInputStream());

        return r;
    } catch (CatalogException cex) {
      if (cex.getExceptionType() == CatalogException.UNPARSEABLE) {
        catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483);
      } else if (cex.getExceptionType()
                 == CatalogException.UNKNOWN_FORMAT) {
        catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483);
      }
      return null;
    } catch (MalformedURLException mue) {
        catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483);
        return null;
    } catch (IOException ie) {
        catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483);
        return null;
    }
}
 
Example 13
Source Project: JDKSourceCode1.8   File: Resolver.java    License: MIT License 4 votes vote down vote up
/**
 * Query an external RFC2483 resolver.
 *
 * @param resolver The URL of the RFC2483 resolver.
 * @param command The command to send the resolver.
 * @param arg1 The first argument to the resolver.
 * @param arg2 The second argument to the resolver, usually null.
 *
 * @return The Resolver constructed.
 */
protected Resolver queryResolver(String resolver,
                                 String command,
                                 String arg1,
                                 String arg2) {
    InputStream iStream = null;
    String RFC2483 = resolver + "?command=" + command
        + "&format=tr9401&uri=" + arg1
        + "&uri2=" + arg2;
    String line = null;

    try {
        URL url = new URL(RFC2483);

        URLConnection urlCon = url.openConnection();

        urlCon.setUseCaches(false);

        Resolver r = (Resolver) newCatalog();

        String cType = urlCon.getContentType();

        // I don't care about the character set or subtype
        if (cType.indexOf(";") > 0) {
            cType = cType.substring(0, cType.indexOf(";"));
        }

        r.parseCatalog(cType, urlCon.getInputStream());

        return r;
    } catch (CatalogException cex) {
      if (cex.getExceptionType() == CatalogException.UNPARSEABLE) {
        catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483);
      } else if (cex.getExceptionType()
                 == CatalogException.UNKNOWN_FORMAT) {
        catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483);
      }
      return null;
    } catch (MalformedURLException mue) {
        catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483);
        return null;
    } catch (IOException ie) {
        catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483);
        return null;
    }
}
 
Example 14
private static String contentType(URL u) throws Exception {
    URLConnection conn = u.openConnection();
    return conn.getContentType();
}
 
Example 15
Source Project: sparkler   File: FetcherDefault.java    License: Apache License 2.0 4 votes vote down vote up
public FetchedData fetch(Resource resource) throws Exception {
    LOG.info("DEFAULT FETCHER {}", resource.getUrl());
    URLConnection urlConn = new URL(resource.getUrl()).openConnection();
    if (httpHeaders != null){
        httpHeaders.forEach(urlConn::setRequestProperty);
        LOG.debug("Adding headers:{}", httpHeaders.keySet());
    } else {
        LOG.debug("No headers are available");
    }
    String userAgentValue = getUserAgent();
    if (userAgentValue != null) {
        LOG.debug(USER_AGENT + ": " + userAgentValue);
        urlConn.setRequestProperty(USER_AGENT, userAgentValue);
    } else {
        LOG.debug("No rotating agents are available");
    }

    urlConn.setConnectTimeout(CONNECT_TIMEOUT);
    urlConn.setReadTimeout(READ_TIMEOUT);
    int responseCode = ((HttpURLConnection)urlConn).getResponseCode();
    LOG.debug("STATUS CODE : " + responseCode + " " + resource.getUrl());
    boolean truncated = false;
    try (InputStream inStream = urlConn.getInputStream()) {
        ByteArrayOutputStream bufferOutStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096]; // 4kb buffer
        int read;
        while((read = inStream.read(buffer, 0, buffer.length)) != -1) {
            bufferOutStream.write(buffer, 0, read);
            if (bufferOutStream.size() >= CONTENT_LIMIT) {
                truncated = true;
                LOG.info("Content Truncated: {}, TotalSize={}, TruncatedSize={}", resource.getUrl(),
                        urlConn.getContentLength(), bufferOutStream.size());
                break;
            }
        }
        bufferOutStream.flush();
        byte[] rawData = bufferOutStream.toByteArray();
        IOUtils.closeQuietly(bufferOutStream);
        FetchedData fetchedData = new FetchedData(rawData, urlConn.getContentType(), responseCode);
        resource.setStatus(ResourceStatus.FETCHED.toString());
        fetchedData.setResource(resource);
        fetchedData.setHeaders(urlConn.getHeaderFields());
        if (truncated) {
            fetchedData.getHeaders().put(TRUNCATED, Collections.singletonList(Boolean.TRUE.toString()));
        }
        return fetchedData;
    }
}
 
Example 16
@Override
protected Reader reader(ConfigParseOptions options) throws IOException {
    try {
        if (ConfigImpl.traceLoadsEnabled())
            trace("Loading config from a URL: " + input.toExternalForm());
        URLConnection connection = input.openConnection();

        // allow server to serve multiple types from one URL
        String acceptContent = acceptContentType(options);
        if (acceptContent != null) {
            connection.setRequestProperty("Accept", acceptContent);
        }

        connection.connect();

        // save content type for later
        contentType = connection.getContentType();
        if (contentType != null) {
            if (ConfigImpl.traceLoadsEnabled())
                trace("URL sets Content-Type: '" + contentType + "'");
            contentType = contentType.trim();
            int semi = contentType.indexOf(';');
            if (semi >= 0)
                contentType = contentType.substring(0, semi);
        }

        InputStream stream = connection.getInputStream();

        return readerFromStream(stream);
    } catch (FileNotFoundException fnf) {
        // If the resource is not found (HTTP response
        // code 404 or something alike), then it's fine to
        // treat it according to the allowMissing setting
        // and "include" spec.  But if we have something
        // like HTTP 503 it seems to be better to fail
        // early, because this may be a sign of broken
        // environment. Java throws FileNotFoundException
        // if it sees 404 or 410.
        throw fnf;
    } catch (IOException e) {
        throw new ConfigException.BugOrBroken("Cannot load config from URL: " + input.toExternalForm(), e);
    }
}
 
Example 17
/**
 * Query an external RFC2483 resolver.
 *
 * @param resolver The URL of the RFC2483 resolver.
 * @param command The command to send the resolver.
 * @param arg1 The first argument to the resolver.
 * @param arg2 The second argument to the resolver, usually null.
 *
 * @return The Resolver constructed.
 */
protected Resolver queryResolver(String resolver,
                                 String command,
                                 String arg1,
                                 String arg2) {
    InputStream iStream = null;
    String RFC2483 = resolver + "?command=" + command
        + "&format=tr9401&uri=" + arg1
        + "&uri2=" + arg2;
    String line = null;

    try {
        URL url = new URL(RFC2483);

        URLConnection urlCon = url.openConnection();

        urlCon.setUseCaches(false);

        Resolver r = (Resolver) newCatalog();

        String cType = urlCon.getContentType();

        // I don't care about the character set or subtype
        if (cType.indexOf(";") > 0) {
            cType = cType.substring(0, cType.indexOf(";"));
        }

        r.parseCatalog(cType, urlCon.getInputStream());

        return r;
    } catch (CatalogException cex) {
      if (cex.getExceptionType() == CatalogException.UNPARSEABLE) {
        catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483);
      } else if (cex.getExceptionType()
                 == CatalogException.UNKNOWN_FORMAT) {
        catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483);
      }
      return null;
    } catch (MalformedURLException mue) {
        catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483);
        return null;
    } catch (IOException ie) {
        catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483);
        return null;
    }
}
 
Example 18
/**
 * Query an external RFC2483 resolver.
 *
 * @param resolver The URL of the RFC2483 resolver.
 * @param command The command to send the resolver.
 * @param arg1 The first argument to the resolver.
 * @param arg2 The second argument to the resolver, usually null.
 *
 * @return The Resolver constructed.
 */
protected Resolver queryResolver(String resolver,
                                 String command,
                                 String arg1,
                                 String arg2) {
    InputStream iStream = null;
    String RFC2483 = resolver + "?command=" + command
        + "&format=tr9401&uri=" + arg1
        + "&uri2=" + arg2;
    String line = null;

    try {
        URL url = new URL(RFC2483);

        URLConnection urlCon = url.openConnection();

        urlCon.setUseCaches(false);

        Resolver r = (Resolver) newCatalog();

        String cType = urlCon.getContentType();

        // I don't care about the character set or subtype
        if (cType.indexOf(";") > 0) {
            cType = cType.substring(0, cType.indexOf(";"));
        }

        r.parseCatalog(cType, urlCon.getInputStream());

        return r;
    } catch (CatalogException cex) {
      if (cex.getExceptionType() == CatalogException.UNPARSEABLE) {
        catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483);
      } else if (cex.getExceptionType()
                 == CatalogException.UNKNOWN_FORMAT) {
        catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483);
      }
      return null;
    } catch (MalformedURLException mue) {
        catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483);
        return null;
    } catch (IOException ie) {
        catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483);
        return null;
    }
}
 
Example 19
/**
 * Query an external RFC2483 resolver.
 *
 * @param resolver The URL of the RFC2483 resolver.
 * @param command The command to send the resolver.
 * @param arg1 The first argument to the resolver.
 * @param arg2 The second argument to the resolver, usually null.
 *
 * @return The Resolver constructed.
 */
protected Resolver queryResolver(String resolver,
                                 String command,
                                 String arg1,
                                 String arg2) {
    InputStream iStream = null;
    String RFC2483 = resolver + "?command=" + command
        + "&format=tr9401&uri=" + arg1
        + "&uri2=" + arg2;
    String line = null;

    try {
        URL url = new URL(RFC2483);

        URLConnection urlCon = url.openConnection();

        urlCon.setUseCaches(false);

        Resolver r = (Resolver) newCatalog();

        String cType = urlCon.getContentType();

        // I don't care about the character set or subtype
        if (cType.indexOf(";") > 0) {
            cType = cType.substring(0, cType.indexOf(";"));
        }

        r.parseCatalog(cType, urlCon.getInputStream());

        return r;
    } catch (CatalogException cex) {
      if (cex.getExceptionType() == CatalogException.UNPARSEABLE) {
        catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483);
      } else if (cex.getExceptionType()
                 == CatalogException.UNKNOWN_FORMAT) {
        catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483);
      }
      return null;
    } catch (MalformedURLException mue) {
        catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483);
        return null;
    } catch (IOException ie) {
        catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483);
        return null;
    }
}
 
Example 20
/**
 * Creates a Reader using the InputStream of a URLConnection.
 * <p>
 * If the URLConnection is not of type HttpURLConnection and there is not
 * 'content-type' header in the fetched data it uses the same logic used for
 * files.
 * <p>
 * If the URLConnection is a HTTP Url or there is a 'content-type' header in
 * the fetched data it uses the same logic used for an InputStream with
 * content-type.
 * <p>
 * It does a lenient charset encoding detection, check the constructor with
 * the lenient parameter for details.
 *
 * @param conn URLConnection to create a Reader from.
 * @param defaultEncoding The default encoding
 * @throws IOException thrown if there is a problem reading the stream of
 *         the URLConnection.
 */
public XmlStreamReader(final URLConnection conn, final String defaultEncoding) throws IOException {
    this.defaultEncoding = defaultEncoding;
    final boolean lenient = true;
    final String contentType = conn.getContentType();
    final InputStream is = conn.getInputStream();
    final BOMInputStream bom = new BOMInputStream(new BufferedInputStream(is, BUFFER_SIZE), false, BOMS);
    final BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES);
    if (conn instanceof HttpURLConnection || contentType != null) {
        this.encoding = doHttpStream(bom, pis, contentType, lenient);
    } else {
        this.encoding = doRawStream(bom, pis, lenient);
    }
    this.reader = new InputStreamReader(pis, encoding);
}