Java Code Examples for org.codehaus.groovy.runtime.ResourceGroovyMethods

The following examples show how to use org.codehaus.groovy.runtime.ResourceGroovyMethods. 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 check out the related API usage on the sidebar.
Example #1
Source Project: gradle-plugins   Author: freefair   File: GenerateLombokConfig.java    License: MIT License 6 votes vote down vote up
@TaskAction
@SneakyThrows
public void generateLombokConfig() {
    File file = outputFile.getAsFile().get();

    if (file.isFile()) {
        try (Stream<String> lines = Files.lines(file.toPath(), StandardCharsets.ISO_8859_1)) {
            if (lines.noneMatch(line -> line.startsWith("#") && line.contains("io.freefair.lombok"))) {
                String message = file + " already exists and was not generated by this task";
                getLogger().warn(message);
                throw new StopExecutionException(message);
            }
        }
    }

    try (PrintWriter writer = ResourceGroovyMethods.newPrintWriter(file, "ISO-8859-1")) {
        writer.println("# This file is generated by the 'io.freefair.lombok' Gradle plugin");
        properties.get().entrySet().stream()
                .sorted(Map.Entry.comparingByKey(String.CASE_INSENSITIVE_ORDER))
                .forEach(entry ->
                        writer.println(entry.getKey() + " = " + entry.getValue())
                );
    }
}
 
Example #2
Source Project: gradle-plugins   Author: freefair   File: GenerateLombokConfig.java    License: MIT License 6 votes vote down vote up
@TaskAction
@SneakyThrows
public void generateLombokConfig() {
    File file = outputFile.getAsFile().get();

    if (file.isFile()) {
        try (Stream<String> lines = Files.lines(file.toPath(), StandardCharsets.ISO_8859_1)) {
            if (lines.noneMatch(line -> line.startsWith("#") && line.contains("io.freefair.lombok"))) {
                String message = file + " already exists and was not generated by this task";
                getLogger().warn(message);
                throw new StopExecutionException(message);
            }
        }
    }

    try (PrintWriter writer = ResourceGroovyMethods.newPrintWriter(file, "ISO-8859-1")) {
        writer.println("# This file is generated by the 'io.freefair.lombok' Gradle plugin");
        properties.get().entrySet().stream()
                .sorted(Map.Entry.comparingByKey(String.CASE_INSENSITIVE_ORDER))
                .forEach(entry ->
                        writer.println(entry.getKey() + " = " + entry.getValue())
                );
    }
}
 
Example #3
Source Project: groovy   Author: apache   File: BaseJsonParser.java    License: Apache License 2.0 6 votes vote down vote up
public Object parse(File file, String charset) {
    Reader reader = null;
    try {
        if (charset == null || charset.length() == 0) {
            reader = ResourceGroovyMethods.newReader(file);
        } else {
            reader = ResourceGroovyMethods.newReader(file, charset);
        }
        return parse(reader);
    } catch (IOException ioe) {
        throw new JsonException("Unable to process file: " + file.getPath(), ioe);
    } finally {
        if (reader != null) {
            DefaultGroovyMethodsSupport.closeWithWarning(reader);
        }
    }
}
 
Example #4
Source Project: groovy   Author: apache   File: JsonSlurperClassic.java    License: Apache License 2.0 6 votes vote down vote up
private Object parseFile(File file, String charset) {
    Reader reader = null;
    try {
        if (charset == null || charset.length() == 0) {
            reader = ResourceGroovyMethods.newReader(file);
        } else {
            reader = ResourceGroovyMethods.newReader(file, charset);
        }
        return parse(reader);
    } catch (IOException ioe) {
        throw new JsonException("Unable to process file: " + file.getPath(), ioe);
    } finally {
        if (reader != null) {
            DefaultGroovyMethodsSupport.closeWithWarning(reader);
        }
    }
}
 
