com.helger.commons.io.resource.URLResource Java Examples

The following examples show how to use com.helger.commons.io.resource.URLResource. 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 check out the related API usage on the sidebar.
Example #1
Source File: XMLResourceBundleControl.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Override
public ResourceBundle newBundle (@Nonnull final String sBaseName,
                                 @Nonnull final Locale aLocale,
                                 @Nonnull final String sFormat,
                                 @Nonnull final ClassLoader aClassLoader,
                                 final boolean bReload) throws IOException
{
  ValueEnforcer.notNull (sBaseName, "BaseName");
  ValueEnforcer.notNull (aLocale, "Locale");
  ValueEnforcer.notNull (sFormat, "Format");
  ValueEnforcer.notNull (aClassLoader, "ClassLoader");

  // We can only handle XML
  if (sFormat.equals (FORMAT_XML))
  {
    final String sBundleName = toBundleName (sBaseName, aLocale);
    final String sResourceName = toResourceName (sBundleName, sFormat);
    final URL aResourceUrl = ClassLoaderHelper.getResource (aClassLoader, sResourceName);
    if (aResourceUrl != null)
      try (final InputStream aIS = StreamHelper.getBuffered (URLResource.getInputStream (aResourceUrl)))
      {
        return new XMLResourceBundle (aIS);
      }
  }
  return null;
}
 
Example #2
Source File: DOMReaderTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testExternalEntityExpansion ()
{
  // Include a dummy file
  final File aFile = new File ("src/test/resources/test1.txt");
  assertTrue (aFile.exists ());
  final String sFileContent = StreamHelper.getAllBytesAsString (new FileSystemResource (aFile),
                                                                StandardCharsets.ISO_8859_1);

  // The XML with XXE problem
  final String sXML = "<?xml version='1.0' encoding='utf-8'?>" +
                      "<!DOCTYPE root [" +
                      " <!ELEMENT root ANY >" +
                      " <!ENTITY xxe SYSTEM \"" +
                      FileHelper.getAsURLString (aFile) +
                      "\" >]>" +
                      "<root>&xxe;</root>";
  final DOMReaderSettings aDRS = new DOMReaderSettings ().setEntityResolver ( (publicId,
                                                                               systemId) -> InputSourceFactory.create (new URLResource (systemId)));

  // Read successful - entity expansion!
  final Document aDoc = DOMReader.readXMLDOM (sXML, aDRS);
  assertNotNull (aDoc);
  assertEquals (sFileContent, aDoc.getDocumentElement ().getTextContent ());

  // Should fail because inline DTD is present
  final CollectingSAXErrorHandler aCEH = new CollectingSAXErrorHandler ();
  assertNull (DOMReader.readXMLDOM (sXML,
                                    aDRS.getClone ()
                                        .setFeatureValues (EXMLParserFeature.AVOID_XXE_SETTINGS)
                                        .setErrorHandler (aCEH)));
  // Expected
  assertEquals (1, aCEH.getErrorList ().size ());
  assertTrue (aCEH.getErrorList ()
                  .getFirst ()
                  .getErrorText (Locale.ROOT)
                  .contains ("http://apache.org/xml/features/disallow-doctype-decl"));
}
 
Example #3
Source File: SimpleLSResourceResolverTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testOSGIBundle () throws BundleException
{
  LSInput aRes;

  // Initializing Apache Felix as OSGI container is required to get the
  // "bundle" URL protocol installed correctly
  // Otherwise the first call would end up as a "file" resource ;-)
  final Framework aOSGI = new FrameworkFactory ().newFramework (new HashMap <String, String> ());
  aOSGI.start ();
  try
  {
    // Bundle 0 is the org.apache.felix.framework bundle
    final Bundle b = aOSGI.getBundleContext ().getBundle (0);
    assertNotNull (b);
    assertEquals (Bundle.ACTIVE, b.getState ());

    // No leading slash is important as the ClassLoader is used!
    assertNotNull (b.getResource ("org/apache/felix/framework/util/Util.class"));

    final LSResourceResolver aRR = new SimpleLSResourceResolver ();

    // No class loader
    aRes = aRR.resolveResource (XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                null,
                                null,
                                "../Felix.class",
                                "bundle://0.0:1/org/apache/felix/framework/util/Util.class");
    assertTrue (aRes instanceof ResourceLSInput);
    final IHasInputStream aISP = ((ResourceLSInput) aRes).getInputStreamProvider ();
    assertTrue (aISP instanceof URLResource);
    // Path maybe a "jar:file:" resource
    assertTrue (((URLResource) aISP).getPath ().endsWith ("org/apache/felix/framework/Felix.class"));
  }
  finally
  {
    aOSGI.stop ();
  }
}
 
Example #4
Source File: PropertiesHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nullable
public static NonBlockingProperties loadProperties (@Nonnull final ISimpleURL aURL)
{
  ValueEnforcer.notNull (aURL, "URL");

  try
  {
    return loadProperties (new URLResource (aURL));
  }
  catch (final MalformedURLException ex)
  {
    return null;
  }
}
 
