Search in sources :

Example 6 with URISyntaxException

use of java.net.URISyntaxException in project elasticsearch by elastic.

the class Security method addClasspathPermissions.

/** Adds access to classpath jars/classes for jar hell scan, etc */
@SuppressForbidden(reason = "accesses fully qualified URLs to configure security")
static void addClasspathPermissions(Permissions policy) throws IOException {
    // really it should be covered by lib/, but there could be e.g. agents or similar configured)
    for (URL url : JarHell.parseClassPath()) {
        Path path;
        try {
            path = PathUtils.get(url.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        // resource itself
        policy.add(new FilePermission(path.toString(), "read,readlink"));
        // classes underneath
        if (Files.isDirectory(path)) {
            policy.add(new FilePermission(path.toString() + path.getFileSystem().getSeparator() + "-", "read,readlink"));
        }
    }
}
Also used : Path(java.nio.file.Path) URISyntaxException(java.net.URISyntaxException) FilePermission(java.io.FilePermission) URL(java.net.URL) SuppressForbidden(org.elasticsearch.common.SuppressForbidden)

Example 7 with URISyntaxException

use of java.net.URISyntaxException in project elasticsearch by elastic.

the class Security method readPolicy.

/**
     * Reads and returns the specified {@code policyFile}.
     * <p>
     * Resources (e.g. jar files and directories) listed in {@code codebases} location
     * will be provided to the policy file via a system property of the short name:
     * e.g. <code>${codebase.joda-convert-1.2.jar}</code> would map to full URL.
     */
@SuppressForbidden(reason = "accesses fully qualified URLs to configure security")
static Policy readPolicy(URL policyFile, URL[] codebases) {
    try {
        try {
            // set codebase properties
            for (URL url : codebases) {
                String shortName = PathUtils.get(url.toURI()).getFileName().toString();
                System.setProperty("codebase." + shortName, url.toString());
            }
            return Policy.getInstance("JavaPolicy", new URIParameter(policyFile.toURI()));
        } finally {
            // clear codebase properties
            for (URL url : codebases) {
                String shortName = PathUtils.get(url.toURI()).getFileName().toString();
                System.clearProperty("codebase." + shortName);
            }
        }
    } catch (NoSuchAlgorithmException | URISyntaxException e) {
        throw new IllegalArgumentException("unable to parse policy file `" + policyFile + "`", e);
    }
}
Also used : URIParameter(java.security.URIParameter) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URISyntaxException(java.net.URISyntaxException) URL(java.net.URL) SuppressForbidden(org.elasticsearch.common.SuppressForbidden)

Example 8 with URISyntaxException

use of java.net.URISyntaxException in project elasticsearch by elastic.

the class ExceptionSerializationTests method testExceptionRegistration.

public void testExceptionRegistration() throws ClassNotFoundException, IOException, URISyntaxException {
    final Set<Class<?>> notRegistered = new HashSet<>();
    final Set<Class<?>> hasDedicatedWrite = new HashSet<>();
    final Set<Class<?>> registered = new HashSet<>();
    final String path = "/org/elasticsearch";
    final Path startPath = PathUtils.get(ElasticsearchException.class.getProtectionDomain().getCodeSource().getLocation().toURI()).resolve("org").resolve("elasticsearch");
    final Set<? extends Class<?>> ignore = Sets.newHashSet(CancellableThreadsTests.CustomException.class, org.elasticsearch.rest.BytesRestResponseTests.WithHeadersException.class, AbstractClientHeadersTestCase.InternalException.class);
    FileVisitor<Path> visitor = new FileVisitor<Path>() {

        private Path pkgPrefix = PathUtils.get(path).getParent();

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            Path next = pkgPrefix.resolve(dir.getFileName());
            if (ignore.contains(next)) {
                return FileVisitResult.SKIP_SUBTREE;
            }
            pkgPrefix = next;
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            checkFile(file.getFileName().toString());
            return FileVisitResult.CONTINUE;
        }

        private void checkFile(String filename) {
            if (filename.endsWith(".class") == false) {
                return;
            }
            try {
                checkClass(loadClass(filename));
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }

        private void checkClass(Class<?> clazz) {
            if (ignore.contains(clazz) || isAbstract(clazz.getModifiers()) || isInterface(clazz.getModifiers())) {
                return;
            }
            if (isEsException(clazz) == false) {
                return;
            }
            if (ElasticsearchException.isRegistered(clazz.asSubclass(Throwable.class), Version.CURRENT) == false && ElasticsearchException.class.equals(clazz.getEnclosingClass()) == false) {
                notRegistered.add(clazz);
            } else if (ElasticsearchException.isRegistered(clazz.asSubclass(Throwable.class), Version.CURRENT)) {
                registered.add(clazz);
                try {
                    if (clazz.getMethod("writeTo", StreamOutput.class) != null) {
                        hasDedicatedWrite.add(clazz);
                    }
                } catch (Exception e) {
                // fair enough
                }
            }
        }

        private boolean isEsException(Class<?> clazz) {
            return ElasticsearchException.class.isAssignableFrom(clazz);
        }

        private Class<?> loadClass(String filename) throws ClassNotFoundException {
            StringBuilder pkg = new StringBuilder();
            for (Path p : pkgPrefix) {
                pkg.append(p.getFileName().toString()).append(".");
            }
            pkg.append(filename.substring(0, filename.length() - 6));
            return getClass().getClassLoader().loadClass(pkg.toString());
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            throw exc;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            pkgPrefix = pkgPrefix.getParent();
            return FileVisitResult.CONTINUE;
        }
    };
    Files.walkFileTree(startPath, visitor);
    final Path testStartPath = PathUtils.get(ExceptionSerializationTests.class.getResource(path).toURI());
    Files.walkFileTree(testStartPath, visitor);
    assertTrue(notRegistered.remove(TestException.class));
    assertTrue(notRegistered.remove(UnknownHeaderException.class));
    assertTrue("Classes subclassing ElasticsearchException must be registered \n" + notRegistered.toString(), notRegistered.isEmpty());
    // check
    assertTrue(registered.removeAll(ElasticsearchException.getRegisteredKeys()));
    assertEquals(registered.toString(), 0, registered.size());
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) IllegalShardRoutingStateException(org.elasticsearch.cluster.routing.IllegalShardRoutingStateException) ActionTransportException(org.elasticsearch.transport.ActionTransportException) SearchContextMissingException(org.elasticsearch.search.SearchContextMissingException) SnapshotException(org.elasticsearch.snapshots.SnapshotException) AccessDeniedException(java.nio.file.AccessDeniedException) SearchException(org.elasticsearch.search.SearchException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) RecoverFilesRecoveryException(org.elasticsearch.indices.recovery.RecoverFilesRecoveryException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) NotDirectoryException(java.nio.file.NotDirectoryException) DirectoryNotEmptyException(java.nio.file.DirectoryNotEmptyException) IOException(java.io.IOException) IndexTemplateMissingException(org.elasticsearch.indices.IndexTemplateMissingException) NoSuchFileException(java.nio.file.NoSuchFileException) FailedNodeException(org.elasticsearch.action.FailedNodeException) SearchParseException(org.elasticsearch.search.SearchParseException) URISyntaxException(java.net.URISyntaxException) AliasesNotFoundException(org.elasticsearch.rest.action.admin.indices.AliasesNotFoundException) RecoveryEngineException(org.elasticsearch.index.engine.RecoveryEngineException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) TimestampParsingException(org.elasticsearch.action.TimestampParsingException) RoutingMissingException(org.elasticsearch.action.RoutingMissingException) RepositoryException(org.elasticsearch.repositories.RepositoryException) AlreadyExpiredException(org.elasticsearch.index.AlreadyExpiredException) InvalidIndexTemplateException(org.elasticsearch.indices.InvalidIndexTemplateException) QueryShardException(org.elasticsearch.index.query.QueryShardException) FileSystemException(java.nio.file.FileSystemException) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) EOFException(java.io.EOFException) FileNotFoundException(java.io.FileNotFoundException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) ActionNotFoundTransportException(org.elasticsearch.transport.ActionNotFoundTransportException) ParsingException(org.elasticsearch.common.ParsingException) FileSystemLoopException(java.nio.file.FileSystemLoopException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) CircuitBreakingException(org.elasticsearch.common.breaker.CircuitBreakingException) AtomicMoveNotSupportedException(java.nio.file.AtomicMoveNotSupportedException) AbstractClientHeadersTestCase(org.elasticsearch.client.AbstractClientHeadersTestCase) FileVisitor(java.nio.file.FileVisitor) CancellableThreadsTests(org.elasticsearch.common.util.CancellableThreadsTests) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) HashSet(java.util.HashSet)

