Java Code Examples for org.gradle.internal.UncheckedException#throwAsUncheckedException()

The following examples show how to use org.gradle.internal.UncheckedException#throwAsUncheckedException() . 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: PayloadSerializer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public PayloadSerializer(PayloadClassLoaderRegistry registry) {
    classLoaderRegistry = registry;

    // On Java 6, there is a public method to lookup a class descriptor given a class. On Java 5, we have to use reflection
    // TODO:ADAM - move this into the service registry
    if (Jvm.current().getJavaVersion().isJava6Compatible()) {
        // Use the public method
        try {
            classLookup = (Transformer<ObjectStreamClass, Class<?>>) getClass().getClassLoader().loadClass("org.gradle.tooling.internal.provider.jdk6.Jdk6ClassLookup").newInstance();
        } catch (Exception e) {
            throw UncheckedException.throwAsUncheckedException(e);
        }
    } else {
        // Use Java 5 fallback which uses reflection
        classLookup = new ReflectionClassLookup();
    }
}
 
Example 2
Source File: PlayWorkerServer.java    From playframework with Apache License 2.0 6 votes vote down vote up
private InetSocketAddress startServer() {
    ClassLoaderUtils.disableUrlConnectionCaching();
    final Thread thread = Thread.currentThread();
    final ClassLoader previousContextClassLoader = thread.getContextClassLoader();
    final ClassLoader classLoader = new URLClassLoader(DefaultClassPath.of(runSpec.getClasspath()).getAsURLArray(), ClassLoader.getSystemClassLoader());
    thread.setContextClassLoader(classLoader);
    try {
        Object buildDocHandler = runAdapter.getBuildDocHandler(classLoader, runSpec.getClasspath());
        Object buildLink = runAdapter.getBuildLink(classLoader, this, runSpec.getProjectPath(), runSpec.getApplicationJar(), runSpec.getChangingClasspath(), runSpec.getAssetsJar(), runSpec.getAssetsDirs());
        return runAdapter.runDevHttpServer(classLoader, classLoader, buildLink, buildDocHandler, runSpec.getHttpPort());
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    } finally {
        thread.setContextClassLoader(previousContextClassLoader);
    }
}
 
