hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e142d9ddc05f1381582b23e30d2afabbf41de94
1,919
java
Java
src/main/java/top/sceon/blog/controller/backend/LoginController.java
secret32/sceonblog
233dae642ddd36b5de701158e0482532b1578cd5
[ "Apache-2.0" ]
null
null
null
src/main/java/top/sceon/blog/controller/backend/LoginController.java
secret32/sceonblog
233dae642ddd36b5de701158e0482532b1578cd5
[ "Apache-2.0" ]
null
null
null
src/main/java/top/sceon/blog/controller/backend/LoginController.java
secret32/sceonblog
233dae642ddd36b5de701158e0482532b1578cd5
[ "Apache-2.0" ]
null
null
null
39.163265
113
0.661803
8,537
package top.sceon.blog.controller.backend; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import top.sceon.blog.controller.BaseController; import top.sceon.blog.util.SessionKey; import top.sceon.common.util.HashUtil; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * @author zhou_wei * @date 8/29/2016 */ @Controller @RequestMapping(path = "/manage") public class LoginController extends BaseController { final private String USERNAME = "admin"; final private String PASSWORD = HashUtil.sha1("1"); @RequestMapping(path = "/login", method = {RequestMethod.POST, RequestMethod.GET}) public ModelAndView login(HttpServletRequest request, String username, String password, String verifyCode) { ModelAndView result; HttpSession session = request.getSession(); String sessionUsername = (String) session.getAttribute(SessionKey.USERNAME); if (username == null && password == null && sessionUsername != null) { result = new ModelAndView("/backend/index"); } else if (username != null) { if (PASSWORD.equals(HashUtil.sha1(password))) { result = new ModelAndView("/backend/index"); result.addObject("username", username); session.setAttribute(SessionKey.USERNAME, username); session.setAttribute(SessionKey.USER_ID, 1); } else { result = new ModelAndView("/backend/login"); result.addObject("error", "Invalid username or password"); } } else { result = new ModelAndView("/backend/login"); } return result; } }
3e142dbd2dd558ea00942fb4a139bd9ad64aee93
41,942
java
Java
agp-7.1.0-alpha01/tools/base/ddmlib/src/main/java/com/android/ddmlib/IDevice.java
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
agp-7.1.0-alpha01/tools/base/ddmlib/src/main/java/com/android/ddmlib/IDevice.java
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
agp-7.1.0-alpha01/tools/base/ddmlib/src/main/java/com/android/ddmlib/IDevice.java
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
42.110442
101
0.678699
8,538
/* * Copyright (C) 2019 The Android Open Source Project * * 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.android.ddmlib; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.ddmlib.log.LogReceiver; import com.android.sdklib.AndroidVersion; import com.google.common.base.Splitter; import com.google.common.collect.Sets; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.channels.SocketChannel; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** A Device. It can be a physical device or an emulator. */ public interface IDevice extends IShellEnabledDevice { String UNKNOWN_PACKAGE = ""; /** Emulator Serial Number regexp. */ String RE_EMULATOR_SN = "emulator-(\\d+)"; //$NON-NLS-1$ String PROP_BUILD_VERSION = "ro.build.version.release"; String PROP_BUILD_API_LEVEL = "ro.build.version.sdk"; String PROP_BUILD_CODENAME = "ro.build.version.codename"; String PROP_BUILD_TAGS = "ro.build.tags"; String PROP_BUILD_TYPE = "ro.build.type"; String PROP_DEVICE_MODEL = "ro.product.model"; String PROP_DEVICE_MANUFACTURER = "ro.product.manufacturer"; String PROP_DEVICE_CPU_ABI_LIST = "ro.product.cpu.abilist"; String PROP_DEVICE_CPU_ABI = "ro.product.cpu.abi"; String PROP_DEVICE_CPU_ABI2 = "ro.product.cpu.abi2"; String PROP_BUILD_CHARACTERISTICS = "ro.build.characteristics"; String PROP_DEVICE_DENSITY = "ro.sf.lcd_density"; String PROP_DEVICE_EMULATOR_DENSITY = "qemu.sf.lcd_density"; String PROP_DEVICE_LANGUAGE = "persist.sys.language"; String PROP_DEVICE_REGION = "persist.sys.country"; String PROP_DEBUGGABLE = "ro.debuggable"; /** Serial number of the first connected emulator. */ String FIRST_EMULATOR_SN = "emulator-5554"; //$NON-NLS-1$ /** Device change bit mask: {@link DeviceState} change. */ int CHANGE_STATE = 0x0001; /** Device change bit mask: {@link Client} list change. */ int CHANGE_CLIENT_LIST = 0x0002; /** Device change bit mask: build info change. */ int CHANGE_BUILD_INFO = 0x0004; /** Device change bit mask: {@link ProfileableClient} list change. */ int CHANGE_PROFILEABLE_CLIENT_LIST = 0x0008; /** Device level software features. */ enum Feature { SCREEN_RECORD, // screen recorder available? PROCSTATS, // procstats service (dumpsys procstats) available ABB_EXEC, // Android Binder Bridge available REAL_PKG_NAME, // Reports the real package name, instead of inferring from client description SKIP_VERIFICATION, // Skips verification on installation. SHELL_V2, // Supports modern `adb shell` features like exit status propagation. } /** Device level hardware features. */ enum HardwareFeature { WATCH("watch"), EMBEDDED("embedded"), TV("tv"), AUTOMOTIVE("automotive"); private final String mCharacteristic; HardwareFeature(String characteristic) { mCharacteristic = characteristic; } public String getCharacteristic() { return mCharacteristic; } } /** @deprecated Use {@link #PROP_BUILD_API_LEVEL}. */ @Deprecated String PROP_BUILD_VERSION_NUMBER = PROP_BUILD_API_LEVEL; String MNT_EXTERNAL_STORAGE = "EXTERNAL_STORAGE"; //$NON-NLS-1$ String MNT_ROOT = "ANDROID_ROOT"; //$NON-NLS-1$ String MNT_DATA = "ANDROID_DATA"; //$NON-NLS-1$ /** The state of a device. */ enum DeviceState { BOOTLOADER("bootloader"), //$NON-NLS-1$ /** bootloader mode with is-userspace = true though `adb reboot fastboot` */ FASTBOOTD("fastbootd"), //$NON-NLS-1$ OFFLINE("offline"), //$NON-NLS-1$ ONLINE("device"), //$NON-NLS-1$ RECOVERY("recovery"), //$NON-NLS-1$ /** Device is in "sideload" state either through `adb sideload` or recovery menu */ SIDELOAD("sideload"), //$NON-NLS-1$ UNAUTHORIZED("unauthorized"), //$NON-NLS-1$ DISCONNECTED("disconnected"), //$NON-NLS-1$ ; private String mState; DeviceState(String state) { mState = state; } /** * Returns a {@link DeviceState} from the string returned by <code>adb devices</code>. * * @param state the device state. * @return a {@link DeviceState} object or <code>null</code> if the state is unknown. */ @Nullable public static DeviceState getState(String state) { for (DeviceState deviceState : values()) { if (deviceState.mState.equals(state)) { return deviceState; } } return null; } public String getState() { return mState; } } /** Namespace of a Unix Domain Socket created on the device. */ enum DeviceUnixSocketNamespace { ABSTRACT("localabstract"), //$NON-NLS-1$ FILESYSTEM("localfilesystem"), //$NON-NLS-1$ RESERVED("localreserved"); //$NON-NLS-1$ private String mType; DeviceUnixSocketNamespace(String type) { mType = type; } public String getType() { return mType; } } /** Returns the serial number of the device. */ @NonNull String getSerialNumber(); /** * Returns the name of the AVD the emulator is running. * * <p>This is only valid if {@link #isEmulator()} returns true. * * <p>If the emulator is not running any AVD (for instance it's running from an Android source * tree build), this method will return "<code>&lt;build&gt;</code>". * * @return the name of the AVD or <code>null</code> if there isn't any. */ @Nullable String getAvdName(); /** * Returns the absolute path to the virtual device in the file system. The path is operating * system dependent; it will have / name separators on Linux and \ separators on Windows. * * @return the AVD path or null if this is a physical device, the emulator console subcommand * failed, or the emulator's version is older than 30.0.18 */ @Nullable String getAvdPath(); /** Returns the state of the device. */ DeviceState getState(); /** * Returns the cached device properties. It contains the whole output of 'getprop' * * @deprecated use {@link #getSystemProperty(String)} instead */ @Deprecated Map<String, String> getProperties(); /** * Returns the number of property for this device. * * @deprecated implementation detail */ @Deprecated int getPropertyCount(); /** * Convenience method that attempts to retrieve a property via {@link * #getSystemProperty(String)} with a very short wait time, and swallows exceptions. * * <p><em>Note: Prefer using {@link #getSystemProperty(String)} if you want control over the * timeout.</em> * * @param name the name of the value to return. * @return the value or <code>null</code> if the property value was not immediately available */ @Nullable String getProperty(@NonNull String name); /** Returns <code>true</code> if properties have been cached */ boolean arePropertiesSet(); /** * A variant of {@link #getProperty(String)} that will attempt to retrieve the given property * from device directly, without using cache. This method should (only) be used for any volatile * properties. * * @param name the name of the value to return. * @return the value or <code>null</code> if the property does not exist * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws ShellCommandUnresponsiveException in case the shell command doesn't send output for a * given time. * @throws IOException in case of I/O error on the connection. * @deprecated use {@link #getSystemProperty(String)} */ @Deprecated String getPropertySync(String name) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException; /** * A combination of {@link #getProperty(String)} and {@link #getPropertySync(String)} that will * attempt to retrieve the property from cache. If not found, will synchronously attempt to * query device directly and repopulate the cache if successful. * * @param name the name of the value to return. * @return the value or <code>null</code> if the property does not exist * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws ShellCommandUnresponsiveException in case the shell command doesn't send output for a * given time. * @throws IOException in case of I/O error on the connection. * @deprecated use {@link #getSystemProperty(String)} instead */ @Deprecated String getPropertyCacheOrSync(String name) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException; /** Returns whether this device supports the given software feature. */ boolean supportsFeature(@NonNull Feature feature); /** Returns whether this device supports the given hardware feature. */ boolean supportsFeature(@NonNull HardwareFeature feature); /** * Returns a mount point. * * @param name the name of the mount point to return * @see #MNT_EXTERNAL_STORAGE * @see #MNT_ROOT * @see #MNT_DATA */ @Nullable String getMountPoint(@NonNull String name); /** * Returns if the device is ready. * * @return <code>true</code> if {@link #getState()} returns {@link DeviceState#ONLINE}. */ boolean isOnline(); /** Returns <code>true</code> if the device is an emulator. */ boolean isEmulator(); /** * Returns if the device is offline. * * @return <code>true</code> if {@link #getState()} returns {@link DeviceState#OFFLINE}. */ boolean isOffline(); /** * Returns if the device is in bootloader mode. * * @return <code>true</code> if {@link #getState()} returns {@link DeviceState#BOOTLOADER}. */ boolean isBootLoader(); /** Returns whether the {@link IDevice} has {@link Client}s. */ boolean hasClients(); /** Returns the array of clients. */ Client[] getClients(); /** * Returns a {@link Client} by its application name. * * @param applicationName the name of the application * @return the <code>Client</code> object or <code>null</code> if no match was found. */ Client getClient(String applicationName); /** Returns the array of profileable clients. */ default ProfileableClient[] getProfileableClients() { return new ProfileableClient[0]; // Returns an empty array by default } /** * Force stop an application by its application name. This removes all pending alarms and queued * computation. * * @param applicationName the name of the application */ default void forceStop(String applicationName) {} /** * Kills an application by its application name. This only destroy the activities, leaving its * state in the Android system alone. * * @param applicationName the name of the application */ default void kill(String applicationName) {} /** * Returns a {@link SyncService} object to push / pull files to and from the device. * * @return <code>null</code> if the SyncService couldn't be created. This can happen if adb * refuse to open the connection because the {@link IDevice} is invalid (or got * disconnected). * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException if the connection with adb failed. */ @Nullable SyncService getSyncService() throws TimeoutException, AdbCommandRejectedException, IOException; /** Returns a {@link FileListingService} for this device. */ FileListingService getFileListingService(); /** * Takes a screen shot of the device and returns it as a {@link RawImage}. * * @return the screenshot as a <code>RawImage</code> or <code>null</code> if something went * wrong. * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException in case of I/O error on the connection. */ RawImage getScreenshot() throws TimeoutException, AdbCommandRejectedException, IOException; RawImage getScreenshot(long timeout, TimeUnit unit) throws TimeoutException, AdbCommandRejectedException, IOException; /** * Initiates screen recording on the device if the device supports {@link * Feature#SCREEN_RECORD}. */ void startScreenRecorder( @NonNull String remoteFilePath, @NonNull ScreenRecorderOptions options, @NonNull IShellOutputReceiver receiver) throws TimeoutException, AdbCommandRejectedException, IOException, ShellCommandUnresponsiveException; /** * @deprecated Use {@link #executeShellCommand(String, IShellOutputReceiver, long, TimeUnit)}. */ @Deprecated void executeShellCommand( String command, IShellOutputReceiver receiver, int maxTimeToOutputResponse) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException; /** * Executes a shell command on the device, and sends the result to a <var>receiver</var> * * <p>This is similar to calling <code> * executeShellCommand(command, receiver, DdmPreferences.getTimeOut())</code>. * * @param command the shell command to execute * @param receiver the {@link IShellOutputReceiver} that will receives the output of the shell * command * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws ShellCommandUnresponsiveException in case the shell command doesn't send output for a * given time. * @throws IOException in case of I/O error on the connection. * @see #executeShellCommand(String, IShellOutputReceiver, int) * @see DdmPreferences#getTimeOut() */ void executeShellCommand(String command, IShellOutputReceiver receiver) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException; /** A version of executeShell command that can take an input stream to send through stdin. */ default void executeShellCommand( String command, IShellOutputReceiver receiver, long maxTimeToOutputResponse, TimeUnit maxTimeUnits, @Nullable InputStream is) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException { throw new UnsupportedOperationException(); } /** * Executes a Binder command on the device, and sends the result to a <var>receiver</var> * * <p>This uses exec:cmd <command> call or faster abb_exec:<command> if both device OS and host * ADB server support Android Binder Bridge execute feature. * * @param parameters the binder command to execute * @param receiver the {@link IShellOutputReceiver} that will receives the output of the binder * command * @param is optional input stream to send through stdin * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws ShellCommandUnresponsiveException in case the binder command doesn't send output for * a given time. * @throws IOException in case of I/O error on the connection. * @see DdmPreferences#getTimeOut() */ default void executeBinderCommand( String[] parameters, IShellOutputReceiver receiver, long maxTimeToOutputResponse, TimeUnit maxTimeUnits, @Nullable InputStream is) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException { throw new UnsupportedOperationException(); } /** * Runs the event log service and outputs the event log to the {@link LogReceiver}. * * <p>This call is blocking until {@link LogReceiver#isCancelled()} returns true. * * @param receiver the receiver to receive the event log entries. * @throws TimeoutException in case of timeout on the connection. This can only be thrown if the * timeout happens during setup. Once logs start being received, no timeout will occur as * it's not possible to detect a difference between no log and timeout. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException in case of I/O error on the connection. */ void runEventLogService(LogReceiver receiver) throws TimeoutException, AdbCommandRejectedException, IOException; /** * Runs the log service for the given log and outputs the log to the {@link LogReceiver}. * * <p>This call is blocking until {@link LogReceiver#isCancelled()} returns true. * * @param logname the logname of the log to read from. * @param receiver the receiver to receive the event log entries. * @throws TimeoutException in case of timeout on the connection. This can only be thrown if the * timeout happens during setup. Once logs start being received, no timeout will occur as * it's not possible to detect a difference between no log and timeout. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException in case of I/O error on the connection. */ void runLogService(String logname, LogReceiver receiver) throws TimeoutException, AdbCommandRejectedException, IOException; /** * Creates a port forwarding between a local and a remote port. * * @param localPort the local port to forward * @param remotePort the remote port. * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException in case of I/O error on the connection. */ void createForward(int localPort, int remotePort) throws TimeoutException, AdbCommandRejectedException, IOException; /** * Creates a port forwarding between a local TCP port and a remote Unix Domain Socket. * * @param localPort the local port to forward * @param remoteSocketName name of the unix domain socket created on the device * @param namespace namespace in which the unix domain socket was created * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException in case of I/O error on the connection. */ void createForward(int localPort, String remoteSocketName, DeviceUnixSocketNamespace namespace) throws TimeoutException, AdbCommandRejectedException, IOException; /** * Removes a port forwarding between a local and a remote port. * * @param localPort the local port to forward * @param remotePort the remote port. * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException in case of I/O error on the connection. */ void removeForward(int localPort, int remotePort) throws TimeoutException, AdbCommandRejectedException, IOException; /** * Removes an existing port forwarding between a local and a remote port. Removes an existing * port forwarding between a local and a remote port. * * @param localPort the local port to forward * @param remoteSocketName the remote unix domain socket name. * @param namespace namespace in which the unix domain socket was created * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException in case of I/O error on the connection. */ void removeForward(int localPort, String remoteSocketName, DeviceUnixSocketNamespace namespace) throws TimeoutException, AdbCommandRejectedException, IOException; /** * Returns the name of the client by pid or <code>null</code> if pid is unknown * * @param pid the pid of the client. */ String getClientName(int pid); /** * Pushes several files or directories. * * @param local the local files to push * @param remote the remote path representing a directory * @throws IOException in case of I/O error on the connection * @throws AdbCommandRejectedException if adb rejects the command * @throws TimeoutException in case of a timeout reading responses from the device * @throws SyncException if some files could not be pushed */ default void push(@NonNull String[] local, @NonNull String remote) throws IOException, AdbCommandRejectedException, TimeoutException, SyncException { throw new UnsupportedOperationException(); } /** * Pushes a single file. * * @param local the local filepath. * @param remote the remote filepath * @throws IOException in case of I/O error on the connection * @throws AdbCommandRejectedException if adb rejects the command * @throws TimeoutException in case of a timeout reading responses from the device * @throws SyncException if the file could not be pushed */ void pushFile(@NonNull String local, @NonNull String remote) throws IOException, AdbCommandRejectedException, TimeoutException, SyncException; /** * Pulls a single file. * * @param remote the full path to the remote file * @param local The local destination. * @throws IOException in case of an IO exception. * @throws AdbCommandRejectedException if adb rejects the command * @throws TimeoutException in case of a timeout reading responses from the device. * @throws SyncException in case of a sync exception. */ void pullFile(String remote, String local) throws IOException, AdbCommandRejectedException, TimeoutException, SyncException; /** * Installs an Android application on device. This is a helper method that combines the * syncPackageToDevice, installRemotePackage, and removePackage steps * * @param packageFilePath the absolute file system path to file on local host to install * @param reinstall set to <code>true</code> if re-install of app should be performed * @param extraArgs optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @throws InstallException if the installation fails. */ void installPackage(String packageFilePath, boolean reinstall, String... extraArgs) throws InstallException; /** * Installs an Android application on device. This is a helper method that combines the * syncPackageToDevice, installRemotePackage, and removePackage steps * * @param packageFilePath the absolute file system path to file on local host to install * @param reinstall set to <code>true</code> if re-install of app should be performed * @param receiver The {@link InstallReceiver} to be used to monitor the install and get final * status. * @param extraArgs optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @throws InstallException if the installation fails. */ void installPackage( String packageFilePath, boolean reinstall, InstallReceiver receiver, String... extraArgs) throws InstallException; /** * Installs an Android application on device. This is a helper method that combines the * syncPackageToDevice, installRemotePackage, and removePackage steps * * @param packageFilePath the absolute file system path to file on local host to install * @param reinstall set to <code>true</code> if re-install of app should be performed * @param receiver The {@link InstallReceiver} to be used to monitor the install and get final * status. * @param maxTimeout the maximum timeout for the command to return. A value of 0 means no max * timeout will be applied. * @param maxTimeToOutputResponse the maximum amount of time during which the command is allowed * to not output any response. A value of 0 means the method will wait forever (until the * <var>receiver</var> cancels the execution) for command output and never throw. * @param maxTimeUnits Units for non-zero {@code maxTimeout} and {@code maxTimeToOutputResponse} * values. * @param extraArgs optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @throws InstallException if the installation fails. */ void installPackage( String packageFilePath, boolean reinstall, InstallReceiver receiver, long maxTimeout, long maxTimeToOutputResponse, TimeUnit maxTimeUnits, String... extraArgs) throws InstallException; /** * Installs an Android application made of several APK files (one main and 0..n split packages) * * @param apks list of apks to install (1 main APK + 0..n split apks) * @param reinstall set to <code>true</code> if re-install of app should be performed * @param installOptions optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @param timeout installation timeout * @param timeoutUnit {@link TimeUnit} corresponding to the timeout parameter * @throws InstallException if the installation fails. */ void installPackages( @NonNull List<File> apks, boolean reinstall, @NonNull List<String> installOptions, long timeout, @NonNull TimeUnit timeoutUnit) throws InstallException; /** * Installs an Android application made of several APK files (one main and 0..n split packages) * with default timeout * * @param apks list of apks to install (1 main APK + 0..n split apks) * @param reinstall set to <code>true</code> if re-install of app should be performed * @param installOptions optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @throws InstallException if the installation fails. */ default void installPackages( @NonNull List<File> apks, boolean reinstall, @NonNull List<String> installOptions) throws InstallException { throw new UnsupportedOperationException(); } /** * Gets the information about the most recent installation on this device. * * @return {@link InstallMetrics} metrics describing the installation. */ default InstallMetrics getLastInstallMetrics() { throw new UnsupportedOperationException(); } /** * Installs an Android application made of several APK files sitting locally on the device * * @param remoteApks list of apk file paths sitting on the device to install * @param reinstall set to <code>true</code> if re-install of app should be performed * @param installOptions optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @param timeout installation timeout * @param timeoutUnit {@link TimeUnit} corresponding to the timeout parameter * @throws InstallException if the installation fails. */ default void installRemotePackages( @NonNull List<String> remoteApks, boolean reinstall, @NonNull List<String> installOptions, long timeout, @NonNull TimeUnit timeoutUnit) throws InstallException { throw new UnsupportedOperationException(); } /** * Installs an Android application made of several APK files sitting locally on the device with * default timeout * * @param remoteApks list of apk file paths on the device to install * @param reinstall set to <code>true</code> if re-install of app should be performed * @param installOptions optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @throws InstallException if the installation fails. */ default void installRemotePackages( @NonNull List<String> remoteApks, boolean reinstall, @NonNull List<String> installOptions) throws InstallException { throw new UnsupportedOperationException(); } /** * Pushes a file to device * * @param localFilePath the absolute path to file on local host * @return {@link String} destination path on device for file * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException in case of I/O error on the connection. * @throws SyncException if an error happens during the push of the package on the device. */ String syncPackageToDevice(String localFilePath) throws TimeoutException, AdbCommandRejectedException, IOException, SyncException; /** * Installs the application package that was pushed to a temporary location on the device. * * @param remoteFilePath absolute file path to package file on device * @param reinstall set to <code>true</code> if re-install of app should be performed * @param extraArgs optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @throws InstallException if the installation fails. * @see #installRemotePackage(String, boolean, InstallReceiver, long, long, TimeUnit, String...) */ void installRemotePackage(String remoteFilePath, boolean reinstall, String... extraArgs) throws InstallException; /** * Installs the application package that was pushed to a temporary location on the device. * * @param remoteFilePath absolute file path to package file on device * @param reinstall set to <code>true</code> if re-install of app should be performed * @param receiver The {@link InstallReceiver} to be used to monitor the install and get final * status. * @param extraArgs optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @throws InstallException if the installation fails. * @see #installRemotePackage(String, boolean, InstallReceiver, long, long, TimeUnit, String...) */ void installRemotePackage( String remoteFilePath, boolean reinstall, InstallReceiver receiver, String... extraArgs) throws InstallException; /** * Installs the application package that was pushed to a temporary location on the device. * * @param remoteFilePath absolute file path to package file on device * @param reinstall set to <code>true</code> if re-install of app should be performed * @param receiver The {@link InstallReceiver} to be used to monitor the install and get final * status. * @param maxTimeout the maximum timeout for the command to return. A value of 0 means no max * timeout will be applied. * @param maxTimeToOutputResponse the maximum amount of time during which the command is allowed * to not output any response. A value of 0 means the method will wait forever (until the * <var>receiver</var> cancels the execution) for command output and never throw. * @param maxTimeUnits Units for non-zero {@code maxTimeout} and {@code maxTimeToOutputResponse} * values. * @param extraArgs optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @throws InstallException if the installation fails. */ void installRemotePackage( String remoteFilePath, boolean reinstall, InstallReceiver receiver, long maxTimeout, long maxTimeToOutputResponse, TimeUnit maxTimeUnits, String... extraArgs) throws InstallException; /** * Removes a file from device. * * @param remoteFilePath path on device of file to remove * @throws InstallException if the installation fails. */ void removeRemotePackage(String remoteFilePath) throws InstallException; /** * Uninstalls a package from the device. * * @param packageName the Android application ID to uninstall * @return a {@link String} with an error code, or <code>null</code> if success. * @throws InstallException if the uninstallation fails. */ String uninstallPackage(String packageName) throws InstallException; /** * Uninstalls an app from the device. * * @param applicationID the Android application ID to uninstall * @param extraArgs optional extra arguments to pass. See 'adb shell pm install --help' for * available options. * @return a {@link String} with an error code, or <code>null</code> if success. * @throws InstallException if the uninstallation fails. */ String uninstallApp(String applicationID, String... extraArgs) throws InstallException; /** * Reboot the device. * * @param into the bootloader name to reboot into, or null to just reboot the device. * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException */ void reboot(String into) throws TimeoutException, AdbCommandRejectedException, IOException; /** * Ask the adb daemon to become root on the device. This may silently fail, and can only succeed * on developer builds. See "adb root" for more information. * * @return true if the adb daemon is running as root, otherwise false. * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command. * @throws ShellCommandUnresponsiveException if the root status cannot be queried. * @throws IOException */ boolean root() throws TimeoutException, AdbCommandRejectedException, IOException, ShellCommandUnresponsiveException; /** * Queries the current root-status of the device. See "adb root" for more information. * * @return true if the adb daemon is running as root, otherwise false. * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command. */ boolean isRoot() throws TimeoutException, AdbCommandRejectedException, IOException, ShellCommandUnresponsiveException; /** * Return the device's battery level, from 0 to 100 percent. * * <p>The battery level may be cached. Only queries the device for its battery level if 5 * minutes have expired since the last successful query. * * @return the battery level or <code>null</code> if it could not be retrieved * @deprecated use {@link #getBattery()} */ @Deprecated Integer getBatteryLevel() throws TimeoutException, AdbCommandRejectedException, IOException, ShellCommandUnresponsiveException; /** * Return the device's battery level, from 0 to 100 percent. * * <p>The battery level may be cached. Only queries the device for its battery level if <code> * freshnessMs</code> ms have expired since the last successful query. * * @param freshnessMs * @return the battery level or <code>null</code> if it could not be retrieved * @throws ShellCommandUnresponsiveException * @deprecated use {@link #getBattery(long, TimeUnit)} */ @Deprecated Integer getBatteryLevel(long freshnessMs) throws TimeoutException, AdbCommandRejectedException, IOException, ShellCommandUnresponsiveException; /** * Return the device's battery level, from 0 to 100 percent. * * <p>The battery level may be cached. Only queries the device for its battery level if 5 * minutes have expired since the last successful query. * * @return a {@link Future} that can be used to query the battery level. The Future will return * a {@link ExecutionException} if battery level could not be retrieved. */ @NonNull Future<Integer> getBattery(); /** * Return the device's battery level, from 0 to 100 percent. * * <p>The battery level may be cached. Only queries the device for its battery level if <code> * freshnessTime</code> has expired since the last successful query. * * @param freshnessTime the desired recency of battery level * @param timeUnit the {@link TimeUnit} of freshnessTime * @return a {@link Future} that can be used to query the battery level. The Future will return * a {@link ExecutionException} if battery level could not be retrieved. */ @NonNull Future<Integer> getBattery(long freshnessTime, @NonNull TimeUnit timeUnit); /** * Returns the ABIs supported by this device. The ABIs are sorted in preferred order, with the * first ABI being the most preferred. * * @return the list of ABIs. */ @NonNull List<String> getAbis(); /** * Returns the density bucket of the device screen by reading the value for system property * {@link #PROP_DEVICE_DENSITY}. * * @return the density, or -1 if it cannot be determined. */ int getDensity(); /** * Returns the user's language. * * @return the user's language, or null if it's unknown */ @Nullable String getLanguage(); /** * Returns the user's region. * * @return the user's region, or null if it's unknown */ @Nullable String getRegion(); /** * Returns the API level of the device. * * @return the API level if it can be determined, {@link AndroidVersion#DEFAULT} otherwise. */ @NonNull AndroidVersion getVersion(); /** * Invoke the host:exec service on a remote device. Return a socket channel that is connected to * the executing process. Note that exec service does not differentiate stdout and stderr so * whatever is read from the socket can come from either output and be interleaved. * * <p>Ownership of the SocketChannel is relinquished to the caller, it must be explicitly closed * after usage. * * @return A SocketChannel connected to the executing process on the device. after use. */ default SocketChannel rawExec(String executable, String[] parameters) throws AdbCommandRejectedException, TimeoutException, IOException { throw new UnsupportedOperationException(); } /** * Invoke the Android Binder Bridge service on a remote device. Return a socket channel that is * connected to the device binder command. * * <p>Ownership of the SocketChannel is relinquished to the caller, it must be explicitly closed * after usage. * * @param service the name of the Android service to connect to * @param parameters the parameters of the binder command * @return A SocketChannel connected to the executing process on the device. after use. */ default SocketChannel rawBinder(String service, String[] parameters) throws AdbCommandRejectedException, TimeoutException, IOException { throw new UnsupportedOperationException(); } /** Returns features obtained by reading the build characteristics property. */ default Set<String> getHardwareCharacteristics() throws Exception { String characteristics = getProperty(PROP_BUILD_CHARACTERISTICS); if (characteristics == null) { return Collections.emptySet(); } return Sets.newHashSet(Splitter.on(',').split(characteristics)); } }
3e1430b391e92b09fb733e9e2e3ae0cda8e82104
5,039
java
Java
tests/java/com/twitter/common/quantity/AmountTest.java
Ranjan2002/commons
fbe015322ada1975f53a3dbfd1ac46f1d14c05dc
[ "Apache-2.0" ]
1,143
2015-01-05T04:19:24.000Z
2019-12-11T12:02:23.000Z
tests/java/com/twitter/common/quantity/AmountTest.java
Ranjan2002/commons
fbe015322ada1975f53a3dbfd1ac46f1d14c05dc
[ "Apache-2.0" ]
144
2015-01-06T05:05:07.000Z
2019-12-12T18:02:37.000Z
tests/java/com/twitter/common/quantity/AmountTest.java
Ranjan2002/commons
fbe015322ada1975f53a3dbfd1ac46f1d14c05dc
[ "Apache-2.0" ]
426
2015-01-08T08:33:41.000Z
2019-12-09T13:15:40.000Z
41.644628
100
0.651717
8,539
// ================================================================================================= // Copyright 2011 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.quantity; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import org.junit.Test; import static com.google.common.testing.junit4.JUnitAsserts.assertNotEqual; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author John Sirois */ public class AmountTest { @Test public void testEquals() { assertEquals("expected value equality semantics", Amount.of(1L, Time.DAYS), Amount.of(1L, Time.DAYS)); assertEquals("expected equality to be calculated from amounts converted to a common unit", Amount.of(1L, Time.DAYS), Amount.of(24L, Time.HOURS)); assertNotEqual("expected unit conversions for equality tests to not lose precision", Amount.of(25L, Time.HOURS), Amount.of(1L, Time.DAYS)); assertNotEqual("expected unit conversions for equality tests to not lose precision", Amount.of(1L, Time.DAYS), Amount.of(25L, Time.HOURS)); assertFalse("expected value equality to work only for the same Number types", Amount.of(1L, Time.DAYS).equals(Amount.of(1.0, Time.DAYS))); assertFalse("expected value equality to work only for the same Number types", Amount.of(1L, Time.DAYS).equals(Amount.of(1, Time.DAYS))); assertFalse("amounts with incompatible units should never be equal even if their values are", Amount.of(1L, Time.NANOSECONDS).equals(Amount.of(1L, Data.BITS))); } @Test public void testComparisonMixedUnits() { assertTrue(Amount.of(1, Time.MINUTES).compareTo(Amount.of(59, Time.SECONDS)) > 0); assertTrue(Amount.of(1, Time.MINUTES).compareTo(Amount.of(60, Time.SECONDS)) == 0); assertTrue(Amount.of(1, Time.MINUTES).compareTo(Amount.of(61, Time.SECONDS)) < 0); assertTrue(Amount.of(59, Time.SECONDS).compareTo(Amount.of(1, Time.MINUTES)) < 0); assertTrue(Amount.of(60, Time.SECONDS).compareTo(Amount.of(1, Time.MINUTES)) == 0); assertTrue(Amount.of(61, Time.SECONDS).compareTo(Amount.of(1, Time.MINUTES)) > 0); } @Test @SuppressWarnings("unchecked") // Needed because type information lost in vargs. public void testOrderingMixedUnits() { assertEquals( Lists.newArrayList( Amount.of(1, Data.BITS), Amount.of(1, Data.KB), Amount.of(1, Data.MB), Amount.of(1, Data.MB)), Ordering.natural().sortedCopy(Lists.newArrayList( Amount.of(1, Data.KB), Amount.of(1024, Data.KB), Amount.of(1, Data.BITS), Amount.of(1, Data.MB)))); } @Test @SuppressWarnings("unchecked") // Needed because type information lost in vargs. public void testOrderingSameUnits() { assertEquals( Lists.newArrayList( Amount.of(1, Time.MILLISECONDS), Amount.of(2, Time.MILLISECONDS), Amount.of(3, Time.MILLISECONDS), Amount.of(4, Time.MILLISECONDS)), Ordering.natural().sortedCopy(Lists.newArrayList( Amount.of(3, Time.MILLISECONDS), Amount.of(2, Time.MILLISECONDS), Amount.of(1, Time.MILLISECONDS), Amount.of(4, Time.MILLISECONDS)))); } @Test public void testConvert() { Amount<Long, Time> integralDuration = Amount.of(15L, Time.MINUTES); assertEquals(Long.valueOf(15 * 60 * 1000), integralDuration.as(Time.MILLISECONDS)); assertEquals("expected conversion losing precision to use truncation", Long.valueOf(0), integralDuration.as(Time.HOURS)); assertEquals("expected conversion losing precision to use truncation", Long.valueOf(0), Amount.of(45L, Time.MINUTES).as(Time.HOURS)); Amount<Double, Time> decimalDuration = Amount.of(15.0, Time.MINUTES); assertEquals(Double.valueOf(15 * 60 * 1000), decimalDuration.as(Time.MILLISECONDS)); assertEquals(Double.valueOf(0.25), decimalDuration.as(Time.HOURS)); } @Test(expected = Amount.TypeOverflowException.class) public void testAmountThrowsTypeOverflowException() { Amount.of(1000, Time.DAYS).asChecked(Time.MILLISECONDS); } }
3e1431972b755770c22bf45246e8484c64faf8c8
1,561
java
Java
src/java/simpledb/storage/HeapPageId.java
LebronAl/simple-db-hw-2021
37d5083e6bcff15e220afd7458839afe2453e8fd
[ "MIT" ]
null
null
null
src/java/simpledb/storage/HeapPageId.java
LebronAl/simple-db-hw-2021
37d5083e6bcff15e220afd7458839afe2453e8fd
[ "MIT" ]
null
null
null
src/java/simpledb/storage/HeapPageId.java
LebronAl/simple-db-hw-2021
37d5083e6bcff15e220afd7458839afe2453e8fd
[ "MIT" ]
null
null
null
22.3
100
0.650865
8,540
package simpledb.storage; import java.util.Objects; /** * Unique identifier for HeapPage objects. */ public class HeapPageId implements PageId { private final int tableId; private final int pageNumber; /** * Constructor. Create a page id structure for a specific page of a specific table. * * @param tableId The table that is being referenced * @param pageNumber The page number in that table. */ public HeapPageId(int tableId, int pageNumber) { this.tableId = tableId; this.pageNumber = pageNumber; } /** * @return the table associated with this PageId */ public int getTableId() { return tableId; } /** * @return the page number in the table getTableId() associated with this PageId */ public int getPageNumber() { return pageNumber; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } HeapPageId that = (HeapPageId) o; return tableId == that.tableId && pageNumber == that.pageNumber; } @Override public int hashCode() { return Objects.hash(tableId, pageNumber); } /** * Return a representation of this object as an array of integers, for writing to disk. Size of * returned array must contain number of integers that corresponds to number of args to one of the * constructors. */ public int[] serialize() { int[] data = new int[2]; data[0] = getTableId(); data[1] = getPageNumber(); return data; } }
3e1431d2092c428c069f8ae4ab0da42f49c0f0b9
345
java
Java
source/chapter7/7.1/7.1.2/hello2/src/com/droider/hello2/MyActiviry.java
TopGuo/android_learn_nixiang
da1876e1949ae9f40a7222dd1ca9eb13916a35a9
[ "MIT" ]
null
null
null
source/chapter7/7.1/7.1.2/hello2/src/com/droider/hello2/MyActiviry.java
TopGuo/android_learn_nixiang
da1876e1949ae9f40a7222dd1ca9eb13916a35a9
[ "MIT" ]
null
null
null
source/chapter7/7.1/7.1.2/hello2/src/com/droider/hello2/MyActiviry.java
TopGuo/android_learn_nixiang
da1876e1949ae9f40a7222dd1ca9eb13916a35a9
[ "MIT" ]
null
null
null
21.5625
53
0.710145
8,541
package com.droider.hello2; import android.app.Activity; import android.os.Bundle; public class MyActiviry extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
3e14325ae0382d3c4b154d5eb4f963bd43a34b03
1,391
java
Java
line-bot-model/src/main/java/com/linecorp/bot/model/message/flex/component/FlexComponent.java
okue/line-bot-sdk-java
e89cce60145321a49349c3e58ac4e138d7fd5c24
[ "Apache-2.0" ]
587
2016-04-15T23:41:16.000Z
2022-03-29T14:28:18.000Z
line-bot-model/src/main/java/com/linecorp/bot/model/message/flex/component/FlexComponent.java
okue/line-bot-sdk-java
e89cce60145321a49349c3e58ac4e138d7fd5c24
[ "Apache-2.0" ]
510
2016-04-18T01:40:25.000Z
2022-03-30T09:52:19.000Z
line-bot-model/src/main/java/com/linecorp/bot/model/message/flex/component/FlexComponent.java
okue/line-bot-sdk-java
e89cce60145321a49349c3e58ac4e138d7fd5c24
[ "Apache-2.0" ]
1,061
2016-04-15T13:02:48.000Z
2022-03-30T09:50:29.000Z
33.926829
78
0.718188
8,542
/* * Copyright 2018 LINE Corporation * * LINE Corporation licenses this file to you 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.linecorp.bot.model.message.flex.component; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; @JsonSubTypes({ @JsonSubTypes.Type(Text.class), @JsonSubTypes.Type(Span.class), @JsonSubTypes.Type(Image.class), @JsonSubTypes.Type(Box.class), @JsonSubTypes.Type(Separator.class), @JsonSubTypes.Type(Filler.class), @JsonSubTypes.Type(Button.class), @JsonSubTypes.Type(Icon.class), @JsonSubTypes.Type(Spacer.class), }) @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type" ) public interface FlexComponent { }
3e1432aab314920ef567bb8999283fd0a6e4ccb0
11,689
java
Java
app/src/main/java/com/huangtao/meetingroom/fragment/MainBusyFragment.java
ist-fwwb/meetingroom-android
85cf18ea66f57612e54bce782653831d8f22f070
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/huangtao/meetingroom/fragment/MainBusyFragment.java
ist-fwwb/meetingroom-android
85cf18ea66f57612e54bce782653831d8f22f070
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/huangtao/meetingroom/fragment/MainBusyFragment.java
ist-fwwb/meetingroom-android
85cf18ea66f57612e54bce782653831d8f22f070
[ "Apache-2.0" ]
1
2018-12-25T09:05:37.000Z
2018-12-25T09:05:37.000Z
35.855828
120
0.593378
8,543
package com.huangtao.meetingroom.fragment; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.format.Time; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.blankj.utilcode.util.TimeUtils; import com.huangtao.dialog.QRCodeDialog; import com.huangtao.meetingroom.R; import com.huangtao.meetingroom.adapter.RecyclerAttendantsAdapter; import com.huangtao.meetingroom.arcsoft.RegisterAndRecognizeActivity; import com.huangtao.meetingroom.common.Constants; import com.huangtao.meetingroom.common.MyLazyFragment; import com.huangtao.meetingroom.helper.CommonUtils; import com.huangtao.meetingroom.model.Meeting; import com.huangtao.meetingroom.model.User; import com.huangtao.meetingroom.network.Network; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.header.BezierRadarHeader; import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import com.uuzuche.lib_zxing.activity.CodeUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; import butterknife.BindView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static android.app.Activity.RESULT_OK; //TODO 物联网 + 会议自动延时或者强制关闭时自动关门 public class MainBusyFragment extends MyLazyFragment { final String TAG = "MainBusyFragment"; static MainBusyFragment mainBusyFragment = null; @BindView(R.id.recyclerView) RecyclerView recyclerView; @BindView(R.id.signin) Button signinButton; @BindView(R.id.signout) Button signoutButton; @BindView(R.id.qrcode) ImageView qrcode; @BindView(R.id.refreshLayout) SmartRefreshLayout refreshLayout; @BindView(R.id.list_container) LinearLayout linearLayout; @BindView(R.id.meetingroom_name) TextView meetingroom_name; Meeting meeting; ProgressDialog progressDialog; RecyclerAttendantsAdapter attendantsAdapter; public static MainBusyFragment getInstance(){ if (mainBusyFragment == null){ synchronized (MainBusyFragment.class){ if (mainBusyFragment == null){ mainBusyFragment = new MainBusyFragment(); } } } return mainBusyFragment; } @Override protected int getLayoutId() { return R.layout.fragment_main_busy; } @Override protected int getTitleBarId() { return 0; } @Override protected void initView() { //View header = LayoutInflater.from(getFragmentActivity()).inflate(R.layout.item_main_busy_header, null, false); progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("正在加载中……"); meetingroom_name.setText(Constants.ROOM_NAME); if (!meeting.isNeedSignIn()) { signinButton.setVisibility(View.GONE); linearLayout.setVisibility(View.GONE); } } public void setMeeting(Meeting meeting) { this.meeting = meeting; } @Override protected void initData() { final ImageView listRefresh = findViewById(R.id.list_refresh); attendantsAdapter = new RecyclerAttendantsAdapter(getContext(), new ArrayList<Map.Entry<String, String>>()); recyclerView.setAdapter(attendantsAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL)); initList(); initRefreshLayout(); listRefresh.setOnClickListener((v)->{ listRefresh.setEnabled(false); refreshList(); }); signinButton.setOnClickListener((v)->{ startActivityForResult(new Intent(getActivity(), RegisterAndRecognizeActivity.class), 0); }); signoutButton.setOnClickListener((v)->{ //TODO 将状态设置为结束(取消掉注释) //meeting.setStatus(Status.Stopped); closeDoor(); Network.getInstance().modifyMeeting(meeting, meeting.getId()).enqueue(new Callback<Meeting>() { @Override public void onResponse(Call<Meeting> call, Response<Meeting> response) { Log.i(TAG, "结束会议成功"); Log.i(TAG, meeting.toString()); closeDoor(); getActivity().getSupportFragmentManager() .beginTransaction() .replace(R.id.fragment_layout, MainFreeFragment.getInstance(), null) .addToBackStack(null) .commit(); } @Override public void onFailure(Call<Meeting> call, Throwable t) { Log.i(TAG, "结束会议失败"); } }); }); qrcode.setOnClickListener((v)->{ QRCodeDialog.Builder dialog = new QRCodeDialog.Builder(getFragmentActivity()); dialog.setQrcode(CodeUtils.createImage(Constants.ROOM_ID, 400, 400, null)); dialog.create().show(); }); } private void closeDoor() { if(Constants.bluetoothSocket == null){ toast("蓝牙未连接"); } else if(!Constants.bluetoothSocket.isConnected()){ CommonUtils.connectRelay(); } CommonUtils.closeRelay(); } private void initList(){ final TextView listRefreshTime = findViewById(R.id.list_refresh_time); final ImageView listRefresh = findViewById(R.id.list_refresh); List<Map.Entry<String, String>> attendants = new ArrayList<>(meeting.getAttendantsName().entrySet()); attendants.sort((x,y)->{ return CommonUtils.compareDate(x.getValue(), y.getValue()); }); attendantsAdapter.setData(attendants); listRefreshTime.setText("上次更新: " + TimeUtils.millis2String(System.currentTimeMillis())); listRefresh.setEnabled(true); Log.i(TAG, meeting.toString()); } private void refreshList(){ final TextView listRefreshTime = findViewById(R.id.list_refresh_time); final ImageView listRefresh = findViewById(R.id.list_refresh); Network.getInstance().queryMeetingById(meeting.getId()).enqueue(new Callback<Meeting>() { @Override public void onResponse(Call<Meeting> call, Response<Meeting> response) { meeting = response.body(); List<Map.Entry<String, String>> attendants = new ArrayList<>(meeting.getAttendantsName().entrySet()); attendants.sort((x,y)->{ return CommonUtils.compareDate(x.getValue(), y.getValue()); }); attendantsAdapter.setData(attendants); listRefreshTime.setText("上次更新: " + TimeUtils.millis2String(System.currentTimeMillis())); listRefresh.setEnabled(true); Log.i(TAG, meeting.toString()); } @Override public void onFailure(Call<Meeting> call, Throwable t) { t.printStackTrace(); } }); } private void initRefreshLayout() { refreshLayout.setRefreshHeader(new BezierRadarHeader(getContext()).setEnableHorizontalDrag(true)); refreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(RefreshLayout refreshlayout) { refreshList(); refreshlayout.finishRefresh(true);//传入false表示刷新失败 } }); refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() { @Override public void onLoadMore(RefreshLayout refreshlayout) { refreshlayout.finishLoadMore(500);//传入false表示加载失败 } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK){ toast("人脸识别成功"); String featureFileName = data.getStringExtra("featureFileName"); Log.i(TAG, featureFileName); Network.getInstance().queryUser(null, null, featureFileName).enqueue(new Callback<List<User>>() { @Override public void onResponse(Call<List<User>> call, Response<List<User>> response) { Log.i(TAG, "获取user信息成功"); User user = response.body().get(0); String id = user.getId(); meeting.getAttendants().put(id, CommonUtils.getTime()); Network.getInstance().modifyMeeting(meeting, meeting.getId()).enqueue(new Callback<Meeting>() { @Override public void onResponse(Call<Meeting> call, Response<Meeting> response) { meeting = response.body(); if (!meeting.modifyMeetingSuccessful()){ toast("上传服务器失败,请重试"); } else{ Log.i(TAG, "修改会议状态成功"); Log.i(TAG, meeting.toString()); toast("欢迎你, " + user.getName()); if (meeting.isNeedSignIn()){ openDoor(); } initList(); } } @Override public void onFailure(Call<Meeting> call, Throwable t) { Log.i(TAG, "修改会议状态失败"); } }); } @Override public void onFailure(Call<List<User>> call, Throwable t) { } }); } else { toast("人脸识别失败"); } } @Override public void onResume() { super.onResume(); if (meeting.isNeedSignIn()){ new Thread(()->{ //延时30秒关门 try { Thread.sleep(30000); closeDoor(); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } if (!meeting.isNeedSignIn()) { signinButton.setVisibility(View.GONE); linearLayout.setVisibility(View.GONE); } initList(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { return true; } return false; } private void openDoor() { if(Constants.bluetoothSocket == null){ toast("蓝牙未连接"); } else if(!Constants.bluetoothSocket.isConnected()){ CommonUtils.connectRelay(); } CommonUtils.openRelay(); new Thread(()->{ //延时30秒关门 try { Thread.sleep(30000); closeDoor(); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } }
3e14336ab98da8cba6d4185fc38ea46e6c96212a
205
java
Java
src/main/java/org/thedryden/workmanager/Status.java
thedryden/workmanager
dba2185366d2f91cc886fa9bb84405662b12f1c1
[ "Apache-2.0" ]
null
null
null
src/main/java/org/thedryden/workmanager/Status.java
thedryden/workmanager
dba2185366d2f91cc886fa9bb84405662b12f1c1
[ "Apache-2.0" ]
null
null
null
src/main/java/org/thedryden/workmanager/Status.java
thedryden/workmanager
dba2185366d2f91cc886fa9bb84405662b12f1c1
[ "Apache-2.0" ]
null
null
null
20.5
60
0.726829
8,544
package org.thedryden.workmanager; /*** * Enum for the various statuses that a Worker can be in * @author thedr * */ public enum Status { EMPTY, PENDING, RUNNING, SUCCESS, FAILED, PRECEDENCE_FAILED }
3e14346bc05533e6735d5e91631b7c0126653b17
1,144
java
Java
src/main/java/com/timeyang/amanda/core/valadation/NotBlank.java
codeSourc3/amanda
60883b77f56f1d053de02d9dff2d3f4e27279448
[ "Apache-2.0" ]
8
2017-05-06T15:16:57.000Z
2021-06-23T08:02:13.000Z
src/main/java/com/timeyang/amanda/core/valadation/NotBlank.java
codeSourc3/amanda
60883b77f56f1d053de02d9dff2d3f4e27279448
[ "Apache-2.0" ]
null
null
null
src/main/java/com/timeyang/amanda/core/valadation/NotBlank.java
codeSourc3/amanda
60883b77f56f1d053de02d9dff2d3f4e27279448
[ "Apache-2.0" ]
6
2017-09-09T05:09:00.000Z
2020-12-13T20:34:58.000Z
28.6
82
0.756993
8,545
package com.timeyang.amanda.core.valadation; import org.hibernate.validator.internal.constraintvalidators.hv.NotBlankValidator; import javax.validation.Constraint; import javax.validation.Payload; import javax.validation.ReportAsSingleViolation; import javax.validation.constraints.NotNull; import java.lang.annotation.*; /** * 字符串内容不为空约束 * * @author chaokunyang * @create 2017-04-15 */ @SuppressWarnings("unused") @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint(validatedBy = {NotBlankValidator.class}) @NotNull @ReportAsSingleViolation public @interface NotBlank { String message() default "{com.timeyang.validation.NotBlank.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented @interface List { NotBlank[] value(); } }
3e14349dbeec38168b9bfea0cceddab69c18ac24
2,884
java
Java
app/src/main/java/com/mobilesaaj/neeraj/siminfo/SimActivity.java
neeraj-singh/SimInfo
3a15aba9cb18ec205dc259ca9136176491b484a4
[ "MIT" ]
null
null
null
app/src/main/java/com/mobilesaaj/neeraj/siminfo/SimActivity.java
neeraj-singh/SimInfo
3a15aba9cb18ec205dc259ca9136176491b484a4
[ "MIT" ]
null
null
null
app/src/main/java/com/mobilesaaj/neeraj/siminfo/SimActivity.java
neeraj-singh/SimInfo
3a15aba9cb18ec205dc259ca9136176491b484a4
[ "MIT" ]
null
null
null
33.929412
116
0.684813
8,546
package com.mobilesaaj.neeraj.siminfo; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.telephony.TelephonyManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class SimActivity extends ActionBarActivity { TelephonyManager telephonyManager ; private TextView simNumber; private Button simInfo; private LinearLayout infoLayout; private Button btnCopy; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sim); telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); simInfo = (Button)findViewById(R.id.btnsim); infoLayout = (LinearLayout)findViewById(R.id.infoLayout); simInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fetchInfo(); } }); simNumber = (TextView)findViewById(R.id.txtsim); btnCopy = (Button)findViewById(R.id.btncopy); btnCopy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { copyInfo(); } }); } private void fetchInfo() { String simSerial = telephonyManager.getSimSerialNumber(); simInfo.setVisibility(View.GONE); infoLayout.setVisibility(View.VISIBLE); simNumber.setText(simSerial); } public void copyInfo(){ ClipboardManager cManager = (ClipboardManager) SimActivity.this.getSystemService(Context.CLIPBOARD_SERVICE); ClipData cData = ClipData.newPlainText("text", simNumber.getText()); cManager.setPrimaryClip(cData); Toast.makeText(SimActivity.this,"Sim Number is copied to clip board.",Toast.LENGTH_LONG).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_sim, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
3e1434ff4ce2f35c2c1eb0d762c550d733f7552a
441
java
Java
lelefruit-ware/src/main/java/com/tianjin/lelefruit/ware/service/UndoLogService.java
ToneXu/lelefruit
7fea94b5845676bc047ab5ba464139302fbd2628
[ "Apache-2.0" ]
5
2021-04-20T10:21:28.000Z
2021-11-07T20:26:38.000Z
lelefruit-ware/src/main/java/com/tianjin/lelefruit/ware/service/UndoLogService.java
T0ngXu/lelefruit
7fea94b5845676bc047ab5ba464139302fbd2628
[ "Apache-2.0" ]
null
null
null
lelefruit-ware/src/main/java/com/tianjin/lelefruit/ware/service/UndoLogService.java
T0ngXu/lelefruit
7fea94b5845676bc047ab5ba464139302fbd2628
[ "Apache-2.0" ]
null
null
null
21.095238
65
0.76298
8,547
package com.tianjin.lelefruit.ware.service; import com.baomidou.mybatisplus.extension.service.IService; import com.tianjin.common.utils.PageUtils; import com.tianjin.lelefruit.ware.entity.UndoLogEntity; import java.util.Map; /** * * * @author xutong * @email upchh@example.com * @date 2021-04-13 14:51:14 */ public interface UndoLogService extends IService<UndoLogEntity> { PageUtils queryPage(Map<String, Object> params); }
3e14361e03e763764a37c3f653b1becb2f8f9662
14,996
java
Java
trace-web/src/main/java/com/ewcms/trace/entity/Trace.java
konglinghai123/rmyy
37608072c8b4126ce4275676e518e71612049f26
[ "Apache-2.0" ]
null
null
null
trace-web/src/main/java/com/ewcms/trace/entity/Trace.java
konglinghai123/rmyy
37608072c8b4126ce4275676e518e71612049f26
[ "Apache-2.0" ]
null
null
null
trace-web/src/main/java/com/ewcms/trace/entity/Trace.java
konglinghai123/rmyy
37608072c8b4126ce4275676e518e71612049f26
[ "Apache-2.0" ]
1
2019-12-11T08:16:18.000Z
2019-12-11T08:16:18.000Z
20.856745
68
0.665577
8,548
package com.ewcms.trace.entity; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.springframework.format.annotation.DateTimeFormat; import com.alibaba.fastjson.annotation.JSONField; import com.ewcms.common.entity.AbstractEntity; /** * * @author wu_zhijun */ @Entity @Table(name = "T_Trace") public class Trace extends AbstractEntity<String>{ private static final long serialVersionUID = 4228413222452893821L; @Column(name = "id") private String id; @Id @Column(name = "CPID") private String cpid; @Column(name = "产品序号") private String productId; @Column(name = "产品编号") private String productNumber; @Column(name = "产品名称") private String productName; @Column(name = "产品分类") private String productCategory; @Column(name = "产品组别") private String productGroup; @Column(name = "单位") private String unit; @Column(name = "拼音") private String pinYin; @Column(name = "规格") private String standard; @Column(name = "型号") private String model; @Column(name = "供应商") private String supplier; @Column(name = "生产厂家") private String manufacturer; @Column(name = "最小数量") private Integer minQuantity; @Column(name = "最大数量") private Integer maxQuantity; @Column(name = "出货单价") private BigDecimal unitPrice; @Column(name = "进货单价") private BigDecimal purchasePrice; @Column(name = "最低单价") private BigDecimal minPrice; @Column(name = "最高单价") private BigDecimal maxPrice; @Column(name = "备注") private String remark; @Column(name = "注册证号") private String regNumber; @Column(name = "state") private Integer state; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "DTIME") @Temporal(TemporalType.TIMESTAMP) private Date dTime; @Column(name = "UserID") private String userId; @Column(name = "DepID") private String depId; @Column(name = "b1") private byte[] b1; @Column(name = "b2") private byte[] b2; @Column(name = "b3") private byte[] b3; @Column(name = "b4") private byte[] b4; @Column(name = "b5") private byte[] b5; @Column(name = "b6") private byte[] b6; @Column(name = "b7") private byte[] b7; @Column(name = "b8") private byte[] b8; @Column(name = "b9") private byte[] b9; @Column(name = "b10") private byte[] b10; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "d1") @Temporal(TemporalType.TIMESTAMP) private Date d1; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "d2") @Temporal(TemporalType.TIMESTAMP) private Date d2; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "d3") @Temporal(TemporalType.TIMESTAMP) private Date d3; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "d4") @Temporal(TemporalType.TIMESTAMP) private Date d4; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "d5") @Temporal(TemporalType.TIMESTAMP) private Date d5; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "d6") @Temporal(TemporalType.TIMESTAMP) private Date d6; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "d7") @Temporal(TemporalType.TIMESTAMP) private Date d7; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "d8") @Temporal(TemporalType.TIMESTAMP) private Date d8; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "d9") @Temporal(TemporalType.TIMESTAMP) private Date d9; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "d10") @Temporal(TemporalType.TIMESTAMP) private Date d10; @Column(name = "HISDM") private String hisdm; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "InDateTime") @Temporal(TemporalType.TIMESTAMP) private Date inDateTime; @Column(name = "InRemar") private String inRemar; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "OutDateTime") @Temporal(TemporalType.TIMESTAMP) private Date outDateTime; @Column(name = "OutRemark") private String outRemark; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "OrderDateTime") @Temporal(TemporalType.TIMESTAMP) private Date orderDateTime; @Column(name = "OrderRemark") private String orderRemark; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "CollarDateTime") @Temporal(TemporalType.TIMESTAMP) private Date collarDateTime; @Column(name = "CollarRemark") private String collarRemark; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "ChangeDateTime") @Temporal(TemporalType.TIMESTAMP) private Date changeDateTime; @Column(name = "ChangeRemark") private String changeRemark; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "TransferDateTime") @Temporal(TemporalType.TIMESTAMP) private Date transferDateTime; @Column(name = "TransferRemark") private String transferRemark; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "ReturnDateTime") @Temporal(TemporalType.TIMESTAMP) private Date returnDateTime; @Column(name = "returnRemark") private String returnRemark; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "TollDateTime") @Temporal(TemporalType.TIMESTAMP) private Date tollDateTime; @Column(name = "TollRemark") private String tollRemark; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCpid() { return cpid; } public void setCpid(String cpid) { this.cpid = cpid; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getProductNumber() { return productNumber; } public void setProductNumber(String productNumber) { this.productNumber = productNumber; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductCategory() { return productCategory; } public void setProductCategory(String productCategory) { this.productCategory = productCategory; } public String getProductGroup() { return productGroup; } public void setProductGroup(String productGroup) { this.productGroup = productGroup; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getPinYin() { return pinYin; } public void setPinYin(String pinYin) { this.pinYin = pinYin; } public String getStandard() { return standard; } public void setStandard(String standard) { this.standard = standard; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getSupplier() { return supplier; } public void setSupplier(String supplier) { this.supplier = supplier; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public Integer getMinQuantity() { return minQuantity; } public void setMinQuantity(Integer minQuantity) { this.minQuantity = minQuantity; } public Integer getMaxQuantity() { return maxQuantity; } public void setMaxQuantity(Integer maxQuantity) { this.maxQuantity = maxQuantity; } public BigDecimal getUnitPrice() { return unitPrice; } public void setUnitPrice(BigDecimal unitPrice) { this.unitPrice = unitPrice; } public BigDecimal getPurchasePrice() { return purchasePrice; } public void setPurchasePrice(BigDecimal purchasePrice) { this.purchasePrice = purchasePrice; } public BigDecimal getMinPrice() { return minPrice; } public void setMinPrice(BigDecimal minPrice) { this.minPrice = minPrice; } public BigDecimal getMaxPrice() { return maxPrice; } public void setMaxPrice(BigDecimal maxPrice) { this.maxPrice = maxPrice; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getRegNumber() { return regNumber; } public void setRegNumber(String regNumber) { this.regNumber = regNumber; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getdTime() { return dTime; } public void setdTime(Date dTime) { this.dTime = dTime; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getDepId() { return depId; } public void setDepId(String depId) { this.depId = depId; } @JSONField(serialize = false) public byte[] getB1() { return b1; } public void setB1(byte[] b1) { this.b1 = b1; } @JSONField(serialize = false) public byte[] getB2() { return b2; } public void setB2(byte[] b2) { this.b2 = b2; } @JSONField(serialize = false) public byte[] getB3() { return b3; } public void setB3(byte[] b3) { this.b3 = b3; } @JSONField(serialize = false) public byte[] getB4() { return b4; } public void setB4(byte[] b4) { this.b4 = b4; } @JSONField(serialize = false) public byte[] getB5() { return b5; } public void setB5(byte[] b5) { this.b5 = b5; } @JSONField(serialize = false) public byte[] getB6() { return b6; } public void setB6(byte[] b6) { this.b6 = b6; } @JSONField(serialize = false) public byte[] getB7() { return b7; } public void setB7(byte[] b7) { this.b7 = b7; } @JSONField(serialize = false) public byte[] getB8() { return b8; } public void setB8(byte[] b8) { this.b8 = b8; } @JSONField(serialize = false) public byte[] getB9() { return b9; } public void setB9(byte[] b9) { this.b9 = b9; } @JSONField(serialize = false) public byte[] getB10() { return b10; } public void setB10(byte[] b10) { this.b10 = b10; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getD1() { return d1; } public void setD1(Date d1) { this.d1 = d1; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getD2() { return d2; } public void setD2(Date d2) { this.d2 = d2; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getD3() { return d3; } public void setD3(Date d3) { this.d3 = d3; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getD4() { return d4; } public void setD4(Date d4) { this.d4 = d4; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getD5() { return d5; } public void setD5(Date d5) { this.d5 = d5; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getD6() { return d6; } public void setD6(Date d6) { this.d6 = d6; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getD7() { return d7; } public void setD7(Date d7) { this.d7 = d7; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getD8() { return d8; } public void setD8(Date d8) { this.d8 = d8; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getD9() { return d9; } public void setD9(Date d9) { this.d9 = d9; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getD10() { return d10; } public void setD10(Date d10) { this.d10 = d10; } public String getHisdm() { return hisdm; } public void setHisdm(String hisdm) { this.hisdm = hisdm; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getInDateTime() { return inDateTime; } public void setInDateTime(Date inDateTime) { this.inDateTime = inDateTime; } public String getInRemar() { return inRemar; } public void setInRemar(String inRemar) { this.inRemar = inRemar; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getOutDateTime() { return outDateTime; } public void setOutDateTime(Date outDateTime) { this.outDateTime = outDateTime; } public String getOutRemark() { return outRemark; } public void setOutRemark(String outRemark) { this.outRemark = outRemark; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getOrderDateTime() { return orderDateTime; } public void setOrderDateTime(Date orderDateTime) { this.orderDateTime = orderDateTime; } public String getOrderRemark() { return orderRemark; } public void setOrderRemark(String orderRemark) { this.orderRemark = orderRemark; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getCollarDateTime() { return collarDateTime; } public void setCollarDateTime(Date collarDateTime) { this.collarDateTime = collarDateTime; } public String getCollarRemark() { return collarRemark; } public void setCollarRemark(String collarRemark) { this.collarRemark = collarRemark; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getChangeDateTime() { return changeDateTime; } public void setChangeDateTime(Date changeDateTime) { this.changeDateTime = changeDateTime; } public String getChangeRemark() { return changeRemark; } public void setChangeRemark(String changeRemark) { this.changeRemark = changeRemark; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getTransferDateTime() { return transferDateTime; } public void setTransferDateTime(Date transferDateTime) { this.transferDateTime = transferDateTime; } public String getTransferRemark() { return transferRemark; } public void setTransferRemark(String transferRemark) { this.transferRemark = transferRemark; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getReturnDateTime() { return returnDateTime; } public void setReturnDateTime(Date returnDateTime) { this.returnDateTime = returnDateTime; } public String getReturnRemark() { return returnRemark; } public void setReturnRemark(String returnRemark) { this.returnRemark = returnRemark; } @JSONField(format = "yyyy-MM-dd HH:mm:ss") public Date getTollDateTime() { return tollDateTime; } public void setTollDateTime(Date tollDateTime) { this.tollDateTime = tollDateTime; } public String getTollRemark() { return tollRemark; } public void setTollRemark(String tollRemark) { this.tollRemark = tollRemark; } }
3e1436e12f14633a85b136487c0f1da60f63b4b8
6,433
java
Java
test/dorkbox/dns/dns/records/KEYBaseTest.java
dorkbox/NetworkDNS
0e4aaaf3f782254e9b9a30ce612c4a0ef124499e
[ "Apache-2.0", "BSD-2-Clause", "MIT", "CC0-1.0", "BSD-3-Clause" ]
null
null
null
test/dorkbox/dns/dns/records/KEYBaseTest.java
dorkbox/NetworkDNS
0e4aaaf3f782254e9b9a30ce612c4a0ef124499e
[ "Apache-2.0", "BSD-2-Clause", "MIT", "CC0-1.0", "BSD-3-Clause" ]
null
null
null
test/dorkbox/dns/dns/records/KEYBaseTest.java
dorkbox/NetworkDNS
0e4aaaf3f782254e9b9a30ce612c4a0ef124499e
[ "Apache-2.0", "BSD-2-Clause", "MIT", "CC0-1.0", "BSD-3-Clause" ]
null
null
null
34.037037
151
0.620861
8,549
/* * Copyright 2021 dorkbox, llc * * 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 dorkbox.dns.dns.records; import java.io.IOException; import java.util.Arrays; import java.util.Base64; import dorkbox.dns.dns.DnsInput; import dorkbox.dns.dns.DnsOutput; import dorkbox.dns.dns.Name; import dorkbox.dns.dns.constants.DnsClass; import dorkbox.dns.dns.constants.DnsRecordType; import dorkbox.dns.dns.exceptions.TextParseException; import dorkbox.dns.dns.records.DNSSEC; import dorkbox.dns.dns.records.DnsRecord; import dorkbox.dns.dns.records.KEYBase; import dorkbox.dns.dns.utils.Options; import dorkbox.dns.dns.utils.Tokenizer; import dorkbox.os.OS; import junit.framework.TestCase; public class KEYBaseTest extends TestCase { private static class TestClass extends KEYBase { public TestClass() {} public TestClass(Name name, int type, int dclass, long ttl, int flags, int proto, int alg, byte[] key) { super(name, type, dclass, ttl, flags, proto, alg, key); } @Override public DnsRecord getObject() { return null; } @Override void rdataFromString(Tokenizer st, Name origin) throws IOException { } } public void test_ctor() throws TextParseException { TestClass tc = new TestClass(); assertEquals(0, tc.getFlags()); assertEquals(0, tc.getProtocol()); assertEquals(0, tc.getAlgorithm()); assertNull(tc.getKey()); Name n = Name.fromString("my.name."); byte[] key = new byte[] {0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF}; tc = new TestClass(n, DnsRecordType.KEY, DnsClass.IN, 100L, 0xFF, 0xF, 0xE, key); assertSame(n, tc.getName()); assertEquals(DnsRecordType.KEY, tc.getType()); assertEquals(DnsClass.IN, tc.getDClass()); assertEquals(100L, tc.getTTL()); assertEquals(0xFF, tc.getFlags()); assertEquals(0xF, tc.getProtocol()); assertEquals(0xE, tc.getAlgorithm()); assertTrue(Arrays.equals(key, tc.getKey())); } public void test_rrFromWire() throws IOException { byte[] raw = new byte[] {(byte) 0xAB, (byte) 0xCD, (byte) 0xEF, (byte) 0x19, 1, 2, 3, 4, 5}; DnsInput in = new DnsInput(raw); TestClass tc = new TestClass(); tc.rrFromWire(in); assertEquals(0xABCD, tc.getFlags()); assertEquals(0xEF, tc.getProtocol()); assertEquals(0x19, tc.getAlgorithm()); assertTrue(Arrays.equals(new byte[] {1, 2, 3, 4, 5}, tc.getKey())); raw = new byte[] {(byte) 0xBA, (byte) 0xDA, (byte) 0xFF, (byte) 0x28}; in = new DnsInput(raw); tc = new TestClass(); tc.rrFromWire(in); assertEquals(0xBADA, tc.getFlags()); assertEquals(0xFF, tc.getProtocol()); assertEquals(0x28, tc.getAlgorithm()); assertNull(tc.getKey()); } public void test_rrToString() throws IOException, TextParseException { Name n = Name.fromString("my.name."); byte[] key = new byte[] {0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF}; TestClass tc = new TestClass(n, DnsRecordType.KEY, DnsClass.IN, 100L, 0xFF, 0xF, 0xE, null); StringBuilder sb = new StringBuilder(); tc.rrToString(sb); String out = sb.toString(); assertEquals("255 15 14", out); tc = new TestClass(n, DnsRecordType.KEY, DnsClass.IN, 100L, 0xFF, 0xF, 0xE, key); sb = new StringBuilder(); tc.rrToString(sb); out = sb.toString(); assertEquals("255 15 14 " + Base64.getEncoder().encodeToString(key), out); Options.set("multiline"); sb = new StringBuilder(); tc.rrToString(sb); out = sb.toString(); assertEquals("255 15 14 (" + OS.LINE_SEPARATOR + Base64.getMimeEncoder().encodeToString(key) + OS.LINE_SEPARATOR + ") ; key_tag = 18509", out); Options.unset("multiline"); } public void test_getFootprint() throws TextParseException { Name n = Name.fromString("my.name."); byte[] key = new byte[] {0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF}; TestClass tc = new TestClass(n, DnsRecordType.KEY, DnsClass.IN, 100L, 0xFF, 0xF, DNSSEC.Algorithm.RSAMD5, key); int foot = tc.getFootprint(); // second-to-last and third-to-last bytes of key for RSAMD5 assertEquals(0xD0E, foot); assertEquals(foot, tc.getFootprint()); // key with an odd number of bytes tc = new TestClass(n, DnsRecordType.KEY, DnsClass.IN, 100L, 0x89AB, 0xCD, 0xEF, new byte[] {0x12, 0x34, 0x56}); // rrToWire gives: { 0x89, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56 } // 89AB + CDEF + 1234 + 5600 = 1BCFE // 1BFCE + 1 = 1BFCF & FFFF = BFCF foot = tc.getFootprint(); assertEquals(0xBFCF, foot); assertEquals(foot, tc.getFootprint()); // empty tc = new TestClass(); assertEquals(0, tc.getFootprint()); } public void test_rrToWire() throws IOException, TextParseException { Name n = Name.fromString("my.name."); byte[] key = new byte[] {0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF}; TestClass tc = new TestClass(n, DnsRecordType.KEY, DnsClass.IN, 100L, 0x7689, 0xAB, 0xCD, key); byte[] exp = new byte[] {(byte) 0x76, (byte) 0x89, (byte) 0xAB, (byte) 0xCD, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; DnsOutput o = new DnsOutput(); // canonical tc.rrToWire(o, null, true); assertTrue(Arrays.equals(exp, o.toByteArray())); // not canonical o = new DnsOutput(); tc.rrToWire(o, null, false); assertTrue(Arrays.equals(exp, o.toByteArray())); } }
3e1436ef01f75edcd49cbad21c59c893278e631b
268
java
Java
template-method/src/AbstractDisplay.java
Andrewpqc/design-patterns
4c30e1d866eaca98d554ee7fb37a50a9fc2cf816
[ "MIT" ]
null
null
null
template-method/src/AbstractDisplay.java
Andrewpqc/design-patterns
4c30e1d866eaca98d554ee7fb37a50a9fc2cf816
[ "MIT" ]
null
null
null
template-method/src/AbstractDisplay.java
Andrewpqc/design-patterns
4c30e1d866eaca98d554ee7fb37a50a9fc2cf816
[ "MIT" ]
null
null
null
17.866667
39
0.55597
8,550
public abstract class AbstractDisplay { public abstract void open(); public abstract void print(); public abstract void close(); public final void display(){ open(); for(int i=0;i<5;++i) print(); close(); } }
3e143700f96a656328b7d0c98907745a8071444d
3,716
java
Java
src/test/java/com/ning/metrics/collector/FastCollectorConfig.java
pierre/collector
f4628f300ebc3658b5c1ade97d71aa213fe090e4
[ "Apache-2.0" ]
2
2015-11-08T12:41:57.000Z
2015-11-09T10:56:41.000Z
src/test/java/com/ning/metrics/collector/FastCollectorConfig.java
pierre/collector
f4628f300ebc3658b5c1ade97d71aa213fe090e4
[ "Apache-2.0" ]
null
null
null
src/test/java/com/ning/metrics/collector/FastCollectorConfig.java
pierre/collector
f4628f300ebc3658b5c1ade97d71aa213fe090e4
[ "Apache-2.0" ]
5
2015-05-22T11:40:20.000Z
2019-07-24T17:18:50.000Z
27.93985
118
0.631055
8,551
/* * Copyright 2010-2011 Ning, Inc. * * Ning licenses this file to you 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.ning.metrics.collector; import com.ning.metrics.collector.binder.config.CollectorConfig; import org.testng.Assert; import java.io.File; import java.io.IOException; import java.net.ServerSocket; public abstract class FastCollectorConfig implements CollectorConfig { private static final long START_TIME = System.currentTimeMillis(); private int cachedPort = -1; /** * @return true - enable a Mock AMQ for tests by default * @see com.ning.metrics.collector.realtime.RealTimeQueueTestModule */ @Override public boolean isActiveMQEnabled() { return true; } /** * Maximum number of events per file in the temporary spooling area. Past this threshold, * buffered events are promoted to the final spool queue. * This is used in the ThresholdEventWriter (size before commits) * * @return the maximum number of events per file * @see com.ning.metrics.serialization.writer.ThresholdEventWriter */ @Override public long getMaxUncommittedWriteCount() { return 2; } /** * Maxixum number of seconds before events are promoted from the temporary spooling area to the final spool queue. * This is used in the ThresholdEventWriter (delay between commits). * * @return maxixmum age of events in seconds in the temporary spool queue * @see com.ning.metrics.serialization.writer.ThresholdEventWriter */ @Override public int getMaxUncommittedPeriodInSeconds() { return 1; } /** * Delay between flushes (in seconds). * This is used in the DiskSpoolEventWriter (delay between flushes). * * @return delay between flushes to HDFS * @see com.ning.metrics.serialization.writer.DiskSpoolEventWriter */ @Override public int getFlushIntervalInSeconds() { return 1; } /** * Directory for the collector to buffer events before writing them to HDFS * * @return the directory path */ @Override public String getSpoolDirectoryName() { final String spoolPath = System.getProperty("java.io.tmpdir") + "/collector-local-spool-" + START_TIME; // Make sure the directory exists new File(spoolPath).mkdirs(); return spoolPath; } @Override public int getLocalPort() { if (cachedPort == -1) { cachedPort = findFreePort(); } return cachedPort; } private int findFreePort() { // Find a free port -- this is needed for TestNG to run test classes in parallel ServerSocket socket = null; try { try { socket = new ServerSocket(0); } catch (IOException e) { return 8080; } return socket.getLocalPort(); } finally { if (socket != null) { try { socket.close(); } catch (IOException ignored) { } } } } }
3e1437369923a84815d51e560df22b89b0308d78
1,884
java
Java
net.violet.my-nabaztag/src/main/java/net/violet/mynabaztag/action/MyAddFriendAction.java
nguillaumin/nabaztag-server
235b4867ad7b2f923f25457722da4bb92ecd48b7
[ "MIT" ]
4
2016-04-01T19:39:30.000Z
2018-03-29T08:10:12.000Z
server/MyNabaztag/net/violet/mynabaztag/action/MyAddFriendAction.java
sebastienhouzet/nabaztag-source-code
65197ea668e40fadb35d8ebd0aeb512311f9f547
[ "MIT" ]
null
null
null
server/MyNabaztag/net/violet/mynabaztag/action/MyAddFriendAction.java
sebastienhouzet/nabaztag-source-code
65197ea668e40fadb35d8ebd0aeb512311f9f547
[ "MIT" ]
8
2016-04-09T03:46:26.000Z
2021-11-26T21:42:01.000Z
33.052632
163
0.758493
8,552
package net.violet.mynabaztag.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.violet.mynabaztag.form.MyAddFriendForm; import net.violet.platform.datamodel.Contact; import net.violet.platform.datamodel.User; import net.violet.platform.datamodel.factories.Factories; import net.violet.platform.dataobjects.UserData; import net.violet.platform.struts.DispatchActionWithLog; import net.violet.platform.util.SessionTools; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class MyAddFriendAction extends DispatchActionWithLog { @Override protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) { final User user = SessionTools.getUserFromSession(request); final MyAddFriendForm myForm = (MyAddFriendForm) form; final User friend = Factories.USER.find(myForm.getFriend_id()); if (friend == null) { return mapping.getInputForward(); } int mode = MyTerrierFriendsAction.FL_ERROR; if (user.existFriend(friend)) { mode = MyTerrierFriendsAction.ALREADY_IN_FL; } if (mode != MyTerrierFriendsAction.ALREADY_IN_FL) { for (final Contact aContact : Factories.CONTACT.findAllSentContactRequest(user, 0, 0)) { if (aContact.getPerson().equals(user)) { mode = MyTerrierFriendsAction.ALREADY_IN_FL; break; } } if (mode != MyTerrierFriendsAction.ALREADY_IN_FL) { mode = MyTerrierFriendsAction.addContact(user, friend); } } myForm.setMode(mode); myForm.setProfil(UserData.find(myForm.getFriend_id())); myForm.setFriend_id(friend.getId().intValue()); return mapping.findForward("success_add_friend"); } }
3e143833ffd0256ed342b4ed63d19186ef1b46a5
1,548
java
Java
src/main/java/com/fundynamic/d2tm/game/entities/units/states/IdleHarvesterState.java
begumerkal/PROJEM24
49e7a7b39297a6da713d5070f54ba72e4597eeab
[ "MIT" ]
47
2015-09-25T16:13:12.000Z
2022-01-21T04:47:28.000Z
src/main/java/com/fundynamic/d2tm/game/entities/units/states/IdleHarvesterState.java
begumerkal/PROJEM24
49e7a7b39297a6da713d5070f54ba72e4597eeab
[ "MIT" ]
132
2015-09-08T06:10:33.000Z
2020-07-10T07:47:53.000Z
src/main/java/com/fundynamic/d2tm/game/entities/units/states/IdleHarvesterState.java
begumerkal/PROJEM24
49e7a7b39297a6da713d5070f54ba72e4597eeab
[ "MIT" ]
20
2015-10-26T21:16:29.000Z
2022-01-21T04:47:29.000Z
35.181818
91
0.656331
8,553
package com.fundynamic.d2tm.game.entities.units.states; import com.fundynamic.d2tm.game.entities.EntitiesSet; import com.fundynamic.d2tm.game.entities.Entity; import com.fundynamic.d2tm.game.entities.EntityRepository; import com.fundynamic.d2tm.game.entities.units.Unit; import com.fundynamic.d2tm.game.map.Map; //TODO: Use goals & tasks to solve this properly (Fear AI) public class IdleHarvesterState extends UnitState { public IdleHarvesterState(Unit unit, EntityRepository entityRepository, Map map) { super(unit, entityRepository, map); } @Override public void update(float deltaInSeconds) { if (unit.isDoneHarvesting()) { unit.findNearestRefineryToReturnSpice(); } else if (unit.canHarvest()) { unit.harvesting(); } else { EntitiesSet entitiesAt = entityRepository.findEntitiesAt(unit.getCoordinate()); EntitiesSet refineriesAtUnitLocation = entitiesAt.filterRefineries(); if (refineriesAtUnitLocation.hasAny()) { // we have arrived at a refinery Entity refinery = refineriesAtUnitLocation.getFirst(); unit.emptyHarvestedSpiceAt(refinery); unit.enterOtherEntity(refinery); return; } // TODO: When seekspice fails, we should time this, so we won't run this code // every frame unit.seekSpice(); } } @Override public String toString() { return "IdleHarvesterState"; } }
3e14384c63e535b8aee163e441e738bc4b91bbe0
1,884
java
Java
TechCrunch/app/src/main/java/com/kazekim/techcrunch/template/callback/JHCallBack.java
kazekim/TechcrunchFeed
f4797445dc0d3c24a121c5a3368860772a439aea
[ "MIT" ]
null
null
null
TechCrunch/app/src/main/java/com/kazekim/techcrunch/template/callback/JHCallBack.java
kazekim/TechcrunchFeed
f4797445dc0d3c24a121c5a3368860772a439aea
[ "MIT" ]
null
null
null
TechCrunch/app/src/main/java/com/kazekim/techcrunch/template/callback/JHCallBack.java
kazekim/TechcrunchFeed
f4797445dc0d3c24a121c5a3368860772a439aea
[ "MIT" ]
null
null
null
23.6
64
0.57786
8,554
package com.kazekim.techcrunch.template.callback; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * @author Jirawat Harnsiriwatanakit (Kim) on 4/7/2017 AD. * @contact efpyi@example.com */ public abstract class JHCallBack<T> implements Callback<T> { private static List<JHCallBack> mList = new ArrayList<>(); private boolean isCanceled = false; private Object mTag = null; public static void cancelAll() { Iterator<JHCallBack> iterator = mList.iterator(); while (iterator.hasNext()){ iterator.next().isCanceled = true; iterator.remove(); } } public static void cancel(Object tag) { if (tag != null) { Iterator<JHCallBack> iterator = mList.iterator(); JHCallBack item; while (iterator.hasNext()) { item = iterator.next(); if (tag.equals(item.mTag)) { item.isCanceled = true; iterator.remove(); } } } } public JHCallBack() { mList.add(this); } public JHCallBack(Object tag) { mTag = tag; mList.add(this); } public void cancel() { isCanceled = true; mList.remove(this); } @Override public void onResponse(Call<T> call, Response<T> response) { if(!isCanceled){ T result = response.body(); onSuccess(response, result); } mList.remove(this); } @Override public void onFailure(Call<T> call, Throwable t) { if (!isCanceled) onFailure(t); mList.remove(this); } public abstract void onSuccess(Response response, T t); public abstract void onFailure(Throwable t); }
3e1438c4fddabcc9cf560823d65f811dc1599c3a
956
java
Java
src/main/java/cn/felord/wepay/ali/sdk/api/response/AlipayMarketingCardActivateurlApplyResponse.java
NotFound403/WePay
50eaac5d92cf9773fe80b544c74a0572e2122ec2
[ "Apache-2.0" ]
5
2017-08-01T02:51:13.000Z
2017-11-14T06:14:38.000Z
src/main/java/cn/felord/wepay/ali/sdk/api/response/AlipayMarketingCardActivateurlApplyResponse.java
NotFound403/WePay
50eaac5d92cf9773fe80b544c74a0572e2122ec2
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/felord/wepay/ali/sdk/api/response/AlipayMarketingCardActivateurlApplyResponse.java
NotFound403/WePay
50eaac5d92cf9773fe80b544c74a0572e2122ec2
[ "Apache-2.0" ]
null
null
null
23.317073
81
0.721757
8,555
package cn.felord.wepay.ali.sdk.api.response; import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField; import cn.felord.wepay.ali.sdk.api.AlipayResponse; /** * ALIPAY API: alipay.marketing.card.activateurl.apply response. * * @author auto create * @version $Id: $Id */ public class AlipayMarketingCardActivateurlApplyResponse extends AlipayResponse { private static final long serialVersionUID = 4439649512457185581L; /** * 会员卡领卡链接。商户获取此链接后可投放到服务窗消息、店铺二维码等。 */ @ApiField("apply_card_url") private String applyCardUrl; /** * <p>Setter for the field <code>applyCardUrl</code>.</p> * * @param applyCardUrl a {@link java.lang.String} object. */ public void setApplyCardUrl(String applyCardUrl) { this.applyCardUrl = applyCardUrl; } /** * <p>Getter for the field <code>applyCardUrl</code>.</p> * * @return a {@link java.lang.String} object. */ public String getApplyCardUrl( ) { return this.applyCardUrl; } }
3e1438da61a768c3acd0fea3513fbb6284a7bfd7
52,148
java
Java
gravitee-am-gateway/gravitee-am-gateway-handler/gravitee-am-gateway-handler-oidc/src/test/java/io/gravitee/am/gateway/handler/oauth2/resources/endpoint/AuthorizationEndpointTest.java
ventuc/graviteeio-access-management
91c756be907fe179d2cbb257f047e4799358a899
[ "Apache-2.0" ]
null
null
null
gravitee-am-gateway/gravitee-am-gateway-handler/gravitee-am-gateway-handler-oidc/src/test/java/io/gravitee/am/gateway/handler/oauth2/resources/endpoint/AuthorizationEndpointTest.java
ventuc/graviteeio-access-management
91c756be907fe179d2cbb257f047e4799358a899
[ "Apache-2.0" ]
null
null
null
gravitee-am-gateway/gravitee-am-gateway-handler/gravitee-am-gateway-handler-oidc/src/test/java/io/gravitee/am/gateway/handler/oauth2/resources/endpoint/AuthorizationEndpointTest.java
ventuc/graviteeio-access-management
91c756be907fe179d2cbb257f047e4799358a899
[ "Apache-2.0" ]
null
null
null
49.242682
224
0.667427
8,556
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.am.gateway.handler.oauth2.resources.endpoint; import io.gravitee.am.common.oauth2.GrantType; import io.gravitee.am.common.oauth2.ResponseType; import io.gravitee.am.gateway.handler.common.client.ClientSyncService; import io.gravitee.am.gateway.handler.common.vertx.RxWebTestBase; import io.gravitee.am.gateway.handler.oauth2.exception.AccessDeniedException; import io.gravitee.am.gateway.handler.oauth2.exception.InvalidScopeException; import io.gravitee.am.gateway.handler.oauth2.resources.endpoint.authorization.AuthorizationEndpoint; import io.gravitee.am.gateway.handler.oauth2.resources.endpoint.authorization.AuthorizationFailureEndpoint; import io.gravitee.am.gateway.handler.oauth2.resources.handler.authorization.AuthorizationRequestParseClientHandler; import io.gravitee.am.gateway.handler.oauth2.resources.handler.authorization.AuthorizationRequestParseParametersHandler; import io.gravitee.am.gateway.handler.oauth2.resources.handler.authorization.AuthorizationRequestParseRequiredParametersHandler; import io.gravitee.am.gateway.handler.oauth2.service.request.AuthorizationRequest; import io.gravitee.am.gateway.handler.oauth2.service.response.*; import io.gravitee.am.gateway.handler.oauth2.service.token.Token; import io.gravitee.am.gateway.handler.oauth2.service.token.impl.AccessToken; import io.gravitee.am.gateway.handler.oidc.service.discovery.OpenIDDiscoveryService; import io.gravitee.am.gateway.handler.oidc.service.discovery.OpenIDProviderMetadata; import io.gravitee.am.gateway.handler.oidc.service.flow.Flow; import io.gravitee.am.model.oidc.Client; import io.gravitee.am.model.Domain; import io.gravitee.common.http.HttpStatusCode; import io.reactivex.Maybe; import io.reactivex.Single; import io.vertx.core.Handler; import io.vertx.core.http.HttpMethod; import io.vertx.reactivex.ext.auth.User; import io.vertx.reactivex.ext.web.RoutingContext; import io.vertx.reactivex.ext.web.handler.SessionHandler; import io.vertx.reactivex.ext.web.sstore.LocalSessionStore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.Arrays; import java.util.Collections; import java.util.Date; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; /** * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com) * @author GraviteeSource Team */ @RunWith(MockitoJUnitRunner.class) public class AuthorizationEndpointTest extends RxWebTestBase { private static final String CLIENT_CONTEXT_KEY = "client"; @Mock private Flow flow; @Mock private Domain domain; @Mock private ClientSyncService clientSyncService; @Mock private OpenIDDiscoveryService openIDDiscoveryService; @InjectMocks private AuthorizationEndpoint authorizationEndpointHandler = new AuthorizationEndpoint(flow, domain); @Override public void setUp() throws Exception { super.setUp(); // set openid provider service OpenIDProviderMetadata openIDProviderMetadata = new OpenIDProviderMetadata(); openIDProviderMetadata.setResponseTypesSupported(Arrays.asList(ResponseType.CODE, ResponseType.TOKEN, io.gravitee.am.common.oidc.ResponseType.CODE_ID_TOKEN, io.gravitee.am.common.oidc.ResponseType.CODE_TOKEN, io.gravitee.am.common.oidc.ResponseType.CODE_ID_TOKEN_TOKEN, io.gravitee.am.common.oidc.ResponseType.ID_TOKEN_TOKEN, io.gravitee.am.common.oidc.ResponseType.ID_TOKEN)); when(openIDDiscoveryService.getConfiguration(anyString())).thenReturn(openIDProviderMetadata); // set domain when(domain.getPath()).thenReturn("test"); // set Authorization endpoint routes SessionHandler sessionHandler = SessionHandler.create(LocalSessionStore.create(vertx)); router.route("/oauth/authorize") .handler(sessionHandler); router.route(HttpMethod.GET, "/oauth/authorize") .handler(new AuthorizationRequestParseRequiredParametersHandler(openIDDiscoveryService)) .handler(new AuthorizationRequestParseClientHandler(domain, clientSyncService)) .handler(new AuthorizationRequestParseParametersHandler(domain)) .handler(authorizationEndpointHandler); router.route() .failureHandler(new AuthorizationFailureEndpoint(domain)); } @Test public void shouldNotInvokeAuthorizationEndpoint_noUser_noRedirectUri() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=access_denied")); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_noUser_withRedirectUri() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?error=access_denied", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_emptyScope() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); router.route().order(-1).handler(routingContext -> { routingContext.put(CLIENT_CONTEXT_KEY, client); routingContext.next(); }); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&scope=", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?error=invalid_scope&error_description=Invalid+parameter%253A+scope+must+not+be+empty", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_invalidScope() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); router.route().order(-1).handler(routingContext -> { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); when(flow.run(any(), any(), any())).thenReturn(Single.error(new InvalidScopeException("Invalid scope(s): unknown"))); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&scope=unknown", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?error=invalid_scope&error_description=Invalid+scope%2528s%2529%253A+unknown", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_emptyRedirectUri() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.CODE); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=invalid_request&error_description=A+redirect_uri+must+be+supplied")); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_emptyRedirectUri_clientHasSeveralRedirectUris() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Arrays.asList("http://redirect1", "http://redirect2")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.CODE); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=invalid_request&error_description=Unable+to+find+suitable+redirect_uri%252C+a+redirect_uri+must+be+supplied")); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_mismatchRedirectUri() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/authorize/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.CODE); authorizationRequest.setRedirectUri("http://localhost:9999/wrong/callback"); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/wrong/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application")); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_mismatchRedirectUri_strictMatching() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/authorize/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.CODE); authorizationRequest.setRedirectUri("http://localhost:9999/authorize/callback?param=param1"); when(domain.isRedirectUriStrictMatching()).thenReturn(true); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/authorize/callback?param=param1", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application")); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldInvokeAuthorizationEndpoint_noStrictMatching() throws Exception { io.gravitee.am.model.User user = new io.gravitee.am.model.User(); final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/authorize/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.CODE); authorizationRequest.setRedirectUri("http://localhost:9999/authorize/callback?param=param1"); AuthorizationResponse authorizationResponse = new AuthorizationCodeResponse(); authorizationResponse.setRedirectUri(authorizationRequest.getRedirectUri()); ((AuthorizationCodeResponse) authorizationResponse).setCode("test-code"); router.route().order(-1).handler(routingContext -> { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(user))); routingContext.next(); }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); when(flow.run(any(), any(), any())).thenReturn(Single.just(authorizationResponse)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/authorize/callback?param=param1", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/authorize/callback?param=param1&code=test-code", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_duplicateParameters() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=invalid_request&error_description=Parameter+%255Bresponse_type%255D+is+included+more+than+once")); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldInvokeAuthorizationEndpoint_approvalPage() throws Exception { AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(false); final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); router.route().order(-1).handler(routingContext -> { routingContext.put(CLIENT_CONTEXT_KEY, new Client()); routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); }); when(flow.run(any(), any(), any())).thenReturn(Single.error(new AccessDeniedException("User denied access"))); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("/test/oauth/confirm_access")); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldInvokeAuthorizationEndpoint_responseTypeCode() throws Exception { io.gravitee.am.model.User user = new io.gravitee.am.model.User(); final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.CODE); authorizationRequest.setRedirectUri("http://localhost:9999/callback"); AuthorizationResponse authorizationResponse = new AuthorizationCodeResponse(); authorizationResponse.setRedirectUri(authorizationRequest.getRedirectUri()); ((AuthorizationCodeResponse) authorizationResponse).setCode("test-code"); router.route().order(-1).handler(routingContext -> { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(user))); routingContext.next(); }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); when(flow.run(any(), any(), any())).thenReturn(Single.just(authorizationResponse)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?code=test-code", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldInvokeAuthorizationEndpoint_noClientResponseType() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setResponseTypes(null); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.TOKEN); authorizationRequest.setRedirectUri("http://localhost:9999/callback"); Token accessToken = new AccessToken("token"); AuthorizationResponse authorizationResponse = new ImplicitResponse(); authorizationResponse.setRedirectUri(authorizationRequest.getRedirectUri()); ((ImplicitResponse) authorizationResponse).setAccessToken(accessToken); router.route().order(-1).handler(routingContext -> { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=token&client_id=client-id&nonce=123&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback#error=unauthorized_client&error_description=Client+should+have+response_type.", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldInvokeAuthorizationEndpoint_missingClientResponseType() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setResponseTypes(Arrays.asList(io.gravitee.am.common.oidc.ResponseType.ID_TOKEN)); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.TOKEN); authorizationRequest.setRedirectUri("http://localhost:9999/callback"); Token accessToken = new AccessToken("token"); AuthorizationResponse authorizationResponse = new ImplicitResponse(); authorizationResponse.setRedirectUri(authorizationRequest.getRedirectUri()); ((ImplicitResponse) authorizationResponse).setAccessToken(accessToken); router.route().order(-1).handler(routingContext -> { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=token&client_id=client-id&nonce=123&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback#error=unauthorized_client&error_description=Client+should+have+all+requested+response_type", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldInvokeAuthorizationEndpoint_responseTypeToken() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); client.setAuthorizedGrantTypes(Arrays.asList(GrantType.IMPLICIT)); client.setResponseTypes(Arrays.asList(ResponseType.TOKEN)); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.TOKEN); authorizationRequest.setRedirectUri("http://localhost:9999/callback"); Token accessToken = new AccessToken("token"); AuthorizationResponse authorizationResponse = new ImplicitResponse(); authorizationResponse.setRedirectUri(authorizationRequest.getRedirectUri()); ((ImplicitResponse) authorizationResponse).setAccessToken(accessToken); router.route().order(-1).handler(routingContext -> { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); when(flow.run(any(), any(), any())).thenReturn(Single.just(authorizationResponse)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=token&client_id=client-id&nonce=123&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback#access_token=token&token_type=bearer&expires_in=0", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_noUser_prompt_none() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); router.route().order(-1).handler(routingContext -> { routingContext.put(CLIENT_CONTEXT_KEY, client); routingContext.next(); }); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&prompt=none", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?error=login_required&error_description=Login+required", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_user_max_age() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(false); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); router.route().order(-1).handler(routingContext -> { io.gravitee.am.model.User endUser = new io.gravitee.am.model.User(); endUser.setLoggedAt(new Date(System.currentTimeMillis()-24*60*60*1000)); routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(endUser))); routingContext.next(); }); // user is logged since yesterday, he must be redirected to the login page testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&max_age=1", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?error=access_denied", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_user_max_age_prompt_none() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(false); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); router.route().order(-1).handler(routingContext -> { io.gravitee.am.model.User endUser = new io.gravitee.am.model.User(); endUser.setLoggedAt(new Date(System.currentTimeMillis()-24*60*60*1000)); routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(endUser))); routingContext.put(CLIENT_CONTEXT_KEY, client); routingContext.next(); }); // user is logged since yesterday, he must be redirected to the login page testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&max_age=1&prompt=none", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?error=login_required&error_description=Login+required", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldInvokeAuthorizationEndpoint_max_age() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.CODE); authorizationRequest.setRedirectUri("http://localhost:9999/callback"); AuthorizationResponse authorizationResponse = new AuthorizationCodeResponse(); authorizationResponse.setRedirectUri(authorizationRequest.getRedirectUri()); ((AuthorizationCodeResponse) authorizationResponse).setCode("test-code"); router.route().order(-1).handler(routingContext -> { io.gravitee.am.model.User endUser = new io.gravitee.am.model.User(); endUser.setLoggedAt(new Date(System.currentTimeMillis()- 60*1000)); routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); when(flow.run(any(), any(), any())).thenReturn(Single.just(authorizationResponse)); // user is logged for 1 min, the max_age is big enough to validate the request testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&max_age=120", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?code=test-code", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_noUser_code_challenge_method_without_code_challenge() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); router.route().order(-1).handler(routingContext -> { routingContext.put(CLIENT_CONTEXT_KEY, client); routingContext.next(); }); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&code_challenge_method=plain", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?error=invalid_request&error_description=Missing+parameter%253A+code_challenge", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_noUser_invalid_code_challenge_method() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); router.route().order(-1).handler(routingContext -> { routingContext.put(CLIENT_CONTEXT_KEY, client); routingContext.next(); }); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&code_challenge_method=invalid&code_challenge=challenge", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?error=invalid_request&error_description=Invalid+parameter%253A+code_challenge_method", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_noUser_invalid_code_challenge() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); router.route().order(-1).handler(routingContext -> { routingContext.put(CLIENT_CONTEXT_KEY, client); routingContext.next(); }); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&code_challenge_method=plain&code_challenge=challenge", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?error=invalid_request&error_description=Invalid+parameter%253A+code_challenge", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_noUser_code_challenge_valid_plain() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.CODE); authorizationRequest.setRedirectUri("http://localhost:9999/callback"); AuthorizationResponse authorizationResponse = new AuthorizationCodeResponse(); authorizationResponse.setRedirectUri(authorizationRequest.getRedirectUri()); ((AuthorizationCodeResponse) authorizationResponse).setCode("test-code"); router.route().order(-1).handler(routingContext -> { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); when(flow.run(any(), any(), any())).thenReturn(Single.just(authorizationResponse)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&code_challenge_method=plain&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?code=test-code", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_noUser_code_challenge_valid_s256() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(ResponseType.CODE); authorizationRequest.setRedirectUri("http://localhost:9999/callback"); AuthorizationResponse authorizationResponse = new AuthorizationCodeResponse(); authorizationResponse.setRedirectUri(authorizationRequest.getRedirectUri()); ((AuthorizationCodeResponse) authorizationResponse).setCode("test-code"); router.route().order(-1).handler(new Handler<RoutingContext>() { @Override public void handle(RoutingContext routingContext) { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); } }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); when(flow.run(any(), any(), any())).thenReturn(Single.just(authorizationResponse)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&code_challenge_method=S256&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?code=test-code", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_prompt_login() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); router.route().order(-1).handler(routingContext -> { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); }); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id&redirect_uri=http://localhost:9999/callback&prompt=login", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback?error=access_denied", location); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_invalidClient() throws Exception { when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.empty()); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code&client_id=client-id", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=invalid_request&error_description=No+client+found+for+client_id+client-id")); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_implicitFlow_nonceMissing() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=id_token&client_id=client-id&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=invalid_request&error_description=Missing+parameter%253A+nonce+is+required+for+Implicit+and+Hybrid+Flow")); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldNotInvokeAuthorizationEndpoint_hybridFlow_nonceMissing() throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=code+id_token&client_id=client-id&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=invalid_request&error_description=Missing+parameter%253A+nonce+is+required+for+Implicit+and+Hybrid+Flow")); }, HttpStatusCode.FOUND_302, "Found", null); } @Test public void shouldInvokeAuthorizationEndpoint_hybridFlow_code_IDToken() throws Exception { shouldInvokeAuthorizationEndpoint_hybridFlow(io.gravitee.am.common.oidc.ResponseType.CODE_ID_TOKEN, "code=test-code&id_token=test-id-token", null, "test-id-token"); } @Test public void shouldInvokeAuthorizationEndpoint_hybridFlow_code_token() throws Exception { Token accessToken = new AccessToken("token"); shouldInvokeAuthorizationEndpoint_hybridFlow(io.gravitee.am.common.oidc.ResponseType.CODE_TOKEN, "code=test-code&access_token=token&token_type=bearer&expires_in=0", accessToken, null); } @Test public void shouldInvokeAuthorizationEndpoint_hybridFlow_code_IDToken_token() throws Exception { Token accessToken = new AccessToken("token"); ((AccessToken) accessToken).setAdditionalInformation(Collections.singletonMap("id_token", "test-id-token")); shouldInvokeAuthorizationEndpoint_hybridFlow(io.gravitee.am.common.oidc.ResponseType.CODE_ID_TOKEN_TOKEN, "code=test-code&access_token=token&token_type=bearer&expires_in=0&id_token=test-id-token", accessToken, null); } @Test public void shouldInvokeAuthorizationEndpoint_implicitFlow_IDToken() throws Exception { shouldInvokeAuthorizationEndpoint_implicitFlow(io.gravitee.am.common.oidc.ResponseType.ID_TOKEN, "id_token=test-id-token", null, "test-id-token"); } @Test public void shouldInvokeAuthorizationEndpoint_implicitFlow_IDToken_token() throws Exception { Token accessToken = new AccessToken("token"); ((AccessToken) accessToken).setAdditionalInformation(Collections.singletonMap("id_token", "test-id-token")); shouldInvokeAuthorizationEndpoint_implicitFlow(io.gravitee.am.common.oidc.ResponseType.ID_TOKEN_TOKEN, "access_token=token&token_type=bearer&expires_in=0&id_token=test-id-token", accessToken, null); } @Test public void shouldInvokeAuthorizationEndpoint_implicitFlow_token() throws Exception { Token accessToken = new AccessToken("token"); shouldInvokeAuthorizationEndpoint_implicitFlow(ResponseType.TOKEN, "access_token=token&token_type=bearer&expires_in=0", accessToken, null); } private void shouldInvokeAuthorizationEndpoint_hybridFlow(String responseType, String expectedCallback, Token accessToken, String idToken) throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); client.setAuthorizedGrantTypes(Arrays.asList(GrantType.AUTHORIZATION_CODE,GrantType.IMPLICIT)); client.setResponseTypes(Arrays.asList(ResponseType.CODE,ResponseType.TOKEN, io.gravitee.am.common.oidc.ResponseType.ID_TOKEN)); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(responseType); authorizationRequest.setRedirectUri("http://localhost:9999/callback"); AuthorizationResponse authorizationResponse = new HybridResponse(); authorizationResponse.setRedirectUri(authorizationRequest.getRedirectUri()); ((HybridResponse) authorizationResponse).setCode("test-code"); if (accessToken != null) { ((HybridResponse) authorizationResponse).setAccessToken(accessToken); } if (idToken != null) { ((HybridResponse) authorizationResponse).setIdToken(idToken); } router.route().order(-1).handler(routingContext -> { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); when(flow.run(any(), any(), any())).thenReturn(Single.just(authorizationResponse)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type=token&client_id=client-id&nonce=123&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback#" + expectedCallback, location); }, HttpStatusCode.FOUND_302, "Found", null); } private void shouldInvokeAuthorizationEndpoint_implicitFlow(String responseType, String expectedCallback, Token accessToken, String idToken) throws Exception { final Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); client.setScopes(Collections.singletonList("read")); client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback")); client.setAuthorizedGrantTypes(Arrays.asList(GrantType.IMPLICIT)); client.setResponseTypes(Arrays.asList(responseType.split("\\s"))); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setApproved(true); authorizationRequest.setResponseType(responseType); authorizationRequest.setRedirectUri("http://localhost:9999/callback"); AuthorizationResponse authorizationResponse = null; if (accessToken != null) { authorizationResponse = new ImplicitResponse(); ((ImplicitResponse) authorizationResponse).setAccessToken(accessToken); } if (idToken != null) { authorizationResponse = new IDTokenResponse(); ((IDTokenResponse) authorizationResponse).setIdToken(idToken); } authorizationResponse.setRedirectUri(authorizationRequest.getRedirectUri()); router.route().order(-1).handler(routingContext -> { routingContext.setUser(new User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(new io.gravitee.am.model.User()))); routingContext.next(); }); when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client)); when(flow.run(any(), any(), any())).thenReturn(Single.just(authorizationResponse)); testRequest( HttpMethod.GET, "/oauth/authorize?response_type="+responseType.replaceAll("\\s","%20")+"&client_id=client-id&nonce=123&redirect_uri=http://localhost:9999/callback", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("http://localhost:9999/callback#" + expectedCallback, location); }, HttpStatusCode.FOUND_302, "Found", null); } }
3e1438f1d109588b6c0c2ea101cdddd69ca8abeb
2,987
java
Java
src/java/org/rapidcontext/core/data/DictComparator.java
cederberg/rapidcontext
6b4abaa40c0a5b2b8bd4859ae0b0c819ff0f201a
[ "RSA-MD" ]
2
2016-07-16T07:17:23.000Z
2017-08-16T07:04:49.000Z
src/java/org/rapidcontext/core/data/DictComparator.java
cederberg/rapidcontext
6b4abaa40c0a5b2b8bd4859ae0b0c819ff0f201a
[ "RSA-MD" ]
null
null
null
src/java/org/rapidcontext/core/data/DictComparator.java
cederberg/rapidcontext
6b4abaa40c0a5b2b8bd4859ae0b0c819ff0f201a
[ "RSA-MD" ]
null
null
null
30.171717
79
0.595246
8,557
/* * RapidContext <https://www.rapidcontext.com/> * Copyright (c) 2007-2019 Per Cederberg. All rights reserved. * * This program is free software: you can redistribute it and/or * modify it under the terms of the BSD license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the RapidContext LICENSE for more details. */ package org.rapidcontext.core.data; import java.util.Comparator; /** * A dictionary value comparator. This comparator only compares the * values of two dictionary keys. All values returned which must * implement Comparable and be of compatible types. * * @author Per Cederberg * @version 1.0 */ public class DictComparator implements Comparator<Object> { /** * The dictionary key name to compare. */ private String key; /** * Creates a new dictionary comparator. * * @param key the dictionary key name */ public DictComparator(String key) { this.key = key; } /** * Compares two dictionaries by comparing their values for a * predefined property key. * * @param o1 the first object * @param o2 the second object * * @return a negative integer, zero, or a positive integer as the * first argument is less than, equal to, or greater than * the second * * @throws ClassCastException if the values were not comparable */ public int compare(Object o1, Object o2) throws ClassCastException { Dict d1 = (Dict) o1; Dict d2 = (Dict) o2; if (d1 == null && d2 == null) { return 0; } else if (d1 == null) { return -1; } else if (d2 == null) { return 1; } else { return compareValues(d1.get(this.key), d2.get(this.key)); } } /** * Compares two values according to generic comparison rules, * i.e. it checks for null values and otherwise uses the * Comparable interface. * * @param o1 the first object * @param o2 the second object * * @return a negative integer, zero, or a positive integer as the * first argument is less than, equal to, or greater than * the second * * @throws ClassCastException if the values were not comparable */ @SuppressWarnings("unchecked") private int compareValues(Object o1, Object o2) throws ClassCastException { Comparable<Object> c1 = (Comparable<Object>) o1; Comparable<Object> c2 = (Comparable<Object>) o2; if (c1 == null && c2 == null) { return 0; } else if (c1 == null) { return -1; } else if (c2 == null) { return 1; } else { return c1.compareTo(c2); } } }
3e143a2ae38feff6cef8baa6e5a13694f0c75f18
5,997
java
Java
src/itest/java/com/sybit/airtable/mock/WireMockBaseTest.java
Sybit-Education/airtable-api
70f03de31299c2506978c893bbfa047bd269d2d8
[ "MIT" ]
46
2017-03-23T20:49:44.000Z
2022-03-29T19:19:45.000Z
src/itest/java/com/sybit/airtable/mock/WireMockBaseTest.java
Sybit-Education/airtable-api
70f03de31299c2506978c893bbfa047bd269d2d8
[ "MIT" ]
44
2017-03-28T06:19:44.000Z
2022-03-21T16:30:04.000Z
src/itest/java/com/sybit/airtable/mock/WireMockBaseTest.java
Sybit-Education/airtable-api
70f03de31299c2506978c893bbfa047bd269d2d8
[ "MIT" ]
22
2017-03-15T07:40:58.000Z
2022-03-09T15:32:00.000Z
26.418502
166
0.591462
8,558
/* * The MIT License (MIT) * Copyright (c) 2017 Sybit GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy */ package com.sybit.airtable.mock; import com.github.tomakehurst.wiremock.WireMockServer; import com.sybit.airtable.Airtable; import com.sybit.airtable.exception.AirtableException; import org.junit.Before; import static com.github.tomakehurst.wiremock.client.WireMock.*; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.extension.Parameters; import com.github.tomakehurst.wiremock.recording.SnapshotRecordResult; import com.sybit.airtable.Base; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.After; /** * Base Class to test using WireMock. * * Config files for the requests are stored at 'src/test/resources/__files' and * 'src/test/resources/mappings'. */ public class WireMockBaseTest { private static WireMockServer wireMockServer; private static WiremockProp prop; protected static Airtable airtable = new Airtable(); protected static Base base; private class WiremockProp { private boolean recording; private boolean cleanDirectorys; private String targetUrl; private String proxyBase; private int proxyPort; private int serverPort; /** * @return the recording */ public boolean isRecording() { return recording; } /** * @param aRecording the recording to set */ public void setRecording(boolean aRecording) { recording = aRecording; } /** * @return the cleanDirectorys */ public boolean isCleanDirectorys() { return cleanDirectorys; } /** * @param aCleanDirectorys the cleanDirectorys to set */ public void setCleanDirectorys(boolean aCleanDirectorys) { cleanDirectorys = aCleanDirectorys; } /** * @return the targetUrl */ public String getTargetUrl() { return targetUrl; } /** * @param aTargetUrl the targetUrl to set */ public void setTargetUrl(String aTargetUrl) { targetUrl = aTargetUrl; } /** * @return the proxyBase */ public String getProxyBase() { return proxyBase; } /** * @param aProxyBase the proxyBase to set */ public void setProxyBase(String aProxyBase) { proxyBase = aProxyBase; } /** * @return the proxyPort */ public int getProxyPort() { return proxyPort; } /** * @param aProxyPort the proxyPort to set */ public void setProxyPort(int aProxyPort) { proxyPort = aProxyPort; } /** * @return the serverPort */ public int getServerPort() { return serverPort; } /** * @param aServerPort the serverPort to set */ public void setServerPort(int aServerPort) { serverPort = aServerPort; } }; @Before public void setUp() throws AirtableException { airtable.configure(); airtable.setProxy("127.0.0.1"); airtable.setEndpointUrl("http://localhost:8080"); base = airtable.base("appTtHA5PfJnVfjdu"); prop = new WiremockProp(); prop.setRecording(false); prop.setCleanDirectorys(false); prop.setProxyBase("192.168.1.254"); prop.setProxyPort(8080); prop.setServerPort(8080); prop.setTargetUrl("https://api.airtable.com/v0"); if (prop.getProxyBase() != null && prop.getProxyPort() != 0) { wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(prop.getServerPort()).proxyVia(prop.getProxyBase(), prop.getProxyPort())); } else { wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(prop.getServerPort())); } //start the Wiremock-Server startServer(); //check if record if (prop.isRecording()) { //check if cleanDirectorys if (prop.isCleanDirectorys()) { cleanExistingRecords(); startRecording(); } else { startRecording(); } } } @After public void tearDown() { if (prop.isRecording()) { stopRecording(); } stopServer(); } public static void startRecording() { wireMockServer.startRecording(recordSpec() .forTarget(prop.getTargetUrl()) .captureHeader("Accept") .captureHeader("Content-Type", true) .extractBinaryBodiesOver(0) .extractTextBodiesOver(0) .makeStubsPersistent(true) .transformers("modify-response-header") .transformerParameters(Parameters.one("headerValue", "123")) .matchRequestBodyWithEqualToJson(false, true)); } public static void stopRecording() { SnapshotRecordResult recordedMappings = wireMockServer.stopRecording(); } public static void startServer() { wireMockServer.start(); } public static void stopServer() { wireMockServer.stop(); } public static void cleanExistingRecords() { File mappings = new File("src/test/resources/mappings"); File bodyFiles = new File("src/test/resources/__files"); try { FileUtils.cleanDirectory(mappings); FileUtils.cleanDirectory(bodyFiles); } catch (IOException ex) { System.out.println("Exception deleting Files: " + ex); } } }
3e143a6b1ab1f26695fe78a61568be9a04cf0538
2,668
java
Java
src/main/java/org/rapidpm/vaadin/api/fluent/builder/button/ButtonMixin.java
vaadin-developer/vaadin10-fluent-api
11403d12e40310495578ea4eb61f0d31b8d3aec9
[ "Apache-2.0" ]
null
null
null
src/main/java/org/rapidpm/vaadin/api/fluent/builder/button/ButtonMixin.java
vaadin-developer/vaadin10-fluent-api
11403d12e40310495578ea4eb61f0d31b8d3aec9
[ "Apache-2.0" ]
null
null
null
src/main/java/org/rapidpm/vaadin/api/fluent/builder/button/ButtonMixin.java
vaadin-developer/vaadin10-fluent-api
11403d12e40310495578ea4eb61f0d31b8d3aec9
[ "Apache-2.0" ]
1
2018-10-29T12:47:35.000Z
2018-10-29T12:47:35.000Z
28.136842
75
0.731388
8,559
/** * Copyright © 2018 Sven Ruppert (efpyi@example.com) * * 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 org.rapidpm.vaadin.api.fluent.builder.button; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.HasSize; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.data.binder.Setter; import org.rapidpm.vaadin.api.fluent.builder.component.ComponentMixin; public interface ButtonMixin extends ComponentMixin<Button> { //delegate @Override default <V> ButtonMixin set(Setter<Button, V> target, V value) { component().ifPresent(c -> target.accept(c, value)); return this; } default ButtonMixin setText(String text) { return set(Button::setText, text); } default ButtonMixin setIcon(Component icon) { return set(Button::setIcon, icon); } default ButtonMixin setIconAfterText(boolean iconAfterText) { return set(Button::setIconAfterText, iconAfterText); } default ButtonMixin setAutofocus(boolean autofocus) { return set(Button::setAutofocus, autofocus); } @Override default ButtonMixin setId(String id) { return set(Button::setId, id); } @Override default ButtonMixin setVisible(boolean visible) { return set(Button::setVisible, visible); } default ButtonMixin setClassName(String className) { return set(Button::setClassName, className); } default ButtonMixin setClassName(String className, boolean set) { component().ifPresent(c -> c.setClassName(className, set)); return this; } default ButtonMixin setTabIndex(int tabIndex) { return set(Button::setTabIndex, tabIndex); } default ButtonMixin setEnabled(boolean enabled) { return set(Button::setEnabled, enabled); } default ButtonMixin setWidth(String width) { return set(Button::setWidth, width); } default ButtonMixin setHeight(String height) { return set(Button::setHeight, height); } default ButtonMixin setSizeFull() { component().ifPresent(HasSize::setSizeFull); return this; } default ButtonMixin setSizeUndefined() { component().ifPresent(HasSize::setSizeUndefined); return this; } }
3e143c6c6466ca8fec4dbbbc7ca9bf2983f685af
3,214
java
Java
core/src/main/java/io/onedev/server/manager/impl/DefaultIssueFieldUnaryManager.java
OpenSrcRepoDataDigging/onedev
1facaef51d35add5eb99740fb5d13a73b210a72e
[ "MIT" ]
null
null
null
core/src/main/java/io/onedev/server/manager/impl/DefaultIssueFieldUnaryManager.java
OpenSrcRepoDataDigging/onedev
1facaef51d35add5eb99740fb5d13a73b210a72e
[ "MIT" ]
null
null
null
core/src/main/java/io/onedev/server/manager/impl/DefaultIssueFieldUnaryManager.java
OpenSrcRepoDataDigging/onedev
1facaef51d35add5eb99740fb5d13a73b210a72e
[ "MIT" ]
1
2019-01-13T05:02:37.000Z
2019-01-13T05:02:37.000Z
32.464646
129
0.761357
8,560
package io.onedev.server.manager.impl; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import javax.persistence.Query; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Root; import io.onedev.server.manager.IssueFieldUnaryManager; import io.onedev.server.model.Issue; import io.onedev.server.model.IssueFieldUnary; import io.onedev.server.persistence.annotation.Sessional; import io.onedev.server.persistence.annotation.Transactional; import io.onedev.server.persistence.dao.AbstractEntityManager; import io.onedev.server.persistence.dao.Dao; import io.onedev.server.util.inputspec.InputSpec; @Singleton public class DefaultIssueFieldUnaryManager extends AbstractEntityManager<IssueFieldUnary> implements IssueFieldUnaryManager { @Inject public DefaultIssueFieldUnaryManager(Dao dao) { super(dao); } @Transactional @Override public void saveFields(Issue issue) { Collection<Long> ids = new HashSet<>(); for (IssueFieldUnary unary: issue.getFieldUnaries()) { if (unary.getId() != null) ids.add(unary.getId()); } if (!ids.isEmpty()) { Query query = getSession().createQuery("delete from IssueFieldUnary where issue = :issue and id not in (:ids)"); query.setParameter("issue", issue); query.setParameter("ids", ids); query.executeUpdate(); } else { Query query = getSession().createQuery("delete from IssueFieldUnary where issue = :issue"); query.setParameter("issue", issue); query.executeUpdate(); } for (IssueFieldUnary unary: issue.getFieldUnaries()) { if (unary.isNew()) save(unary); } } @Transactional @Override public void onRenameGroup(String oldName, String newName) { Query query = getSession().createQuery("update IssueFieldUnary set value=:newName where type=:groupChoice and value=:oldName"); query.setParameter("groupChoice", InputSpec.GROUP); query.setParameter("oldName", oldName); query.setParameter("newName", newName); query.executeUpdate(); } @Transactional @Override public void onRenameUser(String oldName, String newName) { Query query = getSession().createQuery("update IssueFieldUnary set value=:newName where type=:userChoice and value=:oldName"); query.setParameter("userChoice", InputSpec.USER); query.setParameter("oldName", oldName); query.setParameter("newName", newName); query.executeUpdate(); } @Sessional @Override public void populateFields(List<Issue> issues) { CriteriaBuilder builder = getSession().getCriteriaBuilder(); CriteriaQuery<IssueFieldUnary> query = builder.createQuery(IssueFieldUnary.class); Root<IssueFieldUnary> root = query.from(IssueFieldUnary.class); query.select(root); root.join("issue"); Expression<String> issueExpr = root.get("issue"); query.where(issueExpr.in(issues)); for (Issue issue: issues) issue.setFieldUnaries(new ArrayList<>()); for (IssueFieldUnary field: getSession().createQuery(query).getResultList()) field.getIssue().getFieldUnaries().add(field); } }
3e143e1d34b00a740fa287f6a8f354b712c059a9
1,313
java
Java
third_party/java/proguard/proguard6.2.2/src/proguard/classfile/visitor/ClassPoolVisitor.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
16,989
2015-09-01T19:57:15.000Z
2022-03-31T23:54:00.000Z
third_party/java/proguard/proguard6.2.2/src/proguard/classfile/visitor/ClassPoolVisitor.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
12,562
2015-09-01T09:06:01.000Z
2022-03-31T22:26:20.000Z
third_party/java/proguard/proguard6.2.2/src/proguard/classfile/visitor/ClassPoolVisitor.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
3,707
2015-09-02T19:20:01.000Z
2022-03-31T17:06:14.000Z
34.552632
78
0.744097
8,561
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2019 Guardsquare NV * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.classfile.visitor; import proguard.classfile.ClassPool; /** * This interface specifies the methods for a visitor of * <code>ClassPool</code> objects. Note that there is only a single * implementation of <code>ClassPool</code>, such that this interface * is not strictly necessary as a visitor. * * @author Eric Lafortune */ public interface ClassPoolVisitor { public void visitClassPool(ClassPool classPool); }
3e143e7778d0bc261dd926ba683bbf01d8b46b55
5,039
java
Java
java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java
MariEliseeva/intellij-community
49e18fabdfc048f1d304e5d62b7a91a4552eb46c
[ "Apache-2.0" ]
null
null
null
java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java
MariEliseeva/intellij-community
49e18fabdfc048f1d304e5d62b7a91a4552eb46c
[ "Apache-2.0" ]
null
null
null
java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java
MariEliseeva/intellij-community
49e18fabdfc048f1d304e5d62b7a91a4552eb46c
[ "Apache-2.0" ]
null
null
null
46.229358
181
0.727724
8,562
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.miscGenerics; import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.codeInspection.dataFlow.CommonDataflow; import com.intellij.codeInspection.dataFlow.TypeConstraint; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.java.analysis.JavaAnalysisBundle; import com.intellij.psi.*; import com.intellij.psi.util.MethodSignature; import com.intellij.psi.util.PsiUtil; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.List; /** * @author ven */ public class SuspiciousCollectionsMethodCallsInspection extends AbstractBaseJavaLocalInspectionTool { public boolean REPORT_CONVERTIBLE_METHOD_CALLS = true; @Override public boolean isEnabledByDefault() { return true; } @Override @Nullable public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel(JavaAnalysisBundle.message("report.suspicious.but.possibly.correct.method.calls"), this, "REPORT_CONVERTIBLE_METHOD_CALLS"); } @Override @NotNull public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) { final List<SuspiciousMethodCallUtil.PatternMethod> patternMethods = new ArrayList<>(); return new JavaElementVisitor() { @Override public void visitMethodCallExpression(PsiMethodCallExpression methodCall) { final PsiExpression[] args = methodCall.getArgumentList().getExpressions(); if (args.length < 1) return; for (int idx = 0; idx < Math.min(2, args.length); idx ++) { String message = getSuspiciousMethodCallMessage(methodCall, REPORT_CONVERTIBLE_METHOD_CALLS, patternMethods, args[idx], idx); if (message != null) { holder.registerProblem(methodCall.getArgumentList().getExpressions()[idx], message); } } } @Override public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) { final PsiType functionalInterfaceType = expression.getFunctionalInterfaceType(); final PsiClassType.ClassResolveResult functionalInterfaceResolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType); final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType); if (interfaceMethod != null && interfaceMethod.getParameterList().getParametersCount() == 1) { final PsiSubstitutor psiSubstitutor = LambdaUtil.getSubstitutor(interfaceMethod, functionalInterfaceResolveResult); final MethodSignature signature = interfaceMethod.getSignature(psiSubstitutor); String message = SuspiciousMethodCallUtil.getSuspiciousMethodCallMessage(expression, signature.getParameterTypes()[0], REPORT_CONVERTIBLE_METHOD_CALLS, patternMethods, 0); if (message != null) { holder.registerProblem(ObjectUtils.notNull(expression.getReferenceNameElement(), expression), message); } } } }; } @Override @NotNull public String getGroupDisplayName() { return InspectionsBundle.message("group.names.probable.bugs"); } @Override @NotNull public String getShortName() { return "SuspiciousMethodCalls"; } private static String getSuspiciousMethodCallMessage(PsiMethodCallExpression methodCall, boolean reportConvertibleMethodCalls, List<SuspiciousMethodCallUtil.PatternMethod> patternMethods, PsiExpression arg, int i) { PsiType argType = arg.getType(); boolean exactType = arg instanceof PsiNewExpression; final String plainMessage = SuspiciousMethodCallUtil .getSuspiciousMethodCallMessage(methodCall, arg, argType, exactType || reportConvertibleMethodCalls, patternMethods, i); if (plainMessage != null && !exactType) { String methodName = methodCall.getMethodExpression().getReferenceName(); if (!"removeAll".equals(methodName) && !"retainAll".equals(methodName)) { // DFA works on raw types, so anyway we cannot narrow the argument type TypeConstraint constraint = TypeConstraint.fromDfType(CommonDataflow.getDfType(arg)); PsiType type = constraint.getPsiType(methodCall.getProject()); if (type != null && SuspiciousMethodCallUtil.getSuspiciousMethodCallMessage(methodCall, arg, type, reportConvertibleMethodCalls, patternMethods, i) == null) { return null; } } } return plainMessage; } }
3e143eb211b8aea00655b282f00491c960a18898
6,896
java
Java
src/main/java/frc/robot/Calibrations.java
thompsonevan/MM
8b9aeeb23877480d4bf2493b9b7cb29851e5f074
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/Calibrations.java
thompsonevan/MM
8b9aeeb23877480d4bf2493b9b7cb29851e5f074
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/Calibrations.java
thompsonevan/MM
8b9aeeb23877480d4bf2493b9b7cb29851e5f074
[ "BSD-3-Clause" ]
null
null
null
45.368421
156
0.655307
8,563
package frc.robot; public class Calibrations { public final static boolean isCompBot=false; public class auton{ public static final boolean trench = true; } public class CAN_ID { public final static int pigeon = 30; public final static int driveLeft1 = 4; public final static int driveLeft2 = 3; public final static int driveRight1 = 1; public final static int driveRight2 = 2; public final static int shooter1 = 5; public final static int shooter2 = 6; public final static int indexer = 12; public final static int conveyor = 13; public final static int carousel = 11; public final static int intakeMotor1 = 9; public final static int intakeMotor2 = 10; public final static int intakeLifter = 14; public final static int pcm = 0; public final static int CANifier = 20; public final static int leftClimber = 7; public final static int rightClimber = 8; } public class shooter_PID{ public final static double kP = 1.1e-3; public final static double kI = 3.1e-6; public final static double kD = 2e-7; public final static double kIz = 200; //public final static double kFF = 0; public final static double kFF = 0.000137862*1.6; public final static double kMaxOutput = 1; public final static double kMinOutput = -0.15; } public class shooter2_PID{ public final static double kP = 0.5e-3; public final static double kI = 1.0e-6; public final static double kD = 0; public final static double kIz = 100; //public final static double kFF = 0; public final static double kFF = 0.000137862*1.2; public final static double kMaxOutput = 1; public final static double kMinOutput = -0.15; } public class intake_PID{ public final static double kP = 1e-3; public final static double kI = 3e-6; public final static double kD = 2e-7; public final static double kIz = 225; public final static double kFF = 0.000137862*1.08; public final static double kMaxOutput = 1; public final static double kMinOutput = -0.5; public final static int packagePosition = 500; public final static int groundPosition = 0; public final static int limelitePosition = 250; public final static int middlePosition = 350; } public class ballSuperviserVals{ public final static int shooterCurrentLimit = 40; public final static int intakeArmCurrentLimit = 30; public final static double intakeStandardPower = 0.75; public final static double indexerPower = 1; public final static double ledCycleTime = 15; public final static double ledDutyCycle = 0.5; } public class Vision { public static final double kP = 0.027; public static final double kI = 0.06; public static final double kD = 0.001; public static final double kPDistance = 0.05; public static final double kIDistance = 0; public static final double kDistance = 0; public static final double kLimelightDistanceFromFront = 0; // In recording distance minus distance by how far back limelight is from front of robot public static final double deadband = .04; public static final double kHeight = (2.7114 - .17); // Height of Target - Height of Camera public static final double kMountedAngle = 41.1; } public class climberCals{ public static final int rachetID = 4; public static final double kP = 0.05; public static final double kI = 0; public static final double kD = 0; public static final double kF = 0; public static final int kIZ = 0; public static final int acc = 1600/2; public static final int vel = 1600/2; public static final double ticksPerInch = 118; public static final double upperLimit = 70; //Upper Hight Limit public static final double maxDelta = 12; //Max Target Change } public class ArmPositions{ public static final double packagedAngle = 90; public static final double trenchShotAngle = 63; public static final double autoShotAngle = 62; public static final double wallShotAngle = 0; public static final double groundPickupAngle = 0.1; public static final double wofAngle = 59.45; //7015 tiks public static final double maxTicks = 7600; //7700 is max } public class DRIVE_CONSTANTS { //6.5 gear ratio public static final double ticksPerMeter = 38825; //38449.2; public static final double trackWidth = 0.5925; //meters public static final double YawCorrection_kP = 0.025; } //wheel diameter 0.0127 public class AUTO_CONTROLLERS { public static final double velocityPIDkp = 0.0; //0.000183 ; public static final double velocityPIDki = 0.0; public static final double velocityPIDkd = 0.0; public static final double velocityPIDkf = 0.0603; public static final double ramseteB = 3; public static final double ramseteTheta = 0.7; public static final double ffkS = 0.276; //0.577; public static final double ffkV = 0.276; //2.36; //2.36 * 10 *1023 * 0.0635 *2 *pi /6.5 / 12 /4096 public static final double ffkA = 0.0391; //0.196; public static final double voltagekP = 3.72; //3.72; public static final double voltagekI = 0; public static final double voltagekD = 0; } public class ARM{ public static final double kP = 1.5; public static final double kI = 0.01 * 2 /3; public static final double kD = 0; public static final double kF = 0; public static final int kIZ = 480; public static final int acc = 1600; public static final int vel = 1600; public static final double ticksPerDegree = 118; public static final double maxGravityFF = 0.139; public static final double measuredTicksHorizontal = 82; public static final double resetCurrentDraw = 20; //amps, log motion magic to get value public static final double ticksAt90 = 300; //configure by measuring ticks when arm is level using level public static final double limelightHeightAtArm90 = 0.426; //configure, from ground //difference on comp bot becausw of hard stop is 1.51 degrees public static final double lengthOfArmToLimelight = 0.62; } public class hardware{ public static final boolean longPistonExtend = isCompBot?false:true; public static final boolean shortPistonExtend = isCompBot; public static final boolean indexerInvert = isCompBot?false:true; } }
3e143f18e42329bd625ed0099b69b21050665992
424
java
Java
src/main/java/com/example/project/server/model/CalculationResponse.java
fl0w88/demo3
bbb41e28a01f79cfcf783100dbd2b66ab3e4d76e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/project/server/model/CalculationResponse.java
fl0w88/demo3
bbb41e28a01f79cfcf783100dbd2b66ab3e4d76e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/project/server/model/CalculationResponse.java
fl0w88/demo3
bbb41e28a01f79cfcf783100dbd2b66ab3e4d76e
[ "Apache-2.0" ]
null
null
null
16.96
51
0.665094
8,564
package com.example.project.server.model; import java.math.BigDecimal; public class CalculationResponse { private BigDecimal result; public CalculationResponse() { } public CalculationResponse(BigDecimal result) { this.result = result; } public BigDecimal getResult() { return result; } public void setResult(BigDecimal result) { this.result = result; } }
3e143f6c72f46a2d9169079f77e214e322366c93
6,259
java
Java
src/main/java/org/reaktivity/nukleus/http_cache/internal/stream/util/HttpHeadersUtil.java
reaktivity/nukleus-http-cache.java
45cb0b1d37734ae306aa741d1354539c3bbec036
[ "ECL-2.0", "Apache-2.0" ]
1
2017-07-10T05:35:16.000Z
2017-07-10T05:35:16.000Z
src/main/java/org/reaktivity/nukleus/http_cache/internal/stream/util/HttpHeadersUtil.java
reaktivity/nukleus-http-cache.java
45cb0b1d37734ae306aa741d1354539c3bbec036
[ "ECL-2.0", "Apache-2.0" ]
76
2017-06-20T21:44:16.000Z
2020-08-18T05:24:39.000Z
src/main/java/org/reaktivity/nukleus/http_cache/internal/stream/util/HttpHeadersUtil.java
reaktivity/nukleus-http-cache.java
45cb0b1d37734ae306aa741d1354539c3bbec036
[ "ECL-2.0", "Apache-2.0" ]
8
2017-05-23T00:03:58.000Z
2019-09-16T20:29:02.000Z
34.202186
115
0.629813
8,565
/** * Copyright 2016-2021 The Reaktivity Project * * The Reaktivity Project licenses this file to you 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 org.reaktivity.nukleus.http_cache.internal.stream.util; import static org.reaktivity.nukleus.http_cache.internal.stream.util.HttpHeaders.AUTHORITY; import static org.reaktivity.nukleus.http_cache.internal.stream.util.HttpHeaders.EMULATED_PROTOCOL_STACK; import static org.reaktivity.nukleus.http_cache.internal.stream.util.HttpHeaders.IF_NONE_MATCH; import static org.reaktivity.nukleus.http_cache.internal.stream.util.HttpHeaders.RETRY_AFTER; import static org.reaktivity.nukleus.http_cache.internal.stream.util.HttpHeaders.STATUS; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.Date; import java.util.function.Predicate; import org.reaktivity.nukleus.http_cache.internal.types.Array32FW; import org.reaktivity.nukleus.http_cache.internal.types.HttpHeaderFW; public final class HttpHeadersUtil { private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); public static final Predicate<? super HttpHeaderFW> HAS_CACHE_CONTROL = h -> { String name = h.name().asString(); return "cache-control".equalsIgnoreCase(name); }; public static final Predicate<? super HttpHeaderFW> HAS_IF_NONE_MATCH = h -> { String name = h.name().asString(); return IF_NONE_MATCH.equalsIgnoreCase(name); }; public static final Predicate<? super HttpHeaderFW> HAS_AUTHORIZATION = h -> { String name = h.name().asString(); return AUTHORITY.equalsIgnoreCase(name); }; public static final Predicate<? super HttpHeaderFW> HAS_EMULATED_PROTOCOL_STACK = h -> { String name = h.name().asString(); return EMULATED_PROTOCOL_STACK.equalsIgnoreCase(name); }; public static final Predicate<? super HttpHeaderFW> HAS_RETRY_AFTER = h -> { String name = h.name().asString(); return RETRY_AFTER.equalsIgnoreCase(name); }; public static String getRequestURL( Array32FW<HttpHeaderFW> headers) { // TODO, less garbage collection... // streaming API: https://github.com/reaktivity/nukleus-maven-plugin/issues/16 final StringBuilder scheme = new StringBuilder(); final StringBuilder path = new StringBuilder(); final StringBuilder authority = new StringBuilder(); headers.forEach(h -> { switch (h.name().asString()) { case AUTHORITY: authority.append(h.value().asString()); break; case HttpHeaders.PATH: path.append(h.value().asString()); break; case HttpHeaders.SCHEME: scheme.append(h.value().asString()); break; default: break; } }); return scheme.append("://").append(authority.toString()).append(path.toString()).toString(); } public static String getHeader( Array32FW<HttpHeaderFW> cachedRequestHeaders, String headerName) { // TODO remove GC when have streaming API: https://github.com/reaktivity/nukleus-maven-plugin/issues/16 final StringBuilder header = new StringBuilder(); cachedRequestHeaders.forEach(h -> { if (headerName.equalsIgnoreCase(h.name().asString())) { header.append(h.value().asString()); } }); return header.length() == 0 ? null : header.toString(); } public static String getHeaderOrDefault( Array32FW<HttpHeaderFW> responseHeaders, String headerName, String defaulted) { final String result = getHeader(responseHeaders, headerName); return result == null ? defaulted : result; } public static boolean hasStatusCode( Array32FW<HttpHeaderFW> responseHeaders, int statusCode) { return responseHeaders.anyMatch(h -> STATUS.equals(h.name().asString()) && (Integer.toString(statusCode)).equals(h.value().asString())); } public static boolean retry( Array32FW<HttpHeaderFW> responseHeaders) { return hasStatusCode(responseHeaders, 503) && responseHeaders.anyMatch(HAS_RETRY_AFTER); } /* * Retry-After supports two formats. For example: * Retry-After: Wed, 21 Oct 2015 07:28:00 GMT * Retry-After: 120 * * @return wait time in seconds from now for both formats */ public static long retryAfter( Array32FW<HttpHeaderFW> responseHeaders) { HttpHeaderFW header = responseHeaders.matchFirst(HAS_RETRY_AFTER); if (header == null) { return 0L; } String retryAfter = header.value().asString(); try { if (retryAfter != null && !retryAfter.isEmpty()) { if (Character.isDigit(retryAfter.charAt(0))) { return Integer.valueOf(retryAfter); } else { final Date date = DATE_FORMAT.parse(retryAfter); final long epochSecond = date.toInstant().getEpochSecond(); final long nowSecond = Instant.now().getEpochSecond(); final long waitSeconds = epochSecond - nowSecond; return Math.max(waitSeconds, 0); } } } catch (Exception e) { // ignore } return 0L; } private HttpHeadersUtil() { // utility } }
3e143fb8ac2c1b47a7789040a52a067cd82fb445
19,332
java
Java
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/template/ClientMessageTemplate.java
viliam-durina/hazelcast-client-protocol
41b91e89d32f047d72a45c4a6aecdf23f2dd7e70
[ "Apache-2.0" ]
null
null
null
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/template/ClientMessageTemplate.java
viliam-durina/hazelcast-client-protocol
41b91e89d32f047d72a45c4a6aecdf23f2dd7e70
[ "Apache-2.0" ]
null
null
null
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/template/ClientMessageTemplate.java
viliam-durina/hazelcast-client-protocol
41b91e89d32f047d72a45c4a6aecdf23f2dd7e70
[ "Apache-2.0" ]
null
null
null
54
143
0.681357
8,566
/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.client.impl.protocol.template; import com.hazelcast.annotation.GenerateCodec; import com.hazelcast.annotation.Nullable; import com.hazelcast.annotation.Request; import com.hazelcast.annotation.Since; import com.hazelcast.client.impl.protocol.constants.EventMessageConst; import com.hazelcast.client.impl.protocol.constants.ResponseMessageConst; import com.hazelcast.nio.Address; import com.hazelcast.nio.serialization.Data; import java.util.List; import java.util.Map; @GenerateCodec(id = TemplateConstants.CLIENT_TEMPLATE_ID, name = "Client", ns = "Hazelcast.Client.Protocol.Codec") public interface ClientMessageTemplate { /** * @param username Name of the user for authentication. * @param password Password for the user. * @param uuid Unique string identifying the connected client uniquely. This string is generated by the owner member server * on initial connection. When the client connects to a non-owner member it sets this field on the request. * @param ownerUuid Unique string identifying the server member uniquely. * @param isOwnerConnection You must set this field to true while connecting to the owner member, otherwise set to false. * @param clientType The type of the client. E.g. JAVA, CPP, CSHARP, etc. * @param serializationVersion client side supported version to inform server side * @param clientHazelcastVersion The Hazelcast version of the client. (e.g. 3.7.2) * @return Returns the address, uuid and owner uuid. */ @Request(id = 2, retryable = true, response = ResponseMessageConst.AUTHENTICATION) Object authentication(String username, String password, @Nullable String uuid, @Nullable String ownerUuid, boolean isOwnerConnection, String clientType, byte serializationVersion, @Since (value = "1.3") String clientHazelcastVersion); /** * @param credentials Secret byte array for authentication. * @param uuid Unique string identifying the connected client uniquely. This string is generated by the owner member server * on initial connection. When the client connects to a non-owner member it sets this field on the request. * @param ownerUuid Unique string identifying the server member uniquely. * @param isOwnerConnection You must set this field to true while connecting to the owner member, otherwise set to false. * @param clientType The type of the client. E.g. JAVA, CPP, CSHARP, etc. * @param serializationVersion client side supported version to inform server side * @param clientHazelcastVersion The Hazelcast version of the client. (e.g. 3.7.2) * @return Returns the address, uuid and owner uuid. */ @Request(id = 3, retryable = true, response = ResponseMessageConst.AUTHENTICATION) Object authenticationCustom(Data credentials, @Nullable String uuid, @Nullable String ownerUuid, boolean isOwnerConnection, String clientType, byte serializationVersion, @Since (value = "1.3") String clientHazelcastVersion); /** * @param localOnly if true only master node sends events, otherwise all registered nodes send all membership * changes. * @return Returns the registration id for the listener. */ @Request(id = 4, retryable = false, response = ResponseMessageConst.STRING, event = {EventMessageConst.EVENT_MEMBER, EventMessageConst.EVENT_MEMBERLIST, EventMessageConst.EVENT_MEMBERATTRIBUTECHANGE}) Object addMembershipListener(boolean localOnly); /** * @param name The distributed object name for which the proxy is being created for. * @param serviceName The name of the service. Possible service names are: * "hz:impl:listService" * "hz:impl:queueService" * "hz:impl:setService" * "hz:impl:atomicLongService" * "hz:impl:atomicReferenceService" * "hz:impl:countDownLatchService" * "hz:impl:idGeneratorService" * "hz:impl:semaphoreService" * "hz:impl:executorService" * "hz:impl:mapService" * "hz:impl:mapReduceService" * "hz:impl:multiMapService" * "hz:impl:quorumService" * "hz:impl:replicatedMapService" * "hz:impl:ringbufferService" * "hz:core:proxyService" * "hz:impl:reliableTopicService" * "hz:impl:topicService" * "hz:core:txManagerService" * "hz:impl:xaService" */ @Request(id = 5, retryable = false, response = ResponseMessageConst.VOID) void createProxy(String name, String serviceName, Address target); /** * @param name The distributed object name for which the proxy is being destroyed for. * @param serviceName The name of the service. Possible service names are: * "hz:impl:listService" * "hz:impl:queueService" * "hz:impl:setService" * "hz:impl:atomicLongService" * "hz:impl:atomicReferenceService" * "hz:impl:countDownLatchService" * "hz:impl:idGeneratorService" * "hz:impl:semaphoreService" * "hz:impl:executorService" * "hz:impl:mapService" * "hz:impl:mapReduceService" * "hz:impl:multiMapService" * "hz:impl:quorumService" * "hz:impl:replicatedMapService" * "hz:impl:ringbufferService" * "hz:core:proxyService" * "hz:impl:reliableTopicService" * "hz:impl:topicService" * "hz:core:txManagerService" * "hz:impl:xaService" */ @Request(id = 6, retryable = false, response = ResponseMessageConst.VOID) void destroyProxy(String name, String serviceName); /** * @return The partition list for each member address. */ @Request(id = 8, retryable = false, response = ResponseMessageConst.PARTITIONS) Object getPartitions(); @Request(id = 9, retryable = false, response = ResponseMessageConst.VOID) void removeAllListeners(); /** * @param localOnly if true only node that has the partition sends the request, if false * sends all partition lost events. * @return The listener registration id. */ @Request(id = 10, retryable = false, response = ResponseMessageConst.STRING, event = {EventMessageConst.EVENT_PARTITIONLOST}) Object addPartitionLostListener(boolean localOnly); /** * @param registrationId The id assigned during the listener registration. * @return true if the listener existed and removed, false otherwise. */ @Request(id = 11, retryable = true, response = ResponseMessageConst.BOOLEAN) Object removePartitionLostListener(String registrationId); /** * @return An array of distributed object info in the cluster. */ @Request(id = 12, retryable = false, response = ResponseMessageConst.LIST_DISTRIBUTED_OBJECT) Object getDistributedObjects(); /** * @param localOnly If set to true, the server adds the listener only to itself, otherwise the listener is is added for all * members in the cluster. * @return The registration id for the distributed object listener. */ @Request(id = 13, retryable = false, response = ResponseMessageConst.STRING, event = {EventMessageConst.EVENT_DISTRIBUTEDOBJECT}) Object addDistributedObjectListener(boolean localOnly); /** * @param registrationId The id assigned during the registration. * @return true if the listener existed and removed, false otherwise. */ @Request(id = 14, retryable = true, response = ResponseMessageConst.BOOLEAN) Object removeDistributedObjectListener(String registrationId); @Request(id = 15, retryable = true, response = ResponseMessageConst.VOID) void ping(); /** * The statistics is a String that is composed of key=value pairs separated by ',' . The following characters * ('=' '.' ',' '\') should be escaped in IMap and ICache names by the escape character ('\'). E.g. if the map name is * MyMap.First, it will be escaped as: MyMap\.First * * The statistics key identify the category and name of the statistics. It is formatted as: * mainCategory.subCategory.statisticName * * An e.g. Operating system committedVirtualMemorySize path would be: os.committedVirtualMemorySize * * Please note that if any client implementation can not provide the value for a statistics, the corresponding key, valaue * pair will not be presented in the statistics string. Only the ones, that the client can provide will be added. * * The statistics key names can be one of the following (Used IMap named <StatIMapName> and ICache Named * <StatICacheName> and assuming that the near cache is configured): * * clientType: The string that represents the client type. See {@link com.hazelcast.core.ClientType} * * clusterConnectionTimestamp: The time that the client connected to the cluster (milliseconds since epoch). It is reset on * each reconnection. * * credentials.principal: The principal of the client if it exists. For * {@link com.hazelcast.security.UsernamePasswordCredentials}, this is the username, for custom authentication it is set by * the {@link com.hazelcast.security.Credentials} implementer. * * clientAddress: The address of the client. It is formatted as "<IP>:<port>" * * clientName: The name of the client instance. See ClientConfig.setInstanceName. * * enterprise: "true" if the client is an enterprise client, "false" otherwise. * * lastStatisticsCollectionTime: The time stamp (milliseconds since epoch) when the latest update for the statistics is * collected. * * Near cache statistics (see {@link com.hazelcast.monitor.NearCacheStats}): * * nc.<StatIMapName>.creationTime: The creation time (milliseconds since epoch) of this Near Cache on the client. * * nc.<StatIMapName>.evictions: The number of evictions of Near Cache entries owned by this client. * * nc.<StatIMapName>.expirations: The number of TTL and max-idle expirations of Near Cache entries owned by the client. * * nc.<StatIMapName>.hits: The number of hits (reads) of Near Cache entries owned by the client. * * nc.<StatIMapName>.lastPersistenceDuration: The duration in milliseconds of the last Near Cache key persistence * (when the pre-load feature is enabled). * * nc.<StatIMapName>.lastPersistenceFailure: The failure reason of the last Near Cache persistence (when the pre-load * feature is enabled). * * nc.<StatIMapName>.lastPersistenceKeyCount: The number of Near Cache key persistences (when the pre-load feature is * enabled). * * nc.<StatIMapName>.lastPersistenceTime: The timestamp (milliseconds since epoch) of the last Near Cache key * persistence (when the pre-load feature is enabled). * * nc.<StatIMapName>.lastPersistenceWrittenBytes: The written number of bytes of the last Near Cache key persistence * (when the pre-load feature is enabled). * * nc.<StatIMapName>.misses: The number of misses of Near Cache entries owned by the client. * * nc.<StatIMapName>.ownedEntryCount: the number of Near Cache entries owned by the client. * * nc.<StatIMapName>.ownedEntryMemoryCost: Memory cost (number of bytes) of Near Cache entries owned by the client. * * nc.hz/<StatICacheName>.creationTime: The creation time of this Near Cache on the client. * * nc.hz/<StatICacheName>.evictions: The number of evictions of Near Cache entries owned by the client. * * nc.hz/<StatICacheName>.expirations: The number of TTL and max-idle expirations of Near Cache entries owned by the * client. * * nc.hz/<StatICacheName>.hits * nc.hz/<StatICacheName>.lastPersistenceDuration * nc.hz/<StatICacheName>.lastPersistenceFailure * nc.hz/<StatICacheName>.lastPersistenceKeyCount * nc.hz/<StatICacheName>.lastPersistenceTime * nc.hz/<StatICacheName>.lastPersistenceWrittenBytes * nc.hz/<StatICacheName>.misses * nc.hz/<StatICacheName>.ownedEntryCount * nc.hz/<StatICacheName>.ownedEntryMemoryCost * * Operating System Statistics (see {@link com.hazelcast.internal.metrics.metricsets.OperatingSystemMetricSet}, * {@link sun.management.OperatingSystemImpl}) and {@link com.sun.management.UnixOperatingSystemMXBean}: * * os.committedVirtualMemorySize: The amount of virtual memory that is guaranteed to be available to the running process in * bytes, or -1 if this operation is not supported. * * os.freePhysicalMemorySize: The amount of free physical memory in bytes. * * os.freeSwapSpaceSize: The amount of free swap space in bytes. * * os.maxFileDescriptorCount: The maximum number of file descriptors. * * os.openFileDescriptorCount: The number of open file descriptors. * * os.processCpuTime: The CPU time used by the process in nanoseconds. * * os.systemLoadAverage: The system load average for the last minute. (See * {@link java.lang.management.OperatingSystemMXBean#getSystemLoadAverage}) * The system load average is the sum of the number of runnable entities * queued to the {@link java.lang.management.OperatingSystemMXBean#getAvailableProcessors} available processors * and the number of runnable entities running on the available processors * averaged over a period of time. * The way in which the load average is calculated is operating system * specific but is typically a damped time-dependent average. * <p> * If the load average is not available, a negative value is returned. * <p> * * os.totalPhysicalMemorySize: The total amount of physical memory in bytes. * * os.totalSwapSpaceSize: The total amount of swap space in bytes. * * Runtime statistics (See {@link Runtime}: * * runtime.availableProcessors: The number of processors available to the process. * * runtime.freeMemory: an approximation to the total amount of memory currently available for future allocated objects, * measured in bytes. * * runtime.maxMemory: The maximum amount of memory that the process will attempt to use, measured in bytes * * runtime.totalMemory: The total amount of memory currently available for current and future objects, measured in bytes. * * runtime.uptime: The uptime of the process in milliseconds. * * runtime.usedMemory: The difference of total memory and used memory in bytes. * * userExecutor.queueSize: The number of waiting tasks in the client user executor (See ClientExecutionService#getUserExecutor) * * Not: Please observe that the name for the ICache appears to be the hazelcast instance name "hz" followed by "/" and * followed by the cache name provided which is StatICacheName. * * An example stats string (IMap name: StatIMapName and ICache name: StatICacheName with near-cache enabled): * * lastStatisticsCollectionTime=1496137027173,enterprise=false,clientType=JAVA,clusterConnectionTimestamp=1496137018114, * clientAddress=127.0.0.1:5001,clientName=hz.client_0,executionService.userExecutorQueueSize=0,runtime.maxMemory=1065025536, * os.freePhysicalMemorySize=32067584,os.totalPhysicalMemorySize=17179869184,os.systemLoadAverage=249, * runtime.usedMemory=16235040,runtime.freeMemory=115820000,os.totalSwapSpaceSize=5368709120,runtime.availableProcessors=4, * runtime.uptime=13616,os.committedVirtualMemorySize=4081422336,os.maxFileDescriptorCount=10240, * runtime.totalMemory=132055040,os.processCpuTime=6270000000,os.openFileDescriptorCount=67,os.freeSwapSpaceSize=888406016, * nc.StatIMapName.creationTime=1496137021761,nc.StatIMapName.evictions=0,nc.StatIMapName.hits=1, * nc.StatIMapName.lastPersistenceDuration=0,nc.StatIMapName.lastPersistenceKeyCount=0,nc.StatIMapName.lastPersistenceTime=0, * nc.StatIMapName.lastPersistenceWrittenBytes=0,nc.StatIMapName.misses=1,nc.StatIMapName.ownedEntryCount=1, * nc.StatIMapName.expirations=0,nc.StatIMapName.ownedEntryMemoryCost=140,nc.hz/StatICacheName.creationTime=1496137025201, * nc.hz/StatICacheName.evictions=0,nc.hz/StatICacheName.hits=1,nc.hz/StatICacheName.lastPersistenceDuration=0, * nc.hz/StatICacheName.lastPersistenceKeyCount=0,nc.hz/StatICacheName.lastPersistenceTime=0, * nc.hz/StatICacheName.lastPersistenceWrittenBytes=0,nc.hz/StatICacheName.misses=1,nc.hz/StatICacheName.ownedEntryCount=1, * nc.hz/StatICacheName.expirations=0,nc.hz/StatICacheName.ownedEntryMemoryCost=140 * * * @param stats The key=value pairs separated by the ',' character */ @Request(id = 16, retryable = false, response = ResponseMessageConst.VOID) @Since(value = "1.5") void statistics(String stats); /** * Deploys the list of classes to cluster * Each item is a Map.Entry<String, byte[]> in the list. * key of entry is full class name, and byte[] is the class definition. * * @param classDefinitions list of class definitions */ @Request(id = 17, retryable = false, response = ResponseMessageConst.VOID) @Since(value = "1.5") void deployClasses(List<Map.Entry<String, byte[]>> classDefinitions); /** * Adds partition listener to send server. * listener is removed automatically when client disconnected. * There is no corresponding removeListener message. */ @Request(id = 18, retryable = false, response = ResponseMessageConst.VOID, event = {EventMessageConst.EVENT_PARTITIONS}) @Since(value = "1.5") void addPartitionListener(); }
3e143ffbea017e6c0f59fb5be05ad85e3575d07b
1,168
java
Java
configuration/src/main/java/io/github/phantomstr/testing/tool/config/core/ConfigLoader.java
PhantomStr/testing-tools
2534c74dcee11dfcb60aac9ea733af191faff5dc
[ "MIT" ]
1
2021-09-20T11:11:17.000Z
2021-09-20T11:11:17.000Z
configuration/src/main/java/io/github/phantomstr/testing/tool/config/core/ConfigLoader.java
PhantomStr/testing-tools
2534c74dcee11dfcb60aac9ea733af191faff5dc
[ "MIT" ]
null
null
null
configuration/src/main/java/io/github/phantomstr/testing/tool/config/core/ConfigLoader.java
PhantomStr/testing-tools
2534c74dcee11dfcb60aac9ea733af191faff5dc
[ "MIT" ]
2
2020-07-15T21:03:28.000Z
2021-09-16T11:13:44.000Z
40.275862
102
0.753425
8,567
package io.github.phantomstr.testing.tool.config.core; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.FileBasedConfiguration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.commons.configuration2.io.FileHandler; import java.io.InputStream; import static java.lang.String.format; public class ConfigLoader { public static Configuration getConfig(InputStream inputStream) { try { FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class); FileBasedConfiguration config = builder.getConfiguration(); FileHandler fileHandler = new FileHandler(config); fileHandler.load(inputStream); return config; } catch (ConfigurationException cex) { throw new RuntimeException(format("cant load env config resource: %s", inputStream), cex); } } }
3e14400bb4088a118673ed7cdd118be96442179c
389
java
Java
src/main/java/cn/coderoom/juc/containers/TestArray.java
coderoom-cn/javaStudy
c0245f8a39c28219c360db4fdd04a223491effd7
[ "MIT" ]
1
2020-01-10T06:48:27.000Z
2020-01-10T06:48:27.000Z
src/main/java/cn/coderoom/juc/containers/TestArray.java
coderoom-cn/javaStudy
c0245f8a39c28219c360db4fdd04a223491effd7
[ "MIT" ]
1
2020-04-11T16:35:35.000Z
2021-05-10T15:20:32.000Z
src/main/java/cn/coderoom/juc/containers/TestArray.java
coderoom-cn/javaStudy
c0245f8a39c28219c360db4fdd04a223491effd7
[ "MIT" ]
null
null
null
20.684211
75
0.605598
8,568
package cn.coderoom.juc.containers; import java.util.Arrays; /** * @package:cn.coderoom.juc.containers * @author: Leesire * @email:anpch@example.com * @createtime: 2020/4/9 */ public class TestArray { public static void main(String[] args) { int[] a = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; Arrays.stream(a).map(i->i+1).forEach(i->System.out.print(i + " ")); } }
3e1442012861dd074b28c7168f52c60ca9aed31f
3,107
java
Java
hazelcast/src/main/java/com/hazelcast/concurrent/atomiclong/client/AbstractAlterRequest.java
wildnez/hazelcast
e2d9fdddfd341f23547960712eca30d12e660600
[ "Apache-2.0" ]
null
null
null
hazelcast/src/main/java/com/hazelcast/concurrent/atomiclong/client/AbstractAlterRequest.java
wildnez/hazelcast
e2d9fdddfd341f23547960712eca30d12e660600
[ "Apache-2.0" ]
null
null
null
hazelcast/src/main/java/com/hazelcast/concurrent/atomiclong/client/AbstractAlterRequest.java
wildnez/hazelcast
e2d9fdddfd341f23547960712eca30d12e660600
[ "Apache-2.0" ]
null
null
null
31.07
110
0.736402
8,569
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.concurrent.atomiclong.client; import com.hazelcast.client.impl.client.PartitionClientRequest; import com.hazelcast.client.impl.client.SecureRequest; import com.hazelcast.concurrent.atomiclong.AtomicLongService; import com.hazelcast.core.IFunction; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.Data; import com.hazelcast.nio.serialization.Portable; import com.hazelcast.nio.serialization.PortableReader; import com.hazelcast.nio.serialization.PortableWriter; import com.hazelcast.security.permission.ActionConstants; import com.hazelcast.security.permission.AtomicLongPermission; import java.io.IOException; import java.security.Permission; import static com.hazelcast.nio.IOUtil.readNullableData; import static com.hazelcast.nio.IOUtil.writeNullableData; public abstract class AbstractAlterRequest extends PartitionClientRequest implements Portable, SecureRequest { protected String name; protected Data function; public AbstractAlterRequest() { } public AbstractAlterRequest(String name, Data function) { this.name = name; this.function = function; } @Override protected int getPartition() { Data key = serializationService.toData(name); return getClientEngine().getPartitionService().getPartitionId(key); } @Override public String getServiceName() { return AtomicLongService.SERVICE_NAME; } @Override public int getFactoryId() { return AtomicLongPortableHook.F_ID; } @Override public void write(PortableWriter writer) throws IOException { writer.writeUTF("n", name); ObjectDataOutput out = writer.getRawDataOutput(); writeNullableData(out, function); } @Override public void read(PortableReader reader) throws IOException { name = reader.readUTF("n"); ObjectDataInput in = reader.getRawDataInput(); function = readNullableData(in); } protected IFunction<Long, Long> getFunction() { return serializationService.toObject(function); } @Override public Permission getRequiredPermission() { return new AtomicLongPermission(name, ActionConstants.ACTION_MODIFY); } @Override public String getDistributedObjectName() { return name; } @Override public Object[] getParameters() { return new Object[]{function}; } }
3e144208ba04af4ce87f2af67b4d4f1af884060d
2,022
java
Java
app/src/main/java/com/n0hands/todoapp/CategoriesAdapter.java
IvoStoianov/Precrastinate
4fe54e8925115a22f9bcbef7c406915901b8d1b2
[ "MIT" ]
null
null
null
app/src/main/java/com/n0hands/todoapp/CategoriesAdapter.java
IvoStoianov/Precrastinate
4fe54e8925115a22f9bcbef7c406915901b8d1b2
[ "MIT" ]
null
null
null
app/src/main/java/com/n0hands/todoapp/CategoriesAdapter.java
IvoStoianov/Precrastinate
4fe54e8925115a22f9bcbef7c406915901b8d1b2
[ "MIT" ]
null
null
null
30.636364
94
0.697329
8,570
package com.n0hands.todoapp; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.DragEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.n0hands.todoapp.model.Category; import java.util.List; public class CategoriesAdapter extends RecyclerView.Adapter<CategoriesAdapter.MyViewHolder> { private List<Category> categories; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView title, description; public ImageView image; public MyViewHolder(View view) { super(view); title = (TextView) view.findViewById(R.id.category_name); description = (TextView) view.findViewById(R.id.category_description); image = (ImageView) view.findViewById(R.id.category_image); } } public CategoriesAdapter(java.util.List<Category> categories) { this.categories = categories; } @Override public CategoriesAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.category_row, parent, false); return new CategoriesAdapter.MyViewHolder(itemView); } @Override public void onBindViewHolder(CategoriesAdapter.MyViewHolder holder, int position) { Category category = categories.get(position); holder.title.setText(category.getName()); holder.description.setText(category.getDescription()); holder.image.setImageResource(R.mipmap.category); // FIXME: fix this } @Override public int getItemCount() { return categories.size(); } public void removeAt(int position) { categories.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, categories.size()); } }
3e14425eacb32586b9cba1598ed4237da0b966fa
2,720
java
Java
kafka/src/main/java/io/cloudevents/v02/kafka/HeaderMapper.java
bluemonk3y/sdk-java
6962a9799716d55449f86e42b1e541e978dc20f2
[ "Apache-2.0" ]
null
null
null
kafka/src/main/java/io/cloudevents/v02/kafka/HeaderMapper.java
bluemonk3y/sdk-java
6962a9799716d55449f86e42b1e541e978dc20f2
[ "Apache-2.0" ]
8
2019-11-13T12:46:43.000Z
2021-01-21T00:34:04.000Z
kafka/src/main/java/io/cloudevents/v02/kafka/HeaderMapper.java
bluemonk3y/sdk-java
6962a9799716d55449f86e42b1e541e978dc20f2
[ "Apache-2.0" ]
null
null
null
32
75
0.729779
8,571
/** * Copyright 2019 The CloudEvents Authors * * 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 io.cloudevents.v02.kafka; import static io.cloudevents.v02.kafka.AttributeMapper.HEADER_PREFIX; import java.util.AbstractMap.SimpleEntry; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.stream.Collectors; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.common.serialization.Serializer; import io.cloudevents.extensions.ExtensionFormat; import io.cloudevents.fun.FormatHeaderMapper; import io.cloudevents.v02.AttributesImpl; /** * * @author fabiojose * */ public class HeaderMapper { private HeaderMapper() {} private static final Serializer<String> SERIALIZER = Serdes.String().serializer(); /** * Following the signature of {@link FormatHeaderMapper} * @param attributes The map of attributes created by * {@link AttributesImpl#marshal(AttributesImpl)} * @param extensions The map of extensions created by * {@link ExtensionFormat#marshal(java.util.Collection)} * @return The map of Kafka Headers with values as {@code byte[]} */ public static Map<String, byte[]> map(Map<String, String> attributes, Map<String, String> extensions) { Objects.requireNonNull(attributes); Objects.requireNonNull(extensions); Map<String, byte[]> result = attributes.entrySet() .stream() .filter(attribute -> null!= attribute.getValue()) .map(attribute -> new SimpleEntry<>(attribute.getKey() .toLowerCase(Locale.US), attribute.getValue())) .map(attribute -> new SimpleEntry<>(HEADER_PREFIX+attribute.getKey(), attribute.getValue())) .map(attribute -> new SimpleEntry<>(attribute.getKey(), SERIALIZER.serialize(null, attribute.getValue()))) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); result.putAll( extensions.entrySet() .stream() .filter(extension -> null!= extension.getValue()) .map(extension -> new SimpleEntry<>(extension.getKey(), SERIALIZER.serialize(null, extension.getValue()))) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)) ); return result; } }
3e1442c67a0e2e136028623edffe137de2c596a2
3,007
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/gamecode/TestColourSense.java
FIXIT3491/FIX_IT_Ultimate_Goal_GameCode
382c914a394d82789777672ae6067e09bd380907
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/gamecode/TestColourSense.java
FIXIT3491/FIX_IT_Ultimate_Goal_GameCode
382c914a394d82789777672ae6067e09bd380907
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/gamecode/TestColourSense.java
FIXIT3491/FIX_IT_Ultimate_Goal_GameCode
382c914a394d82789777672ae6067e09bd380907
[ "MIT" ]
null
null
null
24.447154
94
0.585634
8,572
package org.firstinspires.ftc.teamcode.gamecode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.hardware.ColorSensor; import com.qualcomm.robotcore.hardware.VoltageSensor; import org.firstinspires.ftc.teamcode.Robots.Beyonce; import org.firstinspires.ftc.teamcode.opmodesupport.AutoOpMode; //@Disabled @Autonomous public class TestColourSense extends AutoOpMode { org.firstinspires.ftc.teamcode.Robots.Beyonce Beyonce; private VoltageSensor ExpansionHub2_VoltageSensor; @Override public void runOp(){ ExpansionHub2_VoltageSensor = hardwareMap.get(VoltageSensor.class, "Expansion Hub 2"); Beyonce beyonce = new Beyonce(); ColorSensor colorSensorL; colorSensorL = (ColorSensor) hardwareMap.get("ColourSensorL"); boolean red = opModeIsActive() && 120 < colorSensorL.red(); waitForStart(); colorSensorL.enableLed(true); // beyonce.Beat(-0.2); // sleep(100); // beyonce.Stop(); while (opModeIsActive() ){ telemetry.addData("red", colorSensorL.red()); } beyonce.Stop(); // //telemetry.addData("blue", colorSensorL.blue()); // // telemetry.addData("green", colorSensorL.green()); // //telemetry.addData("light", colorSensorL.alpha()); // // telemetry.addData("4 colour channels", colorSensorL.argb()); // } // beyonce.StrafeLeft(0.2); // telemetry.addData("staus", "left"); // sleep(1000); // beyonce.Stop(); // // sleep(200); // // beyonce.DriveForward(0.1); // telemetry.addData("staus", "forward"); // sleep(700); // beyonce.Stop(); // // sleep(300); // // clearTimer(1); // // while (opModeIsActive() && 38 > colorSensorL.red() && getSeconds(1) < 4){ // telemetry.addData("status", getSeconds(1)); // telemetry.addData("red", colorSensorL.red()); // // beyonce.StrafeRight(0.1); // } // telemetry.addData("staus", "white"); // telemetry.addData("red", colorSensorL.red()); // // beyonce.Stop(); //nice sleep(500); // // beyonce.StrafeLeft(0.1); // sleep(1250); // beyonce.Stop(); // // sleep(200); // // beyonce.DriveBackward(0.1); // sleep(1300); // beyonce.Stop(); // // sleep(300); // // beyonce.GrabberDown(); // // sleep(600); // // beyonce.DriveForward(0.3); // sleep(300); // beyonce.Stop(); //red in between like 30 and 36 } double getBatteryVoltage() { double result = Double.POSITIVE_INFINITY; for (VoltageSensor sensor : hardwareMap.voltageSensor) { double voltage = sensor.getVoltage(); if (voltage > 0) { result = Math.min(result, voltage); } } return result;} }
3e1442c745f04fc9d76e8cc101a5bff2e57c7ccc
3,531
java
Java
references/bcb_chosen_clones/selected#1359154#364#416.java
cragkhit/elasticsearch
05567b30c5bde08badcac1bf421454e5d995eb91
[ "Apache-2.0" ]
23
2018-10-03T15:02:53.000Z
2021-09-16T11:07:36.000Z
references/bcb_chosen_clones/selected#1359154#364#416.java
cragkhit/elasticsearch
05567b30c5bde08badcac1bf421454e5d995eb91
[ "Apache-2.0" ]
18
2019-02-10T04:52:54.000Z
2022-01-25T02:14:40.000Z
references/bcb_chosen_clones/selected#1359154#364#416.java
cragkhit/Siamese
05567b30c5bde08badcac1bf421454e5d995eb91
[ "Apache-2.0" ]
19
2018-11-16T13:39:05.000Z
2021-09-05T23:59:30.000Z
65.388889
166
0.680827
8,573
private void createIDocPluginProject(IProgressMonitor monitor, String sourceFileName, String pluginName, String pluginNameJCo) throws CoreException, IOException { monitor.subTask(MessageFormat.format(Messages.ProjectGenerator_CreatePluginTaskDescription, pluginName)); final Map<String, byte[]> files = readArchiveFile(sourceFileName); monitor.worked(10); IProject project = workspaceRoot.getProject(pluginName); if (project.exists()) { project.delete(true, true, new SubProgressMonitor(monitor, 5)); } else { monitor.worked(5); } project.create(new SubProgressMonitor(monitor, 5)); project.open(new SubProgressMonitor(monitor, 5)); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID, PLUGIN_NATURE_ID }); project.setDescription(description, new SubProgressMonitor(monitor, 5)); IJavaProject javaProject = JavaCore.create(project); IFolder binDir = project.getFolder("bin"); IPath binPath = binDir.getFullPath(); javaProject.setOutputLocation(binPath, new SubProgressMonitor(monitor, 5)); project.getFile("sapidoc3.jar").create(new ByteArrayInputStream(files.get("sapidoc3.jar")), true, new SubProgressMonitor(monitor, 15)); IFolder metaInfFolder = project.getFolder("META-INF"); metaInfFolder.create(true, true, new SubProgressMonitor(monitor, 5)); StringBuilder manifest = new StringBuilder(); manifest.append("Manifest-Version: 1.0\n"); manifest.append("Bundle-ManifestVersion: 2\n"); manifest.append("Bundle-Name: SAP IDoc Library v3\n"); manifest.append(MessageFormat.format("Bundle-SymbolicName: {0}\n", pluginName)); manifest.append("Bundle-Version: 7.11.0\n"); manifest.append("Bundle-ClassPath: bin/,\n"); manifest.append(" sapidoc3.jar\n"); manifest.append("Bundle-Vendor: SAP AG, Walldorf (packaged using RCER)\n"); manifest.append("Bundle-RequiredExecutionEnvironment: J2SE-1.5\n"); manifest.append("Export-Package: com.sap.conn.idoc,\n"); manifest.append(" com.sap.conn.idoc.jco,\n"); manifest.append(" com.sap.conn.idoc.rt.cp,\n"); manifest.append(" com.sap.conn.idoc.rt.record,\n"); manifest.append(" com.sap.conn.idoc.rt.record.impl,\n"); manifest.append(" com.sap.conn.idoc.rt.trace,\n"); manifest.append(" com.sap.conn.idoc.rt.util,\n"); manifest.append(" com.sap.conn.idoc.rt.xml\n"); manifest.append("Bundle-ActivationPolicy: lazy\n"); manifest.append(MessageFormat.format("Require-Bundle: {0}\n", pluginNameJCo)); writeTextFile(monitor, manifest, metaInfFolder.getFile("MANIFEST.MF")); final IPath jcoPath = new Path(MessageFormat.format("/{0}/sapidoc3.jar", pluginName)); IClasspathEntry jcoEntry = JavaCore.newLibraryEntry(jcoPath, Path.EMPTY, Path.EMPTY, true); javaProject.setRawClasspath(new IClasspathEntry[] { jcoEntry }, new SubProgressMonitor(monitor, 5)); StringBuilder buildProperties = new StringBuilder(); buildProperties.append("bin.includes = META-INF/,\\\n"); buildProperties.append(" sapidoc3.jar,\\\n"); buildProperties.append(" .\n"); writeTextFile(monitor, buildProperties, project.getFile("build.properties")); exportableBundles.add(modelManager.findModel(project)); }
3e1443ccdb502734768bb01af2a7837051926c45
424
java
Java
raw_dataset/65223741@queue@OK.java
zthang/code2vec_treelstm
0c5f98d280b506317738ba603b719cac6036896f
[ "MIT" ]
1
2020-04-24T03:35:40.000Z
2020-04-24T03:35:40.000Z
raw_dataset/65223741@queue@OK.java
ruanyuan115/code2vec_treelstm
0c5f98d280b506317738ba603b719cac6036896f
[ "MIT" ]
2
2020-04-23T21:14:28.000Z
2021-01-21T01:07:18.000Z
raw_dataset/65223741@queue@OK.java
zthang/code2vec_treelstm
0c5f98d280b506317738ba603b719cac6036896f
[ "MIT" ]
null
null
null
22.315789
45
0.398585
8,574
public void queue(int a, int b) { int ra = setSet(a); int rb = setSet(b); if (ra == rb) return; if (r[ra] == r[rb]) { p[ra] = rb; r[rb]++; max[rb] = Math.max(max[ra], max[rb]); return; } if (r[ra] > r[rb]) { p[rb] = ra; max[ra] = Math.max(max[ra], max[rb]); } else { p[ra] = rb; max[rb] = Math.max(max[ra], max[rb]); } }
3e144420d790d9aca3c9358fcedc1af3136947ae
2,244
java
Java
src/net/demilich/metastone/game/behaviour/human/HumanBehaviour.java
hillst/MetaStone
5882d834d32028f5f083543f0700e59ccf1aa1fe
[ "MIT" ]
null
null
null
src/net/demilich/metastone/game/behaviour/human/HumanBehaviour.java
hillst/MetaStone
5882d834d32028f5f083543f0700e59ccf1aa1fe
[ "MIT" ]
null
null
null
src/net/demilich/metastone/game/behaviour/human/HumanBehaviour.java
hillst/MetaStone
5882d834d32028f5f083543f0700e59ccf1aa1fe
[ "MIT" ]
null
null
null
30.739726
105
0.755348
8,575
package net.demilich.metastone.game.behaviour.human; import java.util.ArrayList; import java.util.List; import net.demilich.metastone.AppConfig; import net.demilich.metastone.ApplicationFacade; import net.demilich.metastone.GameNotification; import net.demilich.metastone.game.GameContext; import net.demilich.metastone.game.Player; import net.demilich.metastone.game.actions.GameAction; import net.demilich.metastone.game.actions.IActionSelectionListener; import net.demilich.metastone.game.behaviour.Behaviour; import net.demilich.metastone.game.cards.Card; public class HumanBehaviour extends Behaviour implements IActionSelectionListener { private GameAction selectedAction; private boolean waitingForInput; private List<Card> mulliganCards; @Override public String getName() { return "<Human controlled>"; } @Override public List<Card> mulligan(GameContext context, Player player, List<Card> cards) { if (context.ignoreEvents()) { return new ArrayList<Card>(); } waitingForInput = true; HumanMulliganOptions options = new HumanMulliganOptions(player, this, cards); ApplicationFacade.getInstance().sendNotification(GameNotification.HUMAN_PROMPT_FOR_MULLIGAN, options); while (waitingForInput) { try { Thread.sleep(AppConfig.DEFAULT_SLEEP_DELAY); } catch (InterruptedException e) { } } return mulliganCards; } @Override public void onActionSelected(GameAction action) { this.selectedAction = action; waitingForInput = false; } @Override public GameAction requestAction(GameContext context, Player player, List<GameAction> validActions) { waitingForInput = true; HumanActionOptions options = new HumanActionOptions(this, context, player, validActions); ApplicationFacade.getInstance().sendNotification(GameNotification.HUMAN_PROMPT_FOR_ACTION, options); while (waitingForInput) { try { Thread.sleep(AppConfig.DEFAULT_SLEEP_DELAY); if (context.ignoreEvents()) { return null; } } catch (InterruptedException e) { } } return selectedAction; } public void setMulliganCards(List<Card> mulliganCards) { this.mulliganCards = mulliganCards; waitingForInput = false; } }
3e1444bcee4cb124d3f259b3c9f121c6503fddfc
2,577
java
Java
edu/cmu/lti/algorithm/math/MomentumVec.java
whwang1996/pra
9db550f0a169ad2106ac6fb031b9fdd0d22fec65
[ "MIT" ]
61
2018-02-05T06:43:53.000Z
2022-03-12T12:56:47.000Z
edu/cmu/lti/algorithm/math/MomentumVec.java
irokin/Path-Ranking-Algorithms
ed8daeebb039a78ea10872e1f7505d00fdd5fcff
[ "MIT" ]
8
2018-03-25T02:46:42.000Z
2020-09-19T08:31:38.000Z
edu/cmu/lti/algorithm/math/MomentumVec.java
irokin/Path-Ranking-Algorithms
ed8daeebb039a78ea10872e1f7505d00fdd5fcff
[ "MIT" ]
23
2017-08-17T08:14:45.000Z
2021-11-11T09:17:52.000Z
22.80531
77
0.698875
8,576
package edu.cmu.lti.algorithm.math; import java.io.Serializable; import edu.cmu.lti.algorithm.Interfaces.IGetDblByStr; import edu.cmu.lti.algorithm.Interfaces.IMultiplyOn; import edu.cmu.lti.algorithm.Interfaces.IPlusObj; import edu.cmu.lti.algorithm.Interfaces.IPlusObjOn; import edu.cmu.lti.algorithm.Interfaces.ISetDblByStr; import edu.cmu.lti.algorithm.container.VectorD; public class MomentumVec implements Serializable, IGetDblByStr, ISetDblByStr, IMultiplyOn, IPlusObjOn, IPlusObj {//, IGetObjByString{ private static final long serialVersionUID = 2008042701L; // YYYYMMDD public VectorD variances = new VectorD(); //variance public VectorD means = new VectorD(); // mean public int num_samples = 0; // number of samples public VectorD std_devs = null; public void finish() { this.meanOn(); variances.minusOn(means.sqr()); std_devs = new VectorD(); for (double var : variances) std_devs.add(Momentum.getSD(var, num_samples)); } public void meanOn() { multiplyOn(1.0 / num_samples); } public void addInstance(VectorD vd) { num_samples++; means.plusOnE(vd); variances.plusOnE(vd.sqr()); } public MomentumVec() { } public MomentumVec(MomentumVec exp) { this.copy(exp); } public MomentumVec clone() { MomentumVec s = new MomentumVec(); s.plusOn(this); return s; } public void copy(MomentumVec x) { num_samples = x.num_samples; variances = x.variances; means = x.means; } public void clear() { num_samples = 0; variances.clear(); means.clear(); } public Double getDouble(String name) { //if (name.equals(CTag.g)) return g;//getG(); System.err.println("unknown variable " + name); return null; } public void setDouble(String name, Double d) { //if (name.equals(CTag.we)) we =d; System.err.println("unknown variable " + name); return; } public MomentumVec plusOn(MomentumVec x) { means.plusOn(x.means); variances.plusOn(x.variances); num_samples += x.num_samples; return this; } public MomentumVec plusObjOn(Object x) { return plusOn((MomentumVec) x); } public MomentumVec plusObj(Object x) { return (new MomentumVec(this)).plusOn((MomentumVec) x); } public MomentumVec multiplyOn(Double x) { //n*=x; variances.multiplyOn(x); means.multiplyOn(x); return this; } public static String getTitle() { return "n\tMean\tVariance\tSD"; //\te\teY } /* public String print() { return String.format("%d\t%.2f\t%.2f\t%.2f"//\t%.2f\t%.2f ,n,m,V,getSD() ); } public String toString() { return String.format("%d M)%.2f V)%.2f" ,n,m,V); }*/ }
3e144535be4bb46e1307411f44c0596e7ecd03f6
4,144
java
Java
app/src/main/java/com/example/simpletodo/MainActivity.java
giagia29/SimpleTodo
f2840b7f43d3509510f6744fee0fce1c31a220dc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/simpletodo/MainActivity.java
giagia29/SimpleTodo
f2840b7f43d3509510f6744fee0fce1c31a220dc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/simpletodo/MainActivity.java
giagia29/SimpleTodo
f2840b7f43d3509510f6744fee0fce1c31a220dc
[ "Apache-2.0" ]
null
null
null
34.823529
109
0.646959
8,577
package com.example.simpletodo; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { public static final String KEY_ITEM_TEXT = "item_text"; public static final String KEY_ITEM_POSITION = "item_position"; public static final int EDIT_TEXT_CODE = 20; List<String> items; Button btnAdd; EditText editem; RecyclerView rvitems; ItemsAdapter itemsAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnAdd = findViewById(R.id.btnAdd); editem = findViewById(R.id.editem); rvitems = findViewById(R.id.rvitems); loadItems(); ItemsAdapter.OnLongClickListener onLongClickListener = new ItemsAdapter.OnLongClickListener(){ @Override public void onItemLongClicked(int position) { items.remove(position); itemsAdapter.notifyItemRemoved(position); Toast.makeText(getApplicationContext(), "Item was removed", Toast.LENGTH_SHORT).show(); saveItems(); } }; ItemsAdapter.OnClickListener onClickListener = new ItemsAdapter.OnClickListener() { @Override public void onItemClicked(int position) { Log.d("MainActivity", "Single click at position" + position); Intent i = new Intent(MainActivity.this, EditActivity.class); i.putExtra(KEY_ITEM_TEXT, items.get(position)); i.putExtra(KEY_ITEM_POSITION, position); startActivityForResult(i, EDIT_TEXT_CODE); } }; itemsAdapter = new ItemsAdapter(items, onLongClickListener, onClickListener); rvitems.setAdapter(itemsAdapter); rvitems.setLayoutManager(new LinearLayoutManager(this)); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String todoItem = editem.getText().toString(); items.add(todoItem); itemsAdapter.notifyItemInserted(items.size() - 1); editem.setText(""); Toast.makeText(getApplicationContext(), "Item was added", Toast.LENGTH_SHORT).show(); saveItems(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (resultCode == RESULT_OK && requestCode == EDIT_TEXT_CODE) { String itemText = data.getStringExtra(KEY_ITEM_TEXT); int position = data.getExtras().getInt(KEY_ITEM_POSITION); items.set(position,itemText); itemsAdapter.notifyItemChanged(position); saveItems(); Toast.makeText(getApplicationContext(), "Items updated successfully", Toast.LENGTH_SHORT).show(); } } private File getDataFile(){ return new File(getFilesDir(), "data.txt"); } private void loadItems() { try { items = new ArrayList<>(FileUtils.readLines(getDataFile(), Charset.defaultCharset())); } catch (IOException e) { Log.e("MainActivity", "Error reading items", e); items = new ArrayList<>(); } } private void saveItems() { try { FileUtils.writeLines(getDataFile(), items); } catch (IOException e) { Log.e("MainActivity", "Error reading items", e); } } }
3e1445d43dbc19bf3445ef00374539d06eeff5f2
5,398
java
Java
backend/src/main/java/com/dursuneryilmaz/duscrumtool/domain/Product.java
dursuneryilmaz/Project-Management-Tool
b8801e99b5c867da8c92431089987054e05795b7
[ "MIT" ]
null
null
null
backend/src/main/java/com/dursuneryilmaz/duscrumtool/domain/Product.java
dursuneryilmaz/Project-Management-Tool
b8801e99b5c867da8c92431089987054e05795b7
[ "MIT" ]
1
2020-12-19T13:30:04.000Z
2020-12-19T13:30:04.000Z
backend/src/main/java/com/dursuneryilmaz/duscrumtool/domain/Product.java
dursuneryilmaz/Project-Management-Tool
b8801e99b5c867da8c92431089987054e05795b7
[ "MIT" ]
1
2020-12-19T01:01:31.000Z
2020-12-19T01:01:31.000Z
26.077295
87
0.654502
8,578
package com.dursuneryilmaz.duscrumtool.domain; import com.fasterxml.jackson.annotation.JsonFormat; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; @Entity @Table(name = "products") public class Product implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true, nullable = false) @Size(min = 32, max = 32) private String productId; @NotBlank(message = "Product name cannot be blank!") private String projectName; @NotBlank(message = "Product description cannot be blank!") private String description; @NotNull(message = "Product cost can not be null!") private Double cost; @JsonFormat(pattern = "yyyy-MM-dd@HH:mm") private Date createDate; @JsonFormat(pattern = "yyyy-MM-dd@HH:mm") private Date startDate; @JsonFormat(pattern = "yyyy-MM-dd@HH:mm") private Date endDate; @JsonFormat(pattern = "yyyy-MM-dd@HH:mm") private Date updateDate; @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List<Theme> themeList = new ArrayList<>(); @OneToOne(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private ProductBacklog productBacklog; @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable( name = "products_stake_holders", joinColumns = @JoinColumn(name = "product_id"), inverseJoinColumns = @JoinColumn(name = "user_id") ) private List<User> stakeHolderList = new ArrayList<>(); @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable( name = "products_managers", joinColumns = @JoinColumn(name = "product_id"), inverseJoinColumns = @JoinColumn(name = "user_id") ) private List<User> scrumManagerList = new ArrayList<>(); @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable( name = "products_devs", joinColumns = @JoinColumn(name = "product_id"), inverseJoinColumns = @JoinColumn(name = "user_id") ) private List<User> productDeveloperList = new ArrayList<>(); @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List<Sprint> sprintList = new ArrayList<>(); public Product() { } @PrePersist protected void onCreate() { this.createDate = new Date(); } @PreUpdate protected void onUpdate() { this.updateDate = new Date(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Double getCost() { return cost; } public void setCost(Double cost) { this.cost = cost; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updatedAt) { this.updateDate = updatedAt; } public List<Theme> getThemeList() { return themeList; } public void setThemeList(List<Theme> themeList) { this.themeList = themeList; } public ProductBacklog getProductBacklog() { return productBacklog; } public void setProductBacklog(ProductBacklog productBacklog) { this.productBacklog = productBacklog; } public List<User> getStakeHolderList() { return stakeHolderList; } public void setStakeHolderList(List<User> stakeHolderList) { this.stakeHolderList = stakeHolderList; } public List<User> getScrumManagerList() { return scrumManagerList; } public void setScrumManagerList(List<User> scrumManagerList) { this.scrumManagerList = scrumManagerList; } public List<Sprint> getSprintList() { return sprintList; } public void setSprintList(List<Sprint> sprintList) { this.sprintList = sprintList; } public List<User> getProductDeveloperList() { return productDeveloperList; } public void setProductDeveloperList(List<User> productDevList) { this.productDeveloperList = productDevList; } }
3e1445f793d1d952e9cd3f9e4d45e41dc67019bb
29,264
java
Java
rt-desktop/src/main/java/xyz/redtorch/desktop/layout/base/PositionLayout.java
dingzhenguo/redtorch
e46bca5e232b9eae16826df1f85fa5848f9de3c7
[ "MIT" ]
null
null
null
rt-desktop/src/main/java/xyz/redtorch/desktop/layout/base/PositionLayout.java
dingzhenguo/redtorch
e46bca5e232b9eae16826df1f85fa5848f9de3c7
[ "MIT" ]
null
null
null
rt-desktop/src/main/java/xyz/redtorch/desktop/layout/base/PositionLayout.java
dingzhenguo/redtorch
e46bca5e232b9eae16826df1f85fa5848f9de3c7
[ "MIT" ]
null
null
null
36.39801
108
0.700075
8,579
package xyz.redtorch.desktop.layout.base; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.SortedList; import javafx.scene.Node; import javafx.scene.control.CheckBox; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.input.MouseButton; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import xyz.redtorch.common.util.CommonUtils; import xyz.redtorch.desktop.service.DesktopTradeCachesService; import xyz.redtorch.desktop.service.GuiMainService; import xyz.redtorch.pb.CoreEnum.HedgeFlagEnum; import xyz.redtorch.pb.CoreEnum.PositionDirectionEnum; import xyz.redtorch.pb.CoreField.AccountField; import xyz.redtorch.pb.CoreField.ContractField; import xyz.redtorch.pb.CoreField.PositionField; @Component public class PositionLayout { private static final Logger logger = LoggerFactory.getLogger(PositionLayout.class); private VBox vBox = new VBox(); private boolean layoutCreated = false; private ObservableList<PositionField> positionObservableList = FXCollections.observableArrayList(); private List<PositionField> positionList = new ArrayList<>(); private TableView<PositionField> positionTableView = new TableView<>(); private boolean showMergedPosition = false; private boolean showEmptyPosition = false; private Set<String> selectedPositionIdSet = new HashSet<>(); @Autowired private DesktopTradeCachesService desktopTradeCachesService; @Autowired private GuiMainService guiMainService; public Node getNode() { if (!layoutCreated) { createLayout(); layoutCreated = true; } return this.vBox; } public void updateData(List<PositionField> positionList) { if (!new HashSet<>(this.positionList).equals(new HashSet<>(positionList))) { this.positionList = positionList; fillingData(); } } public void fillingData() { List<PositionField> newPositionList = new ArrayList<>(); for (PositionField position : positionList) { if (guiMainService.getSelectedAccountIdSet().isEmpty() || guiMainService.getSelectedAccountIdSet().contains(position.getAccountId())) { if (!showEmptyPosition) { if (position.getPosition() != 0) { newPositionList.add(position); } } else { newPositionList.add(position); } } } if (!showMergedPosition) { positionObservableList.clear(); positionObservableList.addAll(newPositionList); } else { Map<String, PositionField.Builder> mergedPositionFieldBuilderMap = new HashMap<>(); for (PositionField position : newPositionList) { if (!(guiMainService.getSelectedAccountIdSet().isEmpty() || guiMainService.getSelectedAccountIdSet().contains(position.getAccountId()))) { continue; } String key = position.getContract().getUnifiedSymbol() + "#" + position.getPositionDirectionValue(); PositionField.Builder positionFieldBuilder; if (mergedPositionFieldBuilderMap.containsKey(key)) { positionFieldBuilder = mergedPositionFieldBuilderMap.get(key); int positionInt = positionFieldBuilder.getPosition() + position.getPosition(); if (positionInt != 0) { double openPrice = (positionFieldBuilder.getOpenPrice() * positionFieldBuilder.getPosition() + position.getOpenPrice() * position.getPosition()) / positionInt; positionFieldBuilder.setOpenPrice(openPrice); double price = (positionFieldBuilder.getPrice() * positionFieldBuilder.getPosition() + position.getPrice() * position.getPosition()) / positionInt; positionFieldBuilder.setPrice(price); } positionFieldBuilder.setPrice(position.getPrice()); positionFieldBuilder.setPosition(positionInt); positionFieldBuilder.setFrozen(positionFieldBuilder.getFrozen() + position.getFrozen()); positionFieldBuilder.setTdPosition(positionFieldBuilder.getTdPosition() + position.getTdPosition()); positionFieldBuilder.setTdFrozen(positionFieldBuilder.getTdFrozen() + position.getTdFrozen()); positionFieldBuilder.setYdPosition(positionFieldBuilder.getYdPosition() + position.getYdPosition()); positionFieldBuilder.setYdFrozen(positionFieldBuilder.getYdFrozen() + position.getYdFrozen()); positionFieldBuilder .setContractValue(positionFieldBuilder.getContractValue() + position.getContractValue()); positionFieldBuilder .setExchangeMargin(positionFieldBuilder.getExchangeMargin() + position.getExchangeMargin()); positionFieldBuilder.setUseMargin(positionFieldBuilder.getUseMargin() + position.getUseMargin()); positionFieldBuilder.setOpenPositionProfit( positionFieldBuilder.getOpenPositionProfit() + position.getOpenPositionProfit()); positionFieldBuilder .setPositionProfit(positionFieldBuilder.getPositionProfit() + position.getPositionProfit()); } else { positionFieldBuilder = PositionField.newBuilder(); positionFieldBuilder.setContract(position.getContract()); positionFieldBuilder.setPositionDirection(position.getPositionDirection()); positionFieldBuilder.setPosition(position.getPosition()); positionFieldBuilder.setFrozen(position.getFrozen()); positionFieldBuilder.setTdPosition(position.getTdPosition()); positionFieldBuilder.setTdFrozen(position.getTdFrozen()); positionFieldBuilder.setYdPosition(position.getYdPosition()); positionFieldBuilder.setYdFrozen(position.getYdFrozen()); positionFieldBuilder.setContractValue(position.getContractValue()); positionFieldBuilder.setExchangeMargin(position.getExchangeMargin()); positionFieldBuilder.setUseMargin(position.getUseMargin()); positionFieldBuilder.setOpenPositionProfit(position.getOpenPositionProfit()); positionFieldBuilder.setPositionProfit(position.getPositionProfit()); positionFieldBuilder.setOpenPrice(position.getOpenPrice()); positionFieldBuilder.setPrice(position.getPrice()); positionFieldBuilder.setPositionId(key); mergedPositionFieldBuilderMap.put(key, positionFieldBuilder); } } List<PositionField> mergedPositionFieldList = new ArrayList<>(); for (PositionField.Builder positionFieldBuilder : mergedPositionFieldBuilderMap.values()) { if (positionFieldBuilder.getUseMargin() != 0) { positionFieldBuilder.setOpenPositionProfitRatio( positionFieldBuilder.getOpenPositionProfit() / positionFieldBuilder.getUseMargin()); positionFieldBuilder.setPositionProfitRatio( positionFieldBuilder.getPositionProfit() / positionFieldBuilder.getUseMargin()); } mergedPositionFieldList.add(positionFieldBuilder.build()); } positionObservableList.clear(); positionObservableList.addAll(mergedPositionFieldList); } Set<String> newSelectedPositionIdSet = new HashSet<>(); for (PositionField position : positionObservableList) { if (selectedPositionIdSet.contains(position.getPositionId())) { positionTableView.getSelectionModel().select(position); newSelectedPositionIdSet.add(position.getPositionId()); } } selectedPositionIdSet = newSelectedPositionIdSet; } private void createLayout() { positionTableView.setTableMenuButtonVisible(true); TableColumn<PositionField, Pane> unifiedSymbolCol = new TableColumn<>("合约"); unifiedSymbolCol.setPrefWidth(160); unifiedSymbolCol.setCellValueFactory(feature -> { VBox vBox = new VBox(); try { PositionField position = feature.getValue(); Text unifiedSymbolText = new Text(position.getContract().getUnifiedSymbol()); Text shortNameText = new Text(position.getContract().getName()); vBox.getChildren().add(unifiedSymbolText); vBox.getChildren().add(shortNameText); if (guiMainService.getSelectedContract() != null && guiMainService.getSelectedContract() .getUnifiedSymbol().equals(position.getContract().getUnifiedSymbol())) { unifiedSymbolText.getStyleClass().add("trade-remind-color"); } vBox.setUserData(position); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleObjectProperty<>(vBox); }); unifiedSymbolCol.setComparator((Pane p1, Pane p2) -> { try { PositionField position1 = (PositionField) p1.getUserData(); PositionField position2 = (PositionField) p2.getUserData(); return StringUtils.compare(position1.getContract().getUnifiedSymbol(), position2.getContract().getUnifiedSymbol()); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(unifiedSymbolCol); TableColumn<PositionField, Text> directionCol = new TableColumn<>("方向"); directionCol.setPrefWidth(40); directionCol.setCellValueFactory(feature -> { Text directionText = new Text("未知"); try { PositionField position = feature.getValue(); if (position.getPositionDirection() == PositionDirectionEnum.PD_Long) { directionText.setText("多"); directionText.getStyleClass().add("trade-long-color"); } else if (position.getPositionDirection() == PositionDirectionEnum.PD_Short) { directionText.setText("空"); directionText.getStyleClass().add("trade-short-color"); } else if (position.getPositionDirection() == PositionDirectionEnum.PD_Net) { directionText.setText("净"); } else if (position.getPositionDirection() == PositionDirectionEnum.PD_Unknown) { directionText.setText("未知"); } else { directionText.setText(position.getPositionDirection().getValueDescriptor().getName()); } directionText.setUserData(position); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleObjectProperty<>(directionText); }); directionCol.setComparator((Text t1, Text t2) -> { try { PositionField position1 = (PositionField) t1.getUserData(); PositionField position2 = (PositionField) t2.getUserData(); return Integer.compare(position1.getPositionDirection().getNumber(), position2.getPositionDirection().getNumber()); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(directionCol); TableColumn<PositionField, String> hedgeFlagCol = new TableColumn<>("投机套保"); hedgeFlagCol.setPrefWidth(60); hedgeFlagCol.setCellValueFactory(feature -> { String hedgeFlag = "未知"; try { PositionField position = feature.getValue(); if (position.getHedgeFlag() == HedgeFlagEnum.HF_Speculation) { hedgeFlag = "投机"; } else if (position.getHedgeFlag() == HedgeFlagEnum.HF_Hedge) { hedgeFlag = "套保"; } else if (position.getHedgeFlag() == HedgeFlagEnum.HF_Arbitrage) { hedgeFlag = "套利"; } else if (position.getHedgeFlag() == HedgeFlagEnum.HF_MarketMaker) { hedgeFlag = "做市商"; } else if (position.getHedgeFlag() == HedgeFlagEnum.HF_SpecHedge) { hedgeFlag = "第一条腿投机第二条腿套保 大商所专用"; } else if (position.getHedgeFlag() == HedgeFlagEnum.HF_HedgeSpec) { hedgeFlag = "第一条腿套保第二条腿投机 大商所专用"; } else if (position.getHedgeFlag() == HedgeFlagEnum.HF_Unknown) { hedgeFlag = "未知"; } else { hedgeFlag = position.getHedgeFlag().getValueDescriptor().getName(); } } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleStringProperty(hedgeFlag); }); hedgeFlagCol.setComparator((String s1, String s2) -> StringUtils.compare(s1, s2)); positionTableView.getColumns().add(hedgeFlagCol); TableColumn<PositionField, Pane> positionCol = new TableColumn<>("持仓"); positionCol.setPrefWidth(90); positionCol.setCellValueFactory(feature -> { VBox vBox = new VBox(); try { HBox positionHBox = new HBox(); Text positionLabelText = new Text("持仓"); positionLabelText.setWrappingWidth(35); positionHBox.getChildren().add(positionLabelText); PositionField position = feature.getValue(); Text positionText = new Text("" + position.getPosition()); if (position.getPositionDirection() == PositionDirectionEnum.PD_Long) { positionText.getStyleClass().add("trade-long-color"); } else if (position.getPositionDirection() == PositionDirectionEnum.PD_Short) { positionText.getStyleClass().add("trade-short-color"); } positionHBox.getChildren().add(positionText); vBox.getChildren().add(positionHBox); HBox frozenHBox = new HBox(); Text frozenLabelText = new Text("冻结"); frozenLabelText.setWrappingWidth(35); frozenHBox.getChildren().add(frozenLabelText); Text frozenText = new Text("" + position.getFrozen()); if (position.getFrozen() != 0) { frozenText.getStyleClass().add("trade-info-color"); } frozenHBox.getChildren().add(frozenText); vBox.getChildren().add(frozenHBox); vBox.setUserData(position); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleObjectProperty<>(vBox); }); positionCol.setComparator((Pane p1, Pane p2) -> { try { PositionField position1 = (PositionField) p1.getUserData(); PositionField position2 = (PositionField) p2.getUserData(); return Integer.compare(position1.getPosition(), position2.getPosition()); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(positionCol); TableColumn<PositionField, Pane> tdPositionCol = new TableColumn<>("今仓"); tdPositionCol.setPrefWidth(90); tdPositionCol.setCellValueFactory(feature -> { VBox vBox = new VBox(); try { HBox tdPositionHBox = new HBox(); Text tdPositionLabelText = new Text("持仓"); tdPositionLabelText.setWrappingWidth(35); tdPositionHBox.getChildren().add(tdPositionLabelText); PositionField position = feature.getValue(); Text tdPositionText = new Text("" + position.getTdPosition()); if (position.getPositionDirection() == PositionDirectionEnum.PD_Long) { tdPositionText.getStyleClass().add("trade-long-color"); } else if (position.getPositionDirection() == PositionDirectionEnum.PD_Short) { tdPositionText.getStyleClass().add("trade-short-color"); } tdPositionHBox.getChildren().add(tdPositionText); vBox.getChildren().add(tdPositionHBox); HBox frozenHBox = new HBox(); Text frozenLabelText = new Text("冻结"); frozenLabelText.setWrappingWidth(35); frozenHBox.getChildren().add(frozenLabelText); Text frozenText = new Text("" + position.getTdFrozen()); if (position.getTdFrozen() != 0) { frozenText.getStyleClass().add("trade-info-color"); } frozenHBox.getChildren().add(frozenText); vBox.getChildren().add(frozenHBox); vBox.setUserData(position); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleObjectProperty<>(vBox); }); tdPositionCol.setComparator((Pane p1, Pane p2) -> { try { PositionField position1 = (PositionField) p1.getUserData(); PositionField position2 = (PositionField) p2.getUserData(); return Integer.compare(position1.getPosition(), position2.getPosition()); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(tdPositionCol); TableColumn<PositionField, Pane> openPositionProfitCol = new TableColumn<>("逐笔浮盈"); openPositionProfitCol.setPrefWidth(90); openPositionProfitCol.setCellValueFactory(feature -> { VBox vBox = new VBox(); try { PositionField position = feature.getValue(); Text openPositionProfitText = new Text(String.format("%,.2f", position.getOpenPositionProfit())); Text openPositionProfitRatioText = new Text( String.format("%.2f%%", position.getOpenPositionProfitRatio() * 100)); if (position.getOpenPositionProfit() > 0) { openPositionProfitText.getStyleClass().add("trade-long-color"); openPositionProfitRatioText.getStyleClass().add("trade-long-color"); } else if (position.getOpenPositionProfit() < 0) { openPositionProfitText.getStyleClass().add("trade-short-color"); openPositionProfitRatioText.getStyleClass().add("trade-short-color"); } vBox.getChildren().addAll(openPositionProfitText, openPositionProfitRatioText); vBox.setUserData(position); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleObjectProperty<>(vBox); }); openPositionProfitCol.setComparator((Pane p1, Pane p2) -> { try { PositionField position1 = (PositionField) p1.getUserData(); PositionField position2 = (PositionField) p2.getUserData(); return Double.compare(position1.getOpenPositionProfit(), position2.getOpenPositionProfit()); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(openPositionProfitCol); TableColumn<PositionField, Pane> positionProfitCol = new TableColumn<>("盯市浮盈"); positionProfitCol.setPrefWidth(90); positionProfitCol.setCellValueFactory(feature -> { VBox vBox = new VBox(); try { PositionField position = feature.getValue(); Text positionProfitText = new Text(String.format("%,.2f", position.getPositionProfit())); Text positionProfitRatioText = new Text( String.format("%.2f%%", position.getPositionProfitRatio() * 100)); if (position.getPositionProfit() > 0) { positionProfitText.getStyleClass().add("trade-long-color"); positionProfitRatioText.getStyleClass().add("trade-long-color"); } else if (position.getPositionProfit() < 0) { positionProfitText.getStyleClass().add("trade-short-color"); positionProfitRatioText.getStyleClass().add("trade-short-color"); } vBox.getChildren().addAll(positionProfitText, positionProfitRatioText); vBox.setUserData(position); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleObjectProperty<>(vBox); }); positionProfitCol.setComparator((Pane p1, Pane p2) -> { try { PositionField position1 = (PositionField) p1.getUserData(); PositionField position2 = (PositionField) p2.getUserData(); return Double.compare(position1.getPositionProfit(), position2.getPositionProfit()); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(positionProfitCol); TableColumn<PositionField, Pane> openPriceCol = new TableColumn<>("开仓价格"); openPriceCol.setPrefWidth(90); openPriceCol.setCellValueFactory(feature -> { VBox vBox = new VBox(); try { PositionField position = feature.getValue(); ContractField contract = position.getContract(); int dcimalDigits = CommonUtils.getNumberDecimalDigits(contract.getPriceTick()); if (dcimalDigits < 0) { dcimalDigits = 0; } String priceStringFormat = "%,." + dcimalDigits + "f"; Text openPriceText = new Text(String.format(priceStringFormat, position.getOpenPrice())); vBox.getChildren().add(openPriceText); Text openPriceDiffText = new Text(String.format(priceStringFormat, position.getOpenPriceDiff())); if (position.getOpenPriceDiff() > 0) { openPriceDiffText.getStyleClass().add("trade-long-color"); } else if (position.getOpenPriceDiff() < 0) { openPriceDiffText.getStyleClass().add("trade-short-color"); } vBox.getChildren().add(openPriceDiffText); vBox.setUserData(position); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleObjectProperty<>(vBox); }); openPriceCol.setComparator((Pane p1, Pane p2) -> { try { PositionField position1 = (PositionField) p1.getUserData(); PositionField position2 = (PositionField) p2.getUserData(); return Double.compare(position1.getOpenPrice(), position2.getOpenPrice()); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(openPriceCol); TableColumn<PositionField, Pane> priceCol = new TableColumn<>("持仓价格"); priceCol.setPrefWidth(90); priceCol.setCellValueFactory(feature -> { VBox vBox = new VBox(); try { PositionField position = feature.getValue(); ContractField contract = position.getContract(); int dcimalDigits = CommonUtils.getNumberDecimalDigits(contract.getPriceTick()); if (dcimalDigits < 0) { dcimalDigits = 0; } String priceStringFormat = "%,." + dcimalDigits + "f"; Text priceText = new Text(String.format(priceStringFormat, position.getPrice())); vBox.getChildren().add(priceText); Text priceDiffText = new Text(String.format(priceStringFormat, position.getPriceDiff())); if (position.getPriceDiff() > 0) { priceDiffText.getStyleClass().add("trade-long-color"); } else if (position.getPriceDiff() < 0) { priceDiffText.getStyleClass().add("trade-short-color"); } vBox.getChildren().add(priceDiffText); vBox.setUserData(position); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleObjectProperty<>(vBox); }); priceCol.setComparator((Pane p1, Pane p2) -> { try { PositionField position1 = (PositionField) p1.getUserData(); PositionField position2 = (PositionField) p2.getUserData(); return Double.compare(position1.getPrice(), position2.getPrice()); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(priceCol); TableColumn<PositionField, Pane> marginCol = new TableColumn<>("保证金"); marginCol.setPrefWidth(130); marginCol.setCellValueFactory(feature -> { VBox vBox = new VBox(); try { HBox useMarginHBox = new HBox(); Text useMarginLabelText = new Text("经纪商"); useMarginLabelText.setWrappingWidth(45); useMarginHBox.getChildren().add(useMarginLabelText); PositionField position = feature.getValue(); Text useMarginText = new Text(String.format("%,.2f", position.getUseMargin())); useMarginHBox.getChildren().add(useMarginText); vBox.getChildren().add(useMarginHBox); HBox exchangeMarginHBox = new HBox(); Text exchangeMarginLabelText = new Text("交易所"); exchangeMarginLabelText.setWrappingWidth(45); exchangeMarginHBox.getChildren().add(exchangeMarginLabelText); Text exchangeMarginText = new Text(String.format("%,.2f", position.getExchangeMargin())); exchangeMarginHBox.getChildren().add(exchangeMarginText); vBox.getChildren().add(exchangeMarginHBox); vBox.setUserData(position); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleObjectProperty<>(vBox); }); marginCol.setComparator((Pane p1, Pane p2) -> { try { PositionField position1 = (PositionField) p1.getUserData(); PositionField position2 = (PositionField) p2.getUserData(); return Double.compare(position1.getUseMargin(), position2.getUseMargin()); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(marginCol); TableColumn<PositionField, String> marginRatioCol = new TableColumn<>("保证金占比"); marginRatioCol.setPrefWidth(70); marginRatioCol.setCellValueFactory(feature -> { String marginRatioStr = ""; try { PositionField position = feature.getValue(); if (showMergedPosition) { double allBalance = 0.; Set<String> selectedAccountIdSet = guiMainService.getSelectedAccountIdSet(); List<AccountField> accountList = desktopTradeCachesService.getAccountList(); if (accountList == null || accountList.isEmpty()) { marginRatioStr = "NA"; } else { for (AccountField account : accountList) { if (selectedAccountIdSet.contains(account.getAccountId()) || selectedAccountIdSet.isEmpty()) { allBalance += account.getBalance(); } } if (allBalance == 0) { marginRatioStr = "NA"; } else { double marginRatio = position.getUseMargin() / allBalance * 100; marginRatioStr = String.format("%,.2f", marginRatio) + "%"; } } } else { AccountField account = desktopTradeCachesService.queryAccountByAccountId(position.getAccountId()); if (account == null) { marginRatioStr = "NA"; } else if (account.getBalance() == 0) { marginRatioStr = "NA"; } else { double marginRatio = position.getUseMargin() / account.getBalance() * 100; marginRatioStr = String.format("%,.2f", marginRatio) + "%"; } } } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleStringProperty(marginRatioStr); }); marginRatioCol.setComparator((String s1, String s2) -> { try { return Double.valueOf(s1.replace(",", "")).compareTo(Double.valueOf(s2.replace(",", ""))); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(marginRatioCol); TableColumn<PositionField, String> contractValueCol = new TableColumn<>("合约价值"); contractValueCol.setPrefWidth(90); contractValueCol.setCellValueFactory(feature -> { String contractValue = ""; try { contractValue = String.format("%,.0f", feature.getValue().getContractValue()); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleStringProperty(contractValue); }); contractValueCol.setComparator((String s1, String s2) -> { try { return Double.valueOf(s1.replace(",", "")).compareTo(Double.valueOf(s2.replace(",", ""))); } catch (Exception e) { logger.error("排序错误", e); } return 0; }); positionTableView.getColumns().add(contractValueCol); TableColumn<PositionField, String> accountIdCol = new TableColumn<>("账户ID"); accountIdCol.setPrefWidth(350); accountIdCol.setCellValueFactory(feature -> { String accountId = ""; try { accountId = feature.getValue().getAccountId(); } catch (Exception e) { logger.error("渲染错误", e); } return new SimpleStringProperty(accountId); }); accountIdCol.setComparator((String s1, String s2) -> StringUtils.compare(s1, s2)); positionTableView.getColumns().add(accountIdCol); SortedList<PositionField> sortedItems = new SortedList<>(positionObservableList); positionTableView.setItems(sortedItems); sortedItems.comparatorProperty().bind(positionTableView.comparatorProperty()); positionTableView.setFocusTraversable(false); positionTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); positionTableView.setRowFactory(tv -> { TableRow<PositionField> row = new TableRow<>(); row.setOnMousePressed(event -> { if (!row.isEmpty() && event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 1) { ObservableList<PositionField> selectedItems = positionTableView.getSelectionModel() .getSelectedItems(); selectedPositionIdSet.clear(); for (PositionField position : selectedItems) { selectedPositionIdSet.add(position.getPositionId()); } PositionField clickedItem = row.getItem(); guiMainService.updateSelectedContarct(clickedItem.getContract()); } }); return row; }); vBox.getChildren().add(positionTableView); VBox.setVgrow(positionTableView, Priority.ALWAYS); HBox hBox = new HBox(); CheckBox showMergedCheckBox = new CheckBox("合并持仓"); showMergedCheckBox.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { showMergedPosition = newValue; fillingData(); } }); hBox.getChildren().add(showMergedCheckBox); CheckBox showEmptyCheckBox = new CheckBox("显示空仓"); showEmptyCheckBox.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { showEmptyPosition = newValue; fillingData(); } }); hBox.getChildren().add(showEmptyCheckBox); vBox.getChildren().add(hBox); } }
3e14464e194e5827d7cb57d426f074720e6a2c52
728
java
Java
src/main/java/com/github/rafasantos/error/ErrorReport.java
rafasantos/difffilter
98230f3b1f4f5ae63737cae384cda0efdbfcdccc
[ "MIT" ]
null
null
null
src/main/java/com/github/rafasantos/error/ErrorReport.java
rafasantos/difffilter
98230f3b1f4f5ae63737cae384cda0efdbfcdccc
[ "MIT" ]
2
2017-11-20T15:53:30.000Z
2020-03-05T02:21:21.000Z
src/main/java/com/github/rafasantos/error/ErrorReport.java
rafasantos/difffilter
98230f3b1f4f5ae63737cae384cda0efdbfcdccc
[ "MIT" ]
1
2017-06-30T16:07:58.000Z
2017-06-30T16:07:58.000Z
25.103448
89
0.715659
8,580
package com.github.rafasantos.error; import java.util.ArrayList; import java.util.List; public class ErrorReport { private static List<String> errors = new ArrayList<>(); /** * Add an error to the report * @param errorMessage The java exception message or equivalent * @param lineNumber The line number where the error happened * @param originalLine The original line which caused the error */ public static void addError(String errorMessage, Long lineNumber, String originalLine) { String error = "\nError message: " + errorMessage + "\nLine number: " + lineNumber + "\nOriginal line: " + originalLine; errors.add(error); } public static List<String> getErrors() { return errors; } }
3e144679c31625c6120136661c8ac920aec22c12
7,133
java
Java
JSP/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/JSP1/org/apache/jsp/noida_jsp.java
avinashxr10/Java-Codes
c44a6fe469a9ec68dc207c534f66d0d0147374f1
[ "Unlicense" ]
null
null
null
JSP/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/JSP1/org/apache/jsp/noida_jsp.java
avinashxr10/Java-Codes
c44a6fe469a9ec68dc207c534f66d0d0147374f1
[ "Unlicense" ]
null
null
null
JSP/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/JSP1/org/apache/jsp/noida_jsp.java
avinashxr10/Java-Codes
c44a6fe469a9ec68dc207c534f66d0d0147374f1
[ "Unlicense" ]
null
null
null
45.433121
330
0.622599
8,581
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/9.0.56 * Generated at: 2021-12-29 15:13:07 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class noida_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent, org.apache.jasper.runtime.JspSourceImports { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static final java.util.Set<java.lang.String> _jspx_imports_packages; private static final java.util.Set<java.lang.String> _jspx_imports_classes; private static java.util.Map<java.lang.String, java.lang.Long> _jspx_dependants; static { _jspx_imports_packages = new java.util.HashSet<>(); _jspx_imports_packages.add("javax.servlet"); _jspx_imports_packages.add("javax.servlet.http"); _jspx_imports_packages.add("javax.servlet.jsp"); _jspx_imports_classes = null; } private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String, java.lang.Long> getDependants() { return _jspx_dependants; } public java.util.Set<java.lang.String> getPackageImports() { return _jspx_imports_packages; } public java.util.Set<java.lang.String> getClassImports() { return _jspx_imports_classes; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { if (!javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) { final java.lang.String _jspx_method = request.getMethod(); if ("OPTIONS".equals(_jspx_method)) { response.setHeader("Allow", "GET, HEAD, POST, OPTIONS"); return; } if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method)) { response.setHeader("Allow", "GET, HEAD, POST, OPTIONS"); response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET, POST or HEAD. Jasper also permits OPTIONS"); return; } } final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=ISO-8859-1"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("<!DOCTYPE html>\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<meta charset=\"ISO-8859-1\">\r\n"); out.write("<title>Noida.jsp</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write(" "); org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "header.jsp" + "?" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("cname", request.getCharacterEncoding()) + "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("Java Training Center", request.getCharacterEncoding()), out, false); out.write("\r\n"); out.write(" This is noida.jsp Home Page\r\n"); out.write(" <br>Which shows "); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${param.bn }", java.lang.String.class, (javax.servlet.jsp.PageContext) _jspx_page_context, null)); out.write(" branch detail Contacts\r\n"); out.write(" email:"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${param.email }", java.lang.String.class, (javax.servlet.jsp.PageContext) _jspx_page_context, null)); out.write("\r\n"); out.write("\r\n"); out.write(" "); org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "footer.jsp" + "?" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("cname", request.getCharacterEncoding()) + "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("Java Training Center", request.getCharacterEncoding()), out, false); out.write("\r\n"); out.write("</body>\r\n"); out.write("</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) { } if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
3e14468b18eea1c3606456034274da7fc90298aa
1,492
java
Java
backend/src/main/java/com/smallB/QOS/productCategory/service/ProductCategoryServiceImpl.java
QR-OS/Q-tect-order-system
cfe0d16df998accab3f570ac971329bebc10ed81
[ "MIT" ]
12
2020-11-28T09:23:51.000Z
2021-04-18T07:10:28.000Z
backend/src/main/java/com/smallB/QOS/productCategory/service/ProductCategoryServiceImpl.java
QR-OS/Q-tect-order-system
cfe0d16df998accab3f570ac971329bebc10ed81
[ "MIT" ]
4
2021-09-14T05:28:39.000Z
2022-02-27T10:53:10.000Z
backend/src/main/java/com/smallB/QOS/productCategory/service/ProductCategoryServiceImpl.java
QR-OS/Q-tect-order-system
cfe0d16df998accab3f570ac971329bebc10ed81
[ "MIT" ]
3
2020-12-12T10:35:50.000Z
2020-12-12T15:08:59.000Z
34.697674
112
0.77681
8,582
package com.smallB.QOS.productCategory.service; import com.smallB.QOS.product.domain.ProductDto; import com.smallB.QOS.productCategory.dao.ProductCategoryDao; import com.smallB.QOS.productCategory.domain.ProductCategoryDto; import com.smallB.QOS.productCategory.error.ProductCategoryDuplicatedException; import com.smallB.QOS.productCategory.error.ProductCategoryNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import static java.util.Objects.isNull; @Service public class ProductCategoryServiceImpl implements ProductCategoryService { @Autowired private ProductCategoryDao productCategoryDao; @Override public List<ProductCategoryDto> getProducts(String store_id) throws Exception{ List<ProductCategoryDto> productCategoryDto = productCategoryDao.findProductCategoryByStoreId(store_id); if(isNull(productCategoryDto)){ throw new ProductCategoryNotFoundException(); } return productCategoryDto; } @Override public Boolean CreateProduct(ProductCategoryDto productCategoryDto) throws Exception{ ProductCategoryDto exist = productCategoryDao.findProductCategory(productCategoryDto); if(isNull(exist)){ productCategoryDao.CreateProductCategory(productCategoryDto); return true; }else{ throw new ProductCategoryDuplicatedException(); } } }
3e1446dbc171dd37493e89d45bba0a09345d3620
3,597
java
Java
src/main/java/org/bitsofinfo/s3/toc/S3KeyCopyingTOCPayloadHandler.java
bitsofinfo/s3-bucket-loader
68f876198084665b74a744a37875a4be00c397e1
[ "Apache-2.0" ]
40
2015-01-04T03:14:44.000Z
2022-01-27T21:41:03.000Z
src/main/java/org/bitsofinfo/s3/toc/S3KeyCopyingTOCPayloadHandler.java
bitsofinfo/s3-bucket-loader
68f876198084665b74a744a37875a4be00c397e1
[ "Apache-2.0" ]
1
2016-01-28T20:15:38.000Z
2017-05-19T15:45:54.000Z
src/main/java/org/bitsofinfo/s3/toc/S3KeyCopyingTOCPayloadHandler.java
bitsofinfo/s3-bucket-loader
68f876198084665b74a744a37875a4be00c397e1
[ "Apache-2.0" ]
8
2015-12-22T08:39:42.000Z
2021-03-03T20:44:54.000Z
30.483051
109
0.75563
8,583
package org.bitsofinfo.s3.toc; import org.apache.log4j.Logger; import org.bitsofinfo.s3.cmd.TocPathOpResult; import org.bitsofinfo.s3.worker.WorkerState; import com.amazonaws.event.ProgressEvent; import com.amazonaws.event.ProgressListener; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.CopyObjectRequest; import com.amazonaws.services.s3.model.CopyObjectResult; import com.amazonaws.services.s3.model.StorageClass; public class S3KeyCopyingTOCPayloadHandler implements ProgressListener, TOCPayloadHandler { private static final Logger logger = Logger.getLogger(S3KeyCopyingTOCPayloadHandler.class); private String sourceS3BucketName = null; private String targetS3BucketName = null; private StorageClass storageClass = null; private boolean enableServerSideEncryption = false; private AmazonS3Client s3Client = null; @Override public void destroy() { // nothing to do } @Override public void progressChanged(ProgressEvent progressEvent) { logger.debug("progressChanged() " +progressEvent.getEventType() + " bytes:" + progressEvent.getBytes() + " bytesTransferred: " + progressEvent.getBytesTransferred()); } @Override public void handlePayload(TOCPayload payload) throws Exception { throw new UnsupportedOperationException("S3KeyCopyingTOCPayloadHandler does not " + "support this method variant, call me through Worker"); } @Override public void handlePayload(TOCPayload payload, WorkerState workerState) throws Exception { TocInfo tocInfo = payload.tocInfo; String logPrefix = "handlePayload() KeyCopy s3://" + this.sourceS3BucketName + "/" + tocInfo.path + " => s3://" + this.targetS3BucketName +"/"+ tocInfo.path; try { CopyObjectRequest copyRequest = new CopyObjectRequest(this.sourceS3BucketName, tocInfo.path, this.targetS3BucketName, tocInfo.path); copyRequest.setStorageClass(storageClass); // copyRequest.setGeneralProgressListener(this); if (this.enableServerSideEncryption) { copyRequest.putCustomRequestHeader("x-amz-server-side-encryption", "AES256"); } CopyObjectResult copyResult = s3Client.copyObject(copyRequest); logger.debug(logPrefix + " copied OK"); workerState.addTocPathWritten(new TocPathOpResult(payload.mode, true, tocInfo.path, "s3.copyKey", "OK")); } catch(Exception e) { logger.error(logPrefix + " unexpected ERROR: " + e.getMessage(),e); workerState.addTocPathWriteFailure( new TocPathOpResult(payload.mode, false, tocInfo.path, "s3.copyKey", logPrefix + " " + e.getMessage())); } } public String getSourceS3BucketName() { return sourceS3BucketName; } public void setSourceS3BucketName(String sourceS3BucketName) { this.sourceS3BucketName = sourceS3BucketName; } public String getTargetS3BucketName() { return targetS3BucketName; } public void setTargetS3BucketName(String targetS3BucketName) { this.targetS3BucketName = targetS3BucketName; } public StorageClass getStorageClass() { return storageClass; } public void setStorageClass(StorageClass storageClass) { this.storageClass = storageClass; } public boolean isEnableServerSideEncryption() { return enableServerSideEncryption; } public void setEnableServerSideEncryption(boolean enableServerSideEncryption) { this.enableServerSideEncryption = enableServerSideEncryption; } public AmazonS3Client getS3Client() { return s3Client; } public void setS3Client(AmazonS3Client s3Client) { this.s3Client = s3Client; } }
3e144766430a8341f0d2adffc39c0c92ac7d95f7
2,733
java
Java
src/main/java/net/steelphoenix/chatgames/commands/SubCommand.java
Steve-Tech/ChatGames
83f0f75ce535484fc54cd8d33cfcbe86522fba07
[ "MIT" ]
1
2021-06-16T20:05:44.000Z
2021-06-16T20:05:44.000Z
src/main/java/net/steelphoenix/chatgames/commands/SubCommand.java
Steve-Tech/ChatGames
83f0f75ce535484fc54cd8d33cfcbe86522fba07
[ "MIT" ]
3
2021-04-12T17:28:07.000Z
2021-08-14T19:49:59.000Z
src/main/java/net/steelphoenix/chatgames/commands/SubCommand.java
Steve-Tech/ChatGames
83f0f75ce535484fc54cd8d33cfcbe86522fba07
[ "MIT" ]
7
2020-10-17T13:16:48.000Z
2022-03-13T00:14:34.000Z
35.960526
142
0.76802
8,584
package net.steelphoenix.chatgames.commands; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import net.steelphoenix.annotations.NotNull; import net.steelphoenix.annotations.Nullable; import net.steelphoenix.chatgames.api.ICGPlugin; import net.steelphoenix.chatgames.util.Util; import net.steelphoenix.chatgames.util.messaging.Message; import net.steelphoenix.core.util.Validate; public abstract class SubCommand implements CommandExecutor, TabCompleter { protected final ICGPlugin plugin; private final String permission; private final List<String> aliases; protected SubCommand(ICGPlugin plugin, String permission, String alias) { this(plugin, permission, Arrays.asList(alias)); } protected SubCommand(ICGPlugin plugin, String permission, List<String> aliases) { Validate.isTrue(aliases != null && !aliases.isEmpty(), "Aliases cannot be null"); Validate.noneNull(aliases, "Alias cannot be null"); this.plugin = Validate.notNull(plugin, "Plugin cannot be null"); this.permission = permission; this.aliases = aliases.stream().map(String::toLowerCase).collect(Collectors.toList()); } @Nullable public final String getPermission() { return permission; } @NotNull public final List<String> getAliases() { return aliases; } @NotNull public String getUsage() { return aliases.get(0); } public final boolean isAuthorized(@NotNull CommandSender sender) { // Preconditions Validate.notNull(sender, "Sender cannot be null"); return permission == null || permission.isEmpty() || !(sender instanceof Player) || sender.hasPermission(permission); } @Override public final boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) { // No permission if (!isAuthorized(sender)) { sender.sendMessage(Util.color(Message.COMMAND_NO_PERMISSION)); return true; } return onCommand(sender, label, args); } @NotNull @Override public final List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) { List<String> list = isAuthorized(sender) ? onTabComplete(sender, label, args) : null; return list == null ? new LinkedList<>() : list; } public abstract boolean onCommand(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args); @Nullable public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args) { return null; } }
3e144849684702fabfce3daf23d2efea657ec84c
1,986
java
Java
src/main/java/kashiish/autotext/autocomplete/TrieNode.java
kashiish/autotext
82ebf284e8f920086ed921c3be20b2ec711d0422
[ "MIT" ]
1
2020-04-21T13:50:50.000Z
2020-04-21T13:50:50.000Z
src/main/java/kashiish/autotext/autocomplete/TrieNode.java
kashiish/autotext
82ebf284e8f920086ed921c3be20b2ec711d0422
[ "MIT" ]
null
null
null
src/main/java/kashiish/autotext/autocomplete/TrieNode.java
kashiish/autotext
82ebf284e8f920086ed921c3be20b2ec711d0422
[ "MIT" ]
null
null
null
22.314607
77
0.653575
8,585
package main.java.kashiish.autotext.autocomplete; import java.util.HashMap; import main.java.kashiish.autotext.Node; /** * Node representation for Trie data structure. * @author kashish * */ public class TrieNode implements Node<Character, TrieNode, Character> { /* TrieNode's data */ private Character value; /* Collection of TrieNode's children */ private HashMap<Character, TrieNode> children; /* TrieNode leaf property */ private boolean isLeaf = false; /** Creates a new TrieNode object. */ public TrieNode() { this.children = new HashMap<Character, TrieNode>(); } /** Creates a new TrieNode object with specified character. * @param c Character */ public TrieNode(Character c) { this.value = c; this.children = new HashMap<Character, TrieNode>(); } /** * Returns whether or not TrieNode is a leaf. * @return boolean TrieNode leaf property */ public boolean isLeaf() { return this.isLeaf; } /** * Sets the isLeaf property of TrieNode. * @param value boolean, value of isLeaf property */ public void setLeaf(boolean value) { this.isLeaf = value; } /** * Gets the TrieNode's value. * @return Character TrieNode's value */ @Override public Character getValue() { return this.value; } /** * Gets the TrieNode's children collection. * @return HashMap<Character, TrieNode> */ @Override public HashMap<Character, TrieNode> getChildren() { return this.children; } /** * Gets the child with the specified character. * @return TrieNode child */ @Override public TrieNode getChild(Character c) { return this.children.get(c); } /** * Adds a child to TrieNode's collection of children. * @param child TrieNode, child to be added into the children collection */ @Override public void addChild(TrieNode child) { this.children.put(child.getValue(), child); } }
3e144910bb3ec6fcfd49cf25ac40e89c4fda62ad
2,710
java
Java
HighjetBI-Common/src/main/java/com/highjet/common/modules/common/dao/DaoSupport.java
moutainhigh/Backup-Restore
03f5717b2eddf688e310c47ec1e064e1fdd68bbe
[ "Apache-2.0" ]
null
null
null
HighjetBI-Common/src/main/java/com/highjet/common/modules/common/dao/DaoSupport.java
moutainhigh/Backup-Restore
03f5717b2eddf688e310c47ec1e064e1fdd68bbe
[ "Apache-2.0" ]
null
null
null
HighjetBI-Common/src/main/java/com/highjet/common/modules/common/dao/DaoSupport.java
moutainhigh/Backup-Restore
03f5717b2eddf688e310c47ec1e064e1fdd68bbe
[ "Apache-2.0" ]
1
2021-08-04T10:08:29.000Z
2021-08-04T10:08:29.000Z
20.687023
94
0.692989
8,586
package com.highjet.common.modules.common.dao; import java.util.List; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * @author * 修改时间:2019、02、28 */ @Repository("daoSupport") //@Service public class DaoSupport implements DAO { @Autowired private SqlSessionTemplate sqlSessionTemplate; /** * 保存对象 * @param str * @param obj * @return * @throws Exception */ public Object save(String str, Object obj) throws Exception { return sqlSessionTemplate.insert(str, obj); } /** * 批量更新 * @param str * @param obj * @return * @throws Exception */ public Object batchSave(String str, List objs )throws Exception{ return sqlSessionTemplate.insert(str, objs); } /** * 修改对象 * @param str * @param obj * @return * @throws Exception */ public Object update(String str, Object obj) throws Exception { return sqlSessionTemplate.update(str, obj); } /** * 批量更新 * @param str * @param obj * @return * @throws Exception */ public void batchUpdate(String str, List objs )throws Exception{ SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory(); //批量执行器 SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false); try{ if(objs!=null){ for(int i=0,size=objs.size();i<size;i++){ sqlSession.update(str, objs.get(i)); } sqlSession.flushStatements(); sqlSession.commit(); sqlSession.clearCache(); } }finally{ sqlSession.close(); } } /** * 批量更新 * @param str * @param obj * @return * @throws Exception */ public Object batchDelete(String str, List objs )throws Exception{ return sqlSessionTemplate.delete(str, objs); } /** * 删除对象 * @param str * @param obj * @return * @throws Exception */ public Object delete(String str, Object obj) throws Exception { return sqlSessionTemplate.delete(str, obj); } /** * 查找对象 * @param str * @param obj * @return * @throws Exception */ public Object findForObject(String str, Object obj) throws Exception { return sqlSessionTemplate.selectOne(str, obj); } /** * 查找对象 * @param str * @param obj * @return * @throws Exception */ public Object findForList(String str, Object obj) throws Exception { return sqlSessionTemplate.selectList(str, obj); } public Object findForMap(String str, Object obj, String key, String value) throws Exception { return sqlSessionTemplate.selectMap(str, obj, key); } }
3e1449ece0254660e19d826eaa93a37ad77ca0a8
15,124
java
Java
s4n.core/src/org/netbeans/modules/web/stripes/util/browse/BrowseFolders.java
sustacek/stripes-4-netbeans
b3b6f2ac295619fa65d67795576bea18f938bf00
[ "Apache-2.0" ]
null
null
null
s4n.core/src/org/netbeans/modules/web/stripes/util/browse/BrowseFolders.java
sustacek/stripes-4-netbeans
b3b6f2ac295619fa65d67795576bea18f938bf00
[ "Apache-2.0" ]
null
null
null
s4n.core/src/org/netbeans/modules/web/stripes/util/browse/BrowseFolders.java
sustacek/stripes-4-netbeans
b3b6f2ac295619fa65d67795576bea18f938bf00
[ "Apache-2.0" ]
1
2015-10-18T06:16:46.000Z
2015-10-18T06:16:46.000Z
35.92399
108
0.614917
8,587
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.web.stripes.util.browse; import java.io.File; import java.io.FileFilter; import org.netbeans.api.project.SourceGroup; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.explorer.ExplorerManager; import org.openide.explorer.view.BeanTreeView; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.FilterNode; import org.openide.nodes.Node; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.netbeans.modules.web.stripes.palette.StripesPaletteUtilities; import org.openide.util.NbBundle; /** * @author pfiala */ @SuppressWarnings("unchecked") public class BrowseFolders extends JPanel implements ExplorerManager.Provider { private ExplorerManager manager; private static JScrollPane SAMPLE_SCROLL_PANE = new JScrollPane(); private FileFilter filter; public static final FileFilter imageFileFilter = new FileFilter() { public boolean accept(File pathname) { return FileUtil.toFileObject(pathname).getMIMEType().startsWith("image/"); // NOI18N } }; /** * Creates new form BrowseFolders */ public BrowseFolders(SourceGroup[] folders, FileFilter filter) { initComponents(); this.filter = filter; if (this.filter == null) { this.filter = new FileFilter() { public boolean accept(File pathname) { return true; } }; } manager = new ExplorerManager(); AbstractNode rootNode = new AbstractNode(new SourceGroupsChildren(folders)); manager.setRootContext(rootNode); // Create the templates view BeanTreeView btv = new BeanTreeView(); btv.setRootVisible(false); btv.setSelectionMode(javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION); btv.setBorder(SAMPLE_SCROLL_PANE.getBorder()); btv.setDefaultActionAllowed(false); expandFirstLevel(btv); folderPanel.add(btv, java.awt.BorderLayout.CENTER); } // ExplorerManager.Provider implementation --------------------------------- public ExplorerManager getExplorerManager() { return manager; } private void expandFirstLevel(BeanTreeView btv) { Node root = manager.getRootContext(); Children ch = root.getChildren(); if ( ch == Children.LEAF ) { return; } Node nodes[] = ch.getNodes(true); btv.expandNode(root); for ( int i = 0; i < nodes.length; i++ ) { btv.expandNode( nodes[i] ); if ( i == 0 ) { try { manager.setSelectedNodes( new Node[] { nodes[i] } ); } catch ( java.beans.PropertyVetoException e ) { // No selection for some reason } } } } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jLabel1 = new javax.swing.JLabel(); folderPanel = new javax.swing.JPanel(); setBorder(javax.swing.BorderFactory.createEmptyBorder(12, 12, 12, 12)); setLayout(new java.awt.GridBagLayout()); jLabel1.setText(org.openide.util.NbBundle.getMessage(BrowseFolders.class, "LBL_Folders")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); add(jLabel1, gridBagConstraints); folderPanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(folderPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel folderPanel; private javax.swing.JLabel jLabel1; // End of variables declaration//GEN-END:variables public static FileObject showDialog(SourceGroup[] folders) { return showDialog(folders, null); } static class TreeMouseAdapter extends MouseAdapter { JTree tree; BrowseFolders bf; JButton[] options; TreeMouseAdapter(JTree tree, BrowseFolders bf, JButton[] options) { this.tree = tree; this.bf = bf; this.options = options; } @Override public void mouseClicked(MouseEvent e) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if ((selRow != -1) && SwingUtilities.isLeftMouseButton(e) && (e.getClickCount() % 2) == 0) { FileObject fileObject = bf.getSelectedFileObject(); if (fileObject != null && !fileObject.isFolder()) options[0].doClick(); } } } public static FileObject showDialog(SourceGroup[] folders, FileFilter filter) { final BrowseFolders bf = new BrowseFolders(folders, filter); final JButton options[] = new JButton[]{ new JButton(NbBundle.getMessage(BrowseFolders.class, "LBL_SelectFile")), new JButton(NbBundle.getMessage(BrowseFolders.class, "LBL_Cancel")), }; options[0].setEnabled(false); JTree tree = StripesPaletteUtilities.findTreeComponent(bf); tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { FileObject fileObject = bf.getSelectedFileObject(); options[0].setEnabled(fileObject != null && !fileObject.isFolder()); } }); OptionsListener optionsListener = new OptionsListener(bf); options[0].setActionCommand(OptionsListener.COMMAND_SELECT); options[0].addActionListener(optionsListener); options[1].setActionCommand(OptionsListener.COMMAND_CANCEL); options[1].addActionListener(optionsListener); MouseListener ml = new TreeMouseAdapter(tree, bf, options); tree.addMouseListener(ml); DialogDescriptor dialogDescriptor = new DialogDescriptor(bf, // innerPane NbBundle.getMessage(BrowseFolders.class, "LBL_BrowseFiles"), // displayName true, // modal options, // options options[0], // initial value DialogDescriptor.BOTTOM_ALIGN, // options align null, // helpCtx null); // listener dialogDescriptor.setClosingOptions(new Object[]{options[0], options[1]}); Dialog dialog = DialogDisplayer.getDefault().createDialog(dialogDescriptor); dialog.setVisible(true); return optionsListener.getResult(); } private FileObject getSelectedFileObject() { Node selection[] = getExplorerManager().getSelectedNodes(); if (selection != null && selection.length > 0) { DataObject dobj = selection[0].getLookup().lookup(DataObject.class); return dobj.getPrimaryFile(); } return null; } // Innerclasses ------------------------------------------------------------ /** * Children to be used to show FileObjects from given SourceGroups */ private final class SourceGroupsChildren extends Children.Keys { private SourceGroup[] groups; private SourceGroup group; private FileObject fo; public SourceGroupsChildren(SourceGroup[] groups) { this.groups = groups; } public SourceGroupsChildren(FileObject fo, SourceGroup group) { this.fo = fo; this.group = group; } @Override protected void addNotify() { super.addNotify(); setKeys(getKeys()); } @Override protected void removeNotify() { setKeys(Collections.EMPTY_SET); super.removeNotify(); } protected Node[] createNodes(Object key) { FileObject fObj = null; SourceGroup grp = null; boolean isFile = false; if (key instanceof SourceGroup) { fObj = ((SourceGroup) key).getRootFolder(); grp = (SourceGroup) key; } else if (key instanceof Key) { fObj = ((Key) key).folder; grp = ((Key) key).group; if (!fObj.isFolder()) { isFile = true; } } try { DataObject dobj = DataObject.find(fObj); FilterNode fn = (isFile ? new FilterNode(dobj.getNodeDelegate(), Children.LEAF) : new FilterNode(dobj.getNodeDelegate(), new SourceGroupsChildren(fObj, grp))); if (key instanceof SourceGroup) { fn.setDisplayName(grp.getDisplayName()); } return new Node[]{fn}; } catch (DataObjectNotFoundException e) { return null; } } private Collection getKeys() { if (groups != null) { return Arrays.asList(groups); } else { FileObject files[] = fo.getChildren(); Arrays.sort(files, new FileObjectComparator()); ArrayList children = new ArrayList(files.length); for (int i = 0; i < files.length; i++) { FileObject file = files[i]; if (group.contains(files[i]) && file.isFolder()) { children.add(new Key(files[i], group)); } } // add files for (int i = 0; i < files.length; i++) { FileObject file = files[i]; if (group.contains(file) && !files[i].isFolder()) { if (filter.accept(FileUtil.toFile(file))) { children.add(new Key(files[i], group)); } } } //} return children; } } private class Key { private FileObject folder; private SourceGroup group; private Key(FileObject folder, SourceGroup group) { this.folder = folder; this.group = group; } } } private class FileObjectComparator implements java.util.Comparator { public int compare(Object o1, Object o2) { FileObject fo1 = (FileObject) o1; FileObject fo2 = (FileObject) o2; return fo1.getName().compareTo(fo2.getName()); } } private static final class OptionsListener implements ActionListener { public static final String COMMAND_SELECT = "SELECT"; //NOI18N public static final String COMMAND_CANCEL = "CANCEL"; //NOI18N private BrowseFolders browsePanel; private FileObject result; //private Class target; public OptionsListener(BrowseFolders browsePanel) { this.browsePanel = browsePanel; } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (COMMAND_SELECT.equals(command)) { this.result = browsePanel.getSelectedFileObject(); } } public FileObject getResult() { return result; } } }
3e144a3394fd8f34142ed92a83697e4253c050e4
1,651
java
Java
stratosphere-tests/src/test/java/eu/stratosphere/test/exampleScalaPrograms/RelationalQueryITCase.java
qmlmoon/incubator-flink
708426ba6783bc600e1b818c78d90d567a3734a4
[ "Apache-2.0" ]
28
2015-02-07T12:14:37.000Z
2022-01-03T01:39:49.000Z
stratosphere-tests/src/test/java/eu/stratosphere/test/exampleScalaPrograms/RelationalQueryITCase.java
qmlmoon/incubator-flink
708426ba6783bc600e1b818c78d90d567a3734a4
[ "Apache-2.0" ]
20
2015-11-24T18:15:13.000Z
2021-03-10T20:45:44.000Z
stratosphere-tests/src/test/java/eu/stratosphere/test/exampleScalaPrograms/RelationalQueryITCase.java
qmlmoon/incubator-flink
708426ba6783bc600e1b818c78d90d567a3734a4
[ "Apache-2.0" ]
23
2016-03-24T02:07:28.000Z
2022-01-13T13:16:04.000Z
36.688889
120
0.655966
8,588
/*********************************************************************************************************************** * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.test.exampleScalaPrograms; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import eu.stratosphere.api.common.Plan; import eu.stratosphere.configuration.Configuration; import eu.stratosphere.examples.scala.relational.RelationalQuery; import java.util.Locale; @RunWith(Parameterized.class) public class RelationalQueryITCase extends eu.stratosphere.test.recordJobTests.TPCHQuery3ITCase { public RelationalQueryITCase(Configuration config) { super(config); Locale.setDefault(Locale.US); } @Override protected Plan getTestJob() { RelationalQuery tpch3 = new RelationalQuery(); return tpch3.getScalaPlan( config.getInteger("dop", 1), ordersPath, lineitemsPath, resultPath, 'F', 1993, "5"); } }
3e144a6c8d752ec22013e08d23af51236fc43563
212
java
Java
src/main/java/com/example/Topic/Repository/TopicRepository.java
Sapbasu15/CourseApplication
35ce18bc89c6ea1464558c6e1d04f567461c80c2
[ "MIT" ]
null
null
null
src/main/java/com/example/Topic/Repository/TopicRepository.java
Sapbasu15/CourseApplication
35ce18bc89c6ea1464558c6e1d04f567461c80c2
[ "MIT" ]
null
null
null
src/main/java/com/example/Topic/Repository/TopicRepository.java
Sapbasu15/CourseApplication
35ce18bc89c6ea1464558c6e1d04f567461c80c2
[ "MIT" ]
null
null
null
26.5
72
0.834906
8,589
package com.example.Topic.Repository; import com.example.Topic.Model.Topic; import org.springframework.data.repository.CrudRepository; public interface TopicRepository extends CrudRepository<Topic, String> { }
3e144b530ddad3bd1be0e8dd2c0bbba6fc6653db
1,134
java
Java
taotao-rest/src/main/java/com/wugq/taotao/rest/controller/ContentController.java
wuguoquan/TaoTaoDemoM
c494484e1b7ba23aa1d5ed318a404ac458483b99
[ "Apache-2.0" ]
null
null
null
taotao-rest/src/main/java/com/wugq/taotao/rest/controller/ContentController.java
wuguoquan/TaoTaoDemoM
c494484e1b7ba23aa1d5ed318a404ac458483b99
[ "Apache-2.0" ]
null
null
null
taotao-rest/src/main/java/com/wugq/taotao/rest/controller/ContentController.java
wuguoquan/TaoTaoDemoM
c494484e1b7ba23aa1d5ed318a404ac458483b99
[ "Apache-2.0" ]
null
null
null
30.648649
76
0.776896
8,590
package com.wugq.taotao.rest.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.wugq.taotao.common.pojo.TaotaoResult; import com.wugq.taotao.common.utils.ExceptionUtil; import com.wugq.taotao.manager.pojo.TbContent; import com.wugq.taotao.rest.service.ContentService; /** * 内容管理Controller */ @Controller @RequestMapping("/content") public class ContentController { @Autowired private ContentService contentService; @RequestMapping("/list/{contentCategoryId}") @ResponseBody public TaotaoResult getContentList(@PathVariable Long contentCategoryId) { try { List<TbContent> list = contentService.getContentList(contentCategoryId); return TaotaoResult.ok(list); } catch (Exception e) { e.printStackTrace(); return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e)); } } }
3e144c3a1163ade90442ecd021f54eaa0e645ee8
1,170
java
Java
src/main/java/com/codereligion/flux/converters/net/StringToInetSocketAddressConverter.java
codereligion/flux
a359f95549b9ce474d8f854dd2fddc3982ece432
[ "Apache-2.0" ]
1
2015-10-05T09:39:43.000Z
2015-10-05T09:39:43.000Z
src/main/java/com/codereligion/flux/converters/net/StringToInetSocketAddressConverter.java
codereligion/flux
a359f95549b9ce474d8f854dd2fddc3982ece432
[ "Apache-2.0" ]
null
null
null
src/main/java/com/codereligion/flux/converters/net/StringToInetSocketAddressConverter.java
codereligion/flux
a359f95549b9ce474d8f854dd2fddc3982ece432
[ "Apache-2.0" ]
null
null
null
37.741935
107
0.754701
8,591
package com.codereligion.flux.converters.net; import com.codereligion.flux.Capacitor; import com.codereligion.flux.spi.Dependency; import com.google.common.base.Preconditions; import com.google.common.reflect.TypeToken; import com.codereligion.flux.spi.Converter; import javax.annotation.Nullable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.regex.Matcher; import java.util.regex.Pattern; @Dependency(input = String.class, output = InetAddress.class) public final class StringToInetSocketAddressConverter implements Converter<String, InetSocketAddress> { private final Pattern pattern = Pattern.compile("^([^:]+):(\\d+)$"); @Nullable @Override public <V extends String> InetSocketAddress convert(V value, TypeToken<V> input, Capacitor capacitor) { final Matcher matcher = pattern.matcher(value); Preconditions.checkArgument(matcher.matches(), "%s does not match %s", value, pattern); final InetAddress host = capacitor.convert(matcher.group(1)).to(InetAddress.class); final int port = Integer.parseInt(matcher.group(2)); return new InetSocketAddress(host, port); } }
3e144cd8693cc594355362b5c168299ce5676208
109
java
Java
stilt/core/src/main/java/com/p4ybill/stilt/parser/MappingFunction.java
P4yBill/stilt-index
9708322cfd252648af58bdf4c92ec6b5fd1ab2cf
[ "MIT" ]
null
null
null
stilt/core/src/main/java/com/p4ybill/stilt/parser/MappingFunction.java
P4yBill/stilt-index
9708322cfd252648af58bdf4c92ec6b5fd1ab2cf
[ "MIT" ]
null
null
null
stilt/core/src/main/java/com/p4ybill/stilt/parser/MappingFunction.java
P4yBill/stilt-index
9708322cfd252648af58bdf4c92ec6b5fd1ab2cf
[ "MIT" ]
null
null
null
18.166667
36
0.752294
8,592
package com.p4ybill.stilt.parser; public interface MappingFunction { int map(Object value, int bits); }
3e144cec2b02cb78dc529797debe7f90c8f4fc83
2,375
java
Java
src/main/java/shadows/apotheosis/ench/enchantments/HellInfusionEnchantment.java
tony84727/Apotheosis
f372c14ae9b8bc3907b407a2d95579b5c26aa4f8
[ "MIT" ]
null
null
null
src/main/java/shadows/apotheosis/ench/enchantments/HellInfusionEnchantment.java
tony84727/Apotheosis
f372c14ae9b8bc3907b407a2d95579b5c26aa4f8
[ "MIT" ]
null
null
null
src/main/java/shadows/apotheosis/ench/enchantments/HellInfusionEnchantment.java
tony84727/Apotheosis
f372c14ae9b8bc3907b407a2d95579b5c26aa4f8
[ "MIT" ]
null
null
null
33.450704
106
0.794947
8,593
package shadows.apotheosis.ench.enchantments; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentType; import net.minecraft.enchantment.Enchantments; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.AxeItem; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.text.IFormattableTextComponent; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import shadows.apotheosis.Apotheosis; import shadows.apotheosis.ApotheosisObjects; public class HellInfusionEnchantment extends Enchantment { public HellInfusionEnchantment() { super(Rarity.VERY_RARE, EnchantmentType.WEAPON, new EquipmentSlotType[] { EquipmentSlotType.MAINHAND }); } @Override public int getMinEnchantability(int level) { return 50 + (level - 1) * 13; } @Override public int getMaxEnchantability(int level) { return this.getMinEnchantability(level + 1); } @Override public int getMaxLevel() { return 5; } @Override public boolean canApply(ItemStack stack) { return stack.getItem() instanceof AxeItem ? true : super.canApply(stack); } @Override public void onEntityDamaged(LivingEntity user, Entity target, int level) { if (user.world.getDimensionKey() == World.THE_NETHER) { if (user instanceof PlayerEntity) { DamageSource source = DamageSource.causePlayerDamage((PlayerEntity) user); source.setMagicDamage().setDamageBypassesArmor(); target.attackEntityFrom(source, level * level * 1.3F * Apotheosis.localAtkStrength); } else target.attackEntityFrom(DamageSource.MAGIC, level * level * 1.3F * Apotheosis.localAtkStrength); } } @Override public ITextComponent getDisplayName(int level) { return ((IFormattableTextComponent) super.getDisplayName(level)).mergeStyle(TextFormatting.DARK_GREEN); } @Override protected boolean canApplyTogether(Enchantment ench) { return super.canApplyTogether(ench) && ench != ApotheosisObjects.SEA_INFUSION; } @Override public boolean canApplyAtEnchantingTable(ItemStack stack) { return super.canApplyAtEnchantingTable(stack) || Enchantments.IMPALING.canApplyAtEnchantingTable(stack); } }
3e144d256d815ed738ad24eee753d161b86b1010
9,023
java
Java
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/eevolution/model/I_PP_OrderLine_Candidate.java
askmohanty/metasfresh
a2638a601eff0c157c5a8440098dc6c2521374b7
[ "RSA-MD" ]
1
2015-11-09T07:13:14.000Z
2015-11-09T07:13:14.000Z
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/eevolution/model/I_PP_OrderLine_Candidate.java
metas-fresh/fresh
265b6e00fbbf154d6a7bbb9aaf9cf7135f9d6a27
[ "RSA-MD" ]
null
null
null
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/eevolution/model/I_PP_OrderLine_Candidate.java
metas-fresh/fresh
265b6e00fbbf154d6a7bbb9aaf9cf7135f9d6a27
[ "RSA-MD" ]
null
null
null
25.133705
249
0.719162
8,594
/* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2021 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package org.eevolution.model; import org.adempiere.model.ModelColumn; import javax.annotation.Nullable; import java.math.BigDecimal; /** Generated Interface for PP_OrderLine_Candidate * @author metasfresh (generated) */ @SuppressWarnings("unused") public interface I_PP_OrderLine_Candidate { String Table_Name = "PP_OrderLine_Candidate"; // /** AD_Table_ID=541914 */ // int Table_ID = org.compiere.model.MTable.getTable_ID(Table_Name); /** * Get Client. * Client/Tenant for this installation. * * <br>Type: TableDir * <br>Mandatory: true * <br>Virtual Column: false */ int getAD_Client_ID(); String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** * Set Organisation. * Organisational entity within client * * <br>Type: Search * <br>Mandatory: true * <br>Virtual Column: false */ void setAD_Org_ID (int AD_Org_ID); /** * Get Organisation. * Organisational entity within client * * <br>Type: Search * <br>Mandatory: true * <br>Virtual Column: false */ int getAD_Org_ID(); String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** * Set UOM. * Unit of Measure * * <br>Type: TableDir * <br>Mandatory: true * <br>Virtual Column: false */ void setC_UOM_ID (int C_UOM_ID); /** * Get UOM. * Unit of Measure * * <br>Type: TableDir * <br>Mandatory: true * <br>Virtual Column: false */ int getC_UOM_ID(); String COLUMNNAME_C_UOM_ID = "C_UOM_ID"; /** * Set Component Type. * Component Type for a Bill of Material or Formula * * <br>Type: List * <br>Mandatory: false * <br>Virtual Column: false */ void setComponentType (@Nullable java.lang.String ComponentType); /** * Get Component Type. * Component Type for a Bill of Material or Formula * * <br>Type: List * <br>Mandatory: false * <br>Virtual Column: false */ @Nullable java.lang.String getComponentType(); ModelColumn<I_PP_OrderLine_Candidate, Object> COLUMN_ComponentType = new ModelColumn<>(I_PP_OrderLine_Candidate.class, "ComponentType", null); String COLUMNNAME_ComponentType = "ComponentType"; /** * Get Created. * Date this record was created * * <br>Type: DateTime * <br>Mandatory: true * <br>Virtual Column: false */ java.sql.Timestamp getCreated(); ModelColumn<I_PP_OrderLine_Candidate, Object> COLUMN_Created = new ModelColumn<>(I_PP_OrderLine_Candidate.class, "Created", null); String COLUMNNAME_Created = "Created"; /** * Get Created By. * User who created this records * * <br>Type: Table * <br>Mandatory: true * <br>Virtual Column: false */ int getCreatedBy(); String COLUMNNAME_CreatedBy = "CreatedBy"; /** * Set Description. * * <br>Type: Text * <br>Mandatory: false * <br>Virtual Column: false */ void setDescription (@Nullable java.lang.String Description); /** * Get Description. * * <br>Type: Text * <br>Mandatory: false * <br>Virtual Column: false */ @Nullable java.lang.String getDescription(); ModelColumn<I_PP_OrderLine_Candidate, Object> COLUMN_Description = new ModelColumn<>(I_PP_OrderLine_Candidate.class, "Description", null); String COLUMNNAME_Description = "Description"; /** * Set Active. * The record is active in the system * * <br>Type: YesNo * <br>Mandatory: true * <br>Virtual Column: false */ void setIsActive (boolean IsActive); /** * Get Active. * The record is active in the system * * <br>Type: YesNo * <br>Mandatory: true * <br>Virtual Column: false */ boolean isActive(); ModelColumn<I_PP_OrderLine_Candidate, Object> COLUMN_IsActive = new ModelColumn<>(I_PP_OrderLine_Candidate.class, "IsActive", null); String COLUMNNAME_IsActive = "IsActive"; /** * Set Attributes. * Attribute Instances for Products * * <br>Type: PAttribute * <br>Mandatory: false * <br>Virtual Column: false */ void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID); /** * Get Attributes. * Attribute Instances for Products * * <br>Type: PAttribute * <br>Mandatory: false * <br>Virtual Column: false */ int getM_AttributeSetInstance_ID(); @Nullable org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance(); void setM_AttributeSetInstance(@Nullable org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance); ModelColumn<I_PP_OrderLine_Candidate, org.compiere.model.I_M_AttributeSetInstance> COLUMN_M_AttributeSetInstance_ID = new ModelColumn<>(I_PP_OrderLine_Candidate.class, "M_AttributeSetInstance_ID", org.compiere.model.I_M_AttributeSetInstance.class); String COLUMNNAME_M_AttributeSetInstance_ID = "M_AttributeSetInstance_ID"; /** * Set Product. * Product, Service, Item * * <br>Type: Search * <br>Mandatory: true * <br>Virtual Column: false */ void setM_Product_ID (int M_Product_ID); /** * Get Product. * Product, Service, Item * * <br>Type: Search * <br>Mandatory: true * <br>Virtual Column: false */ int getM_Product_ID(); String COLUMNNAME_M_Product_ID = "M_Product_ID"; /** * Set Manufacturing Order Candidate. * * <br>Type: Search * <br>Mandatory: true * <br>Virtual Column: false */ void setPP_Order_Candidate_ID (int PP_Order_Candidate_ID); /** * Get Manufacturing Order Candidate. * * <br>Type: Search * <br>Mandatory: true * <br>Virtual Column: false */ int getPP_Order_Candidate_ID(); org.eevolution.model.I_PP_Order_Candidate getPP_Order_Candidate(); void setPP_Order_Candidate(org.eevolution.model.I_PP_Order_Candidate PP_Order_Candidate); ModelColumn<I_PP_OrderLine_Candidate, org.eevolution.model.I_PP_Order_Candidate> COLUMN_PP_Order_Candidate_ID = new ModelColumn<>(I_PP_OrderLine_Candidate.class, "PP_Order_Candidate_ID", org.eevolution.model.I_PP_Order_Candidate.class); String COLUMNNAME_PP_Order_Candidate_ID = "PP_Order_Candidate_ID"; /** * Set Manufacturing Order Line Candidate. * * <br>Type: ID * <br>Mandatory: true * <br>Virtual Column: false */ void setPP_OrderLine_Candidate_ID (int PP_OrderLine_Candidate_ID); /** * Get Manufacturing Order Line Candidate. * * <br>Type: ID * <br>Mandatory: true * <br>Virtual Column: false */ int getPP_OrderLine_Candidate_ID(); ModelColumn<I_PP_OrderLine_Candidate, Object> COLUMN_PP_OrderLine_Candidate_ID = new ModelColumn<>(I_PP_OrderLine_Candidate.class, "PP_OrderLine_Candidate_ID", null); String COLUMNNAME_PP_OrderLine_Candidate_ID = "PP_OrderLine_Candidate_ID"; /** * Set BOM Line. * BOM Line * * <br>Type: Search * <br>Mandatory: true * <br>Virtual Column: false */ void setPP_Product_BOMLine_ID (int PP_Product_BOMLine_ID); /** * Get BOM Line. * BOM Line * * <br>Type: Search * <br>Mandatory: true * <br>Virtual Column: false */ int getPP_Product_BOMLine_ID(); org.eevolution.model.I_PP_Product_BOMLine getPP_Product_BOMLine(); void setPP_Product_BOMLine(org.eevolution.model.I_PP_Product_BOMLine PP_Product_BOMLine); ModelColumn<I_PP_OrderLine_Candidate, org.eevolution.model.I_PP_Product_BOMLine> COLUMN_PP_Product_BOMLine_ID = new ModelColumn<>(I_PP_OrderLine_Candidate.class, "PP_Product_BOMLine_ID", org.eevolution.model.I_PP_Product_BOMLine.class); String COLUMNNAME_PP_Product_BOMLine_ID = "PP_Product_BOMLine_ID"; /** * Set Qty. * * <br>Type: Quantity * <br>Mandatory: false * <br>Virtual Column: false */ void setQtyEntered (@Nullable BigDecimal QtyEntered); /** * Get Qty. * * <br>Type: Quantity * <br>Mandatory: false * <br>Virtual Column: false */ BigDecimal getQtyEntered(); ModelColumn<I_PP_OrderLine_Candidate, Object> COLUMN_QtyEntered = new ModelColumn<>(I_PP_OrderLine_Candidate.class, "QtyEntered", null); String COLUMNNAME_QtyEntered = "QtyEntered"; /** * Get Updated. * Date this record was updated * * <br>Type: DateTime * <br>Mandatory: true * <br>Virtual Column: false */ java.sql.Timestamp getUpdated(); ModelColumn<I_PP_OrderLine_Candidate, Object> COLUMN_Updated = new ModelColumn<>(I_PP_OrderLine_Candidate.class, "Updated", null); String COLUMNNAME_Updated = "Updated"; /** * Get Updated By. * User who updated this records * * <br>Type: Table * <br>Mandatory: true * <br>Virtual Column: false */ int getUpdatedBy(); String COLUMNNAME_UpdatedBy = "UpdatedBy"; }
3e144daf4bb1af84415640df458c21686a4e6bb4
1,112
java
Java
st-md-testcatalog/src/main/java/com/systematictesting/utils/TestCatalogUtils.java
SystematicTesting/QDOS-Report
958cb7f2b496af34b6c505080daaef2b6f8251fe
[ "MIT" ]
null
null
null
st-md-testcatalog/src/main/java/com/systematictesting/utils/TestCatalogUtils.java
SystematicTesting/QDOS-Report
958cb7f2b496af34b6c505080daaef2b6f8251fe
[ "MIT" ]
null
null
null
st-md-testcatalog/src/main/java/com/systematictesting/utils/TestCatalogUtils.java
SystematicTesting/QDOS-Report
958cb7f2b496af34b6c505080daaef2b6f8251fe
[ "MIT" ]
null
null
null
30.054054
172
0.747302
8,595
package com.systematictesting.utils; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestCatalogUtils { private static Logger logger = LoggerFactory.getLogger(TestCatalogUtils.class); private static String method_createReportLocation = " :: createCatalogLocation() :: "; public static void createCatalogLocation(String catalogUploadFolderLocation) throws SecurityException { File theDir = new File(catalogUploadFolderLocation); if (!theDir.exists()) { if (logger.isDebugEnabled()) { logger.debug(method_createReportLocation + "Creating Catalog Directory : "+catalogUploadFolderLocation); } boolean result = false; try { theDir.mkdirs(); result = true; } catch (SecurityException se) { se.printStackTrace(); logger.error(method_createReportLocation + "Failed to create catalog directory. Therefore report can not be published. Please contact system administrator of system."); throw se; } if (result) { logger.debug(method_createReportLocation + "Catalog Directory created successfully."); } } } }
3e144e414164caebb31e28a418b97dba77cda855
356
java
Java
raw_dataset/66729739@update@OK.java
zthang/code2vec_treelstm
0c5f98d280b506317738ba603b719cac6036896f
[ "MIT" ]
1
2020-04-24T03:35:40.000Z
2020-04-24T03:35:40.000Z
raw_dataset/66871641@update@OK.java
ruanyuan115/code2vec_treelstm
0c5f98d280b506317738ba603b719cac6036896f
[ "MIT" ]
2
2020-04-23T21:14:28.000Z
2021-01-21T01:07:18.000Z
raw_dataset/66871641@update@OK.java
zthang/code2vec_treelstm
0c5f98d280b506317738ba603b719cac6036896f
[ "MIT" ]
null
null
null
29.666667
65
0.539326
8,596
void update(int ll, int rr, int time, int knight, int l, int r) { lazyPropagation(); if (noIntersection(ll, rr, l, r)) return; if (covered(ll, rr, l, r)) { setLazy(time, knight); return; } int mid = (l + r) / 2; left.update(ll, rr, time, knight, l, mid); right.update(ll, rr, time, knight, mid + 1, r); }
3e144f33074652bd589ad062052bce4c7981d98e
1,030
java
Java
customwidget/src/main/java/cn/xxt/customwidget/thinkinginjava/collection/method17_11/Synchronization.java
Martin-zhq/someexercise
6edd6cc4ce260c189727a487652738549ca61d56
[ "Apache-2.0" ]
null
null
null
customwidget/src/main/java/cn/xxt/customwidget/thinkinginjava/collection/method17_11/Synchronization.java
Martin-zhq/someexercise
6edd6cc4ce260c189727a487652738549ca61d56
[ "Apache-2.0" ]
null
null
null
customwidget/src/main/java/cn/xxt/customwidget/thinkinginjava/collection/method17_11/Synchronization.java
Martin-zhq/someexercise
6edd6cc4ce260c189727a487652738549ca61d56
[ "Apache-2.0" ]
null
null
null
33.225806
98
0.730097
8,597
package cn.xxt.customwidget.thinkinginjava.collection.method17_11; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; /** * @Author zhq * @Date 2019-11-22-10:24 * @Description * @Email anpch@example.com */ public class Synchronization { public static void main(String[] args) { Collection<String> c = Collections.synchronizedCollection(new ArrayList<String>()); List<String> list = Collections.synchronizedList(new ArrayList<String>()); Set<String> s = Collections.synchronizedSet(new HashSet<String>()); Set<String> ss = Collections.synchronizedSortedSet(new TreeSet<String>()); Map<String, String> m = Collections.synchronizedMap(new HashMap<String, String>()); Map<String, String> sm = Collections.synchronizedSortedMap(new TreeMap<String, String>()); } }
3e144f39d9dfcb5794e23f9d61f1a837e856e0c0
1,745
java
Java
multithreading/src/main/java/com/mythtrad/proj6/others/CountDownLatchDemo.java
xiangzz159/JInterview-demo
5669af41897d14e57bdc6f6926ddc3f797edfe8b
[ "MIT" ]
null
null
null
multithreading/src/main/java/com/mythtrad/proj6/others/CountDownLatchDemo.java
xiangzz159/JInterview-demo
5669af41897d14e57bdc6f6926ddc3f797edfe8b
[ "MIT" ]
null
null
null
multithreading/src/main/java/com/mythtrad/proj6/others/CountDownLatchDemo.java
xiangzz159/JInterview-demo
5669af41897d14e57bdc6f6926ddc3f797edfe8b
[ "MIT" ]
null
null
null
31.727273
99
0.547851
8,598
package com.mythtrad.proj6.others; import java.util.concurrent.CountDownLatch; /** * @Author:Yerik Xiang * @Date:2020/10/28 15:37 * @Desc: CountDownLatch计数器演示,由外部线程控制一组线程的放行 */ public class CountDownLatchDemo { private static CountDownLatch countDownLatch = new CountDownLatch(6); private static class InitThread extends Thread { @Override public void run() { System.out.println("InitThread线程" + Thread.currentThread().getName() + "开始初始化...."); countDownLatch.countDown(); } } private static class BusiThread extends Thread { @Override public void run() { try { System.out.println("BusiThread线程" + Thread.currentThread().getName() + "准备运行...."); //只有等countDownLatch的计数器为0,也就是其他计数器的线程都执行完了,才能执行 countDownLatch.await(); Thread.sleep(1000); System.out.println("BusiThread线程" + Thread.currentThread().getName() + "运行完成...."); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println("主线程" + Thread.currentThread().getName() + "开始初始化...."); countDownLatch.countDown(); } }, "main-2").start(); new BusiThread().start(); for (int i = 0; i < 5; i++) { new InitThread().start(); } try { countDownLatch.await(); System.out.println("主线程运行结束......."); } catch (InterruptedException e) { e.printStackTrace(); } } }
3e144f3fd507390df611976c5aff75891db010f8
1,591
java
Java
src/main/java/cn/shijinshi/redis/forward/server/RequestDecoder.java
shijinshi/redis-broker
5b3d95d9ca7ecbdd5a46338e378c794731f93b70
[ "Apache-2.0" ]
10
2019-11-04T09:16:49.000Z
2021-06-11T11:19:23.000Z
src/main/java/cn/shijinshi/redis/forward/server/RequestDecoder.java
shijinshi/redis-broker
5b3d95d9ca7ecbdd5a46338e378c794731f93b70
[ "Apache-2.0" ]
5
2020-02-22T02:57:24.000Z
2021-12-09T21:43:26.000Z
src/main/java/cn/shijinshi/redis/forward/server/RequestDecoder.java
shijinshi/redis-broker
5b3d95d9ca7ecbdd5a46338e378c794731f93b70
[ "Apache-2.0" ]
3
2019-11-04T09:00:55.000Z
2020-12-18T03:12:09.000Z
29.462963
101
0.645506
8,599
package cn.shijinshi.redis.forward.server; import cn.shijinshi.redis.common.protocol.RedisCodec; import cn.shijinshi.redis.common.protocol.RedisRequest; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.List; /** * 解析来自客户端的请求报文 * * @author Gui Jiahai */ public class RequestDecoder extends ByteToMessageDecoder { private static final Logger logger = LoggerFactory.getLogger(RequestDecoder.class); @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (!ctx.channel().isActive()) { return; } InputStream input = new ByteBufInputStream(in); int saveReaderIndex; RedisRequest request; do { saveReaderIndex = in.readerIndex(); try { request = RedisCodec.decodeRequest(input); } catch (IOException e) { in.readerIndex(saveReaderIndex); logger.error("Bad redis bytes stream:\n{}", in.toString(StandardCharsets.UTF_8)); throw e; } if (request == null) { in.readerIndex(saveReaderIndex); break; } else { out.add(request); } } while (in.isReadable()); } }
3e144f86ac11a79f4ebf4341a54a042069e7ec43
24,892
java
Java
uimaj-ep-runtime-deployeditor/src/main/java/org/apache/uima/aae/deployment/impl/AsyncAggregateErrorConfiguration_Impl.java
abrami/uima-async-scaleout
163e92a2573907ce508071d416d7abe56980062d
[ "Apache-2.0" ]
10
2015-11-29T03:32:06.000Z
2020-01-21T21:38:38.000Z
uimaj-ep-runtime-deployeditor/src/main/java/org/apache/uima/aae/deployment/impl/AsyncAggregateErrorConfiguration_Impl.java
abrami/uima-async-scaleout
163e92a2573907ce508071d416d7abe56980062d
[ "Apache-2.0" ]
2
2020-04-08T18:25:17.000Z
2020-04-08T18:25:18.000Z
uimaj-ep-runtime-deployeditor/src/main/java/org/apache/uima/aae/deployment/impl/AsyncAggregateErrorConfiguration_Impl.java
isabella232/uima-as_old
c6faa8b6fd8b4dd914e0fa6ded4ce330462f7236
[ "Apache-2.0" ]
10
2015-12-09T21:38:31.000Z
2020-01-21T21:38:40.000Z
40.148387
197
0.642696
8,600
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /** * * Project UIMA Tooling * * * creation date: Aug 11, 2007, 10:24:35 PM * source: AsyncPrimitiveErrorConfiguration_Impl.java */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.uima.aae.deployment.impl; import org.apache.uima.aae.deployment.AEDeploymentConstants; import org.apache.uima.aae.deployment.AsyncAEErrorConfiguration; import org.apache.uima.aae.deployment.AsyncAggregateErrorConfiguration; import org.apache.uima.aae.deployment.AsyncPrimitiveErrorConfiguration; import org.apache.uima.aae.deployment.CollectionProcessCompleteErrors; import org.apache.uima.aae.deployment.GetMetadataErrors; import org.apache.uima.aae.deployment.ProcessCasErrors; import org.apache.uima.internal.util.XMLUtils; import org.apache.uima.resource.metadata.impl.MetaDataObject_impl; import org.apache.uima.resource.metadata.impl.XmlizationInfo; import org.apache.uima.util.InvalidXMLException; import org.apache.uima.util.XMLParser; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * * */ public class AsyncAggregateErrorConfiguration_Impl extends MetaDataObject_impl implements AEDeploymentConstants, AsyncAggregateErrorConfiguration { private static final long serialVersionUID = 397306920555478205L; protected DeploymentMetaData_Impl parentObject; protected String name = ""; protected String description = ""; protected String version = ""; protected String vendor = ""; protected String importedDescriptor; protected boolean hasImport = false; protected boolean importByLocation = false; protected GetMetadataErrors getMetadataErrors; protected ProcessCasErrors processCasErrors; protected CollectionProcessCompleteErrors collectionProcessCompleteErrors; /*************************************************************************/ public AsyncAggregateErrorConfiguration_Impl() { super(); getMetadataErrors = new GetMetadataErrors_Impl(this); processCasErrors = new ProcessCasErrors_Impl(this); collectionProcessCompleteErrors = new CollectionProcessCompleteErrors_Impl(this); } public AsyncAEErrorConfiguration clone() { AsyncAEErrorConfiguration clone = new AsyncAggregateErrorConfiguration_Impl(); clone.setName(getName()); clone.setDescription(getDescription()); clone.setVersion(getVersion()); clone.setVendor(getVendor()); if (getMetadataErrors != null) { clone.setGetMetadataErrors(getMetadataErrors.clone(clone)); } if (processCasErrors != null) { clone.setProcessCasErrors(processCasErrors.clone(clone)); } if (collectionProcessCompleteErrors != null) { clone.setCollectionProcessCompleteErrors(collectionProcessCompleteErrors.clone(clone)); } return clone; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#buildFromXMLElement(org.w3c.dom.Element, org.apache.uima.util.XMLParser, org.apache.uima.util.XMLParser.ParsingOptions) */ public void buildFromXMLElement (Element aElement, XMLParser aParser, XMLParser.ParsingOptions aOptions) throws InvalidXMLException { String val; NodeList childNodes = aElement.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node curNode = childNodes.item(i); if (curNode instanceof Element) { Element elem = (Element)curNode; if (TAG_NAME.equalsIgnoreCase(elem.getTagName())) { setName(XMLUtils.getText(elem)); } else if (TAG_DESCRIPTION.equalsIgnoreCase(elem.getTagName())) { setDescription(XMLUtils.getText(elem)); } else if (TAG_VERSION.equalsIgnoreCase(elem.getTagName())) { setVersion(XMLUtils.getText(elem)); } else if (TAG_VENDOR.equalsIgnoreCase(elem.getTagName())) { setVendor(XMLUtils.getText(elem)); } else if (TAG_IMPORT.equalsIgnoreCase(elem.getTagName())) { String topDescr = ""; if (elem.getAttribute(TAG_ATTR_LOCATION) != null) { // Trace.err("An import location=" + ((Element)n).getAttribute(TAG_ATTR_LOCATION)); topDescr = elem.getAttribute(TAG_ATTR_LOCATION); setImportByLocation(true); } else if (elem.getAttribute(TAG_ATTR_NAME) != null) { topDescr = elem.getAttribute(TAG_ATTR_NAME); } else { throw new InvalidXMLException( InvalidXMLException.UNKNOWN_ELEMENT, new Object[]{elem.getTagName()}); } setHasImport(true); setImportedDescriptor(topDescr); } else if (TAG_GET_METADATA_ERRORS.equalsIgnoreCase(elem.getTagName())) { setAttributesForGetMetadataErrors(elem); } else if (TAG_PROCESS_CAS_ERRORS.equalsIgnoreCase(elem.getTagName())) { setAttributesForProcessCasErrors(elem); } else if (TAG_COLLECTION_PROCESS_COMPLETE_ERRORS.equalsIgnoreCase(elem.getTagName())) { setAttributesForCollectionProcessCompleteErrors(elem); } else { throw new InvalidXMLException( InvalidXMLException.UNKNOWN_ELEMENT, new Object[]{elem.getTagName()}); } } } } protected void setAttributesForGetMetadataErrors (Element aElement) throws InvalidXMLException { NamedNodeMap map = aElement.getAttributes(); if (map != null) { for (int i=0; i<map.getLength(); ++i) { Node item = map.item(i); String name = item.getNodeName(); String val = item.getNodeValue(); if (val == null) { val = ""; } else { val = val.trim(); } if (TAG_ATTR_MAX_RETRIES.equalsIgnoreCase(name)) { if (val.length() > 0) { getMetadataErrors.setMaxRetries(Integer.parseInt(val)); } } else if (TAG_ATTR_TIMEOUT.equalsIgnoreCase(name)) { if (val.length() > 0) { getMetadataErrors.setTimeout(Integer.parseInt(val)); } } else if (TAG_ATTR_ERROR_ACTION.equalsIgnoreCase(name)) { if (val.length() > 0) { getMetadataErrors.setErrorAction(val); } } else { throw new InvalidXMLException(InvalidXMLException.UNKNOWN_ELEMENT, new Object[]{name}); } } } } protected void setAttributesForProcessCasErrors (Element aElement) throws InvalidXMLException { NamedNodeMap map = aElement.getAttributes(); if (map != null) { for (int i=0; i<map.getLength(); ++i) { Node item = map.item(i); String name = item.getNodeName(); String val = item.getNodeValue(); if (val == null) { val = ""; } else { val = val.trim(); } if (TAG_ATTR_MAX_RETRIES.equalsIgnoreCase(name)) { if (val.length() > 0) { processCasErrors.setMaxRetries(Integer.parseInt(val)); } } else if (TAG_ATTR_TIMEOUT.equalsIgnoreCase(name)) { if (val.length() > 0) { processCasErrors.setTimeout(Integer.parseInt(val)); } } else if (TAG_ATTR_ERROR_ACTION.equalsIgnoreCase(name)) { if (val.length() > 0) { getMetadataErrors.setErrorAction(val); } } else if (TAG_ATTR_CONTINUE_ON_RETRY_FAILURE.equalsIgnoreCase(name)) { if (val.length() > 0) { processCasErrors.setContinueOnRetryFailure(Boolean.parseBoolean(val)); } } else if (TAG_ATTR_THRESHOLD_COUNT.equalsIgnoreCase(name)) { if (val.length() > 0) { processCasErrors.setThresholdCount(Integer.parseInt(val)); } } else if (TAG_ATTR_THRESHOLD_WINDOW.equalsIgnoreCase(name)) { if (val.length() > 0) { processCasErrors.setThresholdWindow(Integer.parseInt(val)); } } else if (TAG_ATTR_THRESHOLD_ACTION.equalsIgnoreCase(name)) { if (val.length() > 0) { processCasErrors.setThresholdAction(val); } } else { throw new InvalidXMLException(InvalidXMLException.UNKNOWN_ELEMENT, new Object[]{name}); } } } } protected void setAttributesForCollectionProcessCompleteErrors (Element aElement) throws InvalidXMLException { NamedNodeMap map = aElement.getAttributes(); if (map != null) { for (int i=0; i<map.getLength(); ++i) { Node item = map.item(i); String name = item.getNodeName(); String val = item.getNodeValue(); if (val == null) { val = ""; } else { val = val.trim(); } if (TAG_ATTR_TIMEOUT.equalsIgnoreCase(name)) { if (val.length() > 0) { collectionProcessCompleteErrors.setTimeout(Integer.parseInt(val)); } } else if (TAG_ATTR_ADDITIONAL_ERROR_ACTION.equalsIgnoreCase(name)) { if (val.length() > 0) { collectionProcessCompleteErrors.setAdditionalErrorAction(val); } } else { throw new InvalidXMLException(InvalidXMLException.UNKNOWN_ELEMENT, new Object[]{name}); } } } } /*************************************************************************/ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#toXML(org.xml.sax.ContentHandler, boolean) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#toXML(org.xml.sax.ContentHandler, boolean) */ public void toXML(ContentHandler aContentHandler, boolean aWriteDefaultNamespaceAttribute) throws SAXException { AttributesImpl attrs = new AttributesImpl(); aContentHandler.startElement("", TAG_ASYNC_AGGREGATE_ERROR_CONFIGURATION, TAG_ASYNC_AGGREGATE_ERROR_CONFIGURATION, attrs); /* // <name> </name> aContentHandler.startElement("", "", "name", attrs); String valStr = getName(); aContentHandler.characters(valStr.toCharArray(), 0, valStr.length()); aContentHandler.endElement("", "", "name"); // <description> </description> aContentHandler.startElement("", "", TAG_DESCRIPTION,attrs); valStr = getDescription(); aContentHandler.characters(valStr.toCharArray(), 0, valStr.length()); aContentHandler.endElement("", "", TAG_DESCRIPTION); // <version> </version> aContentHandler.startElement("", "","version",attrs); valStr = getVersion(); aContentHandler.characters(valStr.toCharArray(), 0, valStr.length()); aContentHandler.endElement("", "", "version"); // <vendor> </vendor> aContentHandler.startElement("", "", "vendor", attrs); valStr = getVendor(); aContentHandler.characters(valStr.toCharArray(), 0, valStr.length()); aContentHandler.endElement("", "", "vendor"); */ // <import location=.../> if ( hasImport ) { if (isImportByLocation()) { attrs.addAttribute("", TAG_ATTR_LOCATION, TAG_ATTR_LOCATION, null, getImportedDescriptor()); } else { attrs.addAttribute("", TAG_ATTR_NAME, TAG_ATTR_NAME, null, getImportedDescriptor()); } aContentHandler.startElement("", TAG_IMPORT, TAG_IMPORT, attrs); aContentHandler.endElement("", "", TAG_IMPORT); attrs.clear(); } // <GetMetadataErrors ...> if (getMetadataErrors != null) { attrs.addAttribute("", TAG_ATTR_MAX_RETRIES, TAG_ATTR_MAX_RETRIES, null, Integer.toString(getMetadataErrors.getMaxRetries())); attrs.addAttribute("", TAG_ATTR_TIMEOUT, TAG_ATTR_TIMEOUT, null, Integer.toString(getMetadataErrors.getTimeout())); attrs.addAttribute("", TAG_ATTR_ERROR_ACTION, TAG_ATTR_ERROR_ACTION, null, getMetadataErrors.getErrorAction()); aContentHandler.startElement("", TAG_GET_METADATA_ERRORS, TAG_GET_METADATA_ERRORS, attrs); aContentHandler.endElement("", "", TAG_GET_METADATA_ERRORS); attrs.clear(); } // <ProcessCasErrors ...> if (processCasErrors != null) { attrs.addAttribute("", TAG_ATTR_MAX_RETRIES, TAG_ATTR_MAX_RETRIES, null, Integer.toString(processCasErrors.getMaxRetries())); attrs.addAttribute("", TAG_ATTR_TIMEOUT, TAG_ATTR_TIMEOUT, null, Integer.toString(processCasErrors.getTimeout())); attrs.addAttribute("", TAG_ATTR_CONTINUE_ON_RETRY_FAILURE, TAG_ATTR_CONTINUE_ON_RETRY_FAILURE, null, Boolean.toString(processCasErrors.isContinueOnRetryFailure())); attrs.addAttribute("", TAG_ATTR_THRESHOLD_COUNT, TAG_ATTR_THRESHOLD_COUNT, null, Integer.toString(processCasErrors.getThresholdCount())); attrs.addAttribute("", TAG_ATTR_THRESHOLD_WINDOW, TAG_ATTR_THRESHOLD_WINDOW, null, Integer.toString(processCasErrors.getThresholdWindow())); attrs.addAttribute("", TAG_ATTR_THRESHOLD_ACTION, TAG_ATTR_THRESHOLD_ACTION, null, processCasErrors.getThresholdAction()); aContentHandler.startElement("", TAG_PROCESS_CAS_ERRORS, TAG_PROCESS_CAS_ERRORS, attrs); aContentHandler.endElement("", "", TAG_PROCESS_CAS_ERRORS); attrs.clear(); } // <CollectionProcessCompleteErrors ...> if (collectionProcessCompleteErrors != null) { attrs.addAttribute("", TAG_ATTR_TIMEOUT, TAG_ATTR_TIMEOUT, null, Integer.toString(collectionProcessCompleteErrors.getTimeout())); attrs.addAttribute("", TAG_ATTR_ADDITIONAL_ERROR_ACTION, TAG_ATTR_ADDITIONAL_ERROR_ACTION, null, collectionProcessCompleteErrors.getAdditionalErrorAction()); aContentHandler.startElement("", TAG_COLLECTION_PROCESS_COMPLETE_ERRORS, TAG_COLLECTION_PROCESS_COMPLETE_ERRORS, attrs); aContentHandler.endElement("", "", TAG_COLLECTION_PROCESS_COMPLETE_ERRORS); attrs.clear(); } aContentHandler.endElement("", "", TAG_ASYNC_AGGREGATE_ERROR_CONFIGURATION); } @Override protected XmlizationInfo getXmlizationInfo() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#getCollectionProcessCompleteErrors() */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#getCollectionProcessCompleteErrors() */ public CollectionProcessCompleteErrors getCollectionProcessCompleteErrors() { return collectionProcessCompleteErrors; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#setCollectionProcessCompleteErrors(com.ibm.uima.aae.deployment.CollectionProcessCompleteErrors) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#setCollectionProcessCompleteErrors(com.ibm.uima.aae.deployment.CollectionProcessCompleteErrors) */ public void setCollectionProcessCompleteErrors( CollectionProcessCompleteErrors collectionProcessCompleteErrors) { this.collectionProcessCompleteErrors = collectionProcessCompleteErrors; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#getDescription() */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#getDescription() */ public String getDescription() { return description; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#setDescription(java.lang.String) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#setDescription(java.lang.String) */ public void setDescription(String description) { this.description = description; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#getGetMetadataErrors() */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#getGetMetadataErrors() */ public GetMetadataErrors getGetMetadataErrors() { return getMetadataErrors; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#setGetMetadataErrors(com.ibm.uima.aae.deployment.GetMetadataErrors) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#setGetMetadataErrors(com.ibm.uima.aae.deployment.GetMetadataErrors) */ public void setGetMetadataErrors(GetMetadataErrors getMetadataErrors) { this.getMetadataErrors = getMetadataErrors; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#getName() */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#getName() */ public String getName() { return name; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#setName(java.lang.String) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#setName(java.lang.String) */ public void setName(String name) { this.name = name; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#getProcessCasErrors() */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#getProcessCasErrors() */ public ProcessCasErrors getProcessCasErrors() { return processCasErrors; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#setProcessCasErrors(com.ibm.uima.aae.deployment.ProcessCasErrors) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#setProcessCasErrors(com.ibm.uima.aae.deployment.ProcessCasErrors) */ public void setProcessCasErrors(ProcessCasErrors processCasErrors) { this.processCasErrors = processCasErrors; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#getVendor() */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#getVendor() */ public String getVendor() { return vendor; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#setVendor(java.lang.String) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#setVendor(java.lang.String) */ public void setVendor(String vendor) { this.vendor = vendor; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#getVersion() */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#getVersion() */ public String getVersion() { return version; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#setVersion(java.lang.String) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#setVersion(java.lang.String) */ public void setVersion(String version) { this.version = version; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#hasImport() */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#hasImport() */ public boolean hasImport() { return hasImport; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#setHasImport(boolean) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#setHasImport(boolean) */ public void setHasImport(boolean hasImport) { this.hasImport = hasImport; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#isImportByLocation() */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#isImportByLocation() */ public boolean isImportByLocation() { return importByLocation; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#setImportByLocation(boolean) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#setImportByLocation(boolean) */ public void setImportByLocation(boolean importByLocation) { this.importByLocation = importByLocation; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#getImportedDescriptor() */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#getImportedDescriptor() */ public String getImportedDescriptor() { return importedDescriptor; } /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncPrimitiveErrorConfiguration#setImportedDescriptor(java.lang.String) */ /* (non-Javadoc) * @see com.ibm.uima.aae.deployment.impl.AsyncAEErrorConfiguration#setImportedDescriptor(java.lang.String) */ public void setImportedDescriptor(String importedDescriptor) { this.importedDescriptor = importedDescriptor; } /** * @return the parentObject */ public DeploymentMetaData_Impl gParentObject() { return parentObject; } /** * @param parentObject the parentObject to set */ public void sParentObject(DeploymentMetaData_Impl parentObject) { this.parentObject = parentObject; } /*************************************************************************/ }
3e144ff09fddd9bdededc8696db580bb3f985f54
20,400
java
Java
modules/activiti-engine/src/main/java/org/activiti/engine/impl/db/DbSqlSessionFactory.java
cloudcube/Activiti
23e96a608c77e60476d1dcede90e4ef34b472473
[ "Apache-1.1" ]
1
2016-03-22T03:40:18.000Z
2016-03-22T03:40:18.000Z
modules/activiti-engine/src/main/java/org/activiti/engine/impl/db/DbSqlSessionFactory.java
orzeh/Activiti
ae303d85b51a860545243c21220b8b7554996920
[ "Apache-1.1" ]
null
null
null
modules/activiti-engine/src/main/java/org/activiti/engine/impl/db/DbSqlSessionFactory.java
orzeh/Activiti
ae303d85b51a860545243c21220b8b7554996920
[ "Apache-1.1" ]
null
null
null
52.713178
179
0.784363
8,601
/* 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 org.activiti.engine.impl.db; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.activiti.engine.impl.cfg.IdGenerator; import org.activiti.engine.impl.interceptor.Session; import org.activiti.engine.impl.interceptor.SessionFactory; import org.apache.ibatis.session.SqlSessionFactory; /** * @author Tom Baeyens */ public class DbSqlSessionFactory implements SessionFactory { protected static final Map<String, Map<String, String>> databaseSpecificStatements = new HashMap<String, Map<String,String>>(); public static final Map<String, String> databaseSpecificLimitBeforeStatements = new HashMap<String, String>(); public static final Map<String, String> databaseSpecificLimitAfterStatements = new HashMap<String, String>(); public static final Map<String, String> databaseSpecificLimitBetweenStatements = new HashMap<String, String>(); public static final Map<String, String> databaseSpecificOrderByStatements = new HashMap<String, String>(); public static final Map<String, String> databaseOuterJoinLimitBetweenStatements = new HashMap<String, String>(); public static final Map<String, String> databaseSpecificLimitBeforeNativeQueryStatements = new HashMap<String, String>(); static { String defaultOrderBy = " order by ${orderBy} "; // h2 databaseSpecificLimitBeforeStatements.put("h2", ""); databaseSpecificLimitAfterStatements.put("h2", "LIMIT #{maxResults} OFFSET #{firstResult}"); databaseSpecificLimitBetweenStatements.put("h2", ""); databaseOuterJoinLimitBetweenStatements.put("h2", ""); databaseSpecificOrderByStatements.put("h2", defaultOrderBy); //mysql specific databaseSpecificLimitBeforeStatements.put("mysql", ""); databaseSpecificLimitAfterStatements.put("mysql", "LIMIT #{maxResults} OFFSET #{firstResult}"); databaseSpecificLimitBetweenStatements.put("mysql", ""); databaseOuterJoinLimitBetweenStatements.put("mysql", ""); databaseSpecificOrderByStatements.put("mysql", defaultOrderBy); addDatabaseSpecificStatement("mysql", "selectProcessDefinitionsByQueryCriteria", "selectProcessDefinitionsByQueryCriteria_mysql"); addDatabaseSpecificStatement("mysql", "selectProcessDefinitionCountByQueryCriteria", "selectProcessDefinitionCountByQueryCriteria_mysql"); addDatabaseSpecificStatement("mysql", "selectDeploymentsByQueryCriteria", "selectDeploymentsByQueryCriteria_mysql"); addDatabaseSpecificStatement("mysql", "selectDeploymentCountByQueryCriteria", "selectDeploymentCountByQueryCriteria_mysql"); addDatabaseSpecificStatement("mysql", "selectModelCountByQueryCriteria", "selectModelCountByQueryCriteria_mysql"); addDatabaseSpecificStatement("mysql", "updateExecutionTenantIdForDeployment", "updateExecutionTenantIdForDeployment_mysql"); addDatabaseSpecificStatement("mysql", "updateTaskTenantIdForDeployment", "updateTaskTenantIdForDeployment_mysql"); addDatabaseSpecificStatement("mysql", "updateJobTenantIdForDeployment", "updateJobTenantIdForDeployment_mysql"); //postgres specific databaseSpecificLimitBeforeStatements.put("postgres", ""); databaseSpecificLimitAfterStatements.put("postgres", "LIMIT #{maxResults} OFFSET #{firstResult}"); databaseSpecificLimitBetweenStatements.put("postgres", ""); databaseOuterJoinLimitBetweenStatements.put("postgres", ""); databaseSpecificOrderByStatements.put("postgres", defaultOrderBy); addDatabaseSpecificStatement("postgres", "insertByteArray", "insertByteArray_postgres"); addDatabaseSpecificStatement("postgres", "updateByteArray", "updateByteArray_postgres"); addDatabaseSpecificStatement("postgres", "selectByteArray", "selectByteArray_postgres"); addDatabaseSpecificStatement("postgres", "selectResourceByDeploymentIdAndResourceName", "selectResourceByDeploymentIdAndResourceName_postgres"); addDatabaseSpecificStatement("postgres", "selectResourcesByDeploymentId", "selectResourcesByDeploymentId_postgres"); addDatabaseSpecificStatement("postgres", "insertIdentityInfo", "insertIdentityInfo_postgres"); addDatabaseSpecificStatement("postgres", "updateIdentityInfo", "updateIdentityInfo_postgres"); addDatabaseSpecificStatement("postgres", "selectIdentityInfoById", "selectIdentityInfoById_postgres"); addDatabaseSpecificStatement("postgres", "selectIdentityInfoByUserIdAndKey", "selectIdentityInfoByUserIdAndKey_postgres"); addDatabaseSpecificStatement("postgres", "selectIdentityInfoByUserId", "selectIdentityInfoByUserId_postgres"); addDatabaseSpecificStatement("postgres", "selectIdentityInfoDetails", "selectIdentityInfoDetails_postgres"); addDatabaseSpecificStatement("postgres", "insertComment", "insertComment_postgres"); addDatabaseSpecificStatement("postgres", "selectComment", "selectComment_postgres"); addDatabaseSpecificStatement("postgres", "selectCommentsByTaskId", "selectCommentsByTaskId_postgres"); addDatabaseSpecificStatement("postgres", "selectCommentsByProcessInstanceId", "selectCommentsByProcessInstanceId_postgres"); addDatabaseSpecificStatement("postgres", "selectCommentsByProcessInstanceIdAndType", "selectCommentsByProcessInstanceIdAndType_postgres"); addDatabaseSpecificStatement("postgres", "selectCommentsByType", "selectCommentsByType_postgres"); addDatabaseSpecificStatement("postgres", "selectCommentsByTaskIdAndType", "selectCommentsByTaskIdAndType_postgres"); addDatabaseSpecificStatement("postgres", "selectEventsByTaskId", "selectEventsByTaskId_postgres"); addDatabaseSpecificStatement("postgres", "insertEventLogEntry", "insertEventLogEntry_postgres"); addDatabaseSpecificStatement("postgres", "selectAllEventLogEntries", "selectAllEventLogEntries_postgres"); addDatabaseSpecificStatement("postgres", "selectEventLogEntries", "selectEventLogEntries_postgres"); addDatabaseSpecificStatement("postgres", "selectEventLogEntriesByProcessInstanceId", "selectEventLogEntriesByProcessInstanceId_postgres"); // oracle databaseSpecificLimitBeforeStatements.put("oracle", "select * from ( select a.*, ROWNUM rnum from ("); databaseSpecificLimitAfterStatements.put("oracle", " ) a where ROWNUM < #{lastRow}) where rnum >= #{firstRow}"); databaseSpecificLimitBetweenStatements.put("oracle", ""); databaseOuterJoinLimitBetweenStatements.put("oracle", ""); databaseSpecificOrderByStatements.put("oracle", defaultOrderBy); addDatabaseSpecificStatement("oracle", "selectExclusiveJobsToExecute", "selectExclusiveJobsToExecute_integerBoolean"); addDatabaseSpecificStatement("oracle", "selectUnlockedTimersByDuedate", "selectUnlockedTimersByDuedate_oracle"); addDatabaseSpecificStatement("oracle", "insertEventLogEntry", "insertEventLogEntry_oracle"); // db2 databaseSpecificLimitBeforeStatements.put("db2", "SELECT SUB.* FROM ("); databaseSpecificLimitAfterStatements.put("db2", ")RES ) SUB WHERE SUB.rnk >= #{firstRow} AND SUB.rnk < #{lastRow}"); databaseSpecificLimitBetweenStatements.put("db2", ", row_number() over (ORDER BY ${orderBy}) rnk FROM ( select distinct RES.* "); databaseOuterJoinLimitBetweenStatements.put("db2", ", row_number() over (ORDER BY ${mssqlOrDB2OrderBy}) rnk FROM ( select distinct "); databaseSpecificOrderByStatements.put("db2", ""); databaseSpecificLimitBeforeNativeQueryStatements.put("db2", "SELECT SUB.* FROM ( select RES.* , row_number() over (ORDER BY ${orderBy}) rnk FROM ("); addDatabaseSpecificStatement("db2", "selectExclusiveJobsToExecute", "selectExclusiveJobsToExecute_integerBoolean"); addDatabaseSpecificStatement("db2", "selectExecutionByNativeQuery", "selectExecutionByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectHistoricActivityInstanceByNativeQuery", "selectHistoricActivityInstanceByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectHistoricProcessInstanceByNativeQuery", "selectHistoricProcessInstanceByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectHistoricTaskInstanceByNativeQuery", "selectHistoricTaskInstanceByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectTaskByNativeQuery", "selectTaskByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectProcessDefinitionByNativeQuery", "selectProcessDefinitionByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectDeploymentByNativeQuery", "selectDeploymentByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectGroupByNativeQuery", "selectGroupByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectUserByNativeQuery", "selectUserByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectModelByNativeQuery", "selectModelByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectHistoricDetailByNativeQuery", "selectHistoricDetailByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectHistoricVariableInstanceByNativeQuery", "selectHistoricVariableInstanceByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectTaskWithVariablesByQueryCriteria", "selectTaskWithVariablesByQueryCriteria_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectProcessInstanceWithVariablesByQueryCriteria", "selectProcessInstanceWithVariablesByQueryCriteria_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectHistoricProcessInstancesWithVariablesByQueryCriteria", "selectHistoricProcessInstancesWithVariablesByQueryCriteria_mssql_or_db2"); addDatabaseSpecificStatement("db2", "selectHistoricTaskInstancesWithVariablesByQueryCriteria", "selectHistoricTaskInstancesWithVariablesByQueryCriteria_mssql_or_db2"); // mssql databaseSpecificLimitBeforeStatements.put("mssql", "SELECT SUB.* FROM ("); databaseSpecificLimitAfterStatements.put("mssql", ")RES ) SUB WHERE SUB.rnk >= #{firstRow} AND SUB.rnk < #{lastRow}"); databaseSpecificLimitBetweenStatements.put("mssql", ", row_number() over (ORDER BY ${orderBy}) rnk FROM ( select distinct RES.* "); databaseOuterJoinLimitBetweenStatements.put("mssql", ", row_number() over (ORDER BY ${mssqlOrDB2OrderBy}) rnk FROM ( select distinct "); databaseSpecificOrderByStatements.put("mssql", ""); databaseSpecificLimitBeforeNativeQueryStatements.put("mssql", "SELECT SUB.* FROM ( select RES.* , row_number() over (ORDER BY ${orderBy}) rnk FROM ("); addDatabaseSpecificStatement("mssql", "selectExclusiveJobsToExecute", "selectExclusiveJobsToExecute_integerBoolean"); addDatabaseSpecificStatement("mssql", "selectExecutionByNativeQuery", "selectExecutionByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectHistoricActivityInstanceByNativeQuery", "selectHistoricActivityInstanceByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectHistoricProcessInstanceByNativeQuery", "selectHistoricProcessInstanceByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectHistoricTaskInstanceByNativeQuery", "selectHistoricTaskInstanceByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectTaskByNativeQuery", "selectTaskByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectProcessDefinitionByNativeQuery", "selectProcessDefinitionByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectDeploymentByNativeQuery", "selectDeploymentByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectGroupByNativeQuery", "selectGroupByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectUserByNativeQuery", "selectUserByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectModelByNativeQuery", "selectModelByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectHistoricDetailByNativeQuery", "selectHistoricDetailByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectHistoricVariableInstanceByNativeQuery", "selectHistoricVariableInstanceByNativeQuery_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectTaskWithVariablesByQueryCriteria", "selectTaskWithVariablesByQueryCriteria_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectProcessInstanceWithVariablesByQueryCriteria", "selectProcessInstanceWithVariablesByQueryCriteria_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectHistoricProcessInstancesWithVariablesByQueryCriteria", "selectHistoricProcessInstancesWithVariablesByQueryCriteria_mssql_or_db2"); addDatabaseSpecificStatement("mssql", "selectHistoricTaskInstancesWithVariablesByQueryCriteria", "selectHistoricTaskInstancesWithVariablesByQueryCriteria_mssql_or_db2"); } protected String databaseType; protected String databaseTablePrefix = ""; private boolean tablePrefixIsSchema; protected String databaseCatalog; /** * In some situations you want to set the schema to use for table checks / * generation if the database metadata doesn't return that correctly, see * https://jira.codehaus.org/browse/ACT-1220, * https://jira.codehaus.org/browse/ACT-1062 */ protected String databaseSchema; protected SqlSessionFactory sqlSessionFactory; protected IdGenerator idGenerator; protected Map<String, String> statementMappings; protected Map<Class<?>,String> insertStatements = new ConcurrentHashMap<Class<?>, String>(); protected Map<Class<?>,String> updateStatements = new ConcurrentHashMap<Class<?>, String>(); protected Map<Class<?>,String> deleteStatements = new ConcurrentHashMap<Class<?>, String>(); protected Map<Class<?>,String> bulkDeleteStatements = new ConcurrentHashMap<Class<?>, String>(); protected Map<Class<?>,String> selectStatements = new ConcurrentHashMap<Class<?>, String>(); protected boolean isDbIdentityUsed = true; protected boolean isDbHistoryUsed = true; protected boolean isOptimizeDeleteOperationsEnabled; public Class< ? > getSessionType() { return DbSqlSession.class; } public Session openSession() { return new DbSqlSession(this); } // insert, update and delete statements ///////////////////////////////////// public String getInsertStatement(PersistentObject object) { return getStatement(object.getClass(), insertStatements, "insert"); } public String getUpdateStatement(PersistentObject object) { return getStatement(object.getClass(), updateStatements, "update"); } public String getDeleteStatement(Class<?> persistentObjectClass) { return getStatement(persistentObjectClass, deleteStatements, "delete"); } public String getBulkDeleteStatement(Class<?> persistentObjectClass) { return getStatement(persistentObjectClass, bulkDeleteStatements, "bulkDelete"); } public String getSelectStatement(Class<?> persistentObjectClass) { return getStatement(persistentObjectClass, selectStatements, "select"); } private String getStatement(Class<?> persistentObjectClass, Map<Class<?>,String> cachedStatements, String prefix) { String statement = cachedStatements.get(persistentObjectClass); if (statement!=null) { return statement; } statement = prefix + persistentObjectClass.getSimpleName(); statement = statement.substring(0, statement.length()-6); // removing 'entity' cachedStatements.put(persistentObjectClass, statement); return statement; } // db specific mappings ///////////////////////////////////////////////////// protected static void addDatabaseSpecificStatement(String databaseType, String activitiStatement, String ibatisStatement) { Map<String, String> specificStatements = databaseSpecificStatements.get(databaseType); if (specificStatements == null) { specificStatements = new HashMap<String, String>(); databaseSpecificStatements.put(databaseType, specificStatements); } specificStatements.put(activitiStatement, ibatisStatement); } public String mapStatement(String statement) { if (statementMappings==null) { return statement; } String mappedStatement = statementMappings.get(statement); return (mappedStatement!=null ? mappedStatement : statement); } // customized getters and setters /////////////////////////////////////////// public void setDatabaseType(String databaseType) { this.databaseType = databaseType; this.statementMappings = databaseSpecificStatements.get(databaseType); } // getters and setters ////////////////////////////////////////////////////// public SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } public String getDatabaseType() { return databaseType; } public Map<String, String> getStatementMappings() { return statementMappings; } public void setStatementMappings(Map<String, String> statementMappings) { this.statementMappings = statementMappings; } public Map<Class< ? >, String> getInsertStatements() { return insertStatements; } public void setInsertStatements(Map<Class< ? >, String> insertStatements) { this.insertStatements = insertStatements; } public Map<Class< ? >, String> getUpdateStatements() { return updateStatements; } public void setUpdateStatements(Map<Class< ? >, String> updateStatements) { this.updateStatements = updateStatements; } public Map<Class< ? >, String> getDeleteStatements() { return deleteStatements; } public void setDeleteStatements(Map<Class< ? >, String> deleteStatements) { this.deleteStatements = deleteStatements; } public Map<Class<?>, String> getBulkDeleteStatements() { return bulkDeleteStatements; } public void setBulkDeleteStatements(Map<Class<?>, String> bulkDeleteStatements) { this.bulkDeleteStatements = bulkDeleteStatements; } public Map<Class< ? >, String> getSelectStatements() { return selectStatements; } public void setSelectStatements(Map<Class< ? >, String> selectStatements) { this.selectStatements = selectStatements; } public boolean isDbIdentityUsed() { return isDbIdentityUsed; } public void setDbIdentityUsed(boolean isDbIdentityUsed) { this.isDbIdentityUsed = isDbIdentityUsed; } public boolean isDbHistoryUsed() { return isDbHistoryUsed; } public void setDbHistoryUsed(boolean isDbHistoryUsed) { this.isDbHistoryUsed = isDbHistoryUsed; } public void setDatabaseTablePrefix(String databaseTablePrefix) { this.databaseTablePrefix = databaseTablePrefix; } public String getDatabaseTablePrefix() { return databaseTablePrefix; } public String getDatabaseCatalog() { return databaseCatalog; } public void setDatabaseCatalog(String databaseCatalog) { this.databaseCatalog = databaseCatalog; } public String getDatabaseSchema() { return databaseSchema; } public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } public void setTablePrefixIsSchema(boolean tablePrefixIsSchema) { this.tablePrefixIsSchema = tablePrefixIsSchema; } public boolean isTablePrefixIsSchema() { return tablePrefixIsSchema; } public boolean isOptimizeDeleteOperationsEnabled() { return isOptimizeDeleteOperationsEnabled; } public void setOptimizeDeleteOperationsEnabled(boolean isOptimizeDeleteOperationsEnabled) { this.isOptimizeDeleteOperationsEnabled = isOptimizeDeleteOperationsEnabled; } }
3e1450b43c258ad056bff7a78a0f5ddfa81ca838
31,968
java
Java
app/src/main/java/com/jiangdg/usbcamera/CameraPresenter.java
WeizhiKong/AndroidUSBCamera
00c0202c2ade6cbc675a62786dca83cc8b428b42
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/jiangdg/usbcamera/CameraPresenter.java
WeizhiKong/AndroidUSBCamera
00c0202c2ade6cbc675a62786dca83cc8b428b42
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/jiangdg/usbcamera/CameraPresenter.java
WeizhiKong/AndroidUSBCamera
00c0202c2ade6cbc675a62786dca83cc8b428b42
[ "Apache-2.0" ]
null
null
null
28.930317
130
0.539446
8,602
package com.jiangdg.usbcamera; import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.ImageFormat; import android.graphics.Matrix; import android.graphics.RectF; import android.hardware.Camera; import android.media.CamcorderProfile; import android.media.MediaRecorder; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.DisplayMetrics; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import com.jiangdg.usbcamera.utils.CameraHelper; //import com.jiangdg.usbcamera.utils.ImageUtil; import com.jiangdg.usbcamera.utils.SystemUtil; import com.jiangdg.usbcamera.utils.ThreadPoolUtil; import com.jiangdg.usbcamera.utils.ToastUtil; import com.jiangdg.usbcamera.view.CustomCameraActivity; import com.jiangdg.usbcamera.view.FaceDeteView; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import androidx.appcompat.app.AppCompatActivity; /** * @author created by knight * @organize * @Date 2019/9/24 18:29 * @descript: */ public class CameraPresenter implements Camera.PreviewCallback { //相机对象 private Camera mCamera; //相机对象参数设置 private Camera.Parameters mParameters; //自定义照相机页面 private AppCompatActivity mAppCompatActivity; //surfaceView 用于预览对象 private SurfaceView mSurfaceView; //SurfaceHolder对象 private SurfaceHolder mSurfaceHolder; //摄像头Id 默认后置 0,前置的值是1 private int mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK; //预览旋转的角度 private int orientation; //自定义回调 private CameraCallBack mCameraCallBack; //手机宽和高 private int screenWidth, screenHeight; //拍照数量 private int photoNum = 0; //拍照存放的文件 private File photosFile = null; //当前缩放具体值 private int mZoom; //视频录制 private MediaRecorder mediaRecorder; //录制视频的videoSize private int height,width; //检测头像的FaceView private FaceDeteView mFaceView; //视频连接 private String videoFilePath; CamcorderProfile profile; private boolean isFull =false; public boolean isFull() { return isFull; } public void setFull(boolean full) { isFull = full; } //自定义回调 public interface CameraCallBack { //预览帧回调 void onPreviewFrame(byte[] data, Camera camera); //拍照回调 void onTakePicture(byte[] data, Camera Camera); //人脸检测回调 void onFaceDetect(ArrayList<RectF> rectFArrayList, Camera camera); //拍照路径返回 void getPhotoFile(String imagePath); //返回视频路径 void getVideoFile(String videoFilePath); } public void setCameraCallBack(CameraCallBack mCameraCallBack) { this.mCameraCallBack = mCameraCallBack; } public CameraPresenter(CustomCameraActivity mAppCompatActivity, SurfaceView mSurfaceView) { this.mAppCompatActivity = mAppCompatActivity; this.mSurfaceView = mSurfaceView; // mSurfaceView.getHolder().setKeepScreenOn(true); mSurfaceHolder = mSurfaceView.getHolder(); DisplayMetrics dm = new DisplayMetrics(); mAppCompatActivity.getWindowManager().getDefaultDisplay().getMetrics(dm); //获取宽高像素 screenWidth = dm.widthPixels; screenHeight = dm.heightPixels; Log.d("sssd-手机宽高尺寸:",screenWidth +"*"+screenHeight); //创建文件夹目录 setUpFile(); init(); } /** * * 人脸检测设置检测的View 矩形框 * @param mFaceView */ public void setFaceView(FaceDeteView mFaceView){ this.mFaceView = mFaceView; } /** * 设置前置还是后置 * * @param mCameraId 前置还是后置 */ public void setFrontOrBack(int mCameraId) { this.mCameraId = mCameraId; } /** * 拍照 */ public void takePicture(final int takePhotoOrientation) { if (mCamera != null) { //拍照回调 点击拍照时回调 写一个空实现 mCamera.takePicture(new Camera.ShutterCallback() { @Override public void onShutter() { } }, new Camera.PictureCallback() { //回调没压缩的原始数据 @Override public void onPictureTaken(byte[] data, Camera camera) { } }, new Camera.PictureCallback() { //回调图片数据 点击拍照后相机返回的照片byte数组,照片数据 @Override public void onPictureTaken(byte[] data, Camera camera) { //拍照后记得调用预览方法,不然会停在拍照图像的界面 mCamera.startPreview(); //回调 mCameraCallBack.onTakePicture(data, camera); //保存图片 getPhotoPath(data,takePhotoOrientation); } }); } } /** * 初始化增加回调 */ public void init() { mSurfaceHolder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { Log.d("sssd-宽",mSurfaceView.getMeasuredWidth() + "*" +mSurfaceView.getMeasuredHeight()); //surface创建时执行 if (mCamera == null) { openCamera(mCameraId); } //并设置预览 startPreview(); //新增获取系统支持视频 getVideoSize(); mediaRecorder = new MediaRecorder(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { //surface绘制时执行 } @Override public void surfaceDestroyed(SurfaceHolder holder) { //surface销毁时执行 releaseCamera(); } }); } /** * 打开相机 并且判断是否支持该摄像头 * * @param FaceOrBack 前置还是后置 * @return */ private boolean openCamera(int FaceOrBack) { //是否支持前后摄像头 boolean isSupportCamera = isSupport(FaceOrBack); //如果支持 if (isSupportCamera) { try { mCamera = Camera.open(FaceOrBack); initParameters(mCamera); //设置预览回调 if (mCamera != null) { mCamera.setPreviewCallback(this); } } catch (Exception e) { e.printStackTrace(); ToastUtil.showShortToast(mAppCompatActivity, "打开相机失败~"); return false; } } mCamera = Camera.open(FaceOrBack); return isSupportCamera; } /** * 设置相机参数 * * @param camera */ private void initParameters(Camera camera) { try { //获取Parameters对象 mParameters = camera.getParameters(); //设置预览格式 mParameters.setPreviewFormat(ImageFormat.NV21); //mParameters.setExposureCompensation(2); if(isFull){ setPreviewSize(screenWidth,screenHeight); } else { setPreviewSize(mSurfaceView.getMeasuredWidth(),mSurfaceView.getMeasuredHeight()); } //getOpyimalPreviewSize(); setPictureSize(); //连续自动对焦图像 if (isSupportFocus(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } else if (isSupportFocus(Camera.Parameters.FOCUS_MODE_AUTO)) { //自动对焦(单次) mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); } //给相机设置参数 mCamera.setParameters(mParameters); } catch (Exception e) { e.printStackTrace(); ToastUtil.showShortToast(mAppCompatActivity, "初始化相机失败"); } } /** * * 设置保存图片的尺寸 */ private void setPictureSize() { List<Camera.Size> localSizes = mParameters.getSupportedPictureSizes(); Camera.Size biggestSize = null; Camera.Size fitSize = null;// 优先选预览界面的尺寸 Camera.Size previewSize = mParameters.getPreviewSize();//获取预览界面尺寸 float previewSizeScale = 0; if (previewSize != null) { previewSizeScale = previewSize.width / (float) previewSize.height; } if (localSizes != null) { int cameraSizeLength = localSizes.size(); for (int n = 0; n < cameraSizeLength; n++) { Camera.Size size = localSizes.get(n); if (biggestSize == null) { biggestSize = size; } else if (size.width >= biggestSize.width && size.height >= biggestSize.height) { biggestSize = size; } // 选出与预览界面等比的最高分辨率 if (previewSizeScale > 0 && size.width >= previewSize.width && size.height >= previewSize.height) { float sizeScale = size.width / (float) size.height; if (sizeScale == previewSizeScale) { if (fitSize == null) { fitSize = size; } else if (size.width >= fitSize.width && size.height >= fitSize.height) { fitSize = size; } } } } // 如果没有选出fitSize, 那么最大的Size就是FitSize if (fitSize == null) { fitSize = biggestSize; } mParameters.setPictureSize(fitSize.width, fitSize.height); } } /** * 设置预览界面尺寸 */ public void setPreviewSize(int width,int height) { //获取系统支持预览大小 List<Camera.Size> localSizes = mParameters.getSupportedPreviewSizes(); Camera.Size biggestSize = null;//最大分辨率 Camera.Size fitSize = null;// 优先选屏幕分辨率 Camera.Size targetSize = null;// 没有屏幕分辨率就取跟屏幕分辨率相近(大)的size Camera.Size targetSiz2 = null;// 没有屏幕分辨率就取跟屏幕分辨率相近(小)的size if (localSizes != null) { int cameraSizeLength = localSizes.size(); // 如果是 预览窗口宽:高 == 3:4的话 if(Float.valueOf(width) / height == 3.0f / 4){ for (int n = 0; n < cameraSizeLength; n++) { Camera.Size size = localSizes.get(n); if(Float.valueOf(size.width) / size.height == 4.0f / 3){ mParameters.setPreviewSize(size.width,size.height); break; } } } else { //全屏幕预览 for (int n = 0; n < cameraSizeLength; n++) { Camera.Size size = localSizes.get(n); if (biggestSize == null || (size.width >= biggestSize.width && size.height >= biggestSize.height)) { biggestSize = size; } //如果支持的比例都等于所获取到的宽高 if (size.width == height && size.height == width) { fitSize = size; //如果任一宽或者高等于所支持的尺寸 } else if (size.width == height || size.height == width) { if (targetSize == null) { targetSize = size; //如果上面条件都不成立 如果任一宽高小于所支持的尺寸 } else if (size.width < height || size.height < width) { targetSiz2 = size; } } } if (fitSize == null) { fitSize = targetSize; } if (fitSize == null) { fitSize = targetSiz2; } if (fitSize == null) { fitSize = biggestSize; } mParameters.setPreviewSize(fitSize.width, fitSize.height); fixScreenSize(fitSize.height,fitSize.width); } } } /** * 解决预览变形问题 * * */ private void getOpyimalPreviewSize(){ List<Camera.Size> sizes = mParameters.getSupportedPreviewSizes(); int w = screenWidth; int h = screenHeight; final double ASPECT_TOLERANCE = 0.1; double targetRatio = (double) w / h; if (sizes == null) return; Camera.Size optimalSize = null; double minDiff = Double.MAX_VALUE; int targetHeight = h; for(Camera.Size size : sizes){ double ratio = (double) size.width / size.height; if(Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;; if(Math.abs(size.height - targetHeight) < minDiff){ optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } if(optimalSize == null){ minDiff = Double.MAX_VALUE; for(Camera.Size size : sizes){ if(Math.abs(size.height - targetHeight) < minDiff){ optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } } mParameters.setPreviewSize(optimalSize.width,optimalSize.height); } /** * 变焦 * @param zoom 缩放系数 */ public void setZoom(int zoom){ if(mCamera == null){ return; } //获取Paramters对象 Camera.Parameters parameters; parameters = mCamera.getParameters(); //如果不支持变焦 if(!parameters.isZoomSupported()){ return; } // parameters.setZoom(zoom); //Camera对象重新设置Paramters对象参数 mCamera.setParameters(parameters); mZoom = zoom; } /** * * 返回缩放值 * @return 返回缩放值 */ public int getZoom(){ return mZoom; } /** * 获取最大Zoom值 * @return zoom */ public int getMaxZoom(){ if(mCamera == null){ return -1; } Camera.Parameters parameters = mCamera.getParameters(); if(!parameters.isZoomSupported()){ return -1; } return parameters.getMaxZoom() > 50 ? 50 : parameters.getMaxZoom(); } /** * 判断是否支持对焦模式 * * @return */ private boolean isSupportFocus(String focusMode) { boolean isSupport = false; //获取所支持对焦模式 List<String> listFocus = mParameters.getSupportedFocusModes(); for (String s : listFocus) { //如果存在 返回true if (s.equals(focusMode)) { isSupport = true; } } return isSupport; } /** * 判断是否支持某个相机 * * @param faceOrBack 前置还是后置 * @return */ private boolean isSupport(int faceOrBack) { Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); for (int i = 0; i < Camera.getNumberOfCameras(); i++) { //返回相机信息 Camera.getCameraInfo(i, cameraInfo); if (cameraInfo.facing == faceOrBack) { return true; } } return false; } @Override public void onPreviewFrame(byte[] data, Camera camera) { if (mCameraCallBack != null) { mCameraCallBack.onPreviewFrame(data, camera); } } /** * 开始预览 */ private void startPreview() { try { //根据所传入的SurfaceHolder对象来设置实时预览 mCamera.setPreviewDisplay(mSurfaceHolder); //调整预览角度 setCameraDisplayOrientation(mAppCompatActivity,mCameraId,mCamera); mCamera.startPreview(); //开启人脸检测 // startFaceDetect(); } catch (IOException e) { e.printStackTrace(); } } /** * 人脸检测 */ private void startFaceDetect() { //开始人脸检测,这个要调用startPreview之后调用 // mCamera.startFaceDetection(); // //添加回调 // mCamera.setFaceDetectionListener(new Camera.FaceDetectionListener() { // @Override // public void onFaceDetection(Camera.Face[] faces, Camera camera) { // // mCameraCallBack.onFaceDetect(transForm(faces), camera); // mFaceView.setFace(transForm(faces)); // Log.d("sssd", "检测到" + faces.length + "人脸"); // for(int i = 0;i < faces.length;i++){ // Log.d("第"+(i+1)+"张人脸","分数"+faces[i].score+"左眼"+faces[i].leftEye+"右眼"+faces[i].rightEye+"嘴巴"+faces[i].mouth); // } // } // }); } /** * 将相机中用于表示人脸矩形的坐标转换成UI页面的坐标 * * @param faces 人脸数组 * @return */ private ArrayList<RectF> transForm(Camera.Face[] faces) { Matrix matrix = new Matrix(); boolean mirror; if (mCameraId == Camera.CameraInfo.CAMERA_FACING_FRONT) { mirror = true; } else { mirror = false; } //前置需要镜像 if (mirror) { matrix.setScale(-1f, 1f); } else { matrix.setScale(1f, 1f); } //后乘旋转角度 matrix.postRotate(Float.valueOf(orientation)); //后乘缩放 matrix.postScale(mSurfaceView.getWidth() / 2000f,mSurfaceView.getHeight() / 2000f); //再进行位移 matrix.postTranslate(mSurfaceView.getWidth() / 2f, mSurfaceView.getHeight() / 2f); ArrayList<RectF> arrayList = new ArrayList<>(); for (Camera.Face rectF : faces) { RectF srcRect = new RectF(rectF.rect); RectF dstRect = new RectF(0f, 0f, 0f, 0f); //通过Matrix映射 将srcRect放入dstRect中 matrix.mapRect(dstRect, srcRect); arrayList.add(dstRect); } return arrayList; } /** * 保证预览方向正确 * * @param appCompatActivity Activity * @param cameraId 相机Id * @param camera 相机 */ private void setCameraDisplayOrientation(AppCompatActivity appCompatActivity, int cameraId, Camera camera) { Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(cameraId, info); //rotation是预览Window的旋转方向,对于手机而言,当在清单文件设置Activity的screenOrientation="portait"时, //rotation=0,这时候没有旋转,当screenOrientation="landScape"时,rotation=1。 int rotation = appCompatActivity.getWindowManager().getDefaultDisplay() .getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int result; //计算图像所要旋转的角度 if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; // compensate the mirror } else { // back-facing result = (info.orientation - degrees + 360) % 360; } orientation = result; //调整预览图像旋转角度 camera.setDisplayOrientation(result); } /** * 前后摄像切换 */ public void switchCamera() { //先释放资源 releaseCamera(); //在Android P之前 Android设备仍然最多只有前后两个摄像头,在Android p后支持多个摄像头 用户想打开哪个就打开哪个 mCameraId = (mCameraId + 1) % Camera.getNumberOfCameras(); //打开摄像头 openCamera(mCameraId); //切换摄像头之后开启预览 startPreview(); } /** * 释放相机资源 */ public void releaseCamera() { if (mCamera != null) { //停止预览 mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; mHandler.removeMessages(1); } if(mediaRecorder != null){ mediaRecorder.release(); mediaRecorder = null; } } /** * 创建拍照照片文件夹 */ private void setUpFile() { //方式1 这里是app的内部存储 这里要注意 不是外部私有目录 详情请看 Configuration这个类 // photosFile = new File(Configuration.insidePath); //方式2 这里改为app的外部存储 私有存储目录 /storage/emulated/0/Android/data/com.knight.cameraone/Pictures photosFile = mAppCompatActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES); if (!photosFile.exists() || !photosFile.isDirectory()) { boolean isSuccess = false; try { isSuccess = photosFile.mkdirs(); } catch (Exception e) { ToastUtil.showShortToast(mAppCompatActivity, "创建存放目录失败,请检查磁盘空间~"); mAppCompatActivity.finish(); } finally { if (!isSuccess) { ToastUtil.showShortToast(mAppCompatActivity, "创建存放目录失败,请检查磁盘空间~"); mAppCompatActivity.finish(); } } } } /** * @return 返回路径 */ private void getPhotoPath(final byte[] data, final int takePhotoOrientation) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { long timeMillis = System.currentTimeMillis(); String time = SystemUtil.formatTime(timeMillis); //拍照数量+1 photoNum++; //图片名字 String name = SystemUtil.formatTime(timeMillis, SystemUtil.formatRandom(photoNum) + ".jpg"); //创建具体文件 File file = new File(photosFile, name); if (!file.exists()) { try { file.createNewFile(); } catch (Exception e) { e.printStackTrace(); return; } } try { FileOutputStream fos = new FileOutputStream(file); try { //将数据写入文件 fos.write(data); } catch (IOException e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } //将图片旋转 // rotateImageView(mCameraId,orientation,Configuration.insidePath + file.getName()); rotateImageView(mCameraId,takePhotoOrientation,file.getAbsolutePath()); //将图片复制到外部 target SDK 设置 Android 10以下 //SystemUtil.copyPicture(Configuration.insidePath + file.getName(),Configuration.OUTPATH,file.getName()); //将图片保存到手机相册 方式1 // SystemUtil.saveAlbum(file.getAbsolutePath(), file.getName(), mAppCompatActivity); //将图片保存到手机相册 方式2 // ImageUtil.saveAlbum(mAppCompatActivity,file); Message message = new Message(); message.what = 1; message.obj = file.getAbsolutePath(); mHandler.sendMessage(message); } catch (FileNotFoundException e) { e.printStackTrace(); } } }); } /** * 旋转图片 * @param cameraId 前置还是后置 * @param orientation 拍照时传感器方向 * @param path 图片路径 */ private void rotateImageView(int cameraId,int orientation,String path){ Bitmap bitmap = BitmapFactory.decodeFile(path); Matrix matrix = new Matrix(); matrix.postRotate(Float.valueOf(orientation)); // 创建新的图片 Bitmap resizedBitmap; if(cameraId == 1){ if(orientation == 90){ matrix.postRotate(180f); } } // 创建新的图片 resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); //新增 如果是前置 需要镜面翻转处理 if(cameraId == 1){ Matrix matrix1 = new Matrix(); matrix1.postScale(-1f,1f); resizedBitmap = Bitmap.createBitmap(resizedBitmap, 0, 0, resizedBitmap.getWidth(), resizedBitmap.getHeight(), matrix1, true); } File file = new File(path); //重新写入文件 try{ // 写入文件 FileOutputStream fos; fos = new FileOutputStream(file); //默认jpg resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); resizedBitmap.recycle(); }catch (Exception e){ e.printStackTrace(); return; } } // if ("png".equals(imageType)) { // bitmap.compress(Bitmap.CompressFormat.PNG, 70, fos); // } else { // bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); // } @SuppressLint("HandlerLeak") Handler mHandler = new Handler(){ @SuppressLint("NewApi") @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: mCameraCallBack.getPhotoFile(msg.obj.toString()); break; default: break; } } }; /** * 自动变焦 */ public void autoFoucus(){ if(mCamera == null){ mCamera.autoFocus(new Camera.AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { } }); } } /** * 获取输出视频的width和height * */ public void getVideoSize(){ int biggest_width=0 ,biggest_height=0;//最大分辨率 int fitSize_width=0,fitSize_height=0; int fitSize_widthBig=0,fitSize_heightBig=0; Camera.Parameters parameters = mCamera.getParameters(); //得到系统支持视频尺寸 List<Camera.Size> videoSize = parameters.getSupportedVideoSizes(); List<Camera.Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes(); //使用官方demo Camera.Size optimalSize = CameraHelper.getOptimalVideoSize(videoSize, mSupportedPreviewSizes, mSurfaceView.getWidth(), mSurfaceView.getHeight()); // Use the same size for recording profile. profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); profile.videoFrameWidth = optimalSize.width; profile.videoFrameHeight = optimalSize.height; } /** * * 停止录制 */ public void stopRecord(){ if(mediaRecorder != null){ mediaRecorder.release(); mediaRecorder = null; } mCameraCallBack.getVideoFile(videoFilePath); if(mCamera != null){ mCamera.release(); } openCamera(mCameraId); //并设置预览 startPreview(); } /** * * 录制方法 */ public void startRecord(String path,String name){ //解锁Camera硬件 mCamera.unlock(); if(mediaRecorder == null){ mediaRecorder = new MediaRecorder(); } mediaRecorder.setCamera(mCamera); //音频源 麦克风 mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); //视频源 camera mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); //设置输出文件格式 录制过程中产生的输出文件的格式 mediaRecorder.setOutputFormat(profile.fileFormat); //设置录制的视频编码比特率 会影响清晰 mediaRecorder.setVideoEncodingBitRate(5* 1024 * 1024); //设置视频编码器 用于录制 mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); //设置Audio编码格式 mediaRecorder.setAudioEncoder(MediaRecorder.VideoEncoder.DEFAULT); //设置捕获的视频宽度和高度 mediaRecorder.setVideoSize(profile.videoFrameWidth,profile.videoFrameHeight); //调整视频旋转角度 如果不设置 后置和前置都会被旋转播放 if(mCameraId == Camera.CameraInfo.CAMERA_FACING_FRONT) { if(orientation == 270 || orientation == 90 || orientation == 180){ mediaRecorder.setOrientationHint(180); }else{ mediaRecorder.setOrientationHint(0); } }else{ if(orientation == 90){ mediaRecorder.setOrientationHint(90); } } //路径问题 可以到Configuration 这个类看 File file = new File(path); if(!file.exists()){ file.mkdirs(); } //设置输出文件名字 mediaRecorder.setOutputFile(path + File.separator + name + ".mp4"); File file1 = new File(path + File.separator + name + ".mp4"); if(file1.exists()){ file1.delete(); } //赋值视频文件 videoFilePath = path + File.separator + name + ".mp4"; //设置预览 mediaRecorder.setPreviewDisplay(mSurfaceView.getHolder().getSurface()); try { //准备录制 mediaRecorder.prepare(); //开始录制 mediaRecorder.start(); } catch (IOException e) { e.printStackTrace(); } } /** * * 闪光灯 * @param turnSwitch true 为开启 false 为关闭 */ public void turnLight(boolean turnSwitch){ if(mCamera == null){ return; } Camera.Parameters parameters = mCamera.getParameters(); if(parameters == null){ return; } parameters.setFlashMode(turnSwitch ? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF); mCamera.setParameters(parameters); } /** * 开启人脸检测 * */ public void turnFaceDetect(boolean isDetect){ // mFaceView.setVisibility(isDetect ? View.VISIBLE : View.GONE); } /** * * * @param mSurfaceView */ public void update(SurfaceView mSurfaceView){ mSurfaceHolder = mSurfaceView.getHolder(); } /** * * 获取视频文件链接 * @return */ public String getVideoFilePath(){ return videoFilePath; } /** * * 适配 华为p40 小米mix 一些不规则尺寸 * * @param fitSizeHeight 获取系统支持最适合的高(现实系统的屏幕宽度) * @param fitSizeWidth 获取系统支持最适合的宽(现实系统的屏幕高度) * */ private void fixScreenSize(int fitSizeHeight,int fitSizeWidth){ // 预览 View 的大小,比如 SurfaceView int viewHeight = screenHeight; int viewWidth = screenWidth; // 相机选择的预览尺寸 int cameraHeight = fitSizeWidth; int cameraWidth = fitSizeHeight; // 计算出将相机的尺寸 => View 的尺寸需要的缩放倍数 float ratioPreview = (float) cameraWidth / cameraHeight; float ratioView = (float) viewWidth / viewHeight; float scaleX, scaleY; if (ratioView < ratioPreview) { scaleX = ratioPreview / ratioView; scaleY = 1; } else { scaleX = 1; scaleY = ratioView / ratioPreview; } // 计算出 View 的偏移量 float scaledWidth = viewWidth * scaleX; float scaledHeight = viewHeight * scaleY; float dx = (viewWidth - scaledWidth) / 2; float dy = (viewHeight - scaledHeight) / 2; Matrix matrix = new Matrix(); matrix.postScale(scaleX, scaleY); matrix.postTranslate(dx, dy); float[] values = new float[9]; matrix.getValues(values); mSurfaceView.setTranslationX(values[Matrix.MTRANS_X]); mSurfaceView.setTranslationY(values[Matrix.MTRANS_Y]); mSurfaceView.setScaleX(values[Matrix.MSCALE_X]); mSurfaceView.setScaleY(values[Matrix.MSCALE_Y]); mSurfaceView.invalidate(); } }
3e1450d3b760c77e319acce5eb34b92b6a6d371b
38,833
java
Java
src/test/java/com/aws/greengrass/deployment/DeploymentServiceTest.java
williamlai/aws-greengrass-nucleus
2999b3c1633e82b14203f305553ef72153841bfa
[ "Apache-2.0" ]
71
2020-12-15T17:27:53.000Z
2022-03-04T19:30:39.000Z
src/test/java/com/aws/greengrass/deployment/DeploymentServiceTest.java
williamlai/aws-greengrass-nucleus
2999b3c1633e82b14203f305553ef72153841bfa
[ "Apache-2.0" ]
363
2020-12-15T17:27:40.000Z
2022-03-31T22:22:35.000Z
src/test/java/com/aws/greengrass/deployment/DeploymentServiceTest.java
williamlai/aws-greengrass-nucleus
2999b3c1633e82b14203f305553ef72153841bfa
[ "Apache-2.0" ]
27
2020-12-15T22:01:45.000Z
2022-03-25T04:44:06.000Z
57.360414
134
0.743414
8,603
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.aws.greengrass.deployment; import com.amazon.aws.iot.greengrass.component.common.DependencyType; import com.aws.greengrass.componentmanager.ComponentManager; import com.aws.greengrass.componentmanager.DependencyResolver; import com.aws.greengrass.componentmanager.KernelConfigResolver; import com.aws.greengrass.config.CaseInsensitiveString; import com.aws.greengrass.config.Node; import com.aws.greengrass.config.Topic; import com.aws.greengrass.config.Topics; import com.aws.greengrass.dependency.State; import com.aws.greengrass.deployment.exceptions.DeploymentTaskFailureException; import com.aws.greengrass.deployment.model.Deployment; import com.aws.greengrass.deployment.model.DeploymentResult; import com.aws.greengrass.deployment.model.DeploymentResult.DeploymentStatus; import com.aws.greengrass.lifecyclemanager.GreengrassService; import com.aws.greengrass.lifecyclemanager.Kernel; import com.aws.greengrass.logging.impl.GreengrassLogMessage; import com.aws.greengrass.logging.impl.Slf4jLogAdapter; import com.aws.greengrass.testcommons.testutilities.GGExtension; import com.aws.greengrass.testcommons.testutilities.GGServiceTestUtil; import org.hamcrest.collection.IsEmptyCollection; import org.hamcrest.core.IsNot; import org.hamcrest.core.IsNull; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.verification.VerificationWithTimeout; import software.amazon.awssdk.iot.iotjobs.model.JobStatus; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.stream.Collectors; import static com.aws.greengrass.deployment.DeploymentService.COMPONENTS_TO_GROUPS_TOPICS; import static com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_SERVICE_TOPICS; import static com.aws.greengrass.deployment.DeploymentService.GROUP_MEMBERSHIP_TOPICS; import static com.aws.greengrass.deployment.DeploymentService.GROUP_TO_ROOT_COMPONENTS_TOPICS; import static com.aws.greengrass.deployment.converter.DeploymentDocumentConverter.LOCAL_DEPLOYMENT_GROUP_NAME; import static com.aws.greengrass.lifecyclemanager.GreengrassService.SERVICE_NAME_KEY; import static com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionUltimateCauseOfType; import static com.aws.greengrass.testcommons.testutilities.ExceptionLogProtector.ignoreExceptionUltimateCauseWithMessage; import static java.util.Collections.emptyMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.collection.IsMapContaining.hasKey; import static org.hamcrest.core.Is.is; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @SuppressWarnings({"PMD.LooseCoupling", "PMD.TestClassWithoutTestCases"}) @ExtendWith({MockitoExtension.class, GGExtension.class}) class DeploymentServiceTest extends GGServiceTestUtil { private static final String TEST_JOB_ID_1 = "TEST_JOB_1"; private static final String EXPECTED_GROUP_NAME = "thinggroup/group1"; private static final String EXPECTED_ROOT_PACKAGE_NAME = "component1"; private static final String TEST_DEPLOYMENT_ID = "testDeploymentId"; private static final String TEST_CONFIGURATION_ARN = "arn:aws:greengrass:us-east-1:12345678910:configuration:thinggroup/group1:1"; private static final VerificationWithTimeout WAIT_FOUR_SECONDS = timeout(Duration.ofSeconds(4).toMillis()); @Mock ExecutorService mockExecutorService; CompletableFuture<DeploymentResult> mockFuture = spy(new CompletableFuture<>()); @Mock private Kernel mockKernel; @Mock private DependencyResolver dependencyResolver; @Mock private ComponentManager componentManager; @Mock private KernelConfigResolver kernelConfigResolver; @Mock private DeploymentConfigMerger deploymentConfigMerger; @Mock private DeploymentStatusKeeper deploymentStatusKeeper; @Mock private Topics mockComponentsToGroupPackages; @Mock private GreengrassService mockGreengrassService; @Mock private DeploymentDirectoryManager deploymentDirectoryManager; @Mock private DeviceConfiguration deviceConfiguration; @Mock private IotJobsHelper iotJobsHelper; @Mock private ThingGroupHelper thingGroupHelper; private Thread deploymentServiceThread; private DeploymentService deploymentService; private DeploymentQueue deploymentQueue; @BeforeEach void setup() { // initialize Greengrass service specific mocks serviceFullName = "DeploymentService"; initializeMockedConfig(); lenient().when(stateTopic.getOnce()).thenReturn(State.INSTALLED); Topic pollingFrequency = Topic.of(context, DeviceConfiguration.DEPLOYMENT_POLLING_FREQUENCY_SECONDS, 1L); when(deviceConfiguration.getDeploymentPollingFrequencySeconds()).thenReturn(pollingFrequency); when(context.get(IotJobsHelper.class)).thenReturn(iotJobsHelper); // Creating the class to be tested deploymentService = new DeploymentService(config, mockExecutorService, dependencyResolver, componentManager, kernelConfigResolver, deploymentConfigMerger, deploymentStatusKeeper, deploymentDirectoryManager, context, mockKernel, deviceConfiguration, thingGroupHelper); deploymentService.postInject(); deploymentQueue = new DeploymentQueue(); deploymentService.setDeploymentsQueue(deploymentQueue); } @AfterEach void afterEach() { deploymentService.shutdown(); verify(iotJobsHelper).unsubscribeFromIotJobsTopics(); if (deploymentServiceThread != null && deploymentServiceThread.isAlive()) { deploymentServiceThread.interrupt(); } mockKernel.shutdown(); } private void startDeploymentServiceInAnotherThread() throws InterruptedException { CountDownLatch cdl = new CountDownLatch(1); Consumer<GreengrassLogMessage> listener = m -> { if (m.getContexts() != null && m.getContexts().containsKey(SERVICE_NAME_KEY) && m.getContexts() .get(SERVICE_NAME_KEY).equalsIgnoreCase(DEPLOYMENT_SERVICE_TOPICS)) { cdl.countDown(); } }; Slf4jLogAdapter.addGlobalListener(listener); deploymentServiceThread = new Thread(() -> { try { deploymentService.startup(); } catch (InterruptedException ignore) { } }); deploymentServiceThread.start(); boolean running = cdl.await(1, TimeUnit.SECONDS); Slf4jLogAdapter.removeGlobalListener(listener); assertTrue(running, "Deployment service must be running"); } @Test void GIVEN_components_to_groups_mapping_WHEN_get_groups_for_component_THEN_gets_correct_groups() { String group1 = "arn:aws:greengrass:testRegion:12345:configuration:testGroup:12"; String group2 = "arn:aws:greengrass:testRegion:67890:configuration:testGroup1:800"; Topics allComponentToGroupsTopics = Topics.of(context, GROUP_TO_ROOT_COMPONENTS_TOPICS, null); Topics componentTopics1 = Topics.of(context, "MockService", allComponentToGroupsTopics); Topics componentTopics2 = Topics.of(context, "MockService2", allComponentToGroupsTopics); Topic groupTopic1 = Topic.of(context, group1, "testGroup"); Topic groupTopic2 = Topic.of(context, group2, "testGroup1"); componentTopics1.children.put(new CaseInsensitiveString("MockService"), groupTopic1); componentTopics2.children.put(new CaseInsensitiveString("MockService2"), groupTopic2); allComponentToGroupsTopics.children.put(new CaseInsensitiveString("MockService"), componentTopics1); allComponentToGroupsTopics.children.put(new CaseInsensitiveString("MockService2"), componentTopics2); when(config.lookupTopics(COMPONENTS_TO_GROUPS_TOPICS)).thenReturn(allComponentToGroupsTopics); Set<String> allGroupConfigs = deploymentService.getAllGroupNames(); assertEquals(2, allGroupConfigs.size()); assertThat(allGroupConfigs, containsInAnyOrder("testGroup", "testGroup1")); Set<String> allComponentGroupConfigs = deploymentService.getGroupNamesForUserComponent("MockService"); assertEquals(1, allComponentGroupConfigs.size()); assertThat(allComponentGroupConfigs, containsInAnyOrder("testGroup")); } @Test void GIVEN_groupsToRootComponents_WHEN_setComponentsToGroupsMapping_THEN_get_correct_componentsToGroupsTopics() throws Exception{ // GIVEN // GroupToRootComponents: // LOCAL_DEPLOYMENT: // component1: // groupConfigArn: "asdf" // groupConfigName: "LOCAL_DEPLOYMENT" // version: "1.0.0" // AnotherRootComponent: // groupConfigArn: "asdf" // groupConfigName: "LOCAL_DEPLOYMENT" // version: "2.0.0" // thinggroup/group1: // component1: // groupConfigArn: "arn:aws:greengrass:us-east-1:12345678910:configuration:thinggroup/group1:1" // groupConfigName: "thinggroup/group1" // version: "1.0.0" Topics allGroupTopics = Topics.of(context, GROUP_TO_ROOT_COMPONENTS_TOPICS, null); Topics deploymentGroupTopics = Topics.of(context, EXPECTED_GROUP_NAME, allGroupTopics); Topics deploymentGroupTopics2 = Topics.of(context, LOCAL_DEPLOYMENT_GROUP_NAME, allGroupTopics); // Set up 1st deployment for EXPECTED_GROUP_NAME Topics pkgTopics = Topics.of(context, EXPECTED_ROOT_PACKAGE_NAME, deploymentGroupTopics); pkgTopics.children.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY), Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY, "1.0.0")); pkgTopics.children.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN), Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN, TEST_CONFIGURATION_ARN)); pkgTopics.children.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_NAME), Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_NAME, EXPECTED_GROUP_NAME)); deploymentGroupTopics.children.put(new CaseInsensitiveString(EXPECTED_ROOT_PACKAGE_NAME), pkgTopics); allGroupTopics.children.putIfAbsent(new CaseInsensitiveString(EXPECTED_GROUP_NAME), deploymentGroupTopics); // Set up 2nd deployment for LOCAL_DEPLOYMENT_GROUP_NAME Topics pkgTopics2 = Topics.of(context, "AnotherRootComponent", deploymentGroupTopics2); pkgTopics2.children.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY), Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY, "2.0.0")); pkgTopics2.children.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN), Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN, "asdf")); pkgTopics2.children.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_NAME), Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_NAME, LOCAL_DEPLOYMENT_GROUP_NAME)); deploymentGroupTopics2.children.put(new CaseInsensitiveString("AnotherRootComponent"), pkgTopics2); Topics pkgTopics3 = Topics.of(context, EXPECTED_ROOT_PACKAGE_NAME, deploymentGroupTopics2); pkgTopics3.children.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY), Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY, "1.0.0")); pkgTopics3.children.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN), Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN, "asdf")); pkgTopics3.children.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_NAME), Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_NAME, LOCAL_DEPLOYMENT_GROUP_NAME)); deploymentGroupTopics2.children.put(new CaseInsensitiveString(EXPECTED_ROOT_PACKAGE_NAME), pkgTopics3); allGroupTopics.children.putIfAbsent(new CaseInsensitiveString(LOCAL_DEPLOYMENT_GROUP_NAME), deploymentGroupTopics2); // Set up mocks Topics componentsToGroupsTopics = mock(Topics.class); doReturn(componentsToGroupsTopics).when(config).lookupTopics(eq(COMPONENTS_TO_GROUPS_TOPICS)); GreengrassService expectedRootService = mock(GreengrassService.class); GreengrassService anotherRootService = mock(GreengrassService.class); GreengrassService dependencyService = mock(GreengrassService.class); doReturn(expectedRootService).when(mockKernel).locate(eq(EXPECTED_ROOT_PACKAGE_NAME)); doReturn(anotherRootService).when(mockKernel).locate(eq("AnotherRootComponent")); doReturn(dependencyService).when(mockKernel).locate(eq("Dependency")); doReturn(new HashMap<GreengrassService, DependencyType>() {{ put(dependencyService, DependencyType.HARD);}}) .when(expectedRootService).getDependencies(); doReturn(new HashMap<GreengrassService, DependencyType>() {{ put(dependencyService, DependencyType.HARD);}}) .when(anotherRootService).getDependencies(); doReturn(emptyMap()).when(dependencyService).getDependencies(); doReturn(EXPECTED_ROOT_PACKAGE_NAME).when(expectedRootService).getName(); doReturn("AnotherRootComponent").when(anotherRootService).getName(); doReturn("Dependency").when(dependencyService).getName(); // WHEN deploymentService.setComponentsToGroupsMapping(allGroupTopics); // THEN // ComponentToGroups: // component1: // "asdf": "LOCAL_DEPLOYMENT" // "arn:aws:greengrass:us-east-1:12345678910:configuration:thinggroup/group1:1": "thinggroup/group1" // AnotherRootComponent: // "asdf": "LOCAL_DEPLOYMENT" // Dependency: // "asdf": "LOCAL_DEPLOYMENT" // "arn:aws:greengrass:us-east-1:12345678910:configuration:thinggroup/group1:1": "thinggroup/group1" ArgumentCaptor<Map<String, Object>> mapCaptor = ArgumentCaptor.forClass(Map.class); verify(componentsToGroupsTopics).replaceAndWait(mapCaptor.capture()); Map<String, Object> groupToRootPackages = mapCaptor.getValue(); assertThat(groupToRootPackages, hasKey(EXPECTED_ROOT_PACKAGE_NAME)); Map<String, String> expectedRootComponentMap = (Map<String, String>) groupToRootPackages.get(EXPECTED_ROOT_PACKAGE_NAME); assertEquals(2, expectedRootComponentMap.size()); assertThat(expectedRootComponentMap, hasEntry(TEST_CONFIGURATION_ARN, EXPECTED_GROUP_NAME)); assertThat(expectedRootComponentMap, hasEntry("asdf", LOCAL_DEPLOYMENT_GROUP_NAME)); assertThat(groupToRootPackages, hasKey("AnotherRootComponent")); Map<String, String> anotherRootComponentMap = (Map<String, String>) groupToRootPackages.get( "AnotherRootComponent"); assertEquals(1, anotherRootComponentMap.size()); assertThat(anotherRootComponentMap, hasEntry("asdf", LOCAL_DEPLOYMENT_GROUP_NAME)); assertThat(groupToRootPackages, hasKey("Dependency")); Map<String, String> expectedDepComponentMap = (Map<String, String>) groupToRootPackages.get(EXPECTED_ROOT_PACKAGE_NAME); assertEquals(2, expectedDepComponentMap.size()); assertThat(expectedDepComponentMap, hasEntry(TEST_CONFIGURATION_ARN, EXPECTED_GROUP_NAME)); assertThat(expectedDepComponentMap, hasEntry("asdf", LOCAL_DEPLOYMENT_GROUP_NAME)); } @Test void GIVEN_groups_to_root_components_WHEN_isRootComponent_called_THEN_returns_value_correctly() { Topics allGroupTopics = Topics.of(context, GROUP_TO_ROOT_COMPONENTS_TOPICS, null); Topics deploymentGroupTopics = Topics.of(context, EXPECTED_GROUP_NAME, allGroupTopics); Topics deploymentGroupTopics2 = Topics.of(context, "AnotherGroup", allGroupTopics); Topic pkgTopic1 = Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY, "1.0.0"); Topic groupTopic1 = Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN, "arn:aws:greengrass:testRegion:12345:configuration:testGroup:12"); Map<CaseInsensitiveString, Node> pkgDetails = new HashMap<>(); pkgDetails.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY), pkgTopic1); pkgDetails.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN), groupTopic1); Topics pkgTopics = Topics.of(context, EXPECTED_ROOT_PACKAGE_NAME, deploymentGroupTopics); pkgTopics.children.putAll(pkgDetails); deploymentGroupTopics.children.put(new CaseInsensitiveString(EXPECTED_ROOT_PACKAGE_NAME), pkgTopics); Topic pkgTopic2 = Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY, "2.0.0"); Topic groupTopic2 = Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN, "arn:aws:greengrass:testRegion:12345:configuration:testGroup2:900"); Map<CaseInsensitiveString, Node> pkgDetails2 = new HashMap<>(); pkgDetails2.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY), pkgTopic2); pkgDetails2.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN), groupTopic2); Topics pkgTopics2 = Topics.of(context, "AnotherRootComponent", deploymentGroupTopics2); pkgTopics2.children.putAll(pkgDetails); deploymentGroupTopics2.children.put(new CaseInsensitiveString("AnotherRootComponent"), pkgTopics2); allGroupTopics.children.putIfAbsent(new CaseInsensitiveString(EXPECTED_GROUP_NAME), deploymentGroupTopics); allGroupTopics.children.putIfAbsent(new CaseInsensitiveString("AnotherGroup"), deploymentGroupTopics2); when(config.lookupTopics(GROUP_TO_ROOT_COMPONENTS_TOPICS)).thenReturn(allGroupTopics); assertTrue(deploymentService.isComponentRoot(EXPECTED_ROOT_PACKAGE_NAME)); assertTrue(deploymentService.isComponentRoot("AnotherRootComponent")); assertFalse(deploymentService.isComponentRoot("RandomComponent")); } @ParameterizedTest @EnumSource(Deployment.DeploymentType.class) void GIVEN_deployment_job_WHEN_deployment_process_succeeds_THEN_correctly_map_components_to_groups( Deployment.DeploymentType type) throws Exception { String expectedGroupName = EXPECTED_GROUP_NAME; if (type.equals(Deployment.DeploymentType.LOCAL)) { expectedGroupName = LOCAL_DEPLOYMENT_GROUP_NAME; } String deploymentDocument = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("TestDeploymentDocument.json"), StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); deploymentQueue.offer(new Deployment(deploymentDocument, type, TEST_JOB_ID_1)); Topics allGroupTopics = Topics.of(context, GROUP_TO_ROOT_COMPONENTS_TOPICS, null); Topics groupMembershipTopics = Topics.of(context, GROUP_MEMBERSHIP_TOPICS, null); groupMembershipTopics.lookup(expectedGroupName); Topics deploymentGroupTopics = Topics.of(context, expectedGroupName, allGroupTopics); Topic pkgTopic1 = Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY, "1.0.0"); Topic groupTopic1 = Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN, "arn:aws:greengrass:testRegion:12345:configuration:testGroup:12"); Topic groupNameTopic1 = Topic.of(context, DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_NAME, expectedGroupName); Map<CaseInsensitiveString, Node> pkgDetails = new HashMap<>(); pkgDetails.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_VERSION_KEY), pkgTopic1); pkgDetails.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_CONFIG_ARN), groupTopic1); pkgDetails.put(new CaseInsensitiveString(DeploymentService.GROUP_TO_ROOT_COMPONENTS_GROUP_NAME), groupNameTopic1); Topics pkgTopics = Topics.of(context, EXPECTED_ROOT_PACKAGE_NAME, deploymentGroupTopics); pkgTopics.children.putAll(pkgDetails); deploymentGroupTopics.children.put(new CaseInsensitiveString(EXPECTED_ROOT_PACKAGE_NAME), pkgTopics); allGroupTopics.children.put(new CaseInsensitiveString(expectedGroupName), deploymentGroupTopics); when(config.lookupTopics(GROUP_MEMBERSHIP_TOPICS)).thenReturn(groupMembershipTopics); when(config.lookupTopics(GROUP_TO_ROOT_COMPONENTS_TOPICS)).thenReturn(allGroupTopics); lenient().when(config.lookupTopics(GROUP_TO_ROOT_COMPONENTS_TOPICS, expectedGroupName)) .thenReturn(deploymentGroupTopics); when(config.lookupTopics(COMPONENTS_TO_GROUPS_TOPICS)).thenReturn(mockComponentsToGroupPackages); when(mockKernel.locate(any())).thenReturn(mockGreengrassService); when(mockGreengrassService.getName()).thenReturn(EXPECTED_ROOT_PACKAGE_NAME); mockFuture.complete(new DeploymentResult(DeploymentStatus.SUCCESSFUL, null)); when(mockExecutorService.submit(any(DefaultDeploymentTask.class))).thenReturn(mockFuture); doNothing().when(deploymentStatusKeeper).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(type), eq(JobStatus.IN_PROGRESS.toString()), any()); startDeploymentServiceInAnotherThread(); verify(deploymentStatusKeeper, timeout(1000)).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(type), eq(JobStatus.IN_PROGRESS.toString()), any()); verify(deploymentStatusKeeper, timeout(10000)) .persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(type), eq(JobStatus.SUCCEEDED.toString()), any()); verify(mockExecutorService, timeout(1000)).submit(any(DefaultDeploymentTask.class)); verify(deploymentStatusKeeper, timeout(2000)).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(type), eq(JobStatus.SUCCEEDED.toString()), any()); ArgumentCaptor<Map<String, Object>> mapCaptor = ArgumentCaptor.forClass(Map.class); verify(mockComponentsToGroupPackages).replaceAndWait(mapCaptor.capture()); Map<String, Object> groupToRootPackages = mapCaptor.getValue(); assertThat(groupToRootPackages, is(IsNull.notNullValue())); assertThat(groupToRootPackages.entrySet(), IsNot.not(IsEmptyCollection.empty())); assertThat(groupToRootPackages, hasKey(EXPECTED_ROOT_PACKAGE_NAME)); assertThat((Map<String, Boolean>) groupToRootPackages.get(EXPECTED_ROOT_PACKAGE_NAME), hasKey("arn:aws:greengrass:testRegion:12345:configuration:testGroup:12")); } @Test void GIVEN_deployment_job_WHEN_deployment_completes_with_non_retryable_error_THEN_report_failed_job_status( ExtensionContext context) throws Exception { String deploymentDocument = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("TestDeploymentDocument.json"), StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); deploymentQueue.offer(new Deployment(deploymentDocument, Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1)); CompletableFuture<DeploymentResult> mockFutureWithException = new CompletableFuture<>(); ignoreExceptionUltimateCauseOfType(context, DeploymentTaskFailureException.class); Throwable t = new DeploymentTaskFailureException(""); mockFutureWithException.completeExceptionally(t); when(mockExecutorService.submit(any(DefaultDeploymentTask.class))).thenReturn(mockFutureWithException); startDeploymentServiceInAnotherThread(); verify(mockExecutorService, WAIT_FOUR_SECONDS).submit(any(DefaultDeploymentTask.class)); verify(deploymentStatusKeeper, WAIT_FOUR_SECONDS).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.IN_PROGRESS.toString()), any()); verify(deploymentStatusKeeper, WAIT_FOUR_SECONDS).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.FAILED.toString()), any()); } @Test void GIVEN_deployment_job_WHEN_deployment_metadata_setup_fails_THEN_report_failed_job_status( ExtensionContext context) throws Exception { String deploymentDocument = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("TestDeploymentDocument.json"), StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); deploymentQueue.offer(new Deployment(deploymentDocument, Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1)); ignoreExceptionUltimateCauseWithMessage(context, "mock error"); when(deploymentDirectoryManager.createNewDeploymentDirectory(any())) .thenThrow(new IOException("mock error")); startDeploymentServiceInAnotherThread(); ArgumentCaptor<Map<String, String>> statusDetails = ArgumentCaptor.forClass(Map.class); verify(deploymentStatusKeeper, WAIT_FOUR_SECONDS).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.IN_PROGRESS.toString()), any()); verify(deploymentStatusKeeper, WAIT_FOUR_SECONDS).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.FAILED.toString()), statusDetails.capture()); assertEquals("java.io.IOException: mock error", statusDetails.getValue().get("error")); } @Test void GIVEN_deployment_job_with_auto_rollback_not_requested_WHEN_deployment_process_fails_THEN_report_failed_job_status() throws Exception { String deploymentDocument = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("TestDeploymentDocument.json"), StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); deploymentQueue.offer(new Deployment(deploymentDocument, Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1)); Topics allGroupTopics = mock(Topics.class); Topics groupMembershipTopics = mock(Topics.class); Topics deploymentGroupTopics = mock(Topics.class); when(allGroupTopics.lookupTopics(EXPECTED_GROUP_NAME)).thenReturn(deploymentGroupTopics); when(config.lookupTopics(GROUP_MEMBERSHIP_TOPICS)).thenReturn(groupMembershipTopics); when(config.lookupTopics(GROUP_TO_ROOT_COMPONENTS_TOPICS)).thenReturn(allGroupTopics); when(config.lookupTopics(COMPONENTS_TO_GROUPS_TOPICS)).thenReturn(mockComponentsToGroupPackages); mockFuture.complete( new DeploymentResult(DeploymentStatus.FAILED_ROLLBACK_NOT_REQUESTED, null)); when(mockExecutorService.submit(any(DefaultDeploymentTask.class))).thenReturn(mockFuture); startDeploymentServiceInAnotherThread(); verify(mockExecutorService, timeout(1000)).submit(any(DefaultDeploymentTask.class)); verify(deploymentStatusKeeper, timeout(2000)).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.IN_PROGRESS.toString()), any()); verify(deploymentStatusKeeper, timeout(2000)).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.FAILED.toString()), any()); ArgumentCaptor<Map<String, Object>> mapCaptor = ArgumentCaptor.forClass(Map.class); verify(deploymentGroupTopics).replaceAndWait(mapCaptor.capture()); Map<String, Object> groupToRootPackages = mapCaptor.getValue(); assertThat(groupToRootPackages, is(IsNull.notNullValue())); assertThat(groupToRootPackages.entrySet(), IsNot.not(IsEmptyCollection.empty())); assertThat(groupToRootPackages, hasKey(EXPECTED_ROOT_PACKAGE_NAME)); Map<String, Object> rootComponentDetails = (Map<String, Object>) groupToRootPackages.get(EXPECTED_ROOT_PACKAGE_NAME); assertThat(rootComponentDetails, hasEntry("groupConfigArn", "arn:aws:greengrass:us-east-1:12345678910:configuration:thinggroup/group1:1")); assertThat(rootComponentDetails, hasEntry("groupConfigName", "thinggroup/group1")); assertThat(rootComponentDetails, hasEntry("version", "1.0.0")); } @Test void GIVEN_deployment_job_with_auto_rollback_requested_WHEN_deployment_fails_and_rollback_succeeds_THEN_report_failed_job_status() throws Exception { String deploymentDocument = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("TestDeploymentDocument.json"), StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); deploymentQueue.offer(new Deployment(deploymentDocument, Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1)); mockFuture.complete(new DeploymentResult(DeploymentStatus.FAILED_ROLLBACK_COMPLETE, null)); when(mockExecutorService.submit(any(DefaultDeploymentTask.class))).thenReturn(mockFuture); startDeploymentServiceInAnotherThread(); verify(mockExecutorService, timeout(1000)).submit(any(DefaultDeploymentTask.class)); verify(deploymentStatusKeeper, timeout(2000)).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.IN_PROGRESS.toString()), any()); verify(deploymentStatusKeeper, timeout(2000)).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.FAILED.toString()), any()); } @Test void GIVEN_deployment_job_with_auto_rollback_requested_WHEN_deployment_fails_and_rollback_fails_THEN_report_failed_job_status() throws Exception { String deploymentDocument = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("TestDeploymentDocument.json"), StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); deploymentQueue.offer(new Deployment(deploymentDocument, Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1)); mockFuture.complete(new DeploymentResult(DeploymentStatus.FAILED_UNABLE_TO_ROLLBACK, null)); when(mockExecutorService.submit(any(DefaultDeploymentTask.class))).thenReturn(mockFuture); startDeploymentServiceInAnotherThread(); verify(mockExecutorService, timeout(1000)).submit(any(DefaultDeploymentTask.class)); verify(deploymentStatusKeeper, timeout(2000)).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.IN_PROGRESS.toString()), any()); verify(deploymentStatusKeeper, timeout(2000)).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.FAILED.toString()), any()); } @Test void GIVEN_deployment_job_cancelled_WHEN_waiting_for_safe_time_THEN_then_cancel_deployment() throws Exception { String deploymentDocument = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("TestDeploymentDocument.json"), StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); deploymentQueue.offer(new Deployment(deploymentDocument, Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1)); when(mockExecutorService.submit(any(DefaultDeploymentTask.class))).thenReturn(mockFuture); when(updateSystemPolicyService.discardPendingUpdateAction(any())).thenReturn(true); startDeploymentServiceInAnotherThread(); // Simulate a cancellation deployment deploymentQueue.offer(new Deployment(Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1, true)); // Expecting three invocations, once for each retry attempt verify(mockExecutorService, WAIT_FOUR_SECONDS).submit(any(DefaultDeploymentTask.class)); verify(deploymentStatusKeeper, WAIT_FOUR_SECONDS).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.IN_PROGRESS.toString()), any()); verify(updateSystemPolicyService, WAIT_FOUR_SECONDS).discardPendingUpdateAction(TEST_DEPLOYMENT_ID); verify(mockFuture, WAIT_FOUR_SECONDS).cancel(true); } @Test void GIVEN_deployment_job_cancelled_WHEN_already_executing_update_THEN_then_finish_deployment() throws Exception { String deploymentDocument = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("TestDeploymentDocument.json"), StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); deploymentQueue.offer(new Deployment(deploymentDocument, Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1)); when(mockExecutorService.submit(any(DefaultDeploymentTask.class))).thenReturn(mockFuture); when(updateSystemPolicyService.discardPendingUpdateAction(any())).thenReturn(false); startDeploymentServiceInAnotherThread(); // Simulate a cancellation deployment deploymentQueue.offer(new Deployment(Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1, true)); // Expecting three invocations, once for each retry attempt verify(mockExecutorService, WAIT_FOUR_SECONDS).submit(any(DefaultDeploymentTask.class)); verify(updateSystemPolicyService, WAIT_FOUR_SECONDS).discardPendingUpdateAction(TEST_DEPLOYMENT_ID); verify(mockFuture, times(0)).cancel(true); verify(deploymentStatusKeeper, WAIT_FOUR_SECONDS).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.IN_PROGRESS.toString()), any()); } @Test void GIVEN_deployment_job_cancelled_WHEN_already_finished_deployment_task_THEN_then_do_nothing() throws Exception { String deploymentDocument = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("TestDeploymentDocument.json"), StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); deploymentQueue.offer(new Deployment(deploymentDocument, Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1)); when(mockExecutorService.submit(any(DefaultDeploymentTask.class))).thenReturn(mockFuture); startDeploymentServiceInAnotherThread(); CountDownLatch cdl = new CountDownLatch(1); Consumer<GreengrassLogMessage> listener = m -> { if (m.getMessage() != null && m.getMessage().equals("Started deployment execution")) { cdl.countDown(); } }; Slf4jLogAdapter.addGlobalListener(listener); // Wait for deployment service to start a new deployment task then simulate finished task cdl.await(1, TimeUnit.SECONDS); Slf4jLogAdapter.removeGlobalListener(listener); // Simulate a cancellation deployment deploymentQueue.offer(new Deployment(Deployment.DeploymentType.IOT_JOBS, TEST_JOB_ID_1, true)); mockFuture.complete(new DeploymentResult(DeploymentStatus.SUCCESSFUL, null)); // Expecting three invocations, once for each retry attempt verify(mockExecutorService, WAIT_FOUR_SECONDS).submit(any(DefaultDeploymentTask.class)); verify(updateSystemPolicyService, times(0)).discardPendingUpdateAction(any()); verify(mockFuture, times(0)).cancel(true); verify(deploymentStatusKeeper, WAIT_FOUR_SECONDS).persistAndPublishDeploymentStatus(eq(TEST_JOB_ID_1), eq(Deployment.DeploymentType.IOT_JOBS), eq(JobStatus.IN_PROGRESS.toString()), any()); } }
3e1452030993905585e1dac5d606f96fb5e40e6d
7,941
java
Java
prestosql/src/main/java/com/zhihu/prestosql/tidb/TypeHelpers.java
sunxiaoguang/TiBigData
0758ff478669edeca9d84b6ac975adbad6ff50b7
[ "Apache-2.0" ]
null
null
null
prestosql/src/main/java/com/zhihu/prestosql/tidb/TypeHelpers.java
sunxiaoguang/TiBigData
0758ff478669edeca9d84b6ac975adbad6ff50b7
[ "Apache-2.0" ]
null
null
null
prestosql/src/main/java/com/zhihu/prestosql/tidb/TypeHelpers.java
sunxiaoguang/TiBigData
0758ff478669edeca9d84b6ac975adbad6ff50b7
[ "Apache-2.0" ]
1
2020-06-09T09:45:09.000Z
2020-06-09T09:45:09.000Z
44.61236
144
0.627377
8,604
/* * Copyright 2020 Zhihu. * * 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.zhihu.prestosql.tidb; import io.prestosql.spi.type.*; import com.pingcap.tikv.types.*; import com.zhihu.presto.tidb.RecordCursorInternal; import org.joda.time.DateTimeZone; import org.joda.time.chrono.ISOChronology; import io.airlift.slice.Slice; import java.sql.Date; import java.sql.Timestamp; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.math.BigDecimal; import java.math.MathContext; import static io.prestosql.spi.type.Decimals.decodeUnscaledValue; import static io.prestosql.spi.type.Decimals.encodeScaledValue; import static io.prestosql.spi.type.Decimals.encodeShortScaledValue; import static com.zhihu.prestosql.tidb.TypeHelper.*; import static io.airlift.slice.Slices.utf8Slice; import static io.airlift.slice.Slices.wrappedBuffer; import static java.lang.Float.floatToRawIntBits; import static java.lang.Float.intBitsToFloat; import static java.lang.Math.max; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.joda.time.DateTimeZone.UTC; final public class TypeHelpers { private static final ISOChronology UTC_CHRONOLOGY = ISOChronology.getInstanceUTC(); private static final ConcurrentHashMap<DataType, Optional<TypeHelper>> TYPE_HELPERS = new ConcurrentHashMap<>(); public static TypeHelper decimalHelper(DataType tidbType, io.prestosql.spi.type.DecimalType decimalType) { int scale = decimalType.getScale(); if (decimalType.isShort()) { return longHelper(tidbType, decimalType, (cursor, columnIndex) -> encodeShortScaledValue(cursor.getBigDecimal(columnIndex), scale)); } return sliceHelper(tidbType, decimalType, (cursor, columnIndex) -> encodeScaledValue(cursor.getBigDecimal(columnIndex), scale), s -> new BigDecimal(decodeUnscaledValue(s), scale, new MathContext(decimalType.getPrecision()))); } public static TypeHelper varcharHelper(DataType tidbType, VarcharType varcharType) { return sliceHelper(tidbType, varcharType, (cursor, columnIndex) -> utf8Slice(cursor.getString(columnIndex))); } private static TypeHelper getHelperInternal(DataType type) { long length = type.getLength(); switch (type.getType()) { case TypeTiny: // FALLTHROUGH case TypeBit: return longHelper(type, io.prestosql.spi.type.TinyintType.TINYINT, RecordCursorInternal::getByte); case TypeYear: case TypeShort: return longHelper(type, io.prestosql.spi.type.SmallintType.SMALLINT, RecordCursorInternal::getShort); case TypeInt24: // FALLTHROUGH case TypeLong: return longHelper(type, io.prestosql.spi.type.IntegerType.INTEGER, RecordCursorInternal::getInteger); case TypeFloat: return longHelper(type, io.prestosql.spi.type.RealType.REAL, (cursor, column) -> floatToRawIntBits(cursor.getFloat(column)), l -> intBitsToFloat(l.intValue())); case TypeDouble: return doubleHelper(type, io.prestosql.spi.type.DoubleType.DOUBLE, RecordCursorInternal::getDouble); case TypeNull: return null; case TypeDatetime: // FALLTHROUGH case TypeTimestamp: return longHelper(type, io.prestosql.spi.type.TimestampType.TIMESTAMP, (cursor, columnIndex) -> cursor.getTimestamp(columnIndex).getTime(), Timestamp::new); case TypeLonglong: return longHelper(type, io.prestosql.spi.type.BigintType.BIGINT, RecordCursorInternal::getLong); case TypeDate: // FALLTHROUGH case TypeNewDate: return longHelper(type, io.prestosql.spi.type.DateType.DATE, (cursor, columnIndex) -> { long localMillis = cursor.getDate(columnIndex).getTime(); DateTimeZone zone = ISOChronology.getInstance().getZone(); return MILLISECONDS.toDays(zone.getMillisKeepLocal(UTC, localMillis)); }, days -> new Date(DAYS.toMillis((long) days))); case TypeDuration: return longHelper(type, io.prestosql.spi.type.TimeType.TIME, (cursor, columnIndex) -> { long localMillis = cursor.getLong(columnIndex) / 1000000L; DateTimeZone zone = ISOChronology.getInstance().getZone(); return zone.convertUTCToLocal(zone.getMillisKeepLocal(UTC, localMillis)); }, millis -> (1000000L * (((long) millis) + 8 * 3600 * 1000L))); case TypeJSON: return null; case TypeSet: // TiKV client might has issue related to set, disable it at this time. return null; case TypeTinyBlob: // FALLTHROUGH case TypeMediumBlob: // FALLTHROUGH case TypeLongBlob: // FALLTHROUGH case TypeBlob: // FALLTHROUGH case TypeEnum: // FALLTHROUGH case TypeVarString: // FALLTHROUGH case TypeString: // FALLTHROUGH case TypeVarchar: // FALLTHROUGH if (type instanceof StringType || type instanceof SetType || type instanceof EnumType) { if (length > (long) VarcharType.MAX_LENGTH || length < 0) { return varcharHelper(type, VarcharType.createUnboundedVarcharType()); } return varcharHelper(type, VarcharType.createVarcharType((int) length)); } else if (type instanceof BytesType) { return sliceHelper(type, io.prestosql.spi.type.VarbinaryType.VARBINARY, (cursor, columnIndex) -> wrappedBuffer(cursor.getBytes(columnIndex)), Slice::getBytes); } else { return null; } case TypeDecimal: // FALLTHROUGH case TypeNewDecimal: int decimalDigits = type.getDecimal(); int precision = (int) length + max(-decimalDigits, 0); // Map decimal(p, -s) (negative scale) to decimal(p+s, 0). if (precision > Decimals.MAX_PRECISION) { return null; } return decimalHelper(type, io.prestosql.spi.type.DecimalType.createDecimalType(precision, max(decimalDigits, 0))); case TypeGeometry: // FALLTHROUGH default: return null; } } public static Optional<TypeHelper> getHelper(DataType type) { Optional<TypeHelper> helper = TYPE_HELPERS.get(type); if (helper != null) { return helper; } helper = Optional.ofNullable(getHelperInternal(type)); TYPE_HELPERS.putIfAbsent(type, helper); return helper; } public static Optional<Type> getPrestoType(DataType type) { return getHelper(type).map(TypeHelper::getPrestoType); } }
3e14528bfb159c36ad6223f376f9c5cec968d994
521
java
Java
viewinject-api/src/main/java/com/nelson/api/Finder.java
MogaoCaves/annotations-sample
5045c9ceea1d40b68f7eb5076ad9746efa03136d
[ "Apache-2.0" ]
null
null
null
viewinject-api/src/main/java/com/nelson/api/Finder.java
MogaoCaves/annotations-sample
5045c9ceea1d40b68f7eb5076ad9746efa03136d
[ "Apache-2.0" ]
null
null
null
viewinject-api/src/main/java/com/nelson/api/Finder.java
MogaoCaves/annotations-sample
5045c9ceea1d40b68f7eb5076ad9746efa03136d
[ "Apache-2.0" ]
null
null
null
18.607143
57
0.589251
8,605
package com.nelson.api; import android.app.Activity; import android.view.View; /** * Created by Nelson on 17/4/26. */ public enum Finder { VIEW { @Override public View findView(Object source, int id) { return ((View) source).findViewById(id); } }, ACTIVITY { @Override public View findView(Object source, int id) { return ((Activity) source).findViewById(id); } }; public abstract View findView(Object source, int id); }
3e1452ba23d6eae131c3026d81e86e51bd4551ee
5,914
java
Java
SMPTETestPattern/src/ca/jvsh/smpte/testpattern/SmpteTestPattern.java
evgenyvinnik/jvsc-android-apps
9f2c91ee6468507d08079e255772d9aea95b9afc
[ "Apache-2.0" ]
1
2018-09-28T17:06:37.000Z
2018-09-28T17:06:37.000Z
SMPTETestPattern/src/ca/jvsh/smpte/testpattern/SmpteTestPattern.java
evgenyvinnik/jvsc-android-apps
9f2c91ee6468507d08079e255772d9aea95b9afc
[ "Apache-2.0" ]
null
null
null
SMPTETestPattern/src/ca/jvsh/smpte/testpattern/SmpteTestPattern.java
evgenyvinnik/jvsc-android-apps
9f2c91ee6468507d08079e255772d9aea95b9afc
[ "Apache-2.0" ]
null
null
null
19.97973
72
0.638316
8,606
/* * Copyright (C) 2010 John Vinnik Software House */ package ca.jvsh.smpte.testpattern; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.os.Handler; import android.service.wallpaper.WallpaperService; import android.view.MotionEvent; import android.view.SurfaceHolder; /* * This animated wallpaper draws a rotating wireframe cube. */ public class SmpteTestPattern extends WallpaperService { private final Handler mHandler = new Handler(); @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); } @Override public Engine onCreateEngine() { return new CubeEngine(); } enum RectangleColors { WideUpperGray, UpperLightGray, UpperYellow, UpperCyan, UpperGreen, UpperMagenta, UpperRed, UpperBlue, UpperGray, MiddleCyan, MiddleDarkBlue, MiddleGray, MiddleBlue, MiddleYellow, MiddlePurple, MiddleRed, Lower1,//gray Lower2,//black Lower3,//white Lower4,//darkgray Lower5,//black Lower6,//darkgray Lower7,//gray Lower8,//darkgray Lower9,//gray Lower10,//darkgray Lower11,//gray RectangleCount } class CubeEngine extends Engine { private final Paint mPaint = new Paint(); private float mTouchX = -1; private float mTouchY = -1; private int mFrameCounter = 0; private Rect mRectFrame; private Rect[] mColorRectangles = new Rect[27]; private int[] rectColor = {0xFF696969, 0xFFC1C1C1, 0xFFC1C100, 0xFF00C1C1, 0xFF00C100, 0xFFC100C1, 0xFFC10000, 0xFF0000C1, 0xFF696969, 0xFF00FFFF, 0xFF052550, 0xFFC1C1C1, 0xFF0000FF, 0xFFFFFF00, 0xFF36056D, 0xFFFF0000, 0xFF2B2B2B, 0xFF050505, 0xFFFFFFFF, 0xFF050505, 0xFF000000, 0xFF050505, 0xFF0A0A0A, 0xFF050505, 0xFF0D0D0D, 0xFF050505, 0xFF2b2b2b}; //width and heights private int upperWideHeigth = 1; private int upperWideWidth = 1; private final Runnable mDrawSmpte = new Runnable() { public void run() { drawFrame(); } }; private boolean mVisible; CubeEngine() { // Create a Paint to draw the lines for our cube final Paint paint = mPaint; paint.setColor(0xffffffff); paint.setAntiAlias(true); paint.setStrokeWidth(2); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStyle(Paint.Style.STROKE); } @Override public void onCreate(SurfaceHolder surfaceHolder) { super.onCreate(surfaceHolder); // By default we don't get touch events, so enable them. setTouchEventsEnabled(true); } @Override public void onDestroy() { super.onDestroy(); mHandler.removeCallbacks(mDrawSmpte); } @Override public void onVisibilityChanged(boolean visible) { mVisible = visible; if (visible) { drawFrame(); } else { mHandler.removeCallbacks(mDrawSmpte); } } @Override public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) { super.onSurfaceChanged(holder, format, width, height); initFrameParams(width, height); drawFrame(); } @Override public void onSurfaceCreated(SurfaceHolder holder) { super.onSurfaceCreated(holder); } @Override public void onSurfaceDestroyed(SurfaceHolder holder) { super.onSurfaceDestroyed(holder); mVisible = false; mHandler.removeCallbacks(mDrawSmpte); } /* * Store the position of the touch event so we can use it for drawing * later */ @Override public void onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_MOVE) { mTouchX = event.getX(); mTouchY = event.getY(); } else { mTouchX = -1; mTouchY = -1; } super.onTouchEvent(event); } /* * Draw one frame of the animation. This method gets called repeatedly * by posting a delayed Runnable. You can do any drawing you want in * here. This example draws a wireframe cube. */ void drawFrame() { final SurfaceHolder holder = getSurfaceHolder(); Canvas c = null; try { c = holder.lockCanvas(); if (c != null) { // draw something drawCube(c); drawTouchPoint(c); } } finally { if (c != null) holder.unlockCanvasAndPost(c); } // Reschedule the next redraw mHandler.removeCallbacks(mDrawSmpte); if (mVisible) { mHandler.postDelayed(mDrawSmpte, 1000 / 25); } } /* * Draw a wireframe cube by drawing 12 3 dimensional lines between * adjacent corners of the cube */ void drawCube(Canvas c) { c.save(); c.drawColor(0xff000000); Rect drawRect = new Rect(); drawRect.left = upperWideHeigth; drawRect.right = mRectFrame.width(); drawRect.top = mFrameCounter; drawRect.bottom = upperWideWidth + mFrameCounter; Paint paint = new Paint(); paint.setARGB(255, 105, 105, 105); c.drawRect(drawRect, paint); mFrameCounter++; if (mFrameCounter > mRectFrame.bottom) mFrameCounter = 0; c.restore(); } void initFrameParams(int width, int height) { mRectFrame = new Rect(0, 0, height, width ); System.out.println("Rect " + mRectFrame ); upperWideHeigth = mRectFrame.height() * 5 /12; upperWideWidth = mRectFrame.width() / 8; System.out.println("upperWideHeigth " + upperWideHeigth ); System.out.println("upperWideWidth " + upperWideWidth ); } /* * Draw a circle around the current touch point, if any. */ void drawTouchPoint(Canvas c) { if (mTouchX >= 0 && mTouchY >= 0) { c.drawCircle(mTouchX, mTouchY, 80, mPaint); } } } }
3e1452e96fafbf0781b1de07b9318e9613c8367e
6,376
java
Java
deeplearning4j-core/src/test/java/org/deeplearning4j/util/ModelGuesserTest.java
firasdib/deeplearning4j
ecfd11e4c6e72361a913821ce38b7a7b01c9b9f4
[ "Apache-2.0" ]
2
2020-10-07T18:23:06.000Z
2021-06-13T16:17:28.000Z
deeplearning4j-core/src/test/java/org/deeplearning4j/util/ModelGuesserTest.java
firasdib/deeplearning4j
ecfd11e4c6e72361a913821ce38b7a7b01c9b9f4
[ "Apache-2.0" ]
null
null
null
deeplearning4j-core/src/test/java/org/deeplearning4j/util/ModelGuesserTest.java
firasdib/deeplearning4j
ecfd11e4c6e72361a913821ce38b7a7b01c9b9f4
[ "Apache-2.0" ]
null
null
null
41.947368
119
0.696048
8,607
package org.deeplearning4j.util; import org.apache.commons.compress.utils.IOUtils; import org.deeplearning4j.nn.api.Model; import org.deeplearning4j.nn.conf.ComputationGraphConfiguration; import org.deeplearning4j.nn.conf.MultiLayerConfiguration; import org.deeplearning4j.nn.conf.NeuralNetConfiguration; import org.deeplearning4j.nn.conf.layers.DenseLayer; import org.deeplearning4j.nn.conf.layers.OutputLayer; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.nn.weights.WeightInit; import org.junit.Test; import org.nd4j.linalg.activations.Activation; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.dataset.api.preprocessor.Normalizer; import org.nd4j.linalg.dataset.api.preprocessor.NormalizerMinMaxScaler; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.io.ClassPathResource; import org.nd4j.linalg.lossfunctions.LossFunctions; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeNotNull; /** * Created by agibsonccc on 12/29/16. */ public class ModelGuesserTest { @Test public void testModelGuess() throws Exception { ClassPathResource sequenceResource = new ClassPathResource("modelimport/keras/examples/mnist_mlp/mnist_mlp_tf_keras_1_model.h5"); assertTrue(sequenceResource.exists()); File f = getTempFile(sequenceResource); Model guess1 = ModelGuesser.loadModelGuess(f.getAbsolutePath()); assumeNotNull(guess1); ClassPathResource sequenceResource2 = new ClassPathResource("modelimport/keras/examples/mnist_cnn/mnist_cnn_tf_keras_1_model.h5"); assertTrue(sequenceResource2.exists()); File f2 = getTempFile(sequenceResource); Model guess2 = ModelGuesser.loadModelGuess(f2.getAbsolutePath()); assumeNotNull(guess2); } @Test public void testLoadNormalizers() throws Exception { int nIn = 5; int nOut = 6; MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345).regularization(true).l1(0.01) .l2(0.01).learningRate(0.1).activation(Activation.TANH).weightInit(WeightInit.XAVIER).list() .layer(0, new DenseLayer.Builder().nIn(nIn).nOut(20).build()) .layer(1, new DenseLayer.Builder().nIn(20).nOut(30).build()).layer(2, new OutputLayer.Builder() .lossFunction(LossFunctions.LossFunction.MSE).nIn(30).nOut(nOut).build()) .build(); MultiLayerNetwork net = new MultiLayerNetwork(conf); net.init(); File tempFile = File.createTempFile("tsfs", "fdfsdf"); tempFile.deleteOnExit(); ModelSerializer.writeModel(net, tempFile, true); NormalizerMinMaxScaler normalizer = new NormalizerMinMaxScaler(0, 1); normalizer.fit(new DataSet(Nd4j.rand(new int[] {2, 2}), Nd4j.rand(new int[] {2, 2}))); ModelSerializer.addNormalizerToModel(tempFile, normalizer); Model model = ModelGuesser.loadModelGuess(tempFile.getAbsolutePath()); Normalizer<?> normalizer1 = ModelGuesser.loadNormalizer(tempFile.getAbsolutePath()); assertEquals(model, net); assertEquals(normalizer, normalizer1); } @Test public void testModelGuesserDl4jModel() throws Exception { int nIn = 5; int nOut = 6; MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345).regularization(true).l1(0.01) .l2(0.01).learningRate(0.1).activation(Activation.TANH).weightInit(WeightInit.XAVIER).list() .layer(0, new DenseLayer.Builder().nIn(nIn).nOut(20).build()) .layer(1, new DenseLayer.Builder().nIn(20).nOut(30).build()).layer(2, new OutputLayer.Builder() .lossFunction(LossFunctions.LossFunction.MSE).nIn(30).nOut(nOut).build()) .build(); MultiLayerNetwork net = new MultiLayerNetwork(conf); net.init(); File tempFile = File.createTempFile("tsfs", "fdfsdf"); tempFile.deleteOnExit(); ModelSerializer.writeModel(net, tempFile, true); MultiLayerNetwork network = (MultiLayerNetwork) ModelGuesser.loadModelGuess(tempFile.getAbsolutePath()); assertEquals(network.getLayerWiseConfigurations().toJson(), net.getLayerWiseConfigurations().toJson()); assertEquals(net.params(), network.params()); assertEquals(net.getUpdater().getStateViewArray(), network.getUpdater().getStateViewArray()); } @Test public void testModelGuessConfig() throws Exception { ClassPathResource resource = new ClassPathResource("modelimport/keras/configs/cnn_tf_config.json", ModelGuesserTest.class.getClassLoader()); File f = getTempFile(resource); String configFilename = f.getAbsolutePath(); Object conf = ModelGuesser.loadConfigGuess(configFilename); assertTrue(conf instanceof MultiLayerConfiguration); ClassPathResource sequenceResource = new ClassPathResource("/keras/simple/mlp_fapi_multiloss_config.json"); File f2 = getTempFile(sequenceResource); Object sequenceConf = ModelGuesser.loadConfigGuess(f2.getAbsolutePath()); assertTrue(sequenceConf instanceof ComputationGraphConfiguration); ClassPathResource resourceDl4j = new ClassPathResource("model.json"); File fDl4j = getTempFile(resourceDl4j); String configFilenameDl4j = fDl4j.getAbsolutePath(); Object confDl4j = ModelGuesser.loadConfigGuess(configFilenameDl4j); assertTrue(confDl4j instanceof ComputationGraphConfiguration); } private File getTempFile(ClassPathResource classPathResource) throws Exception { InputStream is = classPathResource.getInputStream(); File f = new File(UUID.randomUUID().toString()); f.deleteOnExit(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f)); IOUtils.copy(is, bos); bos.flush(); bos.close(); return f; } }
3e1453e9052c62eda65dd025de37f3a8bcd4dea5
483
java
Java
gulimall-product/src/main/java/com/atguigu/gulimall/product/service/ProductAttrValueService.java
Monarchflame/gulimall
1c0663165e85d3fdbc32a42dd63ac24957b29e1d
[ "Apache-2.0" ]
null
null
null
gulimall-product/src/main/java/com/atguigu/gulimall/product/service/ProductAttrValueService.java
Monarchflame/gulimall
1c0663165e85d3fdbc32a42dd63ac24957b29e1d
[ "Apache-2.0" ]
2
2021-04-22T17:08:25.000Z
2021-09-20T20:58:42.000Z
gulimall-product/src/main/java/com/atguigu/gulimall/product/service/ProductAttrValueService.java
Monarchflame/gulimall
1c0663165e85d3fdbc32a42dd63ac24957b29e1d
[ "Apache-2.0" ]
null
null
null
23.190476
83
0.784394
8,608
package com.atguigu.gulimall.product.service; import com.baomidou.mybatisplus.extension.service.IService; import com.atguigu.common.utils.PageUtils; import com.atguigu.gulimall.product.entity.ProductAttrValueEntity; import java.util.Map; /** * spu属性值 * * @author leifengyang * @email ychag@example.com * @date 2020-05-14 17:28:51 */ public interface ProductAttrValueService extends IService<ProductAttrValueEntity> { PageUtils queryPage(Map<String, Object> params); }
3e14540c6e86f47a4d844e94caf7154cfacceded
298
java
Java
src/main/java/com/rickie/order/example/domain/commands/PlaceOrderCommand.java
ty-wssf/axon-order
5a8a8eeb0d013d4b5b0af4bf8c602ea62bb60d2d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/rickie/order/example/domain/commands/PlaceOrderCommand.java
ty-wssf/axon-order
5a8a8eeb0d013d4b5b0af4bf8c602ea62bb60d2d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/rickie/order/example/domain/commands/PlaceOrderCommand.java
ty-wssf/axon-order
5a8a8eeb0d013d4b5b0af4bf8c602ea62bb60d2d
[ "Apache-2.0" ]
null
null
null
19.866667
69
0.778523
8,609
package com.rickie.order.example.domain.commands; import lombok.Data; import org.axonframework.modelling.command.TargetAggregateIdentifier; /** * 发货订单 */ @Data public class PlaceOrderCommand { @TargetAggregateIdentifier private final String orderId; private final String product; }
3e14558b4f1c8023ba0cb38e99187243315d636f
2,113
java
Java
app/src/main/java/net/beaconradar/service/Scheduler.java
falkorichter/beaconradar
8146fbc65e1cff804b70ee930086a29bc421dfc8
[ "Apache-2.0" ]
15
2016-05-05T20:53:59.000Z
2021-09-22T20:28:22.000Z
app/src/main/java/net/beaconradar/service/Scheduler.java
falkorichter/beaconradar
8146fbc65e1cff804b70ee930086a29bc421dfc8
[ "Apache-2.0" ]
3
2016-09-15T17:29:41.000Z
2020-03-09T05:55:46.000Z
app/src/main/java/net/beaconradar/service/Scheduler.java
stanleyguevara/beaconradar
ce990eb18b941429e7d1ba2d4bfda3e11119e5ee
[ "Apache-2.0" ]
2
2016-09-30T10:37:21.000Z
2020-09-06T03:38:09.000Z
37.732143
101
0.727875
8,610
package net.beaconradar.service; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; public abstract class Scheduler { public static final String WAKEUP_JIC = "just_in_case_wakeup"; public static final String WAKEUP_SCAN = "scheduled_scan_wakeup"; public static final int WARNING_NONE = 0; public static final int WARNING_MAY_BE_INACCURATE = 1; public static final int WARNING_HIGH_BATT = 2; public static final int WARNING_EXTREME_BATT = 3; public static final int WARNING_USE_HP_INSTEAD = 4; protected final Context mAppContext; protected final AlarmManager mAlarm; public Scheduler(Context appContext, AlarmManager alarmManager) { mAppContext = appContext; mAlarm = alarmManager; } /** * Schedules alarm, or lets caller know that it should use EternalWakeLock (TM) * @param millis * @param mode * @param foreground * @param exact * @return true if scheduled, false if caller should use EternalWakeLock (TM) */ protected abstract boolean schedule(long millis, int mode, boolean foreground, boolean exact); protected abstract boolean cycle(long millis, int mode, boolean foreground, boolean exact); public abstract int warning(long millis, int mode, boolean foreground, boolean exact); //This actually should be used in BeaconService. public boolean shouldStopService(long millis, int mode) { if(mode == BeaconService.SCAN_FOREGROUND) return false; else return millis > 60000; } public PendingIntent getIntent(String extra) { Intent intent = new Intent(mAppContext, ReceiverStatic.class); intent.setAction(BeaconService.ACTION_WAKEUP); intent.putExtra(BeaconService.EXTRA_KIND, extra); //Can't use FLAG_CANCEL_CURRENT due to Samsung 500 alarms limit. return PendingIntent.getBroadcast(mAppContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } public void cancelScheduled() { mAlarm.cancel(getIntent(WAKEUP_SCAN)); } }
3e14560a909b137dc1c32007fbc07c7dbcd4726f
4,076
java
Java
hexagonal-poc-adapter/src/test/java/br/com/reschoene/poc/architecture/adapter/persistence/ProductJPAAdapterTest.java
reschoene/hexagonal-poc
6825a7156ef1770dca79d6f2bd5fa66d9782744c
[ "MIT" ]
5
2021-04-16T15:08:45.000Z
2021-06-09T13:21:07.000Z
hexagonal-poc-adapter/src/test/java/br/com/reschoene/poc/architecture/adapter/persistence/ProductJPAAdapterTest.java
reschoene/hexagonal-poc
6825a7156ef1770dca79d6f2bd5fa66d9782744c
[ "MIT" ]
null
null
null
hexagonal-poc-adapter/src/test/java/br/com/reschoene/poc/architecture/adapter/persistence/ProductJPAAdapterTest.java
reschoene/hexagonal-poc
6825a7156ef1770dca79d6f2bd5fa66d9782744c
[ "MIT" ]
2
2021-05-20T15:45:43.000Z
2021-05-20T20:19:10.000Z
35.754386
103
0.716634
8,611
package br.com.reschoene.poc.architecture.adapter.persistence; import br.com.reschoene.poc.architecture.adapter.helper.ProductCreator; import br.com.reschoene.poc.architecture.adapter.helper.ProductEntityCreator; import br.com.reschoene.poc.architecture.adapter.output.persistence.jpa.ProductEntity; import br.com.reschoene.poc.architecture.adapter.output.persistence.jpa.ProductJPAAdapter; import br.com.reschoene.poc.architecture.adapter.output.persistence.jpa.ProductJPARepository; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.BDDMockito; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import java.util.Optional; @ExtendWith(MockitoExtension.class) class ProductJPAAdapterTest { @InjectMocks private ProductJPAAdapter productJPAAdapter; @Mock ProductJPARepository jpaRepository; @Test @DisplayName("getProductById returns a product when given product id exists") void getProductById_ReturnsProduct_WhenProductIdExist() { BDDMockito.given(jpaRepository.findById(ArgumentMatchers.anyLong())) .willReturn(Optional.of(ProductEntityCreator.createValid())); var product = productJPAAdapter.getProductById(1L); Assertions.assertThat(product) .isNotNull(); } @Test @DisplayName("getProductById returns an empty optional when given product id exists") void getProductById_ReturnsEmptyOptional_WhenProductIdDoesNotExist() { var product = productJPAAdapter.getProductById(-1L); Assertions.assertThat(product) .isEmpty(); } @Test @DisplayName("getAllProducts returns a product list when success") void getAllProducts_ReturnsProductList_WhenSuccess() { BDDMockito.given(jpaRepository.findAll()) .willReturn(List.of(ProductEntityCreator.createValid())); var products = productJPAAdapter.getAllProducts(); Assertions.assertThat(products) .isNotNull() .hasSize(1); } @Test @DisplayName("addProduct returns a valid product when success") void addProduct_ReturnsValidProduct_WhenSuccess() { BDDMockito.given(jpaRepository.save(ProductEntity.fromModel(ProductCreator.createToBeSaved()))) .willReturn(ProductEntityCreator.createValid()); var product = productJPAAdapter.addProduct(ProductCreator.createToBeSaved()); Assertions.assertThat(product) .isNotNull(); Assertions.assertThat(product.getId()) .isEqualTo(1L); } @Test @DisplayName("updateProduct returns a valid product when success") void updateProduct_ReturnsValidProduct_WhenSuccess() { var prodToBeUpdated = ProductEntityCreator.createProductToBeUpdated(); BDDMockito.given(jpaRepository.save(prodToBeUpdated)) .willReturn(ProductEntityCreator.createUpdatedProduct()); var product = productJPAAdapter.updateProduct(ProductCreator.createProductToBeUpdated()); Assertions.assertThat(product) .isNotNull(); Assertions.assertThat(product.getId()) .isEqualTo(1L); Assertions.assertThat(product.getDescription()) .isNotNull() .isEqualTo(prodToBeUpdated.getDescription()); } @Test @DisplayName("removeProduct returns a valid product when success") void removeProduct_ReturnsValidProduct_WhenSuccess() { var product = productJPAAdapter.removeProduct(ProductCreator.createValid()); Assertions.assertThat(product) .isNotNull(); Assertions.assertThat(product.getId()) .isEqualTo(1L); Assertions.assertThat(product.getDescription()) .isEqualTo(ProductCreator.createValid().getDescription()); } }
3e1457245372f797f9bc912571e0ae954d4fd0d1
480
java
Java
factory/src/main/java/com/example/pattern/runner/FactoryStartRunner.java
nightsoil01/spring-boot-pattern
ea30ebbf03fe440572c46122ca7b9f50fe89663f
[ "Apache-2.0" ]
null
null
null
factory/src/main/java/com/example/pattern/runner/FactoryStartRunner.java
nightsoil01/spring-boot-pattern
ea30ebbf03fe440572c46122ca7b9f50fe89663f
[ "Apache-2.0" ]
null
null
null
factory/src/main/java/com/example/pattern/runner/FactoryStartRunner.java
nightsoil01/spring-boot-pattern
ea30ebbf03fe440572c46122ca7b9f50fe89663f
[ "Apache-2.0" ]
null
null
null
21.818182
62
0.816667
8,612
package com.example.pattern.runner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Configuration; import com.example.pattern.factory.CarFactory; @Configuration public class FactoryStartRunner implements CommandLineRunner { @Autowired private CarFactory carFactory; @Override public void run(String... args) throws Exception { carFactory.produce(); } }
3e14574b52296506dcf7d5c7708712b657771c71
11,219
java
Java
jbpm-persistence-jpa/src/main/java/org/jbpm/persistence/processinstance/JPAProcessInstanceManager.java
Multi-Support/jbpm
e462da6dcb580ce604a0d2d85037f47d7c24e99e
[ "Apache-2.0" ]
1
2016-02-19T21:06:10.000Z
2016-02-19T21:06:10.000Z
jbpm-persistence-jpa/src/main/java/org/jbpm/persistence/processinstance/JPAProcessInstanceManager.java
Multi-Support/jbpm
e462da6dcb580ce604a0d2d85037f47d7c24e99e
[ "Apache-2.0" ]
null
null
null
jbpm-persistence-jpa/src/main/java/org/jbpm/persistence/processinstance/JPAProcessInstanceManager.java
Multi-Support/jbpm
e462da6dcb580ce604a0d2d85037f47d7c24e99e
[ "Apache-2.0" ]
null
null
null
48.5671
194
0.695784
8,613
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 org.jbpm.persistence.processinstance; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.drools.core.common.InternalKnowledgeRuntime; import org.drools.persistence.TransactionManager; import org.drools.persistence.TransactionManagerHelper; import org.jbpm.persistence.ProcessPersistenceContext; import org.jbpm.persistence.ProcessPersistenceContextManager; import org.jbpm.persistence.correlation.CorrelationKeyInfo; import org.jbpm.process.instance.InternalProcessRuntime; import org.jbpm.process.instance.ProcessInstanceManager; import org.jbpm.process.instance.impl.ProcessInstanceImpl; import org.jbpm.process.instance.timer.TimerManager; import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl; import org.jbpm.workflow.instance.node.StateBasedNodeInstance; import org.jbpm.workflow.instance.node.TimerNodeInstance; import org.kie.api.definition.process.Process; import org.kie.api.runtime.EnvironmentName; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.runtime.process.WorkflowProcessInstance; import org.kie.internal.process.CorrelationKey; import org.kie.internal.runtime.manager.InternalRuntimeManager; import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext; /** * This is an implementation of the {@link ProcessInstanceManager} that uses JPA. * </p> * What's important to remember here is that we have a jbpm-console which has 1 static (stateful) knowledge session * which is used by multiple threads: each request sent to the jbpm-console is picked up in it's own thread. * </p> * This means that multiple threads can be using the same instance of this class. */ public class JPAProcessInstanceManager implements ProcessInstanceManager { private InternalKnowledgeRuntime kruntime; // In a scenario in which 1000's of processes are running daily, // lazy initialization is more costly than eager initialization // Added volatile so that if something happens, we can figure out what private volatile transient Map<Long, ProcessInstance> processInstances = new ConcurrentHashMap<Long, ProcessInstance>(); public void setKnowledgeRuntime(InternalKnowledgeRuntime kruntime) { this.kruntime = kruntime; } public void addProcessInstance(ProcessInstance processInstance, CorrelationKey correlationKey) { ProcessInstanceInfo processInstanceInfo = new ProcessInstanceInfo( processInstance, this.kruntime.getEnvironment() ); ProcessPersistenceContext context = ((ProcessPersistenceContextManager) this.kruntime.getEnvironment() .get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER )) .getProcessPersistenceContext(); processInstanceInfo = context.persist( processInstanceInfo ); ((org.jbpm.process.instance.ProcessInstance) processInstance).setId( processInstanceInfo.getId() ); processInstanceInfo.updateLastReadDate(); // persist correlation if exists if (correlationKey != null) { CorrelationKeyInfo correlationKeyInfo = (CorrelationKeyInfo) correlationKey; correlationKeyInfo.setProcessInstanceId(processInstanceInfo.getId()); context.persist(correlationKeyInfo); } internalAddProcessInstance(processInstance); } public void internalAddProcessInstance(ProcessInstance processInstance) { if( ((ConcurrentHashMap<Long, ProcessInstance>) processInstances) .putIfAbsent(processInstance.getId(), processInstance) != null ) { throw new ConcurrentModificationException( "Duplicate process instance [" + processInstance.getProcessId() + "/" + processInstance.getId() + "]" + " added to process instance manager." ); } } public ProcessInstance getProcessInstance(long id) { return getProcessInstance(id, false); } public ProcessInstance getProcessInstance(long id, boolean readOnly) { InternalRuntimeManager manager = (InternalRuntimeManager) kruntime.getEnvironment().get("RuntimeManager"); if (manager != null) { manager.validate((KieSession) kruntime, ProcessInstanceIdContext.get(id)); } TransactionManager txm = (TransactionManager) this.kruntime.getEnvironment().get( EnvironmentName.TRANSACTION_MANAGER ); org.jbpm.process.instance.ProcessInstance processInstance = null; processInstance = (org.jbpm.process.instance.ProcessInstance) this.processInstances.get(id); if (processInstance != null) { if (((WorkflowProcessInstanceImpl) processInstance).isPersisted() && !readOnly) { ProcessPersistenceContextManager ppcm = (ProcessPersistenceContextManager) this.kruntime.getEnvironment().get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER ); ppcm.beginCommandScopedEntityManager(); ProcessPersistenceContext context = ppcm.getProcessPersistenceContext(); ProcessInstanceInfo processInstanceInfo = context.findProcessInstanceInfo( id ); if ( processInstanceInfo == null ) { return null; } TransactionManagerHelper.addToUpdatableSet(txm, processInstanceInfo); processInstanceInfo.updateLastReadDate(); } return processInstance; } // Make sure that the cmd scoped entity manager has started ProcessPersistenceContextManager ppcm = (ProcessPersistenceContextManager) this.kruntime.getEnvironment().get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER ); ppcm.beginCommandScopedEntityManager(); ProcessPersistenceContext context = ppcm.getProcessPersistenceContext(); ProcessInstanceInfo processInstanceInfo = context.findProcessInstanceInfo( id ); if ( processInstanceInfo == null ) { return null; } processInstance = (org.jbpm.process.instance.ProcessInstance) processInstanceInfo.getProcessInstance(kruntime, this.kruntime.getEnvironment()); if (!readOnly) { processInstanceInfo.updateLastReadDate(); TransactionManagerHelper.addToUpdatableSet(txm, processInstanceInfo); } if (((ProcessInstanceImpl) processInstance).getProcessXml() == null) { Process process = kruntime.getKieBase().getProcess( processInstance.getProcessId() ); if ( process == null ) { throw new IllegalArgumentException( "Could not find process " + processInstance.getProcessId() ); } processInstance.setProcess( process ); } if ( processInstance.getKnowledgeRuntime() == null ) { Long parentProcessInstanceId = (Long) ((ProcessInstanceImpl) processInstance).getMetaData().get("ParentProcessInstanceId"); if (parentProcessInstanceId != null) { kruntime.getProcessInstance(parentProcessInstanceId); } processInstance.setKnowledgeRuntime( kruntime ); ((ProcessInstanceImpl) processInstance).reconnect(); } return processInstance; } public Collection<ProcessInstance> getProcessInstances() { return Collections.unmodifiableCollection(processInstances.values()); } public void removeProcessInstance(ProcessInstance processInstance) { ProcessPersistenceContext context = ((ProcessPersistenceContextManager) this.kruntime.getEnvironment().get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER )).getProcessPersistenceContext(); ProcessInstanceInfo processInstanceInfo = context.findProcessInstanceInfo( processInstance.getId() ); if ( processInstanceInfo != null ) { context.remove( processInstanceInfo ); } internalRemoveProcessInstance(processInstance); } public void internalRemoveProcessInstance(ProcessInstance processInstance) { processInstances.remove( processInstance.getId() ); } public void clearProcessInstances() { for (ProcessInstance processInstance: new ArrayList<ProcessInstance>(processInstances.values())) { ((ProcessInstanceImpl) processInstance).disconnect(); } } public void clearProcessInstancesState() { try { // at this point only timers are considered as state that needs to be cleared TimerManager timerManager = ((InternalProcessRuntime)kruntime.getProcessRuntime()).getTimerManager(); for (ProcessInstance processInstance: new ArrayList<ProcessInstance>(processInstances.values())) { WorkflowProcessInstance pi = ((WorkflowProcessInstance) processInstance); for (org.kie.api.runtime.process.NodeInstance nodeInstance : pi.getNodeInstances()) { if (nodeInstance instanceof TimerNodeInstance){ if (((TimerNodeInstance)nodeInstance).getTimerInstance() != null) { timerManager.cancelTimer(((TimerNodeInstance)nodeInstance).getTimerInstance().getId()); } } else if (nodeInstance instanceof StateBasedNodeInstance) { List<Long> timerIds = ((StateBasedNodeInstance) nodeInstance).getTimerInstances(); if (timerIds != null) { for (Long id: timerIds) { timerManager.cancelTimer(id); } } } } } } catch (Exception e) { // catch everything here to make sure it will not break any following // logic to allow complete clean up } } @Override public ProcessInstance getProcessInstance(CorrelationKey correlationKey) { ProcessPersistenceContext context = ((ProcessPersistenceContextManager) this.kruntime.getEnvironment() .get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER )) .getProcessPersistenceContext(); Long processInstanceId = context.getProcessInstanceByCorrelationKey(correlationKey); if (processInstanceId == null) { return null; } return getProcessInstance(processInstanceId); } }
3e1457774bcbeac18e2f7d8975160d3a2aac4be1
869
java
Java
src/main/java/com/codeborne/selenide/commands/GetPreceding.java
eroshenkoam/selenide
b1589a8dc310c45b6e432c41e122b00166819806
[ "MIT" ]
1
2017-08-22T15:58:39.000Z
2017-08-22T15:58:39.000Z
src/main/java/com/codeborne/selenide/commands/GetPreceding.java
eroshenkoam/selenide
b1589a8dc310c45b6e432c41e122b00166819806
[ "MIT" ]
22
2021-01-26T06:18:59.000Z
2022-02-17T09:03:50.000Z
src/main/java/com/codeborne/selenide/commands/GetPreceding.java
eroshenkoam/selenide
b1589a8dc310c45b6e432c41e122b00166819806
[ "MIT" ]
null
null
null
31.035714
108
0.798619
8,614
package com.codeborne.selenide.commands; import com.codeborne.selenide.Command; import com.codeborne.selenide.SelenideElement; import com.codeborne.selenide.impl.WebElementSource; import org.openqa.selenium.By; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import static com.codeborne.selenide.commands.Util.firstOf; @ParametersAreNonnullByDefault public class GetPreceding implements Command<SelenideElement> { @Override @CheckReturnValue @Nonnull public SelenideElement execute(SelenideElement proxy, WebElementSource locator, @Nullable Object[] args) { assert args != null; int siblingIndex = (int) firstOf(args) + 1; return locator.find(proxy, By.xpath(String.format("preceding-sibling::*[%d]", siblingIndex)), 0); } }
3e1457d7b2186bc39bed8e67f4194264c1a4c580
454
java
Java
src/main/java/me/modmuss50/technicaldimensions/server/ScreenShotSaver.java
modmuss50/TechnicalDimensions
34c2bb2e26608d530f06686d04c8ee000cce2e69
[ "MIT" ]
4
2016-08-07T01:27:42.000Z
2021-02-02T15:23:40.000Z
src/main/java/me/modmuss50/technicaldimensions/server/ScreenShotSaver.java
modmuss50/TechnicalDimensions
34c2bb2e26608d530f06686d04c8ee000cce2e69
[ "MIT" ]
6
2016-08-08T02:40:08.000Z
2016-09-15T15:21:05.000Z
src/main/java/me/modmuss50/technicaldimensions/server/ScreenShotSaver.java
modmuss50/TechnicalDimensions
34c2bb2e26608d530f06686d04c8ee000cce2e69
[ "MIT" ]
null
null
null
19.73913
65
0.656388
8,615
package me.modmuss50.technicaldimensions.server; import java.util.List; /** * Created by Mark on 04/08/2016. */ public class ScreenShotSaver { List<ScreenShotData> screenshots; public static class ScreenShotData { public String imageID; public String imageData; public ScreenShotData(String imageID, String imageData) { this.imageID = imageID; this.imageData = imageData; } } }
3e14591522a4bee08f0a774929bd88152b360dc8
4,177
java
Java
corpus/class/eclipse.pde.ui/4393.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
15
2018-07-10T09:38:31.000Z
2021-11-29T08:28:07.000Z
corpus/class/eclipse.pde.ui/4393.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
3
2018-11-16T02:58:59.000Z
2021-01-20T16:03:51.000Z
corpus/class/eclipse.pde.ui/4393.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
6
2018-06-27T20:19:00.000Z
2022-02-19T02:29:53.000Z
38.675926
114
0.645918
8,616
/******************************************************************************* * Copyright (c) 2009, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.pde.internal.ui.shared.target; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.pde.core.target.ITargetDefinition; import org.eclipse.pde.core.target.ITargetLocation; import org.eclipse.pde.internal.ui.*; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.PlatformUI; /** * Wizard page that displays the contents of a bundle container in a table * */ public class PreviewContainerPage extends WizardPage { private ITargetDefinition fTarget; private EditDirectoryContainerPage fPage1; protected TableViewer fPreviewTable; protected Object fInput; protected PreviewContainerPage(ITargetDefinition definition, EditDirectoryContainerPage page1) { //$NON-NLS-1$ super("ContainerPreviewPage"); setTitle(Messages.PreviewContainerPage_1); setMessage(Messages.PreviewContainerPage_2); fTarget = definition; fPage1 = page1; } @Override public void createControl(Composite parent) { Composite composite = SWTFactory.createComposite(parent, 1, 1, GridData.FILL_BOTH); SWTFactory.createLabel(composite, Messages.PreviewContainerPage_3, 1); fPreviewTable = new TableViewer(composite); fPreviewTable.setLabelProvider(new StyledBundleLabelProvider(true, false)); fPreviewTable.setContentProvider(ArrayContentProvider.getInstance()); fPreviewTable.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); setControl(composite); PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.LOCATION_PREVIEW_WIZARD); } /** * Refreshes the contents of the preview table, possible resolving the container * @param resolve whether the current container should be resolved if it hasn't been already */ protected void setInput(final ITargetLocation container) { if (container == null) { fInput = null; fPreviewTable.setInput(null); return; } if (container.isResolved()) { fInput = container.getBundles(); fPreviewTable.setInput(fInput); return; } try { getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { IStatus result = container.resolve(fTarget, monitor); if (monitor.isCanceled()) { fInput = new Object[] { Messages.PreviewContainerPage_0 }; } else if (!result.isOK() && !result.isMultiStatus()) { fInput = new Object[] { result }; } else { fInput = container.getBundles(); } } }); fPreviewTable.setInput(fInput); } catch (InvocationTargetException e) { PDEPlugin.log(e); setErrorMessage(e.getMessage()); } catch (InterruptedException e) { } } @Override public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { setInput(fPage1.getBundleContainer()); } } }
3e1459635a8f6c0d798481aac4e32db39d163571
3,909
java
Java
ifs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/finance/viewmodel/ApplicationFinanceSummaryViewModel.java
danielholdsworth/innovation-funding-service
39748ba4f574c29f3d09adde7af60ca85ffeec06
[ "MIT" ]
null
null
null
ifs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/finance/viewmodel/ApplicationFinanceSummaryViewModel.java
danielholdsworth/innovation-funding-service
39748ba4f574c29f3d09adde7af60ca85ffeec06
[ "MIT" ]
null
null
null
ifs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/finance/viewmodel/ApplicationFinanceSummaryViewModel.java
danielholdsworth/innovation-funding-service
39748ba4f574c29f3d09adde7af60ca85ffeec06
[ "MIT" ]
null
null
null
36.877358
129
0.719366
8,617
package org.innovateuk.ifs.application.finance.viewmodel; import org.innovateuk.ifs.analytics.BaseAnalyticsViewModel; import org.innovateuk.ifs.competition.resource.CollaborationLevel; import org.innovateuk.ifs.competition.resource.CompetitionResource; import java.math.BigDecimal; import java.util.List; import static java.util.stream.Collectors.toList; import static org.innovateuk.ifs.util.CollectionFunctions.negate; /** * View model for finance/finance-summary :: application-finances-summary. */ public class ApplicationFinanceSummaryViewModel implements BaseAnalyticsViewModel { private final FinanceSummaryTableViewModel financeSummaryTableViewModel; private final CollaborationLevel collaborationLevel; private final Long currentUsersOrganisationId; public ApplicationFinanceSummaryViewModel(CompetitionResource competition, FinanceSummaryTableViewModel financeSummaryTableViewModel, Long currentUsersOrganisationId) { this.financeSummaryTableViewModel = financeSummaryTableViewModel; this.collaborationLevel = competition.getCollaborationLevel(); this.currentUsersOrganisationId = currentUsersOrganisationId; } @Override public Long getApplicationId() { return financeSummaryTableViewModel.getApplicationId(); } @Override public String getCompetitionName() { return financeSummaryTableViewModel.getCompetitionName(); } public boolean isReadOnly() { return financeSummaryTableViewModel.isReadOnly(); } public boolean isCollaborativeProject() { return financeSummaryTableViewModel.isCollaborativeProject(); } public Long getCurrentUsersOrganisationId() { return currentUsersOrganisationId; } public BigDecimal getCompetitionMaximumFundingSought() { return financeSummaryTableViewModel.getCompetitionMaximumFundingSought(); } public FinanceSummaryTableViewModel getFinanceSummaryTableViewModel() { return financeSummaryTableViewModel; } public boolean isKtp() { return financeSummaryTableViewModel.isKtp(); } public boolean showCollaborationWarning() { return CollaborationLevel.COLLABORATIVE.equals(collaborationLevel) && !atLeastTwoCompleteOrganisationFinances(); } public boolean showFundingSoughtWarning() { return !isFundingSoughtValid(); } private boolean isFundingSoughtValid() { if (financeSummaryTableViewModel.getCompetitionMaximumFundingSought() == null) { return true; } return financeSummaryTableViewModel.getRows().stream() .map(row -> row.getFundingSought()) .reduce(BigDecimal::add).get().compareTo(financeSummaryTableViewModel.getCompetitionMaximumFundingSought()) <= 0; } public List<FinanceSummaryTableRow> getIncompleteOrganisations() { return financeSummaryTableViewModel.getRows().stream() .filter(negate(FinanceSummaryTableRow::isComplete)) .filter(negate(FinanceSummaryTableRow::isPendingOrganisation)) .collect(toList()); } public boolean isUsersFinancesIncomplete() { return financeSummaryTableViewModel.getRows().stream() .filter(row -> row.getOrganisationId() != null) .anyMatch(row -> row.getOrganisationId().equals(currentUsersOrganisationId) && !row.isComplete()); } public boolean showFinancesIncompleteWarning() { return !financeSummaryTableViewModel.isAllFinancesComplete() && !showFundingSoughtWarning(); } private boolean atLeastTwoCompleteOrganisationFinances() { return financeSummaryTableViewModel.getRows().stream().filter(FinanceSummaryTableRow::isComplete) .count() > 1; } }
3e1459ad1367636d1aa46b43855e156714dc9b08
648
java
Java
org.eniware.central.common.security/src/org/eniware/central/security/SecurityUser.java
eniware-org/org.eniware.central
64d999cd743a1ebc39dccbe89c68772cae5129d7
[ "Apache-2.0" ]
null
null
null
org.eniware.central.common.security/src/org/eniware/central/security/SecurityUser.java
eniware-org/org.eniware.central
64d999cd743a1ebc39dccbe89c68772cae5129d7
[ "Apache-2.0" ]
null
null
null
org.eniware.central.common.security/src/org/eniware/central/security/SecurityUser.java
eniware-org/org.eniware.central
64d999cd743a1ebc39dccbe89c68772cae5129d7
[ "Apache-2.0" ]
null
null
null
17.052632
69
0.493827
8,618
/* ================================================================== * Eniware Open Source:Nikolai Manchev * Apache License 2.0 * ================================================================== */ package org.eniware.central.security; /** * API for user details. * @version 1.0 */ public interface SecurityUser extends SecurityActor { /** * Get a friendly display name. * * @return display name */ String getDisplayName(); /** * Get the email used to authenticate the user with. * * @return email */ String getEmail(); /** * Get a unique user ID. * * @return the user ID */ Long getUserId(); }
3e145a059893a0c9be55c721e01e1bd24ca86626
507
java
Java
modules/orchestration/srs-camunda-flows/src/main/java/org/systems/dipe/srs/orchestration/flows/request/messages/CancelRequestMessage.java
chirkovd/srs-platform
41f35c60084fc8967e289b2de9e66634e113b8cb
[ "Apache-2.0" ]
null
null
null
modules/orchestration/srs-camunda-flows/src/main/java/org/systems/dipe/srs/orchestration/flows/request/messages/CancelRequestMessage.java
chirkovd/srs-platform
41f35c60084fc8967e289b2de9e66634e113b8cb
[ "Apache-2.0" ]
16
2022-02-19T05:38:31.000Z
2022-03-31T08:31:53.000Z
modules/orchestration/srs-camunda-flows/src/main/java/org/systems/dipe/srs/orchestration/flows/request/messages/CancelRequestMessage.java
chirkovd/srs-platform
41f35c60084fc8967e289b2de9e66634e113b8cb
[ "Apache-2.0" ]
null
null
null
25.35
66
0.769231
8,619
package org.systems.dipe.srs.orchestration.flows.request.messages; import com.fasterxml.jackson.annotation.JsonCreator; import lombok.NoArgsConstructor; import org.systems.dipe.srs.orchestration.SrsEventType; @NoArgsConstructor public class CancelRequestMessage extends AbstractRequestMessage { @JsonCreator public CancelRequestMessage(String requestId) { super(requestId); } @Override public String getType() { return SrsEventType.REQUEST_CANCELLED.getId(); } }
3e145a6f29eb6b17b436ecd6a2081573f21ff0b0
1,889
java
Java
AndroidAnnotations/androidannotations-api/src/main/java/org/androidannotations/annotations/ViewById.java
PerfectCarl/androidannotations
04469986967a7e20206420ac4630641407b99916
[ "Apache-2.0" ]
2
2015-12-21T14:13:38.000Z
2016-10-31T03:35:40.000Z
AndroidAnnotations/androidannotations-api/src/main/java/org/androidannotations/annotations/ViewById.java
PerfectCarl/androidannotations
04469986967a7e20206420ac4630641407b99916
[ "Apache-2.0" ]
null
null
null
AndroidAnnotations/androidannotations-api/src/main/java/org/androidannotations/annotations/ViewById.java
PerfectCarl/androidannotations
04469986967a7e20206420ac4630641407b99916
[ "Apache-2.0" ]
null
null
null
28.19403
80
0.701429
8,620
/** * Copyright (C) 2010-2013 eBusiness Information, Excilys Group * * 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 org.androidannotations.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Use it on {@link android.view.View} or {@link android.view.View} subtype * fields in a view related (ie {@link EActivity}, {@link EFragment}, * {@link EViewGroup}, ...) annotated class. * <p/> * The annotation value should be one of R.id.* fields. If not set, the field * name will be used as the R.id.* field name. * <p/> * Your code related to injected views should go in an {@link AfterViews} * annotated method. * <p/> * <blockquote> * * Example : * * <pre> * &#064;EActivity(R.layout.main) * public class MyActivity extends Activity { * * // Injects R.id.myEditText * &#064;ViewById * EditText myEditText; * * &#064;ViewById(R.id.myTextView) * TextView textView; * * &#064;AfterViews * void updateTextWithDate() { * myEditText.setText(&quot;Date: &quot; + new Date()); * } * } * </pre> * * </blockquote> * * @see AfterViews */ @Retention(RetentionPolicy.CLASS) @Target(ElementType.FIELD) public @interface ViewById { int value() default ResId.DEFAULT_VALUE; String resName() default ""; }
3e145a9ce8ec7632cf97a53e8f3a9ddea99c060e
174
java
Java
com/google/common/base/PatternCompiler.java
kelu124/pyS3
86eb139d971921418d6a62af79f2868f9c7704d5
[ "MIT" ]
1
2021-04-09T06:03:36.000Z
2021-04-09T06:03:36.000Z
com/google/common/base/PatternCompiler.java
kelu124/pyS3
86eb139d971921418d6a62af79f2868f9c7704d5
[ "MIT" ]
null
null
null
com/google/common/base/PatternCompiler.java
kelu124/pyS3
86eb139d971921418d6a62af79f2868f9c7704d5
[ "MIT" ]
null
null
null
19.333333
53
0.810345
8,621
package com.google.common.base; import com.google.common.annotations.GwtIncompatible; @GwtIncompatible interface PatternCompiler { CommonPattern compile(String str); }
3e145c2032c6e538452b8ebb95d83c30f85f86fa
13,794
java
Java
src/main/java/org/cloud/sonic/agent/tools/cv/AKAZEFinder.java
yaming116/sonic-agent
536ddd0930f895f7b7e2a5301eea53dda2b597bb
[ "MIT" ]
1,029
2021-12-12T07:49:01.000Z
2022-03-31T21:45:02.000Z
src/main/java/org/cloud/sonic/agent/tools/cv/AKAZEFinder.java
yaming116/sonic-agent
536ddd0930f895f7b7e2a5301eea53dda2b597bb
[ "MIT" ]
36
2021-12-13T04:56:39.000Z
2022-03-25T04:12:10.000Z
src/main/java/org/cloud/sonic/agent/tools/cv/AKAZEFinder.java
yaming116/sonic-agent
536ddd0930f895f7b7e2a5301eea53dda2b597bb
[ "MIT" ]
159
2021-12-12T07:21:15.000Z
2022-03-31T22:59:04.000Z
40.810651
115
0.58337
8,622
/* * Copyright (C) [SonicCloudOrg] Sonic Project * * 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 org.cloud.sonic.agent.tools.cv; import org.bytedeco.opencv.opencv_core.*; import org.bytedeco.opencv.opencv_features2d.AKAZE; import org.bytedeco.opencv.opencv_flann.Index; import org.bytedeco.opencv.opencv_flann.IndexParams; import org.bytedeco.opencv.opencv_flann.LshIndexParams; import org.bytedeco.opencv.opencv_flann.SearchParams; import org.cloud.sonic.agent.automation.FindResult; import org.cloud.sonic.agent.tools.file.UploadTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.Calendar; import java.util.concurrent.ThreadLocalRandom; import static org.bytedeco.opencv.global.opencv_calib3d.CV_RANSAC; import static org.bytedeco.opencv.global.opencv_calib3d.findHomography; import static org.bytedeco.opencv.global.opencv_core.*; import static org.bytedeco.opencv.global.opencv_flann.FLANN_DIST_HAMMING; import static org.bytedeco.opencv.global.opencv_imgcodecs.*; import static org.bytedeco.opencv.global.opencv_imgproc.*; /** * @des AKAZE算法 * @link{https://github.com/bytedeco/javacv} */ public class AKAZEFinder { private final Logger logger = LoggerFactory.getLogger(AKAZEFinder.class); IplImage objectImage = null; AKAZE detector = AKAZE.create(); double distanceThreshold = 0.6; int matchesMin = 4; double ransacReprojThreshold = 1.0; boolean useFLANN = false; KeyPointVector objectKeypoints = null, imageKeypoints = null; Mat objectDescriptors = null, imageDescriptors = null; Mat indicesMat, distsMat; Index flannIndex = null; IndexParams indexParams = null; SearchParams searchParams = null; Mat pt1 = null, pt2 = null, mask = null, H = null; ArrayList<Integer> ptpairs = null; public void init() { objectKeypoints = new KeyPointVector(); objectDescriptors = new Mat(); detector.detectAndCompute(cvarrToMat(objectImage), new Mat(), objectKeypoints, objectDescriptors, false); int total = (int) objectKeypoints.size(); if (useFLANN) { indicesMat = new Mat(total, 2, CV_32SC1); distsMat = new Mat(total, 2, CV_32FC1); flannIndex = new Index(); indexParams = new LshIndexParams(12, 20, 2); // using LSH Hamming distance searchParams = new SearchParams(64, 0, true); // maximum number of leafs checked searchParams.deallocate(false); // for some reason FLANN seems to do it for us } pt1 = new Mat(total, 1, CV_32FC2); pt2 = new Mat(total, 1, CV_32FC2); mask = new Mat(total, 1, CV_8UC1); H = new Mat(3, 3, CV_64FC1); ptpairs = new ArrayList<Integer>(2 * objectDescriptors.rows()); logger.info("模版图一共有" + total + "个特征点"); } public double[] find(IplImage image) { if (objectDescriptors.rows() < matchesMin) { return null; } imageKeypoints = new KeyPointVector(); imageDescriptors = new Mat(); detector.detectAndCompute(cvarrToMat(image), new Mat(), imageKeypoints, imageDescriptors, false); if (imageDescriptors.rows() < matchesMin) { return null; } int total = (int) imageKeypoints.size(); logger.info("原图一共有" + total + "个特征点"); int w = objectImage.width(); int h = objectImage.height(); double[] srcCorners = {0, 0, w, 0, w, h, 0, h}; double[] dstCorners = locatePlanarObject(objectKeypoints, objectDescriptors, imageKeypoints, imageDescriptors, srcCorners); return dstCorners; } private static final int[] bits = new int[256]; static { for (int i = 0; i < bits.length; i++) { for (int j = i; j != 0; j >>= 1) { bits[i] += j & 0x1; } } } private int compareDescriptors(ByteBuffer d1, ByteBuffer d2, int best) { int totalCost = 0; assert d1.limit() - d1.position() == d2.limit() - d2.position(); while (d1.position() < d1.limit()) { totalCost += bits[(d1.get() ^ d2.get()) & 0xFF]; if (totalCost > best) break; } return totalCost; } private int naiveNearestNeighbor(ByteBuffer vec, ByteBuffer modelDescriptors) { int neighbor = -1; int d, dist1 = Integer.MAX_VALUE, dist2 = Integer.MAX_VALUE; int size = vec.limit() - vec.position(); for (int i = 0; i * size < modelDescriptors.capacity(); i++) { ByteBuffer mvec = (ByteBuffer) modelDescriptors.position(i * size).limit((i + 1) * size); d = compareDescriptors((ByteBuffer) vec.reset(), mvec, dist2); if (d < dist1) { dist2 = dist1; dist1 = d; neighbor = i; } else if (d < dist2) { dist2 = d; } } if (dist1 < distanceThreshold * dist2) return neighbor; return -1; } private void findPairs(Mat objectDescriptors, Mat imageDescriptors) { int size = imageDescriptors.cols(); ByteBuffer objectBuf = objectDescriptors.createBuffer(); ByteBuffer imageBuf = imageDescriptors.createBuffer(); for (int i = 0; i * size < objectBuf.capacity(); i++) { ByteBuffer descriptor = (ByteBuffer) objectBuf.position(i * size).limit((i + 1) * size).mark(); int nearestNeighbor = naiveNearestNeighbor(descriptor, imageBuf); if (nearestNeighbor >= 0) { ptpairs.add(i); ptpairs.add(nearestNeighbor); } } } private void flannFindPairs(Mat objectDescriptors, Mat imageDescriptors) { int length = objectDescriptors.rows(); flannIndex.build(imageDescriptors, indexParams, FLANN_DIST_HAMMING); flannIndex.knnSearch(objectDescriptors, indicesMat, distsMat, 2, searchParams); IntBuffer indicesBuf = indicesMat.createBuffer(); IntBuffer distsBuf = distsMat.createBuffer(); for (int i = 0; i < length; i++) { if (distsBuf.get(2 * i) < distanceThreshold * distsBuf.get(2 * i + 1)) { ptpairs.add(i); ptpairs.add(indicesBuf.get(2 * i)); } } } private double[] locatePlanarObject(KeyPointVector objectKeypoints, Mat objectDescriptors, KeyPointVector imageKeypoints, Mat imageDescriptors, double[] srcCorners) { ptpairs.clear(); if (useFLANN) { flannFindPairs(objectDescriptors, imageDescriptors); } else { findPairs(objectDescriptors, imageDescriptors); } int n = ptpairs.size() / 2; logger.info("筛选后共有" + n + "个吻合点"); if (n < matchesMin) { return null; } pt1.resize(n); pt2.resize(n); mask.resize(n); FloatBuffer pt1Idx = pt1.createBuffer(); FloatBuffer pt2Idx = pt2.createBuffer(); for (int i = 0; i < n; i++) { Point2f p1 = objectKeypoints.get(ptpairs.get(2 * i)).pt(); pt1Idx.put(2 * i, p1.x()); pt1Idx.put(2 * i + 1, p1.y()); Point2f p2 = imageKeypoints.get(ptpairs.get(2 * i + 1)).pt(); pt2Idx.put(2 * i, p2.x()); pt2Idx.put(2 * i + 1, p2.y()); } H = findHomography(pt1, pt2, CV_RANSAC, ransacReprojThreshold, mask, 2000, 0.995); if (H.empty() || countNonZero(mask) < matchesMin) { return null; } double[] h = (double[]) H.createIndexer(false).array(); double[] dstCorners = new double[srcCorners.length]; for (int i = 0; i < srcCorners.length / 2; i++) { double x = srcCorners[2 * i], y = srcCorners[2 * i + 1]; double Z = 1 / (h[6] * x + h[7] * y + h[8]); double X = (h[0] * x + h[1] * y + h[2]) * Z; double Y = (h[3] * x + h[4] * y + h[5]) * Z; dstCorners[2 * i] = X; dstCorners[2 * i + 1] = Y; } return dstCorners; } public static Scalar randColor() { int b, g, r; b = ThreadLocalRandom.current().nextInt(0, 255); g = ThreadLocalRandom.current().nextInt(0, 255); r = ThreadLocalRandom.current().nextInt(0, 255); return new Scalar(b, g, r, 0); } public FindResult getAKAZEFindResult(File temFile, File beforeFile) throws IOException { IplImage object = cvLoadImage(temFile.getAbsolutePath(), IMREAD_GRAYSCALE); IplImage image = cvLoadImage(beforeFile.getAbsolutePath(), IMREAD_GRAYSCALE); logger.info("原图宽:" + image.width()); logger.info("原图高:" + image.height()); if (object == null || image == null) { logger.error("读取图片失败!"); temFile.delete(); beforeFile.delete(); return null; } IplImage correspond = IplImage.create(image.width() + object.width(), image.height(), 8, 1); cvSetImageROI(correspond, cvRect(0, 0, image.width(), correspond.height())); cvCopy(image, correspond); cvSetImageROI(correspond, cvRect(image.width(), 0, object.width(), object.height())); cvCopy(object, correspond); cvResetImageROI(correspond); objectImage = object; useFLANN = true; ransacReprojThreshold = 3; init(); long start = System.currentTimeMillis(); double[] dst_corners = find(image); FindResult findResult = new FindResult(); findResult.setTime((int) (System.currentTimeMillis() - start)); logger.info("特征匹配时间: " + (System.currentTimeMillis() - start) + " ms"); IplImage correspondColor = IplImage.create(correspond.width(), correspond.height(), 8, 3); cvCvtColor(correspond, correspondColor, CV_GRAY2BGR); cvSetImageROI(correspondColor, cvRect(0, 0, image.width(), correspondColor.height())); cvCopy(cvLoadImage(beforeFile.getAbsolutePath(), IMREAD_COLOR), correspondColor); cvSetImageROI(correspondColor, cvRect(image.width(), 0, object.width(), object.height())); cvCopy(cvLoadImage(temFile.getAbsolutePath(), IMREAD_COLOR), correspondColor); cvResetImageROI(correspondColor); if (dst_corners != null) { int resultX = 0; int resultY = 0; for (int i = 0; i < 4; i++) { int j = (i + 1) % 4; int x1 = (int) Math.round(dst_corners[2 * i]); int y1 = (int) Math.round(dst_corners[2 * i + 1]); int x2 = (int) Math.round(dst_corners[2 * j]); int y2 = (int) Math.round(dst_corners[2 * j + 1]); line(cvarrToMat(correspondColor), new Point(x1, y1), new Point(x2, y2), Scalar.RED, 2, CV_AA, 0); if (i == 0) { resultX = (x1 + x2) / 2; } if (i == 1) { resultY = (y1 + y2) / 2; } } if (resultX == 0 && resultY == 0) { temFile.delete(); beforeFile.delete(); return null; } findResult.setX(resultX); findResult.setY(resultY); logger.info("结果坐标为(" + resultX + "," + resultY + ")"); } if (objectKeypoints != null) { for (int i = 0; i < objectKeypoints.size(); i++) { KeyPoint r = objectKeypoints.get(i); Point center = new Point(Math.round(r.pt().x()) + image.width(), Math.round(r.pt().y())); int radius = Math.round(r.size() / 2); circle(cvarrToMat(correspondColor), center, radius, randColor(), 1, CV_AA, 0); } } if (imageKeypoints != null) { for (int i = 0; i < imageKeypoints.size(); i++) { KeyPoint r = imageKeypoints.get(i); Point center = new Point(Math.round(r.pt().x()), Math.round(r.pt().y())); int radius = Math.round(r.size() / 2); circle(cvarrToMat(correspondColor), center, radius, randColor(), 1, CV_AA, 0); } } for (int i = 0; i < ptpairs.size(); i += 2) { Point2f pt1 = objectKeypoints.get(ptpairs.get(i)).pt(); Point2f pt2 = imageKeypoints.get(ptpairs.get(i + 1)).pt(); line(cvarrToMat(correspondColor), new Point(Math.round(pt1.x()) + image.width(), Math.round(pt1.y())), new Point(Math.round(pt2.x()), Math.round(pt2.y())), randColor(), 1, CV_AA, 0); } long time = Calendar.getInstance().getTimeInMillis(); String fileName = "test-output" + File.separator + time + ".jpg"; cvSaveImage(fileName, correspondColor); findResult.setUrl(UploadTools.upload(new File(fileName), "imageFiles")); temFile.delete(); beforeFile.delete(); return findResult; } }
3e145c3b51ccfdbf674345be6ffcb29157cc59b8
10,700
java
Java
src/main/java/org/schors/gos/RecognitionTestBot.java
flicus/gosb
620824d6061d0be3cfb6afcee2085d4a0936d6ab
[ "MIT" ]
null
null
null
src/main/java/org/schors/gos/RecognitionTestBot.java
flicus/gosb
620824d6061d0be3cfb6afcee2085d4a0936d6ab
[ "MIT" ]
null
null
null
src/main/java/org/schors/gos/RecognitionTestBot.java
flicus/gosb
620824d6061d0be3cfb6afcee2085d4a0936d6ab
[ "MIT" ]
null
null
null
41.153846
129
0.655794
8,623
package org.schors.gos; import net.sourceforge.tess4j.Tesseract; import net.sourceforge.tess4j.TesseractException; import org.opencv.core.*; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import org.schors.gos.model.BattleLayout; import org.schors.gos.model.Player; import org.schors.gos.model.PlayerLayout; import org.springframework.stereotype.Component; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery; import org.telegram.telegrambots.meta.api.methods.GetFile; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.PhotoSize; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @Component public class RecognitionTestBot extends TelegramLongPollingBot { private PlayerRepository playerRepository; private BattleRepository battleRepository; private PlayerLayout playerLayout = null; private List<Player> players = null; public RecognitionTestBot(PlayerRepository playerRepository, BattleRepository battleRepository) { this.playerRepository = playerRepository; this.battleRepository = battleRepository; } private static PlayerLayout recognize(File file) { System.out.println(file.getAbsolutePath()); Mat img = Imgcodecs.imread(file.getAbsolutePath()); Mat grey = new Mat(); Imgproc.cvtColor(img, grey, Imgproc.COLOR_BGR2GRAY); Mat initialGrey = grey.clone(); Imgproc.adaptiveThreshold(grey, grey, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 15, -2); int horizontal_size = grey.cols() / 2; Mat horizontalStructure = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(horizontal_size, 1)); Imgproc.dilate(grey, grey, Mat.ones(2, 2, CvType.CV_8U)); Imgproc.erode(grey, grey, horizontalStructure); Imgproc.dilate(grey, grey, horizontalStructure); Core.bitwise_not(grey, grey); Mat hierarchy = new Mat(); List<MatOfPoint> list = new ArrayList<>(); Imgproc.findContours(grey, list, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); Tesseract tesseract = new Tesseract(); tesseract.setDatapath("/home/flicus/tera/java/tessdata_best-main"); tesseract.setLanguage("eng"); tesseract.setTessVariable("tessedit_char_whitelist", "0123456789BMKT."); tesseract.setPageSegMode(8); List<String> strings = new ArrayList<>(); list.stream() .map(matOfPoint -> Imgproc.boundingRect(matOfPoint)) .map(rect -> initialGrey.submat(rect)) .filter(mat -> mat.height() > 100) .forEach(first -> { Mat res = first.clone(); Imgproc.medianBlur(first, first, 5); Mat circles = new Mat(); Imgproc.HoughCircles(first, circles, Imgproc.HOUGH_GRADIENT, 1.0, (double) first.rows() / 16, // change this value to detect circles with different distances to each other 100.0, 30.0, 20, 40); // change the last two parameters Mat mask = Mat.zeros(first.rows(), first.cols(), CvType.CV_8U); double mx = 0; int mr = 0; for (int x = 0; x < circles.cols(); x++) { double[] c = circles.get(0, x); mx = Math.max(mx, Math.round(c[1])); mr = Math.max(mr, (int) Math.round(c[2])); Point center = new Point(Math.round(c[0]), Math.round(c[1])); int radius = (int) Math.round(c[2]); Imgproc.circle(first, center, radius + 2, new Scalar(255, 0, 255), -1, 8, 0); } Imgproc.rectangle(mask, new Point(0, 0), new Point(mask.cols(), mx + mr + 2), new Scalar(255, 255, 255), -1); Imgproc.rectangle(first, new Point(0, 0), new Point(first.cols(), mx + mr + 2), new Scalar(255, 255, 255), -1); Core.bitwise_not(mask, mask); Mat result = new Mat(); res.copyTo(result, mask); Mat r_i = res.clone(); Imgproc.threshold(result, result, 140, 255, Imgproc.THRESH_BINARY /*+ Imgproc.THRESH_OTSU*/); Mat hh = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(6, 3)); Imgproc.dilate(result, result, hh); Mat hierarchy2 = new Mat(); List<MatOfPoint> list2 = new ArrayList<>(); Imgproc.findContours(result, list2, hierarchy2, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); list2.stream() .map(matOfPoint -> Imgproc.boundingRect(matOfPoint)) .filter(rect -> rect.width > rect.height * 2 && rect.height > 10) .map(rect -> new Rect(rect.x - 1, rect.y - 1, rect.width + 1, rect.height + 3)) .forEach(rect -> { Imgproc.rectangle(r_i, rect, new Scalar(0, 255, 0), 1); Mat m = r_i.submat(rect); Imgproc.dilate(m, m, Mat.ones(1, 1, CvType.CV_8U)); Core.bitwise_not(m, m); BufferedImage bimg = null; try { bimg = mat2BufferedImage(m); } catch (Exception e) { e.printStackTrace(); } String s = null; try { s = tesseract.doOCR(bimg); } catch (TesseractException e) { e.printStackTrace(); } System.out.println(s); strings.add(s.trim()); }); }); PlayerLayout playerLayout = new PlayerLayout(); playerLayout.setB2(new BattleLayout(strings.get(13), strings.get(12), strings.get(15), strings.get(14))); playerLayout.setB3(new BattleLayout(strings.get(9), strings.get(8), strings.get(11), strings.get(10))); playerLayout.setB5(new BattleLayout(strings.get(5), strings.get(4), strings.get(7), strings.get(6))); playerLayout.setB7(new BattleLayout(strings.get(1), strings.get(0), strings.get(3), strings.get(2))); // ParseResult parseResult = new ParseResult(); // parseResult.setRec7(new String[]{strings.get(0), strings.get(1), strings.get(2), strings.get(3)}); // parseResult.setRec5(new String[]{strings.get(4), strings.get(5), strings.get(6), strings.get(7)}); // parseResult.setRec3(new String[]{strings.get(8), strings.get(9), strings.get(10), strings.get(11)}); // parseResult.setRec2(new String[]{strings.get(12), strings.get(13), strings.get(14), strings.get(15)}); return playerLayout; } static BufferedImage mat2BufferedImage(Mat matrix) throws Exception { MatOfByte mob = new MatOfByte(); Imgcodecs.imencode(".png", matrix, mob); return ImageIO.read(new ByteArrayInputStream(mob.toArray())); } public static <T> Stream<Stream<T>> getTuples(Collection<T> items, int size) { int page = 0; Stream.Builder<Stream<T>> builder = Stream.builder(); Stream<T> stream; do { stream = items.stream().skip(size * page++).limit(size); builder.add(stream); } while (items.size() - size * page > 0); return builder.build(); } @Override public String getBotUsername() { return "pangos_bot"; } @Override public String getBotToken() { return "1059091004:AAHsbBr9bHhziXHap_5VI4Djbo9UEi_3hi8"; } @Override public void onUpdateReceived(Update update) { if (update.hasMessage() && update.getMessage().hasPhoto()) { PhotoSize photo = update.getMessage().getPhoto().stream().max(Comparator.comparing(PhotoSize::getFileSize)).get(); String url = null; if (photo.getFilePath() != null) { // If the file_path is already present, we are done! url = photo.getFilePath(); } else { // If not, let find it // We create a GetFile method and set the file_id from the photo GetFile getFileMethod = new GetFile(); getFileMethod.setFileId(photo.getFileId()); try { // We execute the method using AbsSender::execute method. org.telegram.telegrambots.meta.api.objects.File file = execute(getFileMethod); // We now have the file_path url = file.getFilePath(); } catch (TelegramApiException e) { e.printStackTrace(); } } try { File file = this.downloadFile(url); playerLayout = recognize(file); execute(SendMessage.builder() .chatId(String.valueOf(update.getMessage().getChatId())) .text(playerLayout.readable()).build()); players = playerRepository.getAllPlayers(); InlineKeyboardMarkup.InlineKeyboardMarkupBuilder inlineKeyboardMarkupBuilder = InlineKeyboardMarkup.builder(); getTuples(players, 3). forEach(tuple -> inlineKeyboardMarkupBuilder .keyboardRow(tuple.map(player -> InlineKeyboardButton.builder() .text(player.getName()) .callbackData(player.getId()) .build()) .collect(Collectors.toList()))); execute( SendMessage.builder() .chatId(String.valueOf(update.getMessage().getChatId())) .text("Чья расстановка?") .replyMarkup(inlineKeyboardMarkupBuilder.build()) .build()); } catch (TelegramApiException e) { e.printStackTrace(); } } else if (update.hasCallbackQuery()) { try { execute(AnswerCallbackQuery.builder() .callbackQueryId(update.getCallbackQuery().getId()) .build()); } catch (TelegramApiException e) { e.printStackTrace(); } if (playerLayout != null) { String id = update.getCallbackQuery().getData(); playerLayout.setPlayer(players.stream().filter(player -> player.getId().equals(id)).findAny().get()); battleRepository.addPlayerLayout(playerLayout); playerLayout = null; players = null; } // try { // execute(SendMessage.builder().chatId(String.valueOf(update.getCallbackQuery().getChatId())).text("Добавлено").build()); // } catch (TelegramApiException e) { // e.printStackTrace(); // } } else { try { execute(SendMessage.builder() .chatId(String.valueOf(update.getMessage().getChatId())) .text("Изображение не найдено") .build()); } catch (TelegramApiException e) { e.printStackTrace(); } } } }
3e145c7d26eeb1c2cb5bec6f7cdd5f31ebccdda8
1,010
java
Java
java/src/test/java/io/github/ajoz/iter/TakeIterTest.java
ajoz/functional-concepts-jvm
03bc3fbffe72aa937e1415f5945dfc3eb0013e80
[ "Apache-2.0" ]
1
2019-01-29T22:10:58.000Z
2019-01-29T22:10:58.000Z
java/src/test/java/io/github/ajoz/iter/TakeIterTest.java
ajoz/functional-concepts-jvm
03bc3fbffe72aa937e1415f5945dfc3eb0013e80
[ "Apache-2.0" ]
null
null
null
java/src/test/java/io/github/ajoz/iter/TakeIterTest.java
ajoz/functional-concepts-jvm
03bc3fbffe72aa937e1415f5945dfc3eb0013e80
[ "Apache-2.0" ]
null
null
null
27.297297
76
0.560396
8,624
package io.github.ajoz.iter; import org.junit.Assert; import static org.junit.Assert.*; import org.junit.Test; public class TakeIterTest { @Test public void shouldReturnFailureIfNoItemsUpstream() { Iter.empty() .take(10) .next() .ifSuccess(ignored -> fail("Should not return a value!")); } @Test public void shouldReturnFailureIfReturnedAmountOfItems() { final Iter<Integer> iter = Iter.from(1, 2, 3, 4).take(2); // takes 1 iter.next(); // takes 2 iter.next(); // no more items to take iter.next().ifSuccess(ignored -> fail("Should not return a value")); } @Test public void shouldReturnSuccess() { final Integer expected = 42; Iter.from(expected) .take(1) .next() .ifFailure(exc -> fail("Should return a value!")) .ifSuccess(value -> Assert.assertEquals(expected, value)); } }
3e145cadc5a0060773737f12704832279d57b0b7
1,716
java
Java
app/src/main/java/com/cpxiao/dotsandboxes/mode/extra/GridSize.java
cpxiao/DotsAndBoxes-Multiplayer
848d857d18125c9af24936a35fc51b1e296fb506
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/cpxiao/dotsandboxes/mode/extra/GridSize.java
cpxiao/DotsAndBoxes-Multiplayer
848d857d18125c9af24936a35fc51b1e296fb506
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/cpxiao/dotsandboxes/mode/extra/GridSize.java
cpxiao/DotsAndBoxes-Multiplayer
848d857d18125c9af24936a35fc51b1e296fb506
[ "Apache-2.0" ]
null
null
null
27.238095
88
0.567016
8,625
package com.cpxiao.dotsandboxes.mode.extra; import android.text.TextUtils; import com.cpxiao.androidutils.library.utils.StringUtils; /** * @author cpxiao on 2017/08/16. */ public class GridSize { /** * 方格数量 */ public static final String SIZE_KEY = "SIZE_KEY"; private static final String SIZE_2 = "2 x 2"; private static final String SIZE_3 = "3 x 3"; private static final String SIZE_4 = "4 x 4"; private static final String SIZE_5 = "5 x 5"; private static final String SIZE_6 = "6 x 6"; private static final String[] SIZE_ARRAY = {SIZE_2, SIZE_3, SIZE_4, SIZE_5, SIZE_6}; public static final String SIZE_DEFAULT = SIZE_3; public static int getGridCountX(String size) { if (StringUtils.isEmpty(size)) { return 0; } try { String x = size.substring(0, size.indexOf("x") - 1); return Integer.valueOf(x); } catch (Exception e) { e.printStackTrace(); } return 0; } public static int getGridCountY(String size) { if (StringUtils.isEmpty(size)) { return 0; } try { String x = size.substring(size.indexOf("x") + 2, size.length()); return Integer.valueOf(x); } catch (Exception e) { e.printStackTrace(); } return 0; } public static String getNextGridSize(String gridSize) { int index = 0; for (int i = 0; i < SIZE_ARRAY.length; i++) { if (TextUtils.equals(gridSize, SIZE_ARRAY[i])) { index = i; break; } } return SIZE_ARRAY[(index + 1) % SIZE_ARRAY.length]; } }
3e145ccf66bf1119f3e3f74a0f7922013eebd24f
2,878
java
Java
dom/src/main/java/todoapp/dom/relativepriority/ToDoItem_relativePriority.java
danhaywood/isis-app-todoapp
f284178e61683fe15f79c519df7080caef417fa1
[ "Apache-2.0" ]
52
2015-06-09T22:58:55.000Z
2021-01-17T07:45:19.000Z
dom/src/main/java/todoapp/dom/relativepriority/ToDoItem_relativePriority.java
danhaywood/isis-app-todoapp
f284178e61683fe15f79c519df7080caef417fa1
[ "Apache-2.0" ]
7
2015-04-23T11:30:06.000Z
2020-03-23T18:03:55.000Z
dom/src/main/java/todoapp/dom/relativepriority/ToDoItem_relativePriority.java
danhaywood/isis-app-todoapp
f284178e61683fe15f79c519df7080caef417fa1
[ "Apache-2.0" ]
70
2015-02-24T17:17:23.000Z
2020-10-26T07:47:26.000Z
33.465116
121
0.68902
8,626
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 todoapp.dom.relativepriority; import javax.inject.Inject; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.Contributed; import org.apache.isis.applib.annotation.Editing; import org.apache.isis.applib.annotation.Mixin; import org.apache.isis.applib.annotation.Property; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Where; import org.apache.isis.applib.services.queryresultscache.QueryResultsCache; import todoapp.dom.todoitem.ToDoItem; import todoapp.dom.todoitem.ToDoItems; @Mixin public class ToDoItem_relativePriority { private final ToDoItem toDoItem; public ToDoItem_relativePriority(final ToDoItem toDoItem) { this.toDoItem = toDoItem; } @Action( semantics = SemanticsOf.SAFE, hidden = Where.ALL_TABLES ) @ActionLayout( describedAs = "The relative priority of this item compared to others not yet complete (using 'due by' date)", contributed = Contributed.AS_ASSOCIATION ) @Property( editing = Editing.DISABLED, editingDisabledReason = "Relative priority, derived from due date" ) public Integer $$() { return queryResultsCache.execute(() -> { if(toDoItem.isComplete()) { return null; } // sort items, then locate this one int i=1; for (final ToDoItem each : relativePriorityService.sortedNotYetComplete()) { if(each == toDoItem) { return i; } i++; } return null; }, ToDoItem_relativePriority.class, "relativePriority", toDoItem); } //region > injected services @javax.inject.Inject private ToDoItems toDoItems; @javax.inject.Inject private QueryResultsCache queryResultsCache; @Inject private RelativePriorityService relativePriorityService; }
3e145d86462b678a066cc96bfcf481a2c2e3693c
1,843
java
Java
toop-edm/src/main/java/eu/toop/edm/request/IEDMRequestPayloadProvider.java
de4a-wp5/toop-commons-ng
73382c519e7f5e1f325a8befcef6db89b1db7e8c
[ "Apache-2.0" ]
null
null
null
toop-edm/src/main/java/eu/toop/edm/request/IEDMRequestPayloadProvider.java
de4a-wp5/toop-commons-ng
73382c519e7f5e1f325a8befcef6db89b1db7e8c
[ "Apache-2.0" ]
null
null
null
toop-edm/src/main/java/eu/toop/edm/request/IEDMRequestPayloadProvider.java
de4a-wp5/toop-commons-ng
73382c519e7f5e1f325a8befcef6db89b1db7e8c
[ "Apache-2.0" ]
null
null
null
32.333333
76
0.671731
8,627
/** * This work is protected under copyrights held by the members of the * TOOP Project Consortium as indicated at * http://wiki.ds.unipi.gr/display/TOOP/Contributors * (c) 2018-2021. All rights reserved. * * This work is dual licensed under Apache License, Version 2.0 * and the EUPL 1.2. * * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * * 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. * * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * * Licensed under the EUPL, Version 1.2 or – as soon they will be approved * by the European Commission - subsequent versions of the EUPL * (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * https://joinup.ec.europa.eu/software/page/eupl */ package eu.toop.edm.request; import javax.annotation.Nonnull; import com.helger.commons.annotation.MustImplementEqualsAndHashcode; import eu.toop.regrep.slot.ISlotProvider; /** * Abstract EDM Request payload provider. * * @author Philip Helger * @since 2.0.0-beta3 */ @MustImplementEqualsAndHashcode public interface IEDMRequestPayloadProvider { /** * @return This as an {@link ISlotProvider}. May not be <code>null</code>. */ @Nonnull ISlotProvider getAsSlotProvider (); }
3e145fa69cfc24b8cadd47189979e5c705e34be4
1,007
java
Java
http/open-api-custom/src/main/java/org/agoncal/fascicle/quarkus/http/openapi/custom/AuthorResource.java
wfink/agoncal-fascicle-quarkus
f47ebd3c18e95a8eae59ca7b7168da27c554d3d6
[ "MIT" ]
30
2020-11-03T13:23:34.000Z
2022-03-23T08:58:23.000Z
http/open-api-custom/src/main/java/org/agoncal/fascicle/quarkus/http/openapi/custom/AuthorResource.java
wfink/agoncal-fascicle-quarkus
f47ebd3c18e95a8eae59ca7b7168da27c554d3d6
[ "MIT" ]
7
2020-12-27T17:43:50.000Z
2021-12-27T18:04:39.000Z
http/open-api-custom/src/main/java/org/agoncal/fascicle/quarkus/http/openapi/custom/AuthorResource.java
wfink/agoncal-fascicle-quarkus
f47ebd3c18e95a8eae59ca7b7168da27c554d3d6
[ "MIT" ]
22
2020-09-14T15:41:39.000Z
2022-02-10T15:21:19.000Z
27.972222
76
0.723932
8,628
package org.agoncal.fascicle.quarkus.http.openapi.custom; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * @author Antonio Goncalves * http://www.antoniogoncalves.org * -- */ // @formatter:off // tag::adocSnippet[] @Path("/authors") @Produces(MediaType.TEXT_PLAIN) public class AuthorResource { String[] scifiAuthors = {"Isaac Asimov", "Nora Jemisin", "Douglas Adams"}; @GET @Path("/{index}") @Operation(summary = "Returns an author for a given index") @APIResponse(responseCode = "204", description = "Author not found") @APIResponse(responseCode = "200", description = "Author returned for a given index") public String getScifiAuthor(@PathParam("index") int index) { return scifiAuthors[index]; } } // end::adocSnippet[]
3e14600489cf52d2183d86d526bd3fda9fe3c581
1,801
java
Java
blue-core/src/test/java/test/core/util/JsonUtilTest.java
blue0121/blue
f66ed548cb7c4c4a89341b6d2866a607c03c2243
[ "Apache-2.0" ]
null
null
null
blue-core/src/test/java/test/core/util/JsonUtilTest.java
blue0121/blue
f66ed548cb7c4c4a89341b6d2866a607c03c2243
[ "Apache-2.0" ]
null
null
null
blue-core/src/test/java/test/core/util/JsonUtilTest.java
blue0121/blue
f66ed548cb7c4c4a89341b6d2866a607c03c2243
[ "Apache-2.0" ]
null
null
null
29.048387
107
0.741255
8,629
package test.core.util; import blue.core.dict.State; import blue.core.dict.Type; import blue.core.util.JsonUtil; import blue.internal.core.dict.FastjsonEnumDeserializer; import blue.internal.core.dict.FastjsonEnumSerializer; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializeConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import test.core.model.Group; /** * @author zhengjin * @since 1.0 2017年12月07日 */ public class JsonUtilTest { public JsonUtilTest() { } @Test public void testOutput() { Group group = new Group(1, "blue", Type.YES, State.NORMAL); String json = JsonUtil.output(group); System.out.println(json); Group g2 = new Group(); g2.setId(2); g2.setName("blue"); String json2 = JsonUtil.output(g2); System.out.println(json2); } @Test public void testDecode() { ParserConfig.getGlobalInstance().putDeserializer(Type.class, new FastjsonEnumDeserializer(Type.class)); ParserConfig.getGlobalInstance().putDeserializer(State.class, new FastjsonEnumDeserializer(State.class)); SerializeConfig.getGlobalInstance().put(Type.class, new FastjsonEnumSerializer()); SerializeConfig.getGlobalInstance().put(State.class, new FastjsonEnumSerializer()); Group group = new Group(1, "blue", Type.NO, State.NORMAL); String json = JsonUtil.output(group); System.out.println(json); Group g2 = JsonUtil.fromString(json, Group.class); System.out.println(JsonUtil.toString(g2)); Assertions.assertEquals(Type.NO, g2.getType()); Assertions.assertEquals(State.NORMAL, g2.getState()); String json2 = "{\"id\":1,\"name\":\"blue\",\"type\":\"YES\",\"state\":\"DELETE\"}"; Group g3 = JsonUtil.fromString(json2, Group.class); System.out.println(JsonUtil.toString(g3)); } }
3e1460a2de1101021fd92acfaaa057f6912a899e
3,063
java
Java
src/main/java/edu/uri/cs/hypothesis/VariablesInLiteral.java
benott-cs/CKTAGA
57c8515ac59326ed3e225cca5413a96ae1706478
[ "Apache-2.0" ]
null
null
null
src/main/java/edu/uri/cs/hypothesis/VariablesInLiteral.java
benott-cs/CKTAGA
57c8515ac59326ed3e225cca5413a96ae1706478
[ "Apache-2.0" ]
2
2021-01-21T01:14:18.000Z
2021-12-09T22:19:08.000Z
src/main/java/edu/uri/cs/hypothesis/VariablesInLiteral.java
benott-cs/CKTAGA
57c8515ac59326ed3e225cca5413a96ae1706478
[ "Apache-2.0" ]
null
null
null
31.90625
111
0.63859
8,630
package edu.uri.cs.hypothesis; import com.igormaznitsa.prologparser.terms.AbstractPrologTerm; import com.igormaznitsa.prologparser.terms.PrologStructure; import java.util.List; import java.util.stream.Collectors; /** * Created by Ben on 12/27/18. */ public class VariablesInLiteral { private boolean variableInHead = false; private boolean mostGeneral = false; private List<AbstractPrologTerm> variables; private PrologStructure literal; public VariablesInLiteral(List<LiteralContainingType> literalVariables, PrologStructure literal, List<LiteralContainingType> headVariables, boolean mostGeneral) { this.variables = literalVariables.stream(). map(m -> m.getAbstractPrologTerm()).collect(Collectors.toList()); this.literal = literal; List<AbstractPrologTerm> headVars = headVariables.stream(). map(m -> m.getAbstractPrologTerm()).collect(Collectors.toList()); variableInHead = hasSharedVariable(headVars); this.mostGeneral = mostGeneral; } public boolean hasSharedVariable(List<AbstractPrologTerm> otherVars) { boolean ret = false; for (AbstractPrologTerm t : otherVars) { if(this.variables.contains(t)) { ret = true; break; } } return ret; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VariablesInLiteral that = (VariablesInLiteral) o; if (isVariableInHead() != that.isVariableInHead()) return false; if (isMostGeneral() != that.isMostGeneral()) return false; if (getVariables() != null ? !getVariables().equals(that.getVariables()) : that.getVariables() != null) return false; return getLiteral() != null ? getLiteral().equals(that.getLiteral()) : that.getLiteral() == null; } @Override public int hashCode() { int result = (isVariableInHead() ? 1 : 0); result = 31 * result + (isMostGeneral() ? 1 : 0); result = 31 * result + (getVariables() != null ? getVariables().hashCode() : 0); result = 31 * result + (getLiteral() != null ? getLiteral().hashCode() : 0); return result; } public boolean isMostGeneral() { return mostGeneral; } public void setMostGeneral(boolean mostGeneral) { this.mostGeneral = mostGeneral; } public boolean isVariableInHead() { return variableInHead; } public void setVariableInHead(boolean variableInHead) { this.variableInHead = variableInHead; } public List<AbstractPrologTerm> getVariables() { return variables; } public void setVariables(List<AbstractPrologTerm> variables) { this.variables = variables; } public PrologStructure getLiteral() { return literal; } public void setLiteral(PrologStructure literal) { this.literal = literal; } }
3e146371801609ee869a713b881f19de3a074ebd
648
java
Java
src/main/java/net/revelc/code/formatter/html/package-info.java
saikiran-revuru-sp/formatter-maven-plugin
aa2390042b80084ec7f2f284cdf30ed20f03decf
[ "Apache-2.0" ]
223
2015-05-26T03:37:10.000Z
2022-03-06T16:53:33.000Z
src/main/java/net/revelc/code/formatter/html/package-info.java
saikiran-revuru-sp/formatter-maven-plugin
aa2390042b80084ec7f2f284cdf30ed20f03decf
[ "Apache-2.0" ]
376
2015-05-11T22:07:27.000Z
2022-03-05T15:55:16.000Z
src/main/java/net/revelc/code/formatter/html/package-info.java
saikiran-revuru-sp/formatter-maven-plugin
aa2390042b80084ec7f2f284cdf30ed20f03decf
[ "Apache-2.0" ]
104
2015-05-14T17:20:17.000Z
2022-03-01T10:43:50.000Z
36
75
0.737654
8,631
/* * 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. */ /** * HTML Formatter Extension package. */ package net.revelc.code.formatter.html;
3e146376d46cf177f35c3a3c5f089d7f8175a435
991
java
Java
src/dao/Interface/TrascrizioneQueryInterface.java
klaus97/JLibrary
5f1801c3826d8f1f39994edd303d74958a6b1ba1
[ "MIT" ]
3
2018-06-04T13:59:38.000Z
2018-12-08T17:15:39.000Z
src/dao/Interface/TrascrizioneQueryInterface.java
klaus97/JLibrary
5f1801c3826d8f1f39994edd303d74958a6b1ba1
[ "MIT" ]
null
null
null
src/dao/Interface/TrascrizioneQueryInterface.java
klaus97/JLibrary
5f1801c3826d8f1f39994edd303d74958a6b1ba1
[ "MIT" ]
1
2018-05-14T14:40:57.000Z
2018-05-14T14:40:57.000Z
29.147059
95
0.806256
8,632
package dao.Interface; import model.InfoUserTable; import model.OperaMetadati; import model.TrascrizioneDati; import model.UserModel; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public interface TrascrizioneQueryInterface { ArrayList<TrascrizioneDati> getTrascrizioniList (UserModel userModel) throws SQLException; ArrayList<TrascrizioneDati> getTrascUserAbility() throws SQLException; TrascrizioneDati loadtext(TrascrizioneDati trasc) throws SQLException; void savetext(TrascrizioneDati trasc) throws SQLException; void Create(String titolo) throws SQLException; int AssegnaTrascrizione(OperaMetadati op, InfoUserTable user) throws SQLException; ResultSet LoadTrascrizione(String tit) throws SQLException; void Accept(TrascrizioneDati trasc) throws SQLException; void Decline(TrascrizioneDati trasc) throws SQLException; ArrayList<OperaMetadati> SearchOperaSoft() throws SQLException; }
3e14649093520376d11ee008280523952a79762b
6,756
java
Java
native/src/main/java/io/ballerina/stdlib/http/api/HttpCallableUnitCallback.java
thuva9872/module-ballerina-http
964ab86d61e1b1d2deb761d6e28d9028fec24233
[ "Apache-2.0" ]
1
2022-03-22T23:39:49.000Z
2022-03-22T23:39:49.000Z
native/src/main/java/io/ballerina/stdlib/http/api/HttpCallableUnitCallback.java
Code-distancing/module-ballerina-http
81cc41197552aa4c459f96c1bfcce3a89eeb7e57
[ "Apache-2.0" ]
null
null
null
native/src/main/java/io/ballerina/stdlib/http/api/HttpCallableUnitCallback.java
Code-distancing/module-ballerina-http
81cc41197552aa4c459f96c1bfcce3a89eeb7e57
[ "Apache-2.0" ]
null
null
null
37.325967
120
0.671551
8,633
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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 io.ballerina.stdlib.http.api; import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.Runtime; import io.ballerina.runtime.api.async.Callback; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BObject; import io.ballerina.runtime.observability.ObserveUtils; import io.ballerina.runtime.observability.ObserverContext; import io.ballerina.stdlib.http.api.nativeimpl.ModuleUtils; import io.ballerina.stdlib.http.transport.message.HttpCarbonMessage; import static io.ballerina.stdlib.http.api.HttpConstants.OBSERVABILITY_CONTEXT_PROPERTY; import static java.lang.System.err; /** * {@code HttpCallableUnitCallback} is the responsible for acting on notifications received from Ballerina side. * * @since 0.94 */ public class HttpCallableUnitCallback implements Callback { private final BObject caller; private final Runtime runtime; private final String returnMediaType; private final BMap cacheConfig; private HttpCarbonMessage requestMessage; private static final String ILLEGAL_FUNCTION_INVOKED = "illegal return: response has already been sent"; HttpCallableUnitCallback(HttpCarbonMessage requestMessage, Runtime runtime, String returnMediaType, BMap cacheConfig) { this.requestMessage = requestMessage; this.caller = getCaller(requestMessage); this.runtime = runtime; this.returnMediaType = returnMediaType; this.cacheConfig = cacheConfig; } private BObject getCaller(HttpCarbonMessage requestMessage) { BObject caller = requestMessage.getProperty(HttpConstants.CALLER) == null ? ValueCreatorUtils.createCallerObject(requestMessage) : (BObject) requestMessage.getProperty(HttpConstants.CALLER); caller.addNativeData(HttpConstants.TRANSPORT_MESSAGE, requestMessage); requestMessage.setProperty(HttpConstants.CALLER, caller); return caller; } @Override public void notifySuccess(Object result) { cleanupRequestMessage(); if (alreadyResponded(result)) { stopObserverContext(); return; } if (result instanceof BError) { invokeErrorInterceptors((BError) result, true); return; } returnResponse(result); } private void returnResponse(Object result) { Object[] paramFeed = new Object[6]; paramFeed[0] = result; paramFeed[1] = true; paramFeed[2] = returnMediaType != null ? StringUtils.fromString(returnMediaType) : null; paramFeed[3] = true; paramFeed[4] = cacheConfig; paramFeed[5] = true; invokeBalMethod(paramFeed, "returnResponse"); } private void returnErrorResponse(BError error) { Object[] paramFeed = new Object[6]; paramFeed[0] = error; paramFeed[1] = true; paramFeed[2] = returnMediaType != null ? StringUtils.fromString(returnMediaType) : null; paramFeed[3] = true; paramFeed[4] = requestMessage.getHttpStatusCode(); paramFeed[5] = true; invokeBalMethod(paramFeed, "returnErrorResponse"); } private void invokeBalMethod(Object[] paramFeed, String methodName) { Callback returnCallback = new Callback() { @Override public void notifySuccess(Object result) { stopObserverContext(); printStacktraceIfError(result); } @Override public void notifyFailure(BError result) { sendFailureResponse(result); } }; runtime.invokeMethodAsyncSequentially( caller, methodName, null, ModuleUtils.getNotifySuccessMetaData(), returnCallback, null, PredefinedTypes.TYPE_NULL, paramFeed); } private void stopObserverContext() { if (ObserveUtils.isObservabilityEnabled()) { ObserverContext observerContext = (ObserverContext) requestMessage .getProperty(OBSERVABILITY_CONTEXT_PROPERTY); if (observerContext.isManuallyClosed()) { ObserveUtils.stopObservationWithContext(observerContext); } } } @Override public void notifyFailure(BError error) { // handles panic and check_panic cleanupRequestMessage(); // This check is added to release the failure path since there is an authn/authz failure and responded // with 401/403 internally. if (error.getType().getName().equals(HttpErrorType.DESUGAR_AUTH_ERROR.getErrorName())) { return; } if (alreadyResponded(error)) { return; } invokeErrorInterceptors(error, true); } public void invokeErrorInterceptors(BError error, boolean printError) { requestMessage.setProperty(HttpConstants.INTERCEPTOR_SERVICE_ERROR, error); if (printError) { error.printStackTrace(); } returnErrorResponse(error); } public void sendFailureResponse(BError error) { stopObserverContext(); HttpUtil.handleFailure(requestMessage, error, true); } private void cleanupRequestMessage() { requestMessage.waitAndReleaseAllEntities(); } private boolean alreadyResponded(Object result) { try { HttpUtil.methodInvocationCheck(requestMessage, HttpConstants.INVALID_STATUS_CODE, ILLEGAL_FUNCTION_INVOKED); } catch (BError e) { if (result != null) { // handles nil return and end of resource exec printStacktraceIfError(result); err.println(HttpConstants.HTTP_RUNTIME_WARNING_PREFIX + e.getMessage()); } return true; } return false; } private void printStacktraceIfError(Object result) { if (result instanceof BError) { ((BError) result).printStackTrace(); } } }
3e1464b37b6195bb0aa73194c45a82d7090494da
2,003
java
Java
src/main/form/cn/com/smart/form/parser/factory/FormParserFactory.java
cserverpaasshow/smart-OA
9fc4dce8fcc6342c482cd0e397104f64afc39cc5
[ "Apache-2.0" ]
null
null
null
src/main/form/cn/com/smart/form/parser/factory/FormParserFactory.java
cserverpaasshow/smart-OA
9fc4dce8fcc6342c482cd0e397104f64afc39cc5
[ "Apache-2.0" ]
3
2019-11-13T10:35:03.000Z
2021-01-20T23:55:12.000Z
src/main/form/cn/com/smart/form/parser/factory/FormParserFactory.java
cserverpaasshow/smart-OA
9fc4dce8fcc6342c482cd0e397104f64afc39cc5
[ "Apache-2.0" ]
null
null
null
19.831683
95
0.645532
8,634
package cn.com.smart.form.parser.factory; import java.util.List; import java.util.Map; import cn.com.smart.form.parser.IFormParser; import cn.com.smart.service.SmartContextService; import com.mixsmart.utils.StringUtils; /** * 表单解析工厂 * @author lmq * @create 2015年7月4日 * @version 1.0 * @since * */ public class FormParserFactory { private List<IFormParser> formParsers; private static FormParserFactory instance = new FormParserFactory(); private FormParserFactory() { formParsers = SmartContextService.finds(IFormParser.class); } public static FormParserFactory getInstance() { return instance; } /** * 解析表单设计器元素 * @param plugin * @param dataMap * @return * @throws NotFindParserException */ public String parse(String plugin,Map<String,Object> dataMap) throws NotFindParserException { String parseContent = null; if(StringUtils.isNotEmpty(plugin)) { IFormParser formParser = getParser(plugin); if(null == formParser) { throw new NotFindParserException(plugin); } parseContent = formParser.parse(dataMap); } return parseContent; } /** * 获取解析器 * @param plugin * @return */ protected IFormParser getParser(String plugin) { if(null != formParsers && formParsers.size()>0) { for (IFormParser formParser : formParsers) { if(formParser.getPlugin().equals(plugin)) { return formParser; } } } return null; } /** * 注册解析器 * @param plugin * @param formParser * @return */ public boolean register(IFormParser formParser) { boolean is = false; if(null != formParser) { formParsers.add(formParser); is = true; } return is; } /** * 注册解析器 * @param parserBeans * @return */ public boolean register(List<IFormParser> parsers) { boolean is = false; if(null != parsers && parsers.size()>0) { formParsers.addAll(parsers); is = true; } return is; } }
3e1465ecc7d7463755249b459b6dfb3ad2d0d758
717
java
Java
pac4j-oauth/src/main/java/org/pac4j/oauth/profile/google2/Google2Email.java
wardr/pac4j
0a7930e75d6a5e1d914739a80d9dbc39d492aaec
[ "Apache-2.0" ]
4
2017-08-15T07:53:48.000Z
2020-04-22T11:13:06.000Z
pac4j-oauth/src/main/java/org/pac4j/oauth/profile/google2/Google2Email.java
wardr/pac4j
0a7930e75d6a5e1d914739a80d9dbc39d492aaec
[ "Apache-2.0" ]
null
null
null
pac4j-oauth/src/main/java/org/pac4j/oauth/profile/google2/Google2Email.java
wardr/pac4j
0a7930e75d6a5e1d914739a80d9dbc39d492aaec
[ "Apache-2.0" ]
4
2017-07-13T11:50:49.000Z
2020-03-28T06:12:30.000Z
19.916667
70
0.670851
8,635
package org.pac4j.oauth.profile.google2; import com.fasterxml.jackson.annotation.JsonProperty; import org.pac4j.oauth.profile.JsonObject; /** * This class represents an email object for Google. * * @author Nate Williams * @since 1.6.1 */ public final class Google2Email extends JsonObject { private static final long serialVersionUID = 3273984944635729083L; @JsonProperty("value") private String email; private String type; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
3e14663ab9b4dc9125eeb07a616af84fc730a854
7,257
java
Java
java/debugger.jpda/src/org/netbeans/modules/debugger/jpda/jdi/request/BreakpointRequestWrapper.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,056
2019-04-25T20:00:35.000Z
2022-03-30T04:46:14.000Z
java/debugger.jpda/src/org/netbeans/modules/debugger/jpda/jdi/request/BreakpointRequestWrapper.java
Marc382/netbeans
4bee741d24a3fdb05baf135de5e11a7cd95bd64e
[ "Apache-2.0" ]
1,846
2019-04-25T20:50:05.000Z
2022-03-31T23:40:41.000Z
java/debugger.jpda/src/org/netbeans/modules/debugger/jpda/jdi/request/BreakpointRequestWrapper.java
Marc382/netbeans
4bee741d24a3fdb05baf135de5e11a7cd95bd64e
[ "Apache-2.0" ]
550
2019-04-25T20:04:33.000Z
2022-03-25T17:43:01.000Z
49.705479
256
0.638005
8,636
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.netbeans.modules.debugger.jpda.jdi.request; // DO NOT MODIFY THIS CODE, GENERATED AUTOMATICALLY // Generated by org.netbeans.modules.debugger.jpda.jdi.Generate class located in 'gensrc' folder, // perform the desired modifications there and re-generate by "ant generate". /** * Wrapper for BreakpointRequest JDI class. * Use methods of this class instead of direct calls on JDI objects. * These methods assure that exceptions thrown from JDI calls are handled appropriately. * * @author Martin Entlicher */ public final class BreakpointRequestWrapper { private BreakpointRequestWrapper() {} // DO NOT MODIFY THIS CODE, GENERATED AUTOMATICALLY public static void addInstanceFilter(com.sun.jdi.request.BreakpointRequest a, com.sun.jdi.ObjectReference b) throws org.netbeans.modules.debugger.jpda.jdi.InternalExceptionWrapper, org.netbeans.modules.debugger.jpda.jdi.VMDisconnectedExceptionWrapper { if (org.netbeans.modules.debugger.jpda.JDIExceptionReporter.isLoggable()) { org.netbeans.modules.debugger.jpda.JDIExceptionReporter.logCallStart( "com.sun.jdi.request.BreakpointRequest", "addInstanceFilter", "JDI CALL: com.sun.jdi.request.BreakpointRequest({0}).addInstanceFilter({1})", new Object[] {a, b}); } try { a.addInstanceFilter(b); } catch (com.sun.jdi.InternalException ex) { org.netbeans.modules.debugger.jpda.JDIExceptionReporter.report(ex); throw new org.netbeans.modules.debugger.jpda.jdi.InternalExceptionWrapper(ex); } catch (com.sun.jdi.VMDisconnectedException ex) { if (a instanceof com.sun.jdi.Mirror) { com.sun.jdi.VirtualMachine vm = ((com.sun.jdi.Mirror) a).virtualMachine(); try { vm.dispose(); } catch (com.sun.jdi.VMDisconnectedException vmdex) {} } throw new org.netbeans.modules.debugger.jpda.jdi.VMDisconnectedExceptionWrapper(ex); } finally { if (org.netbeans.modules.debugger.jpda.JDIExceptionReporter.isLoggable()) { org.netbeans.modules.debugger.jpda.JDIExceptionReporter.logCallEnd( "com.sun.jdi.request.BreakpointRequest", "addInstanceFilter", org.netbeans.modules.debugger.jpda.JDIExceptionReporter.RET_VOID); } } } // DO NOT MODIFY THIS CODE, GENERATED AUTOMATICALLY public static void addThreadFilter(com.sun.jdi.request.BreakpointRequest a, com.sun.jdi.ThreadReference b) throws org.netbeans.modules.debugger.jpda.jdi.InternalExceptionWrapper, org.netbeans.modules.debugger.jpda.jdi.VMDisconnectedExceptionWrapper { if (org.netbeans.modules.debugger.jpda.JDIExceptionReporter.isLoggable()) { org.netbeans.modules.debugger.jpda.JDIExceptionReporter.logCallStart( "com.sun.jdi.request.BreakpointRequest", "addThreadFilter", "JDI CALL: com.sun.jdi.request.BreakpointRequest({0}).addThreadFilter({1})", new Object[] {a, b}); } try { a.addThreadFilter(b); } catch (com.sun.jdi.InternalException ex) { org.netbeans.modules.debugger.jpda.JDIExceptionReporter.report(ex); throw new org.netbeans.modules.debugger.jpda.jdi.InternalExceptionWrapper(ex); } catch (com.sun.jdi.VMDisconnectedException ex) { if (a instanceof com.sun.jdi.Mirror) { com.sun.jdi.VirtualMachine vm = ((com.sun.jdi.Mirror) a).virtualMachine(); try { vm.dispose(); } catch (com.sun.jdi.VMDisconnectedException vmdex) {} } throw new org.netbeans.modules.debugger.jpda.jdi.VMDisconnectedExceptionWrapper(ex); } finally { if (org.netbeans.modules.debugger.jpda.JDIExceptionReporter.isLoggable()) { org.netbeans.modules.debugger.jpda.JDIExceptionReporter.logCallEnd( "com.sun.jdi.request.BreakpointRequest", "addThreadFilter", org.netbeans.modules.debugger.jpda.JDIExceptionReporter.RET_VOID); } } } // DO NOT MODIFY THIS CODE, GENERATED AUTOMATICALLY public static com.sun.jdi.Location location(com.sun.jdi.request.BreakpointRequest a) throws org.netbeans.modules.debugger.jpda.jdi.InternalExceptionWrapper, org.netbeans.modules.debugger.jpda.jdi.VMDisconnectedExceptionWrapper { if (org.netbeans.modules.debugger.jpda.JDIExceptionReporter.isLoggable()) { org.netbeans.modules.debugger.jpda.JDIExceptionReporter.logCallStart( "com.sun.jdi.request.BreakpointRequest", "location", "JDI CALL: com.sun.jdi.request.BreakpointRequest({0}).location()", new Object[] {a}); } Object retValue = null; try { com.sun.jdi.Location ret; ret = a.location(); retValue = ret; return ret; } catch (com.sun.jdi.InternalException ex) { retValue = ex; org.netbeans.modules.debugger.jpda.JDIExceptionReporter.report(ex); throw new org.netbeans.modules.debugger.jpda.jdi.InternalExceptionWrapper(ex); } catch (com.sun.jdi.VMDisconnectedException ex) { retValue = ex; if (a instanceof com.sun.jdi.Mirror) { com.sun.jdi.VirtualMachine vm = ((com.sun.jdi.Mirror) a).virtualMachine(); try { vm.dispose(); } catch (com.sun.jdi.VMDisconnectedException vmdex) {} } throw new org.netbeans.modules.debugger.jpda.jdi.VMDisconnectedExceptionWrapper(ex); } catch (Error err) { retValue = err; throw err; } catch (RuntimeException rex) { retValue = rex; throw rex; } finally { if (org.netbeans.modules.debugger.jpda.JDIExceptionReporter.isLoggable()) { org.netbeans.modules.debugger.jpda.JDIExceptionReporter.logCallEnd( "com.sun.jdi.request.BreakpointRequest", "location", retValue); } } } }