Example 9 with URISyntaxException

use of java.net.URISyntaxException in project jetty.project by eclipse.

the class OSGiWebInfConfiguration method convertFragmentPathToResource.

/**
     * Convert a path inside a fragment into a Resource
     * @param resourcePath
     * @param fragment
     * @param resourceMap
     * @throws Exception
     */
private void convertFragmentPathToResource(String resourcePath, Bundle fragment, Map<String, Resource> resourceMap) throws Exception {
    if (resourcePath == null)
        return;
    URL url = fragment.getEntry(resourcePath);
    if (url == null) {
        throw new IllegalArgumentException("Unable to locate " + resourcePath + " inside " + " the fragment '" + fragment.getSymbolicName() + "'");
    }
    url = BundleFileLocatorHelperFactory.getFactory().getHelper().getLocalURL(url);
    URI uri;
    try {
        uri = url.toURI();
    } catch (URISyntaxException e) {
        uri = new URI(url.toString().replaceAll(" ", "%20"));
    }
    String key = resourcePath.startsWith("/") ? resourcePath.substring(1) : resourcePath;
    resourceMap.put(key + ";" + fragment.getSymbolicName(), Resource.newResource(uri));
}
Also used : URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL)

Example 10 with URISyntaxException

use of java.net.URISyntaxException in project jetty.project by eclipse.