Example #5
Source Project: groovy   Author: apache   File: JsonSlurperClassic.java    License: Apache License 2.0 6 votes vote down vote up
private Object parseURL(URL url, Map params) {
    Reader reader = null;
    try {
        if (params == null || params.isEmpty()) {
            reader = ResourceGroovyMethods.newReader(url);
        } else {
            reader = ResourceGroovyMethods.newReader(url, params);
        }
        return parse(reader);
    } catch (IOException ioe) {
        throw new JsonException("Unable to process url: " + url.toString(), ioe);
    } finally {
        if (reader != null) {
            DefaultGroovyMethodsSupport.closeWithWarning(reader);
        }
    }
}
 
Example #6
Source Project: groovy   Author: apache   File: JsonSlurperClassic.java    License: Apache License 2.0 6 votes vote down vote up
private Object parseURL(URL url, Map params, String charset) {
    Reader reader = null;
    try {
        if (params == null || params.isEmpty()) {
            reader = ResourceGroovyMethods.newReader(url, charset);
        } else {
            reader = ResourceGroovyMethods.newReader(url, params, charset);
        }
        return parse(reader);
    } catch (IOException ioe) {
        throw new JsonException("Unable to process url: " + url.toString(), ioe);
    } finally {
        if (reader != null) {
            DefaultGroovyMethodsSupport.closeWithWarning(reader);
        }
    }
}
 
Example #7
Source Project: groovy   Author: apache   File: JsonSlurper.java    License: Apache License 2.0 6 votes vote down vote up
private Object parseURL(URL url, Map params) {
    Reader reader = null;
    try {
        if (params == null || params.isEmpty()) {
            reader = ResourceGroovyMethods.newReader(url);
        } else {
            reader = ResourceGroovyMethods.newReader(url, params);
        }
        return createParser().parse(reader);
    } catch (IOException ioe) {
        throw new JsonException("Unable to process url: " + url.toString(), ioe);
    } finally {
        if (reader != null) {
            DefaultGroovyMethodsSupport.closeWithWarning(reader);
        }
    }
}
 
Example #8
Source Project: groovy   Author: apache   File: JsonSlurper.java    License: Apache License 2.0 6 votes vote down vote up
private Object parseURL(URL url, Map params, String charset) {
    Reader reader = null;
    try {
        if (params == null || params.isEmpty()) {
            reader = ResourceGroovyMethods.newReader(url, charset);
        } else {
            reader = ResourceGroovyMethods.newReader(url, params, charset);
        }
        return parse(reader);
    } catch (IOException ioe) {
        throw new JsonException("Unable to process url: " + url.toString(), ioe);
    } finally {
        if (reader != null) {
            DefaultGroovyMethodsSupport.closeWithWarning(reader);
        }
    }
}
 
Example #9
Source Project: groovy   Author: apache   File: GroovyCodeSource.java    License: Apache License 2.0 6 votes vote down vote up
public GroovyCodeSource(URL url) {
    if (url == null) {
        throw new RuntimeException("Could not construct a GroovyCodeSource from a null URL");
    }
    this.url = url;
    // TODO: GROOVY-6561: GroovyMain got the name this way: script.substring(script.lastIndexOf('/') + 1)
    this.name = url.toExternalForm();
    this.codeSource = new CodeSource(url, (java.security.cert.Certificate[]) null);
    try {
        String contentEncoding = getContentEncoding(url);
        if (contentEncoding != null) {
            this.scriptText = ResourceGroovyMethods.getText(url, contentEncoding);
        } else {
            this.scriptText = ResourceGroovyMethods.getText(url); // falls-back on default encoding
        }
    } catch (IOException e) {
        throw new RuntimeException("Impossible to read the text content from " + name, e);
    }
}
 
Example #10
Source Project: groovy   Author: apache   File: GroovyShellTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testLaunchesJUnitTestSuite() throws Exception {
    // create a valid (empty) test suite on disk
    String testName = "GroovyShellTestJUnit3Test"+System.currentTimeMillis();
    File testSuite = new File(System.getProperty("java.io.tmpdir"), testName);
    ResourceGroovyMethods.write(testSuite, "import junit.framework.*; \r\n" +
            "public class " + testName + " extends TestSuite { \r\n" +
            "    public static Test suite() { \r\n" +
            "        return new TestSuite(); \r\n" +
            "    } \r\n" +
            "} \r\n");
    testSuite.deleteOnExit();
    
    PrintStream out = System.out;
    System.setOut( new PrintStream(new ByteArrayOutputStream()) );
    try {
        // makes this more of an integration test than a unit test...
        GroovyShell.main( new String[] { testSuite.getCanonicalPath() });
    } finally {
        System.setOut( out );
    }
}
 
