Search in sources :

Example 6 with Win32Exception

use of com.github.zhanhb.jnc.platform.win32.Win32Exception in project jna by java-native-access.

the class VersionUtil method getFileVersionInfo.

/**
     * Gets the file's version number info
     * 
     * @param filePath
     *            The path to the file
     * @return The VS_FIXEDFILEINFO structure read from the file.<br>
     *         Use the getFileVersionMajor(), getFileVersionMinor(),
     *         getFileVersionRevision(), and getFileVersionBuild()
     * @throws UnsupportedOperationException
     *             if VerQueryValue fails to get version info from the file.
     */
public static VS_FIXEDFILEINFO getFileVersionInfo(String filePath) {
    IntByReference dwDummy = new IntByReference();
    int versionLength = Version.INSTANCE.GetFileVersionInfoSize(filePath, dwDummy);
    // throw a Win32Exception with GetLastError()
    if (versionLength == 0) {
        throw new Win32Exception(Native.getLastError());
    }
    // buffer to hold version info
    Pointer lpData = new Memory(versionLength);
    // pointer to pointer to location in aforementioned buffer
    PointerByReference lplpBuffer = new PointerByReference();
    if (!Version.INSTANCE.GetFileVersionInfo(filePath, 0, versionLength, lpData)) {
        throw new Win32Exception(Native.getLastError());
    }
    // here to make VerQueryValue happy.
    IntByReference puLen = new IntByReference();
    // this does not set GetLastError, so no need to throw a Win32Exception
    if (!Version.INSTANCE.VerQueryValue(lpData, "\\", lplpBuffer, puLen)) {
        throw new UnsupportedOperationException("Unable to extract version info from the file: \"" + filePath + "\"");
    }
    VS_FIXEDFILEINFO fileInfo = new VS_FIXEDFILEINFO(lplpBuffer.getValue());
    fileInfo.read();
    return fileInfo;
}
Also used : VS_FIXEDFILEINFO(com.sun.jna.platform.win32.VerRsrc.VS_FIXEDFILEINFO) IntByReference(com.sun.jna.ptr.IntByReference) Memory(com.sun.jna.Memory) PointerByReference(com.sun.jna.ptr.PointerByReference) Pointer(com.sun.jna.Pointer) Win32Exception(com.sun.jna.platform.win32.Win32Exception)

Example 7 with Win32Exception

use of com.github.zhanhb.jnc.platform.win32.Win32Exception in project jna by java-native-access.

the class GDI32Util method getScreenshot.

/**
	 * Takes a screenshot of the given window
	 * 
	 * @param target
	 *            The window to target
	 * @return the window captured as a screenshot, or null if the BufferedImage doesn't construct properly
	 * @throws IllegalStateException
	 *             if the rectangle from GetWindowRect has a width and/or height
	 *             of 0. <br>
	 *             if the device context acquired from the original HWND doesn't
	 *             release properly
	 */
