001/*
002 * Copyright 2012-2014 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.boot.loader.tools;
018
019import java.io.File;
020import java.io.IOException;
021import java.util.Arrays;
022
023import org.springframework.util.Assert;
024import org.springframework.util.StringUtils;
025
026/**
027 * Provides access to the java binary executable, regardless of OS.
028 *
029 * @author Phillip Webb
030 * @since 1.1.0
031 */
032public class JavaExecutable {
033
034        private File file;
035
036        public JavaExecutable() {
037                String javaHome = System.getProperty("java.home");
038                Assert.state(StringUtils.hasLength(javaHome),
039                                "Unable to find java executable due to missing 'java.home'");
040                this.file = findInJavaHome(javaHome);
041        }
042
043        private File findInJavaHome(String javaHome) {
044                File bin = new File(new File(javaHome), "bin");
045                File command = new File(bin, "java.exe");
046                command = (command.exists() ? command : new File(bin, "java"));
047                Assert.state(command.exists(), "Unable to find java in " + javaHome);
048                return command;
049        }
050
051        /**
052         * Create a new {@link ProcessBuilder} that will run with the Java executable.
053         * @param arguments the command arguments
054         * @return a {@link ProcessBuilder}
055         */
056        public ProcessBuilder processBuilder(String... arguments) {
057                ProcessBuilder processBuilder = new ProcessBuilder(toString());
058                processBuilder.command().addAll(Arrays.asList(arguments));
059                return processBuilder;
060        }
061
062        @Override
063        public String toString() {
064                try {
065                        return this.file.getCanonicalPath();
066                }
067                catch (IOException ex) {
068                        throw new IllegalStateException(ex);
069                }
070        }
071
072}