Example #11
Source Project: nifi   Author: apache   File: ExecuteGroovyScriptTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_sql_04_insert_and_json() throws Exception {
    //read blob from database written at previous step and write to flow file
    runner.setProperty(proc.SCRIPT_FILE, TEST_RESOURCE_LOCATION + "test_sql_04_insert_and_json.groovy");
    runner.setProperty("SQL.mydb", "dbcp");
    runner.setValidateExpressionUsage(false);
    runner.assertValid();

    runner.enqueue(new FileInputStream(TEST_RESOURCE_LOCATION + "test_sql_04_insert_and_json.json"));
    runner.run();

    runner.assertAllFlowFilesTransferred(proc.REL_SUCCESS.getName(), 3);  //number of inserted rows
    final List<MockFlowFile> result = runner.getFlowFilesForRelationship(proc.REL_SUCCESS.getName());
    MockFlowFile resultFile = result.get(0);
    List<String> lines = ResourceGroovyMethods.readLines(new File(TEST_RESOURCE_LOCATION + "test_sql_04_insert_and_json.json"), "UTF-8");
    //pass through to&from json before compare
    resultFile.assertContentEquals(JsonOutput.toJson(new JsonSlurper().parseText(lines.get(1))), "UTF-8");
}
 
Example #12
Source Project: joinfaces   Author: joinfaces   File: PropertyDocumentation.java    License: Apache License 2.0 5 votes vote down vote up
@TaskAction
public void generatePropertyDocumentation() throws IOException {
	ConfigurationMetadataRepository configurationMetadataRepository;

	configurationMetadataRepository = ConfigurationMetadataRepositoryJsonBuilder.create()
			.withJsonResource(new FileInputStream(getInputFile().getAsFile().get()))
			.build();

	try (PrintWriter writer = ResourceGroovyMethods.newPrintWriter(getOutputFile().getAsFile().get(), "UTF-8")) {

		writer.println("[source,properties,indent=0,subs=\"verbatim,attributes,macros\"]");
		writer.println("----");

		configurationMetadataRepository.getAllGroups().values().stream()
				.sorted(Comparator.comparing(ConfigurationMetadataGroup::getId))
				.forEach(group -> {
					writer.printf("## %s\n", group.getId());

					group.getSources().values()
							.stream()
							.map(ConfigurationMetadataSource::getShortDescription)
							.filter(s -> s != null && !s.isEmpty())
							.forEach(d -> writer.printf("# %s\n", d));

					group.getProperties().values().stream()
							.sorted(Comparator.comparing(ConfigurationMetadataProperty::getId))
							.forEach(property -> printProperty(writer, property));
					writer.println();
					writer.flush();
				});

		writer.println("----");
	}
}
 
Example #13
Source Project: joinfaces   Author: joinfaces   File: BomDocumentation.java    License: Apache License 2.0 5 votes vote down vote up
@TaskAction
public void generateBomDocumentation() throws IOException, XmlPullParserException {
	MavenXpp3Reader reader = new MavenXpp3Reader();
	Model model = reader.read(new FileReader(inputFile.getAsFile().get()));



	try (PrintWriter writer = ResourceGroovyMethods.newPrintWriter(getOutputFile().getAsFile().get(), "UTF-8")) {

		writer.println("|===");
		writer.println("|Group ID |Artifact ID |Version");

		model.getDependencyManagement()
				.getDependencies()
				.stream()
				.sorted(Comparator.comparing(Dependency::getGroupId).thenComparing(Dependency::getArtifactId))
				.forEach(dependency -> {

					writer.println();
					writer.printf("|`%s`\n", dependency.getGroupId());
					writer.printf("|`%s`\n", dependency.getArtifactId());
					writer.printf("|%s\n", dependency.getVersion());
				});

		writer.println("|===");
	}

}
 