public static BufferedImage getScreenshot(HWND target) {
    RECT rect = new RECT();
    if (!User32.INSTANCE.GetWindowRect(target, rect)) {
        throw new Win32Exception(Native.getLastError());
    }
    Rectangle jRectangle = rect.toRectangle();
    int windowWidth = jRectangle.width;
    int windowHeight = jRectangle.height;
    if (windowWidth == 0 || windowHeight == 0) {
        throw new IllegalStateException("Window width and/or height were 0 even though GetWindowRect did not appear to fail.");
    }
    HDC hdcTarget = User32.INSTANCE.GetDC(target);
    if (hdcTarget == null) {
        throw new Win32Exception(Native.getLastError());
    }
    Win32Exception we = null;
    // device context used for drawing
    HDC hdcTargetMem = null;
    // handle to the bitmap to be drawn to
    HBITMAP hBitmap = null;
    // original display surface associated with the device context
    HANDLE hOriginal = null;
    // final java image structure we're returning.
    BufferedImage image = null;
    try {
        hdcTargetMem = GDI32.INSTANCE.CreateCompatibleDC(hdcTarget);
        if (hdcTargetMem == null) {
            throw new Win32Exception(Native.getLastError());
        }
        hBitmap = GDI32.INSTANCE.CreateCompatibleBitmap(hdcTarget, windowWidth, windowHeight);
        if (hBitmap == null) {
            throw new Win32Exception(Native.getLastError());
        }
        hOriginal = GDI32.INSTANCE.SelectObject(hdcTargetMem, hBitmap);
        if (hOriginal == null) {
            throw new Win32Exception(Native.getLastError());
        }
        // draw to the bitmap
        if (!GDI32.INSTANCE.BitBlt(hdcTargetMem, 0, 0, windowWidth, windowHeight, hdcTarget, 0, 0, GDI32.SRCCOPY)) {
            throw new Win32Exception(Native.getLastError());
        }
        BITMAPINFO bmi = new BITMAPINFO();
        bmi.bmiHeader.biWidth = windowWidth;
        bmi.bmiHeader.biHeight = -windowHeight;
        bmi.bmiHeader.biPlanes = 1;
        bmi.bmiHeader.biBitCount = 32;
        bmi.bmiHeader.biCompression = WinGDI.BI_RGB;
        Memory buffer = new Memory(windowWidth * windowHeight * 4);
        int resultOfDrawing = GDI32.INSTANCE.GetDIBits(hdcTarget, hBitmap, 0, windowHeight, buffer, bmi, WinGDI.DIB_RGB_COLORS);
        if (resultOfDrawing == 0 || resultOfDrawing == WinError.ERROR_INVALID_PARAMETER) {
            throw new Win32Exception(Native.getLastError());
        }
        int bufferSize = windowWidth * windowHeight;
        DataBuffer dataBuffer = new DataBufferInt(buffer.getIntArray(0, bufferSize), bufferSize);
        WritableRaster raster = Raster.createPackedRaster(dataBuffer, windowWidth, windowHeight, windowWidth, SCREENSHOT_BAND_MASKS, null);
        image = new BufferedImage(SCREENSHOT_COLOR_MODEL, raster, false, null);
    } catch (Win32Exception e) {
        we = e;
    } finally {
        if (hOriginal != null) {
            // per MSDN, set the display surface back when done drawing
            HANDLE result = GDI32.INSTANCE.SelectObject(hdcTargetMem, hOriginal);
            // failure modes are null or equal to HGDI_ERROR
            if (result == null || WinGDI.HGDI_ERROR.equals(result)) {
                Win32Exception ex = new Win32Exception(Native.getLastError());
                if (we != null) {
                    ex.addSuppressed(we);
                }
                we = ex;
            }
        }
        if (hBitmap != null) {
            if (!GDI32.INSTANCE.DeleteObject(hBitmap)) {
                Win32Exception ex = new Win32Exception(Native.getLastError());
                if (we != null) {
                    ex.addSuppressed(we);
                }
                we = ex;
            }
        }
        if (hdcTargetMem != null) {
            // get rid of the device context when done
            if (!GDI32.INSTANCE.DeleteDC(hdcTargetMem)) {
                Win32Exception ex = new Win32Exception(Native.getLastError());
                if (we != null) {
                    ex.addSuppressed(we);
                }
                we = ex;
            }
        }
        if (hdcTarget != null) {
            if (0 == User32.INSTANCE.ReleaseDC(target, hdcTarget)) {
                throw new IllegalStateException("Device context did not release properly.");
            }
        }
    }
    if (we != null) {
        throw we;
    }
    return image;
}
Also used : RECT(com.sun.jna.platform.win32.WinDef.RECT) HDC(com.sun.jna.platform.win32.WinDef.HDC) Memory(com.sun.jna.Memory) Rectangle(java.awt.Rectangle) DataBufferInt(java.awt.image.DataBufferInt) BufferedImage(java.awt.image.BufferedImage) Win32Exception(com.sun.jna.platform.win32.Win32Exception) WritableRaster(java.awt.image.WritableRaster) BITMAPINFO(com.sun.jna.platform.win32.WinGDI.BITMAPINFO) HBITMAP(com.sun.jna.platform.win32.WinDef.HBITMAP) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE) DataBuffer(java.awt.image.DataBuffer)

Example 8 with Win32Exception

use of com.github.zhanhb.jnc.platform.win32.Win32Exception in project osumer by mob41.

the class Installer method getAvailableBrowsers.

public static String[] getAvailableBrowsers() throws DebuggableException {
    try {
        String[] keys = Advapi32Util.registryGetKeys(WinReg.HKEY_LOCAL_MACHINE, WIN_REG_CLIENTS_PATH);
        List<String> filteredList = new ArrayList<String>(50);
        for (int i = 0; i < keys.length; i++) {
            if (!keys[i].equals(WIN_REG_INTERNET_CLIENT_KEY)) {
                filteredList.add(keys[i]);
            }
        }
        String[] out = new String[filteredList.size()];
        for (int i = 0; i < out.length; i++) {
            out[i] = filteredList.get(i);
        }
        return out;
    } catch (Win32Exception e) {
        throw new DebuggableException(null, "(Try&catch try)", "Throw debuggable exception", "(End of function)", "Error reading registry", false, e);
    }
}
Also used : DebuggableException(com.github.mob41.organdebug.exceptions.DebuggableException) ArrayList(java.util.ArrayList) Win32Exception(com.sun.jna.platform.win32.Win32Exception)

