/*
 * Copyright 2016 ZJNU ACM.
 *
 * 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 cn.edu.zjnu.acm.judge.sandbox.win32;

import java.util.Objects;
import jnc.platform.win32.Kernel32;

import static jnc.platform.win32.WinBase.SEM_FAILCRITICALERRORS;
import static jnc.platform.win32.WinBase.SEM_NOGPFAULTERRORBOX;
import static jnc.platform.win32.WinBase.SEM_NOOPENFILEERRORBOX;

/**
 *
 * @author zhanhb
 */
@SuppressWarnings("PublicInnerClass")
public interface ProcessCreationHelper {

    static <V, E extends Throwable> V execute(ExceptionCallable<V, E> supplier) throws E {
        Objects.requireNonNull(supplier);
        synchronized (java.lang.Runtime.getRuntime()) {
            int oldErrorMode = Kernel32.INSTANCE.SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
            try {
                return supplier.call();
            } finally {
                Kernel32.INSTANCE.SetErrorMode(oldErrorMode);
            }
        }
    }

    static <E extends Throwable> void execute(ExceptionRunnable<E> runnable) throws E {
        Objects.requireNonNull(runnable);
        execute(() -> {
            runnable.run();
            return null;
        });
    }

    @FunctionalInterface
    interface ExceptionCallable<V, E extends Throwable> {

        V call() throws E;

    }

    @FunctionalInterface
    interface ExceptionRunnable<E extends Throwable> {

        void run() throws E;

    }

}

@@ -1047,32 +1047,34 @@
 xecute(Exception
+al
 Callable%3CV, E%3E s
@@ -1549,32 +1549,34 @@
 xecute(Exception
+al
 Runnable%3CE%3E runn
@@ -1604,128 +1604,58 @@
     
-Objects.requireNonNull(runnable);%0A        execute(() -%3E %7B%0A            runnable.run();%0A            return null;%0A        %7D
+execute(ExceptionalCallable.fromRunnable(runnable)
 );%0A 
@@ -1708,16 +1708,18 @@
 xception
+al
 Callable
@@ -1770,24 +1770,297 @@
  throws E;%0A%0A
+        static %3CV, E extends Throwable%3E ExceptionalCallable%3CV, E%3E fromRunnable(ExceptionalRunnable%3CE%3E runnable) %7B%0A            Objects.requireNonNull(runnable);%0A            return () -%3E %7B%0A                runnable.run();%0A                return null;%0A            %7D;%0A        %7D%0A
     %7D%0A%0A    @
@@ -2102,16 +2102,18 @@
 xception
+al
 Runnable

Update ProcessCreationHelper.java