Java 类org.gradle.api.tasks.TaskExecutionException 实例源码

项目:gradle-circle-style    文件:CircleBuildFailureListener.java   
@Override
public synchronized void afterExecute(Task task, TaskState state) {
    if (isUntracked(task)) {
        Report.TestCase.Builder testCase = new Report.TestCase.Builder()
                .name(":" + task.getProject().getName() + ":" + task.getName());

        Throwable failure = state.getFailure();
        if (failure != null && isUntracked(task)) {
            if (failure instanceof TaskExecutionException && failure.getCause() != null) {
                failure = failure.getCause();
            }
            StringWriter stackTrace = new StringWriter();
            failure.printStackTrace(new PrintWriter(stackTrace));

            testCase.failure(new Report.Failure.Builder()
                    .message(getMessage(failure))
                    .details(stackTrace.toString())
                    .build());
        }
        testCases.add(testCase.build());
    }
}
项目:Reer    文件:DefaultExceptionAnalyser.java   
private Throwable findDeepestRootException(Throwable exception) {
    // TODO: fix the way we work out which exception is important: TaskExecutionException is not always the most helpful
    Throwable locationAware = null;
    Throwable result = null;
    Throwable contextMatch = null;
    for (Throwable current = exception; current != null; current = current.getCause()) {
        if (current instanceof LocationAwareException) {
            locationAware = current;
        } else if (current instanceof GradleScriptException || current instanceof TaskExecutionException) {
            result = current;
        } else if (contextMatch == null && current.getClass().getAnnotation(Contextual.class) != null) {
            contextMatch = current;
        }
    }
    if (locationAware != null) {
        return locationAware;
    } else if (result != null) {
        return result;
    } else if (contextMatch != null) {
        return contextMatch;
    } else {
        return exception;
    }
}
项目:gretl    文件:IliValidator.java   
@TaskAction
public void validate() {
    log = LogEnvironment.getLogger(IliValidator.class);

    if (dataFiles==null || dataFiles.size()==0) {
        return;
    }
    List<String> files=new ArrayList<String>();
    for(Object fileObj:dataFiles) {
        String fileName=this.getProject().file(fileObj).getPath();
        files.add(fileName);
    }

    Settings settings=new Settings();
    initSettings(settings);
    validationOk=new Validator().validate(files.toArray(new String[files.size()]), settings);
    if(!validationOk && failOnError) {
        throw new TaskExecutionException(this,new Exception("validation failed"));
    }
}
项目:gretl    文件:ShpValidator.java   
@TaskAction
public void validate() {
    log = LogEnvironment.getLogger(ShpValidator.class);

    if (dataFiles==null || dataFiles.size()==0) {
        return;
    }
    List<String> files=new ArrayList<String>();
    for(Object fileObj:dataFiles) {
        String fileName=this.getProject().file(fileObj).getPath();
        files.add(fileName);
    }

    Settings settings=new Settings();
    initSettings(settings);
    if(encoding!=null) {
        settings.setValue(ShapeReader.ENCODING, encoding);
    }

    validationOk=new ShpValidatorImpl().validate(files.toArray(new String[files.size()]), settings);
    if(!validationOk && failOnError) {
        throw new TaskExecutionException(this,new Exception("validation failed"));
    }
}
项目:neo-java-web-gradle-plugin    文件:InstallLocal.java   
@TaskAction
public void installLocal() {
    getLogger().info("Entering installLocal task class");


    getLogger().info("Preparing command " + CommandsAndParams.COMMAND_INSTALL_LOCAL);
    List<String> command = new ArrayList<>();

    command.add(CommandsAndParams.COMMAND_INSTALL_LOCAL);
    command.add(CommandsAndParams.PARAM_LOCATION);
    try {
        command.add(getExtension().getServerLocation());
        getLogger().info("Intstalling Server to: " + getExtension().getServerLocation() );
    } catch (Throwable e) {
        throw new TaskExecutionException(this, e);
    }


    getLogger().info("Running command " + CommandsAndParams.COMMAND_INSTALL_LOCAL + " with params. " + command.toString());
    cliRunner(command);
}
项目:neo-java-web-gradle-plugin    文件:Stop.java   
/**
 * Stops the application in the Sap Cloud Platform account
 */