Example 9 with Win32Exception

use of com.github.zhanhb.jnc.platform.win32.Win32Exception in project open-ecard by ecsec.

the class RichClient method setup.

public void setup() {
    GUIDefaults.initialize();
    String title = LANG.translationForKey("client.startup.failed.headline", AppVersion.getName());
    String message = null;
    // Set up GUI
    SwingUserConsent gui = new SwingUserConsent(new SwingDialogWrapper());
    try {
        tray = new AppTray(this);
        tray.beginSetup();
        // Set up client environment
        env = new ClientEnv();
        // Set up the Dispatcher
        MessageDispatcher dispatcher = new MessageDispatcher(env);
        env.setDispatcher(dispatcher);
        // Set up EventDispatcherImpl
        eventDispatcher = new EventDispatcherImpl();
        env.setEventDispatcher(eventDispatcher);
        // Set up Management
        TinyManagement management = new TinyManagement(env);
        env.setManagement(management);
        // Set up MiddlewareConfig
        MiddlewareConfigLoader mwConfigLoader = new MiddlewareConfigLoader();
        List<MiddlewareSALConfig> mwSALConfigs = mwConfigLoader.getMiddlewareSALConfigs();
        // Set up CardRecognitionImpl
        recognition = new CardRecognitionImpl(env);
        recognition.setGUI(gui);
        env.setRecognition(recognition);
        // Set up StateCallbacks
        cardStates = new CardStateMap();
        SALStateCallback salCallback = new SALStateCallback(env, cardStates);
        eventDispatcher.add(salCallback);
        // Set up the IFD
        ifd = new IFD();
        ifd.addProtocol(ECardConstants.Protocol.PACE, new PACEProtocolFactory());
        ifd.setGUI(gui);
        ifd.setEnvironment(env);
        env.setIFD(ifd);
        // Set up SAL
        TinySAL mainSal = new TinySAL(env, cardStates);
        mainSal.setGUI(gui);
        sal = new SelectorSAL(mainSal, env);
        env.setSAL(sal);
        env.setCIFProvider(sal);
        // Set up Middleware SAL
        MwStateCallback mwCallback = new MwStateCallback(env, cardStates, mwConfigLoader);
        for (MiddlewareSALConfig mwSALConfig : mwSALConfigs) {
            if (!mwSALConfig.isDisabled()) {
                MiddlewareSAL mwSal = new MiddlewareSAL(env, cardStates, mwSALConfig, mwCallback);
                mwSal.setGui(gui);
                sal.addSpecializedSAL(mwSal);
            }
        }
        // Start up control interface
        SettingsAndDefaultViewWrapper guiWrapper = new SettingsAndDefaultViewWrapper();
        try {
            manager = new AddonManager(env, gui, cardStates, guiWrapper);
            guiWrapper.setAddonManager(manager);
            mainSal.setAddonManager(manager);
            // initialize http binding
            int port = 24727;
            boolean dispatcherMode = false;
            WinReg.HKEY hk = WinReg.HKEY_LOCAL_MACHINE;
            String regPath = "SOFTWARE\\" + OpenecardProperties.getProperty("registry.app_name");
            if (Platform.isWindows()) {
                LOG.debug("Checking if dispatcher mode should be used.");
                try {
                    if (regKeyExists(hk, regPath, "Dispatcher_Mode")) {
                        String value = Advapi32Util.registryGetStringValue(hk, regPath, "Dispatcher_Mode");
                        dispatcherMode = Boolean.valueOf(value);
                        // let socket chose its port
                        port = 0;
                    }
                } catch (Win32Exception ex) {
                    LOG.warn("Failed to read 'Dispatcher_Mode' registry key. Using normal operation mode.", ex);
                }
            }
            if (!dispatcherMode) {
                try {
                    port = Integer.parseInt(OpenecardProperties.getProperty("http-binding.port"));
                } catch (NumberFormatException ex) {
                    LOG.warn("Error in config file, HTTP binding port is malformed.");
                }
            }
            // start HTTP server
            httpBinding = new HttpBinding(port);
            httpBinding.setAddonManager(manager);
            httpBinding.start();
            if (dispatcherMode) {
                long waitTime = getRegInt(hk, regPath, "Retry_Wait_Time", 5000L);
                long timeout = getRegInt(hk, regPath, "DP_Timeout", 3600000L);
                // try to register with dispatcher service
                LOG.debug("Trying to register HTTP binding port with dispatcher service.");
                final int realPort = httpBinding.getPort();
                final URL regUrl = new URL("http://127.0.0.1:24727/dp/register");
                FutureTask ft = new FutureTask(new DispatcherRegistrator(regUrl, realPort, waitTime, timeout), 1);
                Thread registerThread = new Thread(ft, "Register-Dispatcher-Service");
                registerThread.setDaemon(true);
                registerThread.start();
                // wait until thread is finished
                ft.get();
            }
        } catch (BindException e) {
            message = LANG.translationForKey("client.startup.failed.portinuse", AppVersion.getName());
            throw e;
        }
        tray.endSetup(env, manager);
        // Initialize the EventManager
        eventDispatcher.add(tray.status(), EventType.TERMINAL_ADDED, EventType.TERMINAL_REMOVED, EventType.CARD_INSERTED, EventType.CARD_RECOGNIZED, EventType.CARD_REMOVED);
        // start event dispatcher
        eventDispatcher.start();
        // initialize SAL
        WSHelper.checkResult(sal.initialize(new Initialize()));
        // Perform an EstablishContext to get a ContextHandle
        try {
            EstablishContext establishContext = new EstablishContext();
            EstablishContextResponse establishContextResponse = ifd.establishContext(establishContext);
            WSHelper.checkResult(establishContextResponse);
            contextHandle = establishContextResponse.getContextHandle();
        } catch (WSHelper.WSException ex) {
            message = LANG.translationForKey("client.startup.failed.nocontext");
            throw ex;
        }
        // perform GC to bring down originally allocated memory
        new Timer().schedule(new GCTask(), 5000);
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);
        if (message == null || message.isEmpty()) {
            // Add exception message if no custom message is set
            message = ex.getMessage();
        }
        // Show dialog to the user and shut down the client
        String msg = String.format("%s%n%n%s", title, message);
        gui.obtainMessageDialog().showMessageDialog(msg, AppVersion.getName(), DialogType.ERROR_MESSAGE);
        teardown();
    } catch (Throwable ex) {
        LOG.error("Unexpected error occurred. Exiting client.", ex);
        System.exit(1);
    }
}
Also used : SALStateCallback(org.openecard.common.sal.state.SALStateCallback) EventDispatcherImpl(org.openecard.common.event.EventDispatcherImpl) IFD(org.openecard.ifd.scio.IFD) WinReg(com.sun.jna.platform.win32.WinReg) CardRecognitionImpl(org.openecard.recognition.CardRecognitionImpl) Initialize(iso.std.iso_iec._24727.tech.schema.Initialize) MiddlewareSAL(org.openecard.mdlw.sal.MiddlewareSAL) URL(java.net.URL) SwingDialogWrapper(org.openecard.gui.swing.SwingDialogWrapper) MessageDispatcher(org.openecard.transport.dispatcher.MessageDispatcher) FutureTask(java.util.concurrent.FutureTask) HttpBinding(org.openecard.control.binding.http.HttpBinding) CardStateMap(org.openecard.common.sal.state.CardStateMap) MwStateCallback(org.openecard.mdlw.event.MwStateCallback) EstablishContext(iso.std.iso_iec._24727.tech.schema.EstablishContext) TinySAL(org.openecard.sal.TinySAL) WSHelper(org.openecard.common.WSHelper) MiddlewareConfigLoader(org.openecard.mdlw.sal.config.MiddlewareConfigLoader) BindException(java.net.BindException) EstablishContextResponse(iso.std.iso_iec._24727.tech.schema.EstablishContextResponse) PACEProtocolFactory(org.openecard.ifd.protocol.pace.PACEProtocolFactory) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Win32Exception(com.sun.jna.platform.win32.Win32Exception) BindException(java.net.BindException) HttpException(org.openecard.apache.http.HttpException) IOException(java.io.IOException) JoranException(ch.qos.logback.core.joran.spi.JoranException) Win32Exception(com.sun.jna.platform.win32.Win32Exception) AppTray(org.openecard.richclient.gui.AppTray) ClientEnv(org.openecard.common.ClientEnv) MiddlewareSALConfig(org.openecard.mdlw.sal.config.MiddlewareSALConfig) Timer(java.util.Timer) SwingUserConsent(org.openecard.gui.swing.SwingUserConsent) TinyManagement(org.openecard.management.TinyManagement) AddonManager(org.openecard.addon.AddonManager) SelectorSAL(org.openecard.sal.SelectorSAL) SettingsAndDefaultViewWrapper(org.openecard.richclient.gui.SettingsAndDefaultViewWrapper)