Example #14
Source Project: groovy   Author: apache   File: GroovyRootDocBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private void setOverview() {
    String path = properties.getProperty("overviewFile");
    if (path != null && path.length() > 0) {
        try {
            String content = ResourceGroovyMethods.getText(new File(path));
            calcThenSetOverviewDescription(content);
        } catch (IOException e) {
            System.err.println("Unable to load overview file: " + e.getMessage());
        }
    }
}
 
Example #15
Source Project: groovy   Author: apache   File: FileOutputTool.java    License: Apache License 2.0 5 votes vote down vote up
public void writeToOutput(String fileName, String text, String charset) throws Exception {
    File file = new File(fileName);
    Path path = file.getParentFile().toPath();
    if (!Files.exists(path)) {
        try {
            Files.createDirectories(path);
        } catch (IOException e) {
            System.err.println("Unable to create parent directory '" + path + "' due to '" + e.getMessage() + "'; attempting to continue...");
        }
    }
    ResourceGroovyMethods.write(file, text, charset, true);
}
 
Example #16
Source Project: groovy   Author: apache   File: GroovyDocTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomClassTemplate() throws Exception {
    rule.executeTarget("testCustomClassTemplate");

    final File testfilesPackageDir = new File(tmpDir, "org/codehaus/groovy/tools/groovydoc/testfiles");
    final String[] list = testfilesPackageDir.list((file, name) -> name.equals("DocumentedClass.html"));

    assertNotNull("Dir not found: " + testfilesPackageDir.getAbsolutePath(), list);
    assertEquals(1, list.length);
    File documentedClassHtmlDoc = new File(testfilesPackageDir, list[0]);

    List<String> lines = ResourceGroovyMethods.readLines(documentedClassHtmlDoc);
    assertTrue("\"<title>DocumentedClass</title>\" not in: " + lines, lines.contains("<title>DocumentedClass</title>"));
    assertTrue("\"This is a custom class template.\" not in: " + lines, lines.contains("This is a custom class template."));
}
 
Example #17
Source Project: groovy   Author: apache   File: Groovy.java    License: Apache License 2.0 5 votes vote down vote up
private void createNewArgs(String txt) throws IOException {
    final String[] args = cmdline.getCommandline();
    // Temporary file - delete on exit, create (assured unique name).
    final File tempFile = FileUtils.getFileUtils().createTempFile(PREFIX, SUFFIX, null, true, true);
    final String[] commandline = new String[args.length + 1];
    ResourceGroovyMethods.write(tempFile, txt);
    commandline[0] = tempFile.getCanonicalPath();
    System.arraycopy(args, 0, commandline, 1, args.length);
    super.clearArgs();
    for (String arg : commandline) {
        final Commandline.Argument argument = super.createArg();
        argument.setValue(arg);
    }
}
 
Example #18
Source Project: groovy   Author: apache   File: LexerFrame.java    License: Apache License 2.0 5 votes vote down vote up
private void safeScanScript(File file) {
    try {
        scanScript(new StringReader(ResourceGroovyMethods.getText(file)));
    } catch (final Exception ex) {
        ex.printStackTrace();
    }
}
 
Example #19
Source Project: groovy   Author: apache   File: DefaultTypeTransformation.java    License: Apache License 2.0 5 votes vote down vote up
public static Collection asCollection(Object value) {
    if (value == null) {
        return Collections.EMPTY_LIST;
    } else if (value instanceof Collection) {
        return (Collection) value;
    } else if (value instanceof Map) {
        Map map = (Map) value;
        return map.entrySet();
    } else if (value.getClass().isArray()) {
        return arrayAsCollection(value);
    } else if (value instanceof MethodClosure) {
        MethodClosure method = (MethodClosure) value;
        IteratorClosureAdapter adapter = new IteratorClosureAdapter(method.getDelegate());
        method.call(adapter);
        return adapter.asList();
    } else if (value instanceof String || value instanceof GString) {
        return StringGroovyMethods.toList((CharSequence) value);
    } else if (value instanceof File) {
        try {
            return ResourceGroovyMethods.readLines((File) value);
        } catch (IOException e) {
            throw new GroovyRuntimeException("Error reading file: " + value, e);
        }
    } else if (value instanceof Class && ((Class) value).isEnum()) {
        Object[] values = (Object[]) InvokerHelper.invokeMethod(value, "values", EMPTY_OBJECT_ARRAY);
        return Arrays.asList(values);
    } else {
        // let's assume it's a collection of 1
        return Collections.singletonList(value);
    }
}
 