//TODO implement --synchronous
@TaskAction
public void start() {
    getLogger().info("Entering Stop task..");

    List<String> command;
    try {
        command = super.baseCommandlineArguments(CommandsAndParams.COMMAND_STOP);
    } catch (Throwable e) {
        throw new TaskExecutionException(this, e);
    }

    getLogger().info("Running command " + CommandsAndParams.COMMAND_STOP + " with params. " + command.toString());
    cliRunner(command);

}
项目:neo-java-web-gradle-plugin    文件:Start.java   
/**
 * Starts the application in the Sap Cloud Platform account
 */

//TODO implement --synchronous
@TaskAction
public void start() {
    getLogger().info("Entering Start task..");

    List<String> command;
    try {
        command = super.baseCommandlineArguments(CommandsAndParams.COMMAND_START);
    } catch (Throwable e) {
        throw new TaskExecutionException(this, e);
    }


    getLogger().info("Running command " + CommandsAndParams.COMMAND_START + " with params. " + command.toString());
    cliRunner(command);

}
项目:neo-java-web-gradle-plugin    文件:Restart.java   
/**
 * Restarts the application in the Sap Cloud Platform account
 */

//TODO implement --synchronous and restart single process id
@TaskAction
public void start() {
    getLogger().info("Entering Restart task..");

    List<String> command;
    try {
        command = super.baseCommandlineArguments(CommandsAndParams.COMMAND_RESTART);
    } catch (Throwable e) {
        throw new TaskExecutionException(this, e);
    }


    getLogger().info("Running command " + CommandsAndParams.COMMAND_RESTART + " with params. " + command.toString());
    cliRunner(command);

}
项目:Pushjet-Android    文件:DefaultExceptionAnalyser.java   
private Throwable findDeepestRootException(Throwable exception) {
    // TODO: fix the way we work out which exception is important: TaskExecutionException is not always the most helpful
    Throwable locationAware = null;
    Throwable result = null;
    Throwable contextMatch = null;
    for (Throwable current = exception; current != null; current = current.getCause()) {
        if (current instanceof LocationAwareException) {
            locationAware = current;
        } else if (current instanceof GradleScriptException || current instanceof TaskExecutionException) {
            result = current;
        } else if (contextMatch == null && current.getClass().getAnnotation(Contextual.class) != null) {
            contextMatch = current;
        }
    }
    if (locationAware != null) {
        return locationAware;
    } else if (result != null) {
        return result;
    } else if (contextMatch != null) {
        return contextMatch;
    } else {
        return exception;
    }
}
项目:Pushjet-Android    文件:DefaultExceptionAnalyser.java   
private Throwable findDeepestRootException(Throwable exception) {
    // TODO: fix the way we work out which exception is important: TaskExecutionException is not always the most helpful
    Throwable locationAware = null;
    Throwable result = null;
    Throwable contextMatch = null;
    for (Throwable current = exception; current != null; current = current.getCause()) {
        if (current instanceof LocationAwareException) {
            locationAware = current;
        } else if (current instanceof GradleScriptException || current instanceof TaskExecutionException) {
            result = current;
        } else if (contextMatch == null && current.getClass().getAnnotation(Contextual.class) != null) {
            contextMatch = current;
        }
    }
    if (locationAware != null) {
        return locationAware;
    } else if (result != null) {
        return result;
    } else if (contextMatch != null) {
        return contextMatch;
    } else {
        return exception;
    }
}
项目:jenetics    文件:Lyx2PDFTask.java   
private void convert() {
    final File workingDir = _document.getParentFile();
    final String documentName = _document.getName();

    final ProcessBuilder builder = new ProcessBuilder(
        BINARY, "-e", "pdf2", documentName
    );
    builder.directory(workingDir);
    builder.redirectErrorStream(true);
    getLogger().debug(workingDir + "/" + documentName);

    try {
        final Process process = builder.start();
        output(process.getInputStream());
        _exitValue = process.waitFor();
        if (_exitValue != 0) {
            getLogger().lifecycle("Error while generating PDF.");
            getLogger().lifecycle("Manual PDF has not been created.");
        }
    } catch (IOException | InterruptedException e) {
        throw new TaskExecutionException(this, e);
    }
}
项目:jenetics    文件:ChecksumTask.java   
@TaskAction
public void checksum() {
    try {
        final MessageDigest digest = MessageDigest.getInstance(_algorithm);

        // Read the file.
        try (FileInputStream in = new FileInputStream(_inputFile)) {
            final byte[] data = new byte[4096];
            for (int l = in.read(data); l != -1; l = in.read(data)) {
                digest.update(data, 0, l);
            }
        }

        // Write the checksum file.
        try (FileOutputStream out = new FileOutputStream(getChecksumFile())) {
            out.write(toString(digest.digest()).getBytes());
        }
    } catch (NoSuchAlgorithmException | IOException e) {
        throw new TaskExecutionException(this, e);
    }
}
项目:gradle-download-task    文件:TimeoutTest.java   
/**
 * Tests that the task times out if the response takes too long
 * @throws Exception if anything else goes wrong
 */