Example 10 with Win32Exception

use of com.github.zhanhb.jnc.platform.win32.Win32Exception in project gitblit by gitblit.

the class WindowsAuthProvider method authenticate.

@Override
public UserModel authenticate(String username, char[] password) {
    String defaultDomain = settings.getString(Keys.realm.windows.defaultDomain, null);
    if (StringUtils.isEmpty(defaultDomain)) {
        // ensure that default domain is null
        defaultDomain = null;
    }
    if (defaultDomain != null) {
        // sanitize username
        if (username.startsWith(defaultDomain + "\\")) {
            // strip default domain from domain\ username
            username = username.substring(defaultDomain.length() + 1);
        } else if (username.endsWith("@" + defaultDomain)) {
            // strip default domain from username@domain
            username = username.substring(0, username.lastIndexOf('@'));
        }
    }
    IWindowsIdentity identity = null;
    try {
        if (username.indexOf('@') > -1 || username.indexOf('\\') > -1) {
            // manually specified domain
            identity = waffle.logonUser(username, new String(password));
        } else {
            // no domain specified, use default domain
            identity = waffle.logonDomainUser(username, defaultDomain, new String(password));
        }
    } catch (Win32Exception e) {
        logger.error(e.getMessage());
        return null;
    }
    if (identity.isGuest() && !settings.getBoolean(Keys.realm.windows.allowGuests, false)) {
        logger.warn("Guest account access is disabled");
        identity.dispose();
        return null;
    }
    UserModel user = userManager.getUserModel(username);
    if (user == null) {
        // create user object for new authenticated user
        user = new UserModel(username.toLowerCase());
    }
    // create a user cookie
    setCookie(user);
    // update user attributes from Windows identity
    user.accountType = getAccountType();
    String fqn = identity.getFqn();
    if (fqn.indexOf('\\') > -1) {
        user.displayName = fqn.substring(fqn.lastIndexOf('\\') + 1);
    } else {
        user.displayName = fqn;
    }
    user.password = Constants.EXTERNAL_ACCOUNT;
    Set<String> groupNames = new TreeSet<String>();
    for (IWindowsAccount group : identity.getGroups()) {
        groupNames.add(group.getFqn());
    }
    if (settings.getBoolean(Keys.realm.windows.permitBuiltInAdministrators, true)) {
        if (groupNames.contains("BUILTIN\\Administrators")) {
            // local administrator
            user.canAdmin = true;
        }
    }
    // TODO consider mapping Windows groups to teams
    // push the changes to the backing user service
    updateUser(user);
    // cleanup resources
    identity.dispose();
    return user;
}
Also used : UserModel(com.gitblit.models.UserModel) TreeSet(java.util.TreeSet) IWindowsAccount(waffle.windows.auth.IWindowsAccount) IWindowsIdentity(waffle.windows.auth.IWindowsIdentity) Win32Exception(com.sun.jna.platform.win32.Win32Exception)