Example #20
Source Project: groovy   Author: apache   File: MyIntegerAnnoTraceASTTransformation.java    License: Apache License 2.0 5 votes vote down vote up
public void visit(ASTNode[] nodes, final SourceUnit source) {
    if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) {
        throw new RuntimeException("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes));
    }
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    File f = new File("temp/log.txt");
    try {
        ResourceGroovyMethods.append(f, parent.getClass().getSimpleName() + " " +
                parent.getAnnotations().get(0).getMember("value").getText() + " ");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #21
Source Project: jwala   Author: cerner   File: ResourceServiceImplTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testGenerateResourceFile() {
    File httpdTemplate = new File("../jwala-common/src/test/resources/HttpdConfTemplate.tpl");
    try {
        List<Group> groups = new ArrayList<>();
        List<Jvm> jvms = new ArrayList<>();
        List<WebServer> webServers = new ArrayList<>();
        List<Application> applications = new ArrayList<>();
        Group group = new Group(new Identifier<Group>(1111L),
                "groupName",
                new HashSet<>(jvms),
                new HashSet<>(webServers),
                new HashSet<History>(),
                new HashSet<>(applications));
        groups.add(group);
        applications.add(new Application(new Identifier<Application>(111L), "hello-world-1", "d:/jwala/app/archive", "/hello-world-1", group, true, true, false, "testWar.war", "d:/test1/deployPath"));
        applications.add(new Application(new Identifier<Application>(222L), "hello-world-2", "d:/jwala/app/archive", "/hello-world-2", group, true, true, false, "testWar.war", "d:/test2/deployPath"));
        applications.add(new Application(new Identifier<Application>(333L), "hello-world-3", "d:/jwala/app/archive", "/hello-world-3", group, true, true, false, "testWar.war", "d:/test3/deployPath"));
        WebServer webServer = new WebServer(new Identifier<WebServer>(1L), groups, "Apache2.4", "localhost", 80, 443,
                new com.cerner.jwala.common.domain.model.path.Path("/statusPath"), WebServerReachableState.WS_UNREACHABLE, null);
        webServers.add(webServer);
        jvms.add(new Jvm(new Identifier<Jvm>(11L), "tc1", "someHostGenerateMe", new HashSet<>(groups), 11010, 11011, 11012, -1, 11013,
                new com.cerner.jwala.common.domain.model.path.Path("/statusPath"), "EXAMPLE_OPTS=%someEvn%/someVal", JvmState.JVM_STOPPED, "", null, null, null, null, null, null, null));
        jvms.add(new Jvm(new Identifier<Jvm>(22L), "tc2", "someHostGenerateMe", new HashSet<>(groups), 11020, 11021, 11022, -1, 11023,
                new com.cerner.jwala.common.domain.model.path.Path("/statusPath"), "EXAMPLE_OPTS=%someEvn%/someVal", JvmState.JVM_STOPPED, "", null, null, null, null, null, null, null));

        when(Config.mockGroupPesistenceService.getGroups()).thenReturn(groups);
        when(Config.mockAppPersistenceService.findApplicationsBelongingTo(anyString())).thenReturn(applications);
        when(Config.mockJvmPersistenceService.getJvmsAndWebAppsByGroupName(anyString())).thenReturn(jvms);
        when(Config.mockWebServerPersistenceService.getWebServersByGroupName(anyString())).thenReturn(webServers);

        System.setProperty(ApplicationProperties.PROPERTIES_ROOT_PATH,
                this.getClass().getClassLoader().getResource("vars.properties").getPath().replace("vars.properties", ""));

        final ResourceGroup resourceGroup = resourceService.generateResourceGroup();
        String output = resourceService.generateResourceFile(ResourceGroovyMethods.getText(httpdTemplate), ResourceGroovyMethods.getText(httpdTemplate), resourceGroup, webServer, ResourceGeneratorType.TEMPLATE);

        String expected = ResourceGroovyMethods.getText(new File("../jwala-common/src/test/resources/HttpdConfTemplate-EXPECTED.conf"));
        expected = expected.replaceAll("\\r", "").replaceAll("\\n", "");
        output = output.replaceAll("\\r", "").replaceAll("\\n", "");
        String diff = StringUtils.difference(output, expected);
        assertEquals(expected, output);
    } catch (IOException e) {
        fail(e.getMessage());
    }
}
 
Example #22
Source Project: groovy   Author: apache   File: FileSystemResourceManager.java    License: Apache License 2.0 4 votes vote down vote up
public Reader getReader(String resourceName) throws IOException {
    return ResourceGroovyMethods.newReader(new File(basedir + resourceName));
}
 
Example #23
Source Project: groovy   Author: apache   File: GroovyRootDocBuilder.java    License: Apache License 2.0 4 votes vote down vote up
private void processFile(String filename, File srcFile, boolean isAbsolute) throws IOException {
    String src = ResourceGroovyMethods.getText(srcFile);
    String relPackage = GroovyDocUtil.getPath(filename).replace('\\', FS);
    String packagePath = isAbsolute ? "DefaultPackage" : relPackage;
    String file = GroovyDocUtil.getFile(filename);
    SimpleGroovyPackageDoc packageDoc = null;
    if (!isAbsolute) {
        packageDoc = (SimpleGroovyPackageDoc) rootDoc.packageNamed(packagePath);
    }
    // todo: this might not work correctly for absolute paths
    if (filename.endsWith("package.html") || filename.endsWith("package-info.java") || filename.endsWith("package-info.groovy")) {
        if (packageDoc == null) {
            packageDoc = new SimpleGroovyPackageDoc(relPackage);
            packagePath = relPackage;
        }
        processPackageInfo(src, filename, packageDoc);
        rootDoc.put(packagePath, packageDoc);
        return;
    }
    try {
        GroovyDocParserI docParser = new GroovyDocParser(links, properties);
        Map<String, GroovyClassDoc> classDocs = docParser.getClassDocsFromSingleSource(packagePath, file, src);
        rootDoc.putAllClasses(classDocs);
        if (isAbsolute) {
            Iterator<Map.Entry<String, GroovyClassDoc>> iterator = classDocs.entrySet().iterator();
            if (iterator.hasNext()) {
                final Map.Entry<String, GroovyClassDoc> docEntry = iterator.next();
                String fullPath = docEntry.getValue().getFullPathName();
                int slash = fullPath.lastIndexOf(FS);
                if (slash > 0) packagePath = fullPath.substring(0, slash);
                packageDoc = (SimpleGroovyPackageDoc) rootDoc.packageNamed(packagePath);
            }
        }
        if (packageDoc == null) {
            packageDoc = new SimpleGroovyPackageDoc(packagePath);
        }
        packageDoc.putAll(classDocs);
        rootDoc.put(packagePath, packageDoc);
    } catch (RuntimeException e) {
        e.printStackTrace(System.err);
        log.error("ignored due to parsing exception: " + filename + " [" + e.getMessage() + "]");
        log.debug("ignored due to parsing exception: " + filename + " [" + e.getMessage() + "]", e);
    }
}
 
Example #24
Source Project: groovy   Author: apache   File: GroovyDocTest.java    License: Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
    ResourceGroovyMethods.deleteDir(tmpDir);
}
 
Example #25
Source Project: groovy   Author: apache   File: BSFTest.java    License: Apache License 2.0 4 votes vote down vote up
protected void execScript(String fileName) throws Exception {
    manager.exec("groovy", fileName, 0, 0, ResourceGroovyMethods.getText(new File(fileName)));
}
 
Example #26
Source Project: groovy   Author: apache   File: GroovyCodeSource.java    License: Apache License 2.0 4 votes vote down vote up
public GroovyCodeSource(final File infile, final String encoding) throws IOException {
    // avoid files which confuse us like ones with .. in path
    final File file = new File(infile.getCanonicalPath());
    if (!file.exists()) {
        throw new FileNotFoundException(file.toString() + " (" + file.getAbsolutePath() + ")");
    }
    if (file.isDirectory()) {
        throw new IllegalArgumentException(file.toString() + " (" + file.getAbsolutePath() + ") is a directory not a Groovy source file.");
    }
    try {
        if (!file.canRead())
            throw new RuntimeException(file.toString() + " can not be read. Check the read permission of the file \"" + file.toString() + "\" (" + file.getAbsolutePath() + ").");
    }
    catch (SecurityException e) {
        throw e;
    }

    this.file = file;
    this.cachable = true;
    //The calls below require access to user.dir - allow here since getName() and getCodeSource() are
    //package private and used only by the GroovyClassLoader.
    try {
        Object[] info = AccessController.doPrivileged((PrivilegedExceptionAction<Object[]>) () -> {
            // retrieve the content of the file using the provided encoding
            if (encoding != null) {
                scriptText = ResourceGroovyMethods.getText(infile, encoding);
            } else {
                scriptText = ResourceGroovyMethods.getText(infile);
            }

            Object[] info1 = new Object[2];
            URL url = file.toURI().toURL();
            info1[0] = url.toExternalForm();
            //toURI().toURL() will encode, but toURL() will not.
            info1[1] = new CodeSource(url, (Certificate[]) null);
            return info1;
        });

        this.name = (String) info[0];
        this.codeSource = (CodeSource) info[1];
    } catch (PrivilegedActionException pae) {
        Throwable cause = pae.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw new RuntimeException("Could not construct CodeSource for file: " + file, cause);
    }
}
 
Example #27
Source Project: groovy   Author: apache   File: GroovyMain.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Get the text of the Groovy script at the given location.
 * If the location is a file path and it does not exist as given,
 * then {@link GroovyMain#huntForTheScriptFile(String)} is called to try
 * with some Groovy extensions appended.
 *
 * This method is not used to process scripts and is retained for backward
 * compatibility.  If you want to modify how GroovyMain processes scripts
 * then use {@link GroovyMain#getScriptSource(boolean, String)}.
 *
 * @param uriOrFilename
 * @return the text content at the location
 * @throws IOException
 * @deprecated
 */
@Deprecated
public String getText(String uriOrFilename) throws IOException {
    if (URI_PATTERN.matcher(uriOrFilename).matches()) {
        try {
            return ResourceGroovyMethods.getText(new URL(uriOrFilename));
        } catch (Exception e) {
            throw new GroovyRuntimeException("Unable to get script from URL: ", e);
        }
    }
    return ResourceGroovyMethods.getText(huntForTheScriptFile(uriOrFilename));
}
 
Example #28
Source Project: groovy   Author: apache   File: BaseTemplate.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Includes contents of another file, not as a template but as escaped text.
 *
 * @param templatePath the path to the other file
 * @throws IOException
 */
public void includeEscaped(String templatePath) throws IOException {
    URL resource = engine.resolveTemplate(templatePath);
    yield(ResourceGroovyMethods.getText(resource, engine.getCompilerConfiguration().getSourceEncoding()));
}
 
Example #29
Source Project: groovy   Author: apache   File: BaseTemplate.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Includes contents of another file, not as a template but as unescaped text.
 *
 * @param templatePath the path to the other file
 * @throws IOException
 */
public void includeUnescaped(String templatePath) throws IOException {
    URL resource = engine.resolveTemplate(templatePath);
    yieldUnescaped(ResourceGroovyMethods.getText(resource, engine.getCompilerConfiguration().getSourceEncoding()));
}
 
Example #30
Source Project: groovy   Author: apache   File: GPathResult.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Converts the text of this GPathResult to a URL object.
 *
 * @return the GPathResult, converted to a <code>URL</code>
 */
public URL toURL() throws MalformedURLException {
    return ResourceGroovyMethods.toURL((CharSequence)text());
}