@Test
public void timeout() throws Exception {
    Download t = makeProjectAndTask();
    t.timeout(TIMEOUT_MS);
    assertEquals(TIMEOUT_MS, t.getTimeout());
    t.src(makeSrc(TIMEOUT));
    File dst = folder.newFile();
    t.dest(dst);
    try {
        t.execute();
        fail("Connection should have timed out by now");
    } catch (TaskExecutionException e) {
        assertTrue(e.getCause() instanceof UncheckedIOException);
        assertTrue(e.getCause().getCause() instanceof SocketTimeoutException);
    }
}
项目:gradle-download-task    文件:VerifyTest.java   
/**
 * Tests if the Verify task fails if the checksum is wrong
 * @throws Exception if anything goes wrong
 */
@Test(expected = TaskExecutionException.class)
public void verifyWrongMD5() throws Exception {
    Download t = makeProjectAndTask();
    t.src(makeSrc(TEST_FILE_NAME));
    File dst = folder.newFile();
    t.dest(dst);

    Verify v = makeVerifyTask(t);
    v.algorithm("MD5");
    v.checksum("WRONG");
    v.src(t.getDest());

    t.execute();
    v.execute(); // should throw
}
项目:Reer    文件:VerifyNoInputChangesTaskExecuter.java   
@Override
public void execute(TaskInternal task, TaskStateInternal state, TaskExecutionContext context) {
    BuildCacheKey beforeExecution = context.getTaskArtifactState().calculateCacheKey();
    delegate.execute(task, state, context);
    if (beforeExecution != null) {
        BuildCacheKey afterExecution = repository.getStateFor(task).calculateCacheKey();
        if (afterExecution == null || !beforeExecution.getHashCode().equals(afterExecution.getHashCode())) {
            throw new TaskExecutionException(task, new GradleException("The inputs for the task changed during the execution! Check if you have a `doFirst` changing the inputs."));
        }
    }
}
项目:gretl    文件:CsvValidator.java   
@TaskAction
public void validate() {
    log = LogEnvironment.getLogger(CsvValidator.class);

    if (dataFiles==null || dataFiles.size()==0) {
        return;
    }
    List<String> files=new ArrayList<String>();
    for(Object fileObj:dataFiles) {
        String fileName=this.getProject().file(fileObj).getPath();
        files.add(fileName);
    }

    Settings settings=new Settings();
    initSettings(settings);
    // set optional parameters
    settings.setValue(IoxWkfConfig.SETTING_FIRSTLINE,firstLineIsHeader?IoxWkfConfig.SETTING_FIRSTLINE_AS_HEADER:IoxWkfConfig.SETTING_FIRSTLINE_AS_VALUE);
    if(valueDelimiter!=null) {
        settings.setValue(IoxWkfConfig.SETTING_VALUEDELIMITER,valueDelimiter.toString());
    }
    if(valueSeparator!=null) {
        settings.setValue(IoxWkfConfig.SETTING_VALUESEPARATOR,valueSeparator.toString());
    }
    if(encoding!=null) {
        settings.setValue(CsvReader.ENCODING, encoding);
    }

    validationOk=new CsvValidatorImpl().validate(files.toArray(new String[files.size()]), settings);
    if(!validationOk && failOnError) {
        throw new TaskExecutionException(this,new Exception("validation failed"));
    }
}
项目:neo-java-web-gradle-plugin    文件:TestTask.java   
@TaskAction
private void pub() {
    getLogger().info(getExtension().toString());
    try {
        getLogger().info("USER from gradle user home: " + getExtension().getUser() );
    } catch (Throwable e) {
        throw new TaskExecutionException(this, e);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:BuildInfo.java   
@TaskAction
public void generateBuildProperties() {
    try {
        new BuildPropertiesWriter(this.outputFile)
                .writeBuildProperties(new ProjectDetails(this.projectGroup,
                        this.projectArtifact, this.projectVersion, this.projectName,
                        coerceToStringValues(this.additionalProperties)));
    }
    catch (IOException ex) {
        throw new TaskExecutionException(this, ex);
    }
}
项目:parsec    文件:ParsecGenerateTask.java   
/**
 * RDL generate.
 *
 * @param type type
 * @param sourcePath source path
 * @param options options
 * @throws TaskExecutionException TaskExecutionException
 */
void rdlGenerate(
    final String executable,
    String type,
    String sourcePath,
    List<String> options
) throws TaskExecutionException {
    try {
        File f = new File(executable);
        List<String> command =  new ArrayList<>();
        command.addAll(Arrays.asList(executable, "generate", type, sourcePath));
        command.addAll(2, options);

        getLogger().info(" Generating " + type);
        ProcessBuilder processBuilder = new ProcessBuilder(command)
            .directory(getProject().getProjectDir())
            .inheritIO();

        // Add execute PATH
        Map<String, String> env = processBuilder.environment();
        env.put("PATH", pathUtils.getBinPath());
        Process process = processBuilder.start();

        int errorCode = process.waitFor();
        if (errorCode != 0) {
            throw new IOException("Error parsing RDL file " + sourcePath);
        }
    } catch (IOException | InterruptedException e) {
        throw new TaskExecutionException(this, e);
    }
}
项目:spring-boot-concourse    文件:BuildInfo.java   
@TaskAction
public void generateBuildProperties() {
    try {
        new BuildPropertiesWriter(this.outputFile)
                .writeBuildProperties(new ProjectDetails(this.projectGroup,
                        this.projectArtifact, this.projectVersion, this.projectName,
                        coerceToStringValues(this.additionalProperties)));
    }
    catch (IOException ex) {
        throw new TaskExecutionException(this, ex);
    }
}
项目:spotless    文件:PaddedCellTaskTest.java   
private String checkFailureMsg() {
    try {
        check.execute();
        throw new AssertionError();
    } catch (TaskExecutionException e) {
        GradleException cause = (GradleException) e.getCause();
        return cause.getMessage();
    }
}
项目:spotless    文件:DiffMessageFormatterTest.java   
protected String getTaskErrorMessage(SpotlessTask task) {
    try {
        task.execute();
        throw new AssertionError("Expected a TaskExecutionException");
    } catch (TaskExecutionException e) {
        GradleException cause = (GradleException) e.getCause();
        return cause.getMessage();
    }
}
项目:gradle-xray    文件:XrayTask.java   
@TaskAction
public void runXray() {
    XrayReportProcessor processor = new XrayReportProcessor();
    System.out.println("Running tests at " + url);
    long startTime = Calendar.getInstance().getTimeInMillis();
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpUriRequest request = new HttpGet(url);
    String json = null;
    try {
        HttpResponse httpResponse = client.execute(request);
        json = EntityUtils.toString(httpResponse.getEntity());
        if (json != null) {
            XrayReport report = processor.processXrayReport(json);
            long endTime = Calendar.getInstance().getTimeInMillis();
            System.out.println(report.getPassedTests() + "/" + report.getTotalTests() + " Xray tests passed in " + ((endTime - startTime) / 1000) + " seconds");
            System.out.println(report.getIgnoredTests() + " Xray tests ignored");
            if (!report.getErrors().isEmpty()) {
                for (String failedTest : report.getErrors()) {
                    System.out.println(failedTest);
                }
                throw new TaskExecutionException(this, new RuntimeException("xray tests failed"));
            }
        } else {
            System.out.println("xray failed");
            throw new TaskExecutionException(this, new RuntimeException("xray failed"));
        }
    } catch (IOException e) {
        System.out.println("xray failed");
        throw new TaskExecutionException(this, e);
    }
}
项目:jenetics    文件:ColorizerTask.java   
@TaskAction
public void colorize() {
    try {
        final Colorizer colorizer = new Colorizer(_directory);
        colorizer.colorize();

        getLogger().lifecycle(
            "Colorizer processed {} files and modified {}.",
            colorizer.getProcessed(), colorizer.getModified()
        );
    } catch (final IOException e) {
        throw new TaskExecutionException(this, e);
    }
}
项目:gradle-download-task    文件:DownloadTest.java   
/**
 * Tests if the task throws an exception if you try to download
 * multiple files to a single destination file
 * @throws Exception if anything goes wrong
 */
@Test(expected = TaskExecutionException.class)
public void downloadMultipleFilesToFile() throws Exception {
    Download t = makeProjectAndTask();
    t.src(Arrays.asList(makeSrc(TEST_FILE_NAME), makeSrc(TEST_FILE_NAME2)));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();
}
项目:gradle-download-task    文件:ContentLengthTest.java   
/**
 * Tests if the plugin can handle an incorrect Content-Length header
 * @throws Exception if anything goes wrong
 */
@Test(expected = TaskExecutionException.class)
public void tooLargeContentLength() throws Exception {
    contentLength = "10000";

    Download t = makeProjectAndTask();
    t.src(makeSrc(CONTENT_LENGTH));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();
}
项目:gradle-download-task    文件:SslTest.java   
/**
 * Tests if connecting to a HTTPS URL fails if the certificate is unknown
 * @throws Exception if anything goes wrong
 */
@Test(expected = TaskExecutionException.class)
public void unknownCertificate() throws Exception {
    Download t = makeProjectAndTask();
    t.src(makeSrc(SSL).replace("http", "https"));
    File dst = folder.newFile();
    t.dest(dst);
    assertFalse(t.isAcceptAnyCertificate());
    t.execute();
}
项目:gradle-download-task    文件:RedirectTest.java   
/**
 * Tests if the plugin can handle circular redirects
 * @throws Exception if anything goes wrong
 */
@Test(expected = TaskExecutionException.class)
public void circularRedirect() throws Exception {
    redirects = 10;
    circular = true;

    Download t = makeProjectAndTask();
    t.src(makeSrc(REDIRECT));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();
}
项目:gradle-download-task    文件:RedirectTest.java   
/**
 * Make sure the plugin fails with too many redirects
 * @throws Exception if anything goes wrong
 */
@Test(expected = TaskExecutionException.class)
public void tooManyRedirects() throws Exception {
    redirects = 51;

    Download t = makeProjectAndTask();
    t.src(makeSrc(REDIRECT));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();
}
项目:gradle-download-task    文件:AuthenticationTest.java   
/**
 * Tests if the plugin can handle failed authentication
 * @throws Exception if anything goes wrong
 */
@Test(expected = TaskExecutionException.class)
public void noAuthorization() throws Exception {
    Download t = makeProjectAndTask();
    t.src(makeSrc(AUTHENTICATE));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();
}
项目:gradle-download-task    文件:AuthenticationTest.java   
/**
 * Tests if the plugin can handle failed authentication
 * @throws Exception if anything goes wrong
 */
@Test(expected = TaskExecutionException.class)
public void invalidCredentials() throws Exception {
    Download t = makeProjectAndTask();
    t.src(makeSrc(AUTHENTICATE));
    File dst = folder.newFile();
    t.dest(dst);
    t.username(USERNAME + "!");
    t.password(PASSWORD + "!");
    t.execute();
}
项目:gradle-download-task    文件:AuthenticationTest.java   
/**
 * Make sure the plugin rejects an invalid authentication scheme if
 * username and password are set
 * @throws Exception if anything goes wrong
 */
@Test(expected = TaskExecutionException.class)
public void invalidAuthSchemeWithUserAndPass() throws Exception {
    Download t = makeProjectAndTask();
    t.src(makeSrc(AUTHENTICATE));
    File dst = folder.newFile();
    t.dest(dst);
    t.username(USERNAME);
    t.password(PASSWORD);
    t.authScheme(new NTLMScheme());
    t.execute();
}
项目:Reer    文件:JsHint.java   
@TaskAction
public void doJsHint() {
    RhinoWorkerHandleFactory handleFactory = new DefaultRhinoWorkerHandleFactory(getWorkerProcessBuilderFactory());

    LogLevel logLevel = getProject().getGradle().getStartParameter().getLogLevel();
    JsHintProtocol worker = handleFactory.create(getRhinoClasspath(), JsHintProtocol.class, JsHintWorker.class, logLevel, getProject().getProjectDir());

    JsHintSpec spec = new JsHintSpec();
    spec.setSource(getSource().getFiles()); // flatten because we need to serialize
    spec.setEncoding(getEncoding());
    spec.setJsHint(getJsHint().getSingleFile());

    JsHintResult result = worker.process(spec);
    setDidWork(true);

    // TODO - this is all terribly lame. We need some proper reporting here (which means implementing Reporting).

    Logger logger = getLogger();
    boolean anyErrors = false;

    Map<String, Map<?, ?>> reportData = new LinkedHashMap<String, Map<?, ?>>(result.getResults().size());
    for (Map.Entry<File, Map<String, Object>> fileEntry: result.getResults().entrySet()) {
        File file = fileEntry.getKey();
        Map<String, Object> data = fileEntry.getValue();

        reportData.put(file.getAbsolutePath(), data);

        if (data.containsKey("errors")) {
            anyErrors = true;

            URI projectDirUri = getProject().getProjectDir().toURI();
            @SuppressWarnings("unchecked") Map<String, Object> errors = (Map<String, Object>) data.get("errors");
            if (!errors.isEmpty()) {
                URI relativePath = projectDirUri.relativize(file.toURI());
                logger.warn("JsHint errors for file: {}", relativePath.getPath());
                for (Map.Entry<String, Object> errorEntry : errors.entrySet()) {
                    @SuppressWarnings("unchecked") Map<String, Object> error = (Map<String, Object>) errorEntry.getValue();
                    int line = Float.valueOf(error.get("line").toString()).intValue();
                    int character = Float.valueOf(error.get("character").toString()).intValue();
                    String reason = error.get("reason").toString();

                    logger.warn("  {}:{} > {}", new Object[] {line, character, reason});
                }
            }
        }
    }

    File jsonReportFile = getJsonReport();
    if (jsonReportFile != null) {
        try {
            FileWriter reportWriter = new FileWriter(jsonReportFile);
            new GsonBuilder().setPrettyPrinting().create().toJson(reportData, reportWriter);
            reportWriter.close();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    if (anyErrors) {
        throw new TaskExecutionException(this, new GradleException("JsHint detected errors"));
    }
}
项目:neo-java-web-gradle-plugin    文件:Deploy.java   
@TaskAction
public void deploy() {
    getLogger().info("Entering deploy task class");
    List<String> commands = null;
    try {
        commands = super.baseCommandlineArguments(CommandsAndParams.COMMAND_DEPLOY);

        commands.add(CommandsAndParams.PARAM_SOURCE);
        commands.add(getExtension().getSourceFileLocation());
        commands.add(CommandsAndParams.PARAM_RUNTIME_VERSION);
        commands.add(getExtension().getRuntimeVersion());
        commands.add(CommandsAndParams.PARAM_RUNTIME);
        commands.add(getExtension().getRuntime());

    } catch (Throwable e) {
        throw new TaskExecutionException(this, e);
    }

    // Now we add optional parameters
    if (getExtension().getEnviromentVariables() != null && !getExtension().getEnviromentVariables().isEmpty()) {
        getLogger().info("Adding enviroment Variables");
        Set<Entry<String, String>> set = getExtension().getEnviromentVariables().entrySet();
        for (Entry<String, String> entry : set) {
            commands.add(CommandsAndParams.PARAM_ENV_VARS);
            commands.add(entry.getKey() + "=" + entry.getValue());
        }

    }

    // jvm arguments
    if (getExtension().getJvmArgs() != null && !getExtension().getJvmArgs().isEmpty()) {
        getLogger().info("Adding jvm args");
        for (String jvmArg : getExtension().getJvmArgs()) {
            commands.add(CommandsAndParams.PARAM_JVM_ARGS);
            commands.add(jvmArg);
        }
    }
    // Delta Deploy
    if (getExtension().isDelta()) {
        getLogger().info("Adding delta deploy");
        commands.add(CommandsAndParams.PARAM_DELTA);
    }

    //FIXME password is visible
    getLogger()
            .info("Running command " + CommandsAndParams.COMMAND_DEPLOY + " with params. " + commands.toString());
    cliRunner(commands);

}
项目:parsec    文件:ParsecInitTask.java   
/**
 * Execute.
 *
 * @throws TaskExecutionException TaskExecutionException
 */
@TaskAction
public void executeTask() throws TaskExecutionException {

    try {
        // Create ${buildDir}/bin
        fileUtils.checkAndCreateDirectory(pathUtils.getBinPath());
        String rdlBinSuffix = System.getProperty("os.name").equals("Mac OS X") ? "darwin" : "linux";

        // Extract rdl parser to ${buildDir}/bin
        extractRdlBinary(rdlBinSuffix);

        // Extract generator
        extractParsecRdlGenerator(rdlBinSuffix,
                Arrays.asList("java-model", "java-server", "java-client", "swagger"));

        // Create ${baseDir}/parsec-bin
        fileUtils.checkAndCreateDirectory(pathUtils.getBinPath());

        // Copy all scripts under resource/scripts to ${baseDir}/parsec-bin
        for (Path scriptPath : fileUtils.listDirFilePaths("scripts")) {
            String scriptPathString = scriptPath.toString();
            if (scriptPathString.endsWith(".sh") || scriptPathString.endsWith(".rb")) {
                fileUtils.writeResourceAsExecutable(
                    scriptPath.toString(),
                    pathUtils.getBinPath() + "/" + scriptPath.getFileName()
                );
            }
        }
        String test = pathUtils.getBinPath();
        if (pluginExtension.isGenerateSwagger()) {
            String swaggerUIPath = pathUtils.getSwaggerUIPath();

            // Create ${buildDir}/generated-resources/swagger-ui
            fileUtils.checkAndCreateDirectory(swaggerUIPath);

            // Extract swagger-ui archive if ${buildDir}/generated-resources/swagger-ui is empty
            if (new File(swaggerUIPath).list().length <= 0) {
                fileUtils.unTarZip("/swagger-ui/swagger-ui.tgz", swaggerUIPath, true);
            }
        }
    } catch (IOException e) {
        throw new TaskExecutionException(this, e);
    }
}
项目:gradle-backup-plugin    文件:ObtainGoogleDriveTokensTask.java   
/**
 * Initiates Google Drive tokens obtaining flow.
 */
@TaskAction
public void run() {
    final Console console = System.console();

    if (null == console) {
        throw new TaskExecutionException(this,
                new UnsupportedOperationException("This task cannot be run without console."));
    }

    try {
        Preconditions.checkNotNull(this.clientId, "Google Drive client ID must not be null");
        Preconditions.checkNotNull(this.clientSecret, "Google Drive client secret must not be null");

        final HttpTransport transport = new NetHttpTransport();
        final JsonFactory jsonFactory = new JacksonFactory();
        final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
                .Builder(transport, jsonFactory, clientId, clientSecret, Arrays.asList(DriveScopes.DRIVE))
                .build();
        final String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();

        System.out.println((new Ansi()).
                a("Navigate to the following url: ").
                fg(Ansi.Color.YELLOW).
                a(url).
                reset().
                a(", and then paste the authorization code here:"));

        final String authorizationCode = console.readLine().trim();
        final GoogleTokenResponse tokenResponse = flow.newTokenRequest(authorizationCode)
                .setRedirectUri(REDIRECT_URI)
                .execute();

        System.out.println((new Ansi()).
                a("Your access token is ").
                fg(Ansi.Color.YELLOW).
                a(tokenResponse.getAccessToken()).
                reset().
                a(". Store it somewhere for future use. It will expire in ").
                a(tokenResponse.getExpiresInSeconds()).
                a(" seconds"));
        System.out.println((new Ansi()).
                a("Your refresh token is ").
                fg(Ansi.Color.YELLOW).
                a(tokenResponse.getRefreshToken()).
                reset().
                a(". Store it somewhere for future use."));
    } catch (IOException ioException) {
        throw new TaskExecutionException(this, ioException);
    }
}
项目:gradle-backup-plugin    文件:GoogleDriveUploadTask.java   
/**
 * Uploads {@link #setArchive(File) specified file} to Google Drive.
 */
@TaskAction
public void run() {
    try {
        Preconditions.checkNotNull(this.clientId, "Google Drive client ID must not be null");
        Preconditions.checkNotNull(this.clientSecret, "Google Drive client secret must not be null");
        Preconditions.checkNotNull(this.accessToken, "Google Drive access token must not be null");
        Preconditions.checkNotNull(this.refreshToken, "Google Drive refresh token must not be null");
        Preconditions.checkNotNull(this.archive, "Archive must not be null");
        Preconditions.checkArgument(this.archive.exists(), "Archive must exist");
        Preconditions.checkArgument(this.archive.isFile(), "Archive must be a file");

        final Drive drive = constructDrive();

        final com.google.api.services.drive.model.File parent = locateParent(drive);

        final com.google.api.services.drive.model.File descriptor = new com.google.api.services.drive.model.File();
        final FileContent content = new FileContent(mimeType, archive);

        if (null != parent) {
            descriptor.setParents(Arrays.<ParentReference>asList(new ParentReference().setId(parent.getId())));
        }
        descriptor.setMimeType(content.getType());
        descriptor.setTitle(content.getFile().getName());

        final Drive.Files.Insert insert = drive.files().insert(descriptor, content);
        final MediaHttpUploader uploader = insert.getMediaHttpUploader();

        uploader.setChunkSize(1 * 1024 * 1024 /* bytes */);

        if (listenForUpload) {
            uploader.setProgressListener(new MediaHttpUploaderProgressListener() {
                @Override
                public void progressChanged(MediaHttpUploader u) throws IOException {
                    final double progress = (double) u.getNumBytesUploaded() / content.getLength();

                    System.out.printf("\r[%-50.50s] %.2f%%", Strings.repeat("#", (int) (progress * 50)), progress * 100);
                    System.out.flush();
                }
            });
        }

        insert.execute();
    } catch (Exception e) {
        throw new TaskExecutionException(this, e);
    }
}
项目:gradle-download-task    文件:DownloadTest.java   
/**
 * Test if the plugin throws an exception if the 'src' property is empty
 */
@Test(expected = TaskExecutionException.class)
public void testExecuteEmptySrc() {
    Download t = makeProjectAndTask();
    t.execute();
}