Example 3
Source File: IvyDependencyResolverAdapter.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void getDependency(DependencyMetaData dependency, BuildableModuleVersionMetaDataResolveResult result) {
    IvyContext.getContext().setResolveData(resolveData);
    try {
        ResolvedModuleRevision revision = resolver.getDependency(dependency.getDescriptor(), resolveData);
        if (revision == null) {
            LOGGER.debug("Performed resolved of module '{}' in repository '{}': not found", dependency.getRequested(), getName());
            result.missing();
        } else {
            LOGGER.debug("Performed resolved of module '{}' in repository '{}': found", dependency.getRequested(), getName());
            ModuleDescriptorAdapter metaData = new ModuleDescriptorAdapter(revision.getDescriptor());
            metaData.setChanging(isChanging(revision));
            result.resolved(metaData, null);
        }
    } catch (ParseException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 4
Source File: DefaultClassLoaderFactory.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private ClassLoader doCreateIsolatedClassLoader(Collection<URL> classpath) {
    // This piece of ugliness copies the JAXP (ie XML API) provider, if any, from the system ClassLoader. Here's why:
    //
    // 1. When looking for a provider, JAXP looks for a service resource in the context ClassLoader, which is our isolated ClassLoader. If our classpath above does not contain a
    //    provider, this returns null. If it does contain a provider, JAXP extracts the classname from the service resource.
    // 2. If not found, JAXP looks for a service resource in the system ClassLoader. This happens to include all the application classes specified on the classpath. If the application
    //    classpath does not contain a provider, this returns null. If it does contain a provider, JAXP extracts the implementation classname from the service resource.
    // 3. If not found, JAXP uses a default classname
    // 4. JAXP attempts to load the provider using the context ClassLoader. which is our isolated ClassLoader. This is fine if the classname came from step 1 or 3. It blows up if the
    //    classname came from step 2.
    //
    // So, as a workaround, locate and include the JAXP provider jar in the classpath for our isolated ClassLoader.
    //
    // Note that in practise, this is only triggered when running in our tests

    if (needJaxpImpl()) {
        try {
            classpath.add(ClasspathUtil.getClasspathForResource(ClassLoader.getSystemClassLoader(), "META-INF/services/javax.xml.parsers.SAXParserFactory").toURI().toURL());
        } catch (MalformedURLException e) {
            throw UncheckedException.throwAsUncheckedException(e);
        }
    }

    return new URLClassLoader(classpath.toArray(new URL[classpath.size()]), ClassLoader.getSystemClassLoader().getParent());
}
 
Example 5
Source File: FindBugsWorkerClient.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public FindBugsResult getResult() {
    try {
        return findbugsResults.take();
    } catch (InterruptedException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 6
Source File: CompilerDaemonClient.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public <T extends CompileSpec> CompileResult execute(Compiler<T> compiler, T spec) {
    // currently we just allow a single compilation thread at a time (per compiler daemon)
    // one problem to solve when allowing multiple threads is how to deal with memory requirements specified by compile tasks
    try {
        server.execute(compiler, spec);
        return compileResults.take();
    } catch (InterruptedException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 7
Source File: GFileUtils.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns a relative path from 'from' to 'to'
 *
 * @param from where to calculate from
 * @param to where to calculate to
 * @return The relative path
 */
public static String relativePath(File from, File to) {
    try {
        return org.apache.tools.ant.util.FileUtils.getRelativePath(from, to);
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 8
Source File: AsyncReceive.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void receiveMessages(Receive<? extends T> receive) {
    while (true) {
        Dispatch<? super T> dispatch;
        lock.lock();
        try {
            while (dispatches.isEmpty() && state == State.Init) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    throw UncheckedException.throwAsUncheckedException(e);
                }
            }
            if (state != State.Init) {
                return;
            }
            dispatch = dispatches.remove(0);
        } finally {
            lock.unlock();
        }

        try {
            T message = receive.receive();
            if (message == null) {
                return;
            }

            dispatch.dispatch(message);
        } finally {
            lock.lock();
            try {
                dispatches.add(dispatch);
                condition.signalAll();
            } finally {
                lock.unlock();
            }
        }
    }
}
 
Example 9
Source File: AbstractRepositoryCacheManager.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected ModuleDescriptor parseModuleDescriptor(DependencyResolver resolver, Artifact moduleArtifact, CacheMetadataOptions options, File artifactFile, Resource resource) throws ParseException {
    ModuleRevisionId moduleRevisionId = moduleArtifact.getId().getModuleRevisionId();
    try {
        IvySettings ivySettings = IvyContextualiser.getIvyContext().getSettings();
        ParserSettings parserSettings = new LegacyResolverParserSettings(ivySettings, resolver, moduleRevisionId);
        ModuleDescriptorParser parser = ModuleDescriptorParserRegistry.getInstance().getParser(resource);
        return parser.parseDescriptor(parserSettings, new URL(artifactFile.toURI().toASCIIString()), resource, options.isValidate());
    } catch (IOException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 10
Source File: XmlTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Element asElement() {
    if (element == null) {
        Document document;
        try {
            document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(toString())));
        } catch (Exception e) {
            throw UncheckedException.throwAsUncheckedException(e);
        }
        element = document.getDocumentElement();
        builder = null;
        node = null;
    }
    return element;
}
 
Example 11
Source File: ConsoleRenderer.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Renders a path name as a file URL that is likely recognized by consoles.
 */
public String asClickableFileUrl(File path) {
    // File.toURI().toString() leads to an URL like this on Mac: file:/reports/index.html
    // This URL is not recognized by the Mac console (too few leading slashes). We solve
    // this be creating an URI with an empty authority.
    try {
        return new URI("file", "", path.toURI().getPath(), null, null).toString();
    } catch (URISyntaxException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 12
Source File: DistributionLocator.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private URI getDistribution(String repositoryUrl, GradleVersion version, String archiveName,
                               String archiveClassifier) {
    try {
        return new URI(String.format("%s/%s-%s-%s.zip", repositoryUrl, archiveName, version.getVersion(), archiveClassifier));
    } catch (URISyntaxException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 13
Source File: CompilerDaemonClient.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public <T extends CompileSpec> CompileResult execute(Compiler<T> compiler, T spec) {
    // currently we just allow a single compilation thread at a time (per compiler daemon)
    // one problem to solve when allowing multiple threads is how to deal with memory requirements specified by compile tasks
    try {
        server.execute(compiler, spec);
        return compileResults.take();
    } catch (InterruptedException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 14
Source File: JUnitXmlResultWriter.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void write(TestClassResult result, OutputStream output) {
    String className = result.getClassName();
    long classId = result.getId();

    try {
        SimpleXmlWriter writer = new SimpleXmlWriter(output, "  ");
        writer.startElement("testsuite")
                .attribute("name", className)
                .attribute("tests", String.valueOf(result.getTestsCount()))
                .attribute("skipped", String.valueOf(result.getSkippedCount()))
                .attribute("failures", String.valueOf(result.getFailuresCount()))
                .attribute("errors", "0")
                .attribute("timestamp", DateUtils.format(result.getStartTime(), DateUtils.ISO8601_DATETIME_PATTERN))
                .attribute("hostname", hostName)
                .attribute("time", String.valueOf(result.getDuration() / 1000.0));

        writer.startElement("properties");
        writer.endElement();

        writeTests(writer, result.getResults(), className, classId);

        writer.startElement("system-out");
        writeOutputs(writer, classId, outputAssociation.equals(TestOutputAssociation.WITH_SUITE), TestOutputEvent.Destination.StdOut);
        writer.endElement();
        writer.startElement("system-err");
        writeOutputs(writer, classId, outputAssociation.equals(TestOutputAssociation.WITH_SUITE), TestOutputEvent.Destination.StdErr);
        writer.endElement();

        writer.endElement();
    } catch (IOException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 15
Source File: ImportsReader.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public String getImports() {
    if (importsText == null) {
        try {
            URL url = getClass().getResource("/default-imports.txt");
            InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF8");
            try {
                int bufferSize = 2048; // at time of writing, the file was about 1k so this should cover in one read
                StringBuilder imports = new StringBuilder(bufferSize);
                char[] chars = new char[bufferSize];

                int numRead = reader.read(chars, 0, bufferSize);
                while (numRead != -1) {
                    imports.append(chars, 0, numRead);
                    numRead = reader.read(chars, 0, bufferSize);
                }

                importsText = imports.toString();
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw UncheckedException.throwAsUncheckedException(e);
        }
    }

    return importsText;
}
 
Example 16
Source File: PlayApplication.java    From playframework with Apache License 2.0 5 votes vote down vote up
private <T> T waitForEvent(BlockingQueue<T> queue) {
    try {
        return queue.take();
    } catch (InterruptedException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 17
Source File: ProtocolStack.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void stop() {
    requestStop();
    try {
        protocolsStopped.await();
    } catch (InterruptedException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
    callbackQueue.clear();
    CompositeStoppable.stoppable(callbackQueue, receiver, workQueue, incomingQueue, outgoingQueue).stop();
}
 
Example 18
Source File: MethodMetaInfo.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Method findMethod(ClassLoader classLoader) {
    try {
        Class<?> declaringClass = this.type.load(classLoader);
        Class<?>[] paramTypes = new Class[this.paramTypes.length];
        for (int i = 0; i < this.paramTypes.length; i++) {
            Type paramType = this.paramTypes[i];
            paramTypes[i] = paramType.load(classLoader);
        }
        return declaringClass.getMethod(methodName, paramTypes);
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 19
Source File: PayloadSerializer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Object deserialize(SerializedPayload payload) {
    final DeserializeMap map = classLoaderRegistry.newDeserializeSession();
    try {
        final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader().getParent();
        final Map<Short, ClassLoaderDetails> classLoaderDetails = (Map<Short, ClassLoaderDetails>) payload.getHeader();

        final ObjectInputStream objectStream = new ObjectInputStream(new ByteArrayInputStream(payload.getSerializedModel())) {
            @Override
            protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {
                Class<?> aClass = readClass();
                ObjectStreamClass descriptor = classLookup.transform(aClass);
                if (descriptor == null) {
                    throw new ClassNotFoundException(aClass.getName());
                }
                return descriptor;
            }

            @Override
            protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                return desc.forClass();
            }

            private Class<?> readClass() throws IOException, ClassNotFoundException {
                short id = readShort();
                String className = readUTF();
                if (id == SYSTEM_CLASS_LOADER_ID) {
                    return Class.forName(className, false, systemClassLoader);
                }
                ClassLoaderDetails classLoader = classLoaderDetails.get(id);
                return map.resolveClass(classLoader, className);
            }

            @Override
            protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
                int count = readInt();
                Class<?>[] actualInterfaces = new Class<?>[count];
                for (int i = 0; i < count; i++) {
                    actualInterfaces[i] = readClass();
                }
                return Proxy.getProxyClass(actualInterfaces[0].getClassLoader(), actualInterfaces);
            }
        };
        return objectStream.readObject();
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 20
Source File: DefaultFileCollectionResolveContext.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private <T> List<T> doResolve(Converter<? extends T> converter) {
    List<T> result = new ArrayList<T>();
    while (!queue.isEmpty()) {
        Object element = queue.remove(0);
        if (element instanceof DefaultFileCollectionResolveContext) {
            DefaultFileCollectionResolveContext nestedContext = (DefaultFileCollectionResolveContext) element;
            converter.convertInto(nestedContext, result, fileResolver);
        } else if (element instanceof FileCollectionContainer) {
            FileCollectionContainer fileCollection = (FileCollectionContainer) element;
            resolveNested(fileCollection);
        } else if (element instanceof FileCollection || element instanceof MinimalFileCollection) {
            converter.convertInto(element, result, fileResolver);
        } else if (element instanceof Task) {
            Task task = (Task) element;
            queue.add(0, task.getOutputs().getFiles());
        } else if (element instanceof TaskOutputs) {
            TaskOutputs outputs = (TaskOutputs) element;
            queue.add(0, outputs.getFiles());
        } else if (element instanceof Closure) {
            Closure closure = (Closure) element;
            Object closureResult = closure.call();
            if (closureResult != null) {
                queue.add(0, closureResult);
            }
        } else if (element instanceof Callable) {
            Callable callable = (Callable) element;
            Object callableResult;
            try {
                callableResult = callable.call();
            } catch (Exception e) {
                throw UncheckedException.throwAsUncheckedException(e);
            }
            if (callableResult != null) {
                queue.add(0, callableResult);
            }
        } else if (element instanceof Iterable) {
            Iterable<?> iterable = (Iterable) element;
            GUtil.addToCollection(queue.subList(0, 0), iterable);
        } else if (element instanceof Object[]) {
            Object[] array = (Object[]) element;
            GUtil.addToCollection(queue.subList(0, 0), Arrays.asList(array));
        } else {
            converter.convertInto(element, result, fileResolver);
        }
    }
    return result;
}