Example #5
Source File: DefaultResourceResolver.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static URLResource _resolveURLResource (final String sSystemId,
                                                final URL aBaseURL) throws MalformedURLException
{
  // Take only the path
  String sBasePath = aBaseURL.getPath ();

  /*
   * Heuristics to check if the base URI is a file is to check for the
   * existence of a dot ('.') in the last part of the filename. This is not
   * ideal but should do the trick In case you have a filename that has no
   * extension (e.g. 'test') simply append a dot (e.g. 'test.') to have the
   * same effect.
   */
  final String sBaseFilename = FilenameHelper.getWithoutPath (sBasePath);
  if (sBaseFilename != null && sBaseFilename.indexOf ('.') >= 0)
  {
    // Take only the path
    sBasePath = FilenameHelper.getPath (sBasePath);
  }

  // Concatenate the path with the URI to search
  final String sNewPath = FilenameHelper.getCleanConcatenatedUrlPath (sBasePath, sSystemId);

  // Rebuild the URL with the new path
  final URL aNewURL = new URL (aBaseURL.getProtocol (),
                               aBaseURL.getHost (),
                               aBaseURL.getPort (),
                               URLHelper.getURLString (sNewPath, aBaseURL.getQuery (), aBaseURL.getRef ()));
  final URLResource ret = new URLResource (aNewURL);
  if (isDebugResolve ())
    if (LOGGER.isInfoEnabled ())
      LOGGER.info ("  [URL] resolved base + system to " + ret);
  return ret;
}
 
Example #6
Source File: FileSystemResourceProvider.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public boolean supportsReading (@Nullable final String sName)
{
  if (StringHelper.hasNoText (sName))
    return false;
  if (ClassPathResource.isExplicitClassPathResource (sName))
    return false;
  if (URLResource.isExplicitURLResource (sName))
    return false;

  if (isCanReadRelativePaths ())
    return true;
  // Must be an absolute path (for backwards compatibility)
  return _getFile (sName).isAbsolute ();
}
 
Example #7
Source File: FileSystemResourceProvider.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public boolean supportsWriting (@Nullable final String sName)
{
  if (StringHelper.hasNoText (sName))
    return false;
  if (ClassPathResource.isExplicitClassPathResource (sName))
    return false;
  if (URLResource.isExplicitURLResource (sName))
    return false;

  return true;
}
 
Example #8
Source File: URLResourceProvider.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public IReadableResource getReadableResource (@Nonnull final String sURL)
{
  ValueEnforcer.notNull (sURL, "URL");

  try
  {
    return new URLResource (sURL);
  }
  catch (final MalformedURLException ex)
  {
    throw new IllegalArgumentException ("Passed name '" + sURL + "' is not a URL!", ex);
  }
}
 
Example #9
Source File: CssUtils.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String stripEmbeddableStyles(URL remoteStyleSheet, String mediaType, boolean prettyPrint) {
    CascadingStyleSheet styles = CSSReader.readFromStream(new URLResource(remoteStyleSheet), StandardCharsets.UTF_8, ECSSVersion.CSS30);
    return stripEmbeddableStyles(styles, mediaType, prettyPrint);
}
 
Example #10
Source File: TransformSourceFactory.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static ResourceStreamSource create (@Nonnull final URL aURL)
{
  return create (new URLResource (aURL));
}
 
Example #11
Source File: InputSourceFactory.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static InputSource create (@Nonnull final URL aURL)
{
  return create (new URLResource (aURL));
}
 
Example #12
Source File: DefaultResourceResolver.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static URLResource _resolveJarFileResource (@Nonnull final String sSystemId,
                                                    @Nonnull final String sBaseURI) throws MalformedURLException
{
  // Base URI is inside a jar file? Skip the JAR file
  // See issue #8 - use lastIndexOf here
  final int i = sBaseURI.lastIndexOf ("!/");
  String sPrefix;
  String sBasePath;
  if (i < 0)
  {
    sPrefix = "";
    sBasePath = sBaseURI;
  }
  else
  {
    sPrefix = sBaseURI.substring (0, i + 2);
    sBasePath = sBaseURI.substring (i + 2);
  }

  // Skip any potentially leading path separator
  if (FilenameHelper.startsWithPathSeparatorChar (sBasePath))
    sBasePath = sBasePath.substring (1);

  // Get the parent path of the base path
  final File aBaseFile = new File (sBasePath).getParentFile ();

  // Concatenate the path with the URI to search
  final String sNewPath = FilenameHelper.getCleanPath (aBaseFile == null ? sSystemId
                                                                         : aBaseFile.getPath () + '/' + sSystemId);

  String sAggregatedPath;
  if (sPrefix.endsWith ("/") && sNewPath.startsWith ("/"))
  {
    // Avoid "//"
    sAggregatedPath = sPrefix + sNewPath.substring (1);
  }
  else
    sAggregatedPath = sPrefix + sNewPath;

  final URLResource ret = new URLResource (sAggregatedPath);
  if (isDebugResolve ())
    if (LOGGER.isInfoEnabled ())
      LOGGER.info ("  [JarFile] resolved base + system to " + ret);
  return ret;
}
 
Example #13
Source File: URLResourceProvider.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
public boolean supportsReading (@Nullable final String sName)
{
  return URLResource.isExplicitURLResource (sName);
}
 
Example #14
Source File: SchematronResourcePure.java    From ph-schematron with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new {@link SchematronResourcePure} from Schematron rules provided
 * at a URL
 *
 * @param sSCHURL
 *        The URL to the Schematron rules. May neither be <code>null</code>
 *        nor empty.
 * @return Never <code>null</code>.
 * @throws MalformedURLException
 *         In case an invalid URL is provided
 */
@Nonnull
public static SchematronResourcePure fromURL (@Nonnull @Nonempty final String sSCHURL) throws MalformedURLException
{
  return new SchematronResourcePure (new URLResource (sSCHURL));
}
 
Example #15
Source File: SchematronResourcePure.java    From ph-schematron with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new {@link SchematronResourcePure} from Schematron rules provided
 * at a URL
 *
 * @param aSCHURL
 *        The URL to the Schematron rules. May not be <code>null</code>.
 * @return Never <code>null</code>.
 */
@Nonnull
public static SchematronResourcePure fromURL (@Nonnull final URL aSCHURL)
{
  return new SchematronResourcePure (new URLResource (aSCHURL));
}