Aggregations

Win32Exception (com.sun.jna.platform.win32.Win32Exception)7 DebuggableException (com.github.mob41.organdebug.exceptions.DebuggableException)3 IOException (java.io.IOException)3 NotExecutableException (cn.edu.zjnu.acm.judge.core.NotExecutableException)2 Memory (com.sun.jna.Memory)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 Win32Exception (jnc.platform.win32.Win32Exception)2 JoranException (ch.qos.logback.core.joran.spi.JoranException)1 ExecuteResult (cn.edu.zjnu.acm.judge.core.ExecuteResult)1 Option (cn.edu.zjnu.acm.judge.core.Option)1 Language (cn.edu.zjnu.acm.judge.domain.Language)1 RunResult (cn.edu.zjnu.acm.judge.support.RunResult)1 UserModel (com.gitblit.models.UserModel)1 EXPLICIT_ACCESS (com.github.zhanhb.jnc.platform.win32.EXPLICIT_ACCESS)1 NO_MULTIPLE_TRUSTEE (com.github.zhanhb.jnc.platform.win32.MULTIPLE_TRUSTEE_OPERATION.NO_MULTIPLE_TRUSTEE)1 TRUSTEE (com.github.zhanhb.jnc.platform.win32.TRUSTEE)1 Win32Exception (com.github.zhanhb.jnc.platform.win32.Win32Exception)1 Pointer (com.sun.jna.Pointer)1 VS_FIXEDFILEINFO (com.sun.jna.platform.win32.VerRsrc.VS_FIXEDFILEINFO)1