com.formkiq.core.service.sign.MacWrapperConfig.java Source code

Java tutorial

Introduction

Here is the source code for com.formkiq.core.service.sign.MacWrapperConfig.java

Source

/*
 * Copyright (C) 2017 FormKiQ Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.formkiq.core.service.sign;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;

import com.github.jhonnymertz.wkhtmltopdf.wrapper.configurations.WrapperConfig;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.configurations.XvfbConfig;

/**
 * Custom wkhtmltopdf wrapper to handle Mac's Path not working.
 *
 */
public class MacWrapperConfig extends WrapperConfig {

    @Override
    public String findExecutable() {

        String osname = System.getProperty("os.name").toLowerCase();
        if (osname.startsWith("mac")) {
            return "/usr/local/bin/" + getWkhtmltopdfCommand();
        }

        return super.findExecutable();
    }

    /**
     * Attempts to find an executable in the system path.
     * @param executable {@link String}
     * @return {@link String}
     */
    public String findExecutable(final String executable) {
        try {
            String osname = System.getProperty("os.name").toLowerCase();

            String cmd = osname.contains("windows") ? "where " + executable : "which " + executable;

            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            String text = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());

            if (text.isEmpty()) {
                throw new RuntimeException();
            }

            return text;

        } catch (InterruptedException e) {
            return null;
        } catch (IOException e) {
            return null;
        } catch (RuntimeException e) {
            return null;
        }
    }

    @Override
    public void setXvfbConfig(final XvfbConfig xvfbConfig) {

        if (findExecutable(xvfbConfig.getCommand()) != null) {
            super.setXvfbConfig(xvfbConfig);
        } else {
            super.setXvfbConfig(null);
        }
    }
}