the class CommandLineConfigSource method findJettyHomePath.

private final Path findJettyHomePath() {
    // If a jetty property is defined, use it
    Prop prop = this.props.getProp(BaseHome.JETTY_HOME, false);
    if (prop != null && !Utils.isBlank(prop.value)) {
        return FS.toPath(prop.value);
    }
    // If a system property is defined, use it
    String val = System.getProperty(BaseHome.JETTY_HOME);
    if (!Utils.isBlank(val)) {
        return FS.toPath(val);
    }
    // Attempt to find path relative to content in jetty's start.jar
    // based on lookup for the Main class (from jetty's start.jar)
    String classRef = "org/eclipse/jetty/start/Main.class";
    URL jarfile = this.getClass().getClassLoader().getResource(classRef);
    if (jarfile != null) {
        Matcher m = Pattern.compile("jar:(file:.*)!/" + classRef).matcher(jarfile.toString());
        if (m.matches()) {
            // ${jetty.home} is relative to found BaseHome class
            try {
                return new File(new URI(m.group(1))).getParentFile().toPath();
            } catch (URISyntaxException e) {
                throw new UsageException(UsageException.ERR_UNKNOWN, e);
            }
        }
    }
    // Lastly, fall back to ${user.dir} default
    Path home = FS.toPath(System.getProperty("user.dir", "."));
    setProperty(BaseHome.JETTY_HOME, home.toString(), ORIGIN_INTERNAL_FALLBACK);
    return home;
}
Also used : Path(java.nio.file.Path) UsageException(org.eclipse.jetty.start.UsageException) Prop(org.eclipse.jetty.start.Props.Prop) Matcher(java.util.regex.Matcher) URISyntaxException(java.net.URISyntaxException) File(java.io.File) URI(java.net.URI) URL(java.net.URL)

Aggregations

URISyntaxException (java.net.URISyntaxException)4043 URI (java.net.URI)2496 IOException (java.io.IOException)1273 File (java.io.File)716 URL (java.net.URL)702 ArrayList (java.util.ArrayList)407 Test (org.junit.Test)274 MalformedURLException (java.net.MalformedURLException)270 InputStream (java.io.InputStream)224 HashMap (java.util.HashMap)212 Response (javax.ws.rs.core.Response)194 Test (org.testng.annotations.Test)175 Parameters (org.testng.annotations.Parameters)166 Builder (javax.ws.rs.client.Invocation.Builder)165 ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)165 Map (java.util.Map)162 StorageException (com.microsoft.azure.storage.StorageException)142 Path (java.nio.file.Path)141 URIBuilder (org.apache.http.client.utils.URIBuilder)140 List (